-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStateMachine.cs
More file actions
459 lines (402 loc) · 18.4 KB
/
StateMachine.cs
File metadata and controls
459 lines (402 loc) · 18.4 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace BAStudio.StatePattern
{
public partial class StateMachine<T>
{
protected System.Action<string, object[]> debugOutput;
public event System.Action<string, object[]> DebugOutput { add => debugOutput += value; remove => debugOutput -= value; }
public int DebugFlags { get; set; } = 0;
public const int DebugFlag_StateChange = 1 << 0;
public const int DebugFlag_PopupState = 1 << 1;
public const int DebugFlag_Event = 1 << 2;
public const int DebugFlag_Component = 1 << 3;
public const int DebugFlag_All = DebugFlag_StateChange | DebugFlag_PopupState | DebugFlag_Event | DebugFlag_Component;
public StateMachine(T subject)
{
Subject = subject;
UpdatePaused = false;
}
public T Subject { get; }
public State CurrentState { get; protected set; }
private bool updatePaused;
/// <summary>
/// <para>If false, Update() simply returns immediately.</para>
/// <para>This is recommended over not calling Update() because states can check on this and know it's not getting Update().</para>
/// </summary>
public virtual bool UpdatePaused
{
get => updatePaused;
set
{
updatePaused = value;
SendEvent(value? InternalSignal.MachinePaused : InternalSignal.MachineResumed);
}
}
/// <summary>
/// <para> Optimization flag.</para>
/// <para> The generic ChangeState<S> create, cache and reuse the S. </para>
/// <para> Enable this to skip DI if you make sure all needed components are already provided via SetComponent.</para>
/// </summary>
public bool DeliverOnlyOnceForCachedStates { get; set; } = false;
public event Action<State, State> OnStateChanging;
public event Action<State, State> OnStateChanged;
protected Dictionary<Type, State> AutoStateCache { get; set; }
protected List<IPopupState> PopupStates { get; set; }
protected List<IPopupState> PopupStatesToEnd { get; set; }
public event Action<IPopupState> PopupStateStarted;
public event Action<IPopupState> PopupStateEnded;
Dictionary<Type, object> Components { get; set; }
Dictionary<Type, bool> TypesDisabledAutoComponents { get; set; }
Dictionary<Type, PropertyInfo[]?> PropInfoMap { get; set; }
public bool IsUpdating { get; protected set; }
public bool IsChangingState { get => stateChangingDepth > 0; }
int stateChangingDepth;
public void Popup(IPopupState s, object parameter = null)
{
if (PopupStates == null)
PopupStates = new List<IPopupState>();
if (PopupStates.Contains(s))
throw new Exception("PopupState already added");
PopupStates.Add(s);
s.OnStarting(this, Subject, parameter);
SendEvent(new NewPopupStateEvent(s));
PopupStateStarted?.Invoke(s);
}
/// <summary>
/// The new PopupState is returned so you can do something to it like Update() once immediately.
/// </summary>
public S Popup<S>(object parameter = null) where S : IPopupState, new()
{
if (PopupStates == null)
PopupStates = new List<IPopupState>();
S s = new S();
if (PopupStates.Contains(s))
throw new Exception("PopupState already added");
PopupStates.Add(s);
s.OnStarting(this, Subject, parameter);
SendEvent(new NewPopupStateEvent(s));
PopupStateStarted?.Invoke(s);
return s;
}
public void EndPopupState(IPopupState s, object parameter = null)
{
if (PopupStatesToEnd == null)
PopupStatesToEnd = new List<IPopupState>();
s.OnEnding(this, Subject, parameter);
PopupStateEnded?.Invoke(s);
SendEvent(new PopupStateEndedEvent(s));
if (IsUpdating)
{
PopupStatesToEnd.Add(s);
return;
}
PopupStates.Remove(s);
}
public IReadOnlyCollection<IPopupState>? ViewPopupStates ()
{
return PopupStates?.AsReadOnly();
}
public void SetComponent<PT, CT>(CT obj) where CT : PT
{
if (Components == null) Components = new Dictionary<Type, object>();
Components[typeof(PT)] = obj;
}
/// <summary>
/// <para>Change the state to the provide instance, with parameter supplied.</para>
/// <para>It is recommended to use the generic version instead, internal cached states will be used.</para>
/// <para>However, this could be useful in situations like state instances carry different data, or a non-stateful state is shared by massive amount of StateMachines.</para>
/// </summary>
public virtual void ChangeState(State state, object parameter = null)
{
PreStateChange(CurrentState, state, parameter);
var prev = CurrentState;
CurrentState = state;
DeliverComponents(state); // Though maybe not useful, calling this here give prev a chance to provide components
state.OnEntered(this, prev, Subject, parameter);
PostStateChange(prev);
prev?.Reset();
}
/// <summary>
/// <para>Change the state to the specified type, with parameter supplied.</para>
/// <para>The StateMachine automatically manages and keeps the state objects used.</para>
/// </summary>
public virtual void ChangeState<S>(object parameter = null) where S : State, new()
{
if (AutoStateCache == null) AutoStateCache = new Dictionary<Type, State>();
if (!AutoStateCache.ContainsKey(typeof(S)))
{
S newS = new S();
AutoStateCache.Add(typeof(S), newS);
if (DeliverOnlyOnceForCachedStates) DeliverComponents(newS);
}
var prev = CurrentState;
var state = AutoStateCache[typeof(S)];
PreStateChange(CurrentState, state, parameter);
CurrentState = state;
if (!DeliverOnlyOnceForCachedStates)
DeliverComponents(state); // Though maybe not useful, calling this here give prev a chance to provide components
state.OnEntered(this, prev, Subject, parameter);
PostStateChange(prev);
prev?.Reset();
}
/// <summary>
/// If the state is an IComponentUser, this walks through all properties and try to fill in with type-matching components provided.
/// </summary>
/// <param name="state"></param>
protected virtual void DeliverComponents(State state)
{
if (state is IComponentUser cu)
{
Type stateType = state.GetType();
if (!TypesDisabledAutoComponents.TryGetValue(stateType, out var isDisabled))
{
isDisabled = stateType.GetCustomAttribute<DisableAutoComponents>() != null;
TypesDisabledAutoComponents[stateType] = isDisabled;
}
if (isDisabled)
{
foreach (var kvp in Components)
cu.OnComponentSupplied(kvp.Key, kvp.Value);
return;
}
if (PropInfoMap == null) PropInfoMap = new Dictionary<Type, PropertyInfo[]?>();
// This state type has not been queried yet
if (!PropInfoMap.TryGetValue(stateType, out var allPropInfos))
{
var queried = stateType.GetProperties(System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.NonPublic
| BindingFlags.SetProperty)
.Where(
pi => pi.GetCustomAttribute(typeof(AutoComponentAttribute), false) != null
).ToArray();
if (queried .Length == 0) PropInfoMap[stateType] = null;
else
{
allPropInfos = queried;
PropInfoMap[stateType] = allPropInfos;
}
}
if (allPropInfos == null)
{
foreach (var kvp in Components)
cu.OnComponentSupplied(kvp.Key, kvp.Value);
}
else
{
foreach (var pi in allPropInfos)
{
Type propType = pi.PropertyType;
if (Components.TryGetValue(propType, out var comp))
{
pi.SetValue(state, comp);
cu.OnComponentSupplied(propType, comp);
}
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual void PreStateChange(State fromState, State toState, object parameter = null)
{
if (debugOutput != null && (DebugFlags & DebugFlag_StateChange) != 0) LogFormat("A StateMachine<{0}> is switching from {1} to {2}.", Subject.GetType().Name, fromState?.GetType()?.Name, toState.GetType().Name);
stateChangingDepth++;
fromState?.OnLeaving(this, toState, Subject, parameter);
OnStateChanging?.Invoke(fromState, toState);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual void PostStateChange(State fromState)
{
if (debugOutput != null && (DebugFlags & DebugFlag_StateChange) != 0)
LogFormat("A StateMachine<{0}> has switched from {1} to {2}.", Subject.GetType().Name, fromState?.GetType()?.Name, CurrentState.GetType().Name);
SendEvent(new MainStateChangedEvent(fromState, CurrentState));
OnStateChanged?.Invoke(fromState, CurrentState);
stateChangingDepth--;
}
/// <summary>
/// Cache the provided state instance.
/// This is useful when a state is configured with constructor and it's needed to be swapped on the fly.
/// </summary>
/// <param name="state"></param>
/// <typeparam name="S"></typeparam>
public void Cache<S> (S state) where S : State
{
if (DeliverOnlyOnceForCachedStates) DeliverComponents(state);
if (AutoStateCache == null) AutoStateCache = new Dictionary<Type, State>();
AutoStateCache[typeof(S)] = state;
}
public virtual void Update()
{
SelfDiagnosticOnUpdate();
if (UpdatePaused) return;
if (Subject == null) throw new System.NullReferenceException("Target is null.");
IsUpdating = true;
UpdateMainState();
UpdatePopupStates();
IsUpdating = false;
}
#if UNITY_2017_1_OR_NEWER
public bool IsFixedUpdating { get; protected set; }
public bool IsLateUpdating { get; protected set; }
public virtual void FixedUpdate(StateMachine<T> machine, T subject)
{
SelfDiagnosticOnUpdate();
if (UpdatePaused) return;
if (Subject == null) throw new System.NullReferenceException("Target is null.");
IsFixedUpdating = true;
FixedUpdateMainState();
FixedUpdatePopStates();
IsFixedUpdating = false;
}
public virtual void LateUpdate(StateMachine<T> machine, T subject)
{
SelfDiagnosticOnUpdate();
if (UpdatePaused) return;
if (Subject == null) throw new System.NullReferenceException("Target is null.");
IsLateUpdating = true;
LateUpdateMainState();
LateUpdatePopStates();
IsLateUpdating = false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void FixedUpdateMainState()
{
if (CurrentState is not NoOpState)
{
if (CurrentState == null) throw new System.NullReferenceException("CurrentState is null. Did you set a state after instantiate this controller?");
else CurrentState.FixedUpdate(this, Subject);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void FixedUpdatePopStates()
{
if (PopupStates != null)
foreach (var ps in PopupStates) ps.FixedUpdate(this, Subject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void LateUpdateMainState()
{
if (CurrentState is not NoOpState)
{
if (CurrentState == null) throw new System.NullReferenceException("CurrentState is null. Did you set a state after instantiate this controller?");
else CurrentState.LateUpdate(this, Subject);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void LateUpdatePopStates()
{
if (PopupStates != null)
foreach (var ps in PopupStates) ps.LateUpdate(this, Subject);
}
#endif
protected virtual void SelfDiagnosticOnUpdate ()
{
if (stateChangingDepth > 0)
throw new Exception("State change is not properly finished. Is there an exception?");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void UpdateMainState()
{
if (CurrentState is not NoOpState)
{
if (CurrentState == null) throw new System.NullReferenceException("CurrentState is null. Did you set a state after instantiate this controller?");
else CurrentState.Update(this, Subject);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void UpdatePopupStates()
{
if (PopupStates == null)
return;
foreach (var ps in PopupStates)
ps.Update(this, Subject);
if (PopupStatesToEnd != null)
{
foreach (var ps in PopupStatesToEnd)
PopupStates.Remove(ps);
PopupStatesToEnd.Clear();
}
}
public virtual bool SendEvent<E>(E ev)
{
if (debugOutput != null && (DebugFlags & DebugFlag_Event) != 0 && CurrentState != null)
LogFormat("A StateMachine<{0}> is sending event {1} to {2}",
Subject!.GetType().Name,
ev.GetType().Name,
CurrentState?.GetType()?.Name);
SendEventToCurrentState(ev);
SendEventToPopupStates(ev);
return true;
}
public virtual bool SendEvent<S, E>(E ev, bool shouldThrow) where S : StateMachine<T>.State
{
if (CurrentState is not S)
if (shouldThrow) throw new Exception($"Event sender expected {typeof(S)}, but current state is {CurrentState.GetType().Name}.");
else return false;
SendEventToCurrentState(ev);
SendEventToPopupStates(ev);
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void SendEventToCurrentState<E>(E ev)
{
if (CurrentState is IEventReceiverState<T, E> ers)
ers.ReceiveEvent(this, Subject, ev);
else if (CurrentState is IEventReceiverState<E> ers2)
ers2.ReceiveEvent(ev);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void SendEventToPopupStates<E>(E ev)
{
if (PopupStates != null)
foreach (var ps in PopupStates)
if (ps is IEventReceiverState<T, E> ers) ers.ReceiveEvent(this, Subject, ev);
else if (ps is IEventReceiverState<E> ers2) ers2.ReceiveEvent(ev);
}
protected virtual void Log(string content)
{
// if (debugOutput == null) return;
// debugOutput(content);
debugOutput?.Invoke(content, null);
}
protected virtual void LogFormat(string format, params object[] args)
{
// if (debugOutput == null) return;
// if (DebugStringBuilder == null) DebugStringBuilder = new StringBuilder();
// DebugStringBuilder.AppendFormat(format, arg0);
// debugOutput(DebugStringBuilder.ToString());
// DebugStringBuilder.Clear();
debugOutput?.Invoke(string.Format(format, args), args);
}
// protected virtual void LogFormat(string format, object arg0, object arg1)
// {
// // if (debugOutput == null) return;
// // if (DebugStringBuilder == null) DebugStringBuilder = new StringBuilder();
// // DebugStringBuilder.AppendFormat(format, arg0, arg1);
// // debugOutput(DebugStringBuilder.ToString());
// // DebugStringBuilder.Clear();
// }
// protected virtual void LogFormat(string format, object arg0, object arg1, object arg2)
// {
// // if (debugOutput == null) return;
// // if (DebugStringBuilder == null) DebugStringBuilder = new StringBuilder();
// // DebugStringBuilder.AppendFormat(format, arg0, arg1, arg2);
// // debugOutput(DebugStringBuilder.ToString());
// // DebugStringBuilder.Clear();
// }
// protected virtual void LogFormat(string format, object arg0, object arg1, object arg2, object arg3)
// {
// // if (debugOutput == null) return;
// // if (DebugStringBuilder == null) DebugStringBuilder = new StringBuilder();
// // DebugStringBuilder.AppendFormat(format, arg0, arg1, arg2, arg3);
// // debugOutput(DebugStringBuilder.ToString());
// // DebugStringBuilder.Clear();
// }
}
}