-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBehavior.cs
298 lines (258 loc) · 8.6 KB
/
Behavior.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
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright (c) 2020-2023 Vladimir Popov [email protected] https://github.com/ZorPastaman/Behavior-Tree
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using UnityEngine.Profiling;
using Zor.BehaviorTree.Debugging;
using Zor.SimpleBlackboard.Core;
namespace Zor.BehaviorTree.Core
{
/// <summary>
/// Base class for behavior tree behaviors.
/// </summary>
/// <remarks>
/// <para>
/// Don't derive it. You need to derive <see cref="Zor.BehaviorTree.Core.Composites.Composite"/>,
/// <see cref="Zor.BehaviorTree.Core.Decorators.Decorator"/>,
/// <see cref="Zor.BehaviorTree.Core.Leaves.Actions.Action"/>,
/// <see cref="Zor.BehaviorTree.Core.Leaves.Conditions.Condition"/> or
/// <see cref="Zor.BehaviorTree.Core.Leaves.Leaf"/>.
/// </para>
/// <para>
/// In setup methods you always don't have children. They're set right after a setup.
/// </para>
/// </remarks>
public abstract class Behavior
{
/// <summary>
/// Behavior tree blackboard.
/// </summary>
private Blackboard m_blackboard;
/// <summary>
/// Current status. It's updated after each tick.
/// </summary>
private Status m_status = Status.Idle;
/// <summary>
/// Current status. It's updated after each tick.
/// </summary>
public Status status
{
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
get => m_status;
}
/// <summary>
/// Behavior tree blackboard.
/// </summary>
protected Blackboard blackboard
{
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
get => m_blackboard;
}
/// <summary>
/// Ticks a behavior.
/// </summary>
/// <returns>New status of the behavior.</returns>
public Status Tick()
{
Profiler.BeginSample(GetType().FullName);
if (m_status != Status.Running)
{
Profiler.BeginSample("Begin");
Begin();
Profiler.EndSample();
}
Profiler.BeginSample("Execute");
m_status = Execute();
Profiler.EndSample();
if (m_status != Status.Running)
{
Profiler.BeginSample("End");
End();
Profiler.EndSample();
}
#if DEBUG
if (m_status != Status.Success & m_status != Status.Running & m_status != Status.Failure & m_status != Status.Error)
{
BehaviorTreeDebug.LogError($"Behavior of type {GetType()} returned {m_status} as a result of Execute. But only {Status.Success}, {Status.Running}, {Status.Failure} and {Status.Error} are acceptable");
}
#endif
Profiler.EndSample();
return m_status;
}
/// <summary>
/// Aborts a behavior if it's in <see cref="Status.Running"/> state.
/// </summary>
/// <returns>
/// <para>
/// New state (<see cref="Status.Abort"/>) if the behavior was in <see cref="Status.Running"/> state
/// before the call.
/// </para>
/// <para>Current state if the behavior wasn't in <see cref="Status.Running"/> state before the call.</para>
/// </returns>
public Status Abort()
{
Profiler.BeginSample(GetType().FullName);
if (m_status == Status.Running)
{
OnAbortInternal();
Profiler.BeginSample("OnAbort");
OnAbort();
Profiler.EndSample();
m_status = Status.Abort;
}
Profiler.EndSample();
return m_status;
}
/// <summary>
/// Initializes a behavior. It's called once before a first tick.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal virtual void Initialize()
{
Profiler.BeginSample(GetType().FullName);
OnInitialize();
Profiler.EndSample();
}
/// <summary>
/// Disposes a behavior. It's called once before a behavior tree is destroyed.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal virtual void Dispose()
{
Profiler.BeginSample(GetType().FullName);
OnDispose();
Profiler.EndSample();
}
/// <summary>
/// Sets <paramref name="blackboardToSet"/> as a behavior blackboard.
/// It's called once right after a creation of a behavior tree.
/// </summary>
/// <param name="blackboardToSet">Blackboard to set.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal virtual void SetBlackboard([NotNull] Blackboard blackboardToSet)
{
m_blackboard = blackboardToSet;
}
/// <summary>
/// The method is called once before a first tick.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual void OnInitialize() {}
/// <summary>
/// The method is called each tick before <see cref="Execute"/>
/// if <see cref="status"/> is not <see cref="Status.Running"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual void Begin() {}
/// <summary>
/// The method is called each tick. Its returned value is set to <see cref="status"/> right after the call.
/// </summary>
/// <returns>Result of the execution.</returns>
/// <remarks>
/// The method must return one of these values: <see cref="Status.Success"/>, <see cref="Status.Running"/>,
/// <see cref="Status.Failure"/> or <see cref="Status.Error"/>.
/// </remarks>
protected abstract Status Execute();
/// <summary>
/// The method is called each tick after <see cref="Execute"/>
/// if <see cref="status"/> after <see cref="Execute"/> is not <see cref="Status.Running"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual void End() {}
/// <summary>
/// The method is called when <see cref="Abort"/> is called and
/// current <see cref="status"/> is <see cref="Status.Running"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual void OnAbort() {}
/// <summary>
/// The method is called once before a behavior tree is destroyed.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected virtual void OnDispose() {}
/// <summary>
/// The method is called before <see cref="OnAbort"/>. It's used to call <see cref="OnAbort"/>
/// in from child to parent order.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected private virtual void OnAbortInternal() {}
/// <summary>
/// Calls an appropriate setup method of <paramref name="behavior"/>.
/// </summary>
/// <param name="behavior"><see cref="Behavior"/> with the setup method.</param>
/// <param name="parameters">Setup method arguments.</param>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="behavior"/> doesn't have an appropriate setup method.
/// </exception>
protected private static void CreateSetup([NotNull] Behavior behavior,
[NotNull, ItemCanBeNull] object[] parameters)
{
Type behaviorType = behavior.GetType();
Type[] interfaceTypes = behaviorType.GetInterfaces();
int parametersCount = parameters.Length;
var parameterTypes = new Type[parametersCount];
for (int i = 0; i < parametersCount; ++i)
{
object parameter = parameters[i];
parameterTypes[i] = parameter?.GetType();
}
Type baseSetupableType;
switch (parametersCount)
{
case 1:
baseSetupableType = typeof(ISetupable<>);
break;
case 2:
baseSetupableType = typeof(ISetupable<,>);
break;
case 3:
baseSetupableType = typeof(ISetupable<,,>);
break;
case 4:
baseSetupableType = typeof(ISetupable<,,,>);
break;
case 5:
baseSetupableType = typeof(ISetupable<,,,,>);
break;
case 6:
baseSetupableType = typeof(ISetupable<,,,,,>);
break;
case 7:
baseSetupableType = typeof(ISetupable<,,,,,,>);
break;
case 8:
baseSetupableType = typeof(ISetupable<,,,,,,,>);
break;
default:
throw new ArgumentException($"Failed to setup a behavior of type {behaviorType}. Too many parameters are passed. It supports up to 8 parameters.");
}
for (int i = 0, iCount = interfaceTypes.Length; i < iCount; ++i)
{
Type interfaceType = interfaceTypes[i];
// TODO Support derivation
if (!interfaceType.IsGenericType || interfaceType.GetGenericTypeDefinition() != baseSetupableType)
{
continue;
}
Type[] interfaceParameters = interfaceType.GetGenericArguments();
bool goodInterface = true;
for (int j = 0, jCount = interfaceParameters.Length; j < jCount & goodInterface; ++j)
{
goodInterface = parameterTypes[j] == null
? interfaceParameters[j].IsClass
: interfaceParameters[j].IsAssignableFrom(parameterTypes[j]);
}
if (!goodInterface)
{
continue;
}
Profiler.BeginSample("Setup");
interfaceType.InvokeMember("Setup", BindingFlags.InvokeMethod, null, behavior, parameters);
Profiler.EndSample();
return;
}
throw new ArgumentException($"Failed to setup a behavior of type {behaviorType}. It doesn't have an appropriate setup method for passed arguments.");
}
}
}