-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlockManager.cs
More file actions
260 lines (209 loc) · 6.66 KB
/
FlockManager.cs
File metadata and controls
260 lines (209 loc) · 6.66 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
public class FlockManager : Cullable
{
[Header("Job")]
private NativeArray<BoidData> _agentsDataArray;
private NativeArray<float2> _steeringOutputArray;
private NativeArray<float> _speedMultiplierOutput, _currentSpeedMultiplier;
private NativeArray<uint> _randomSeeds;
[Title("Main config")]
[SerializeField] private bool isActive = true;
[SerializeField] private FlockBehaviorSO flockBehavior;
[SerializeField] private FlockAgentJob agentPrefab;
[SerializeField] private Transform spawnPoint;
[Range(2, 500)]
public int numAgents = 250;
[Range(1f, 100f)]
public float acceleration = 10f;
//--- behaviors stuff
private FlockBehaviorBase[] _behaviors;
private readonly List<FlockAgentJob> _agents = new List<FlockAgentJob>();
public Transform[] agentTransforms { get; private set; }
//Keep tracking
private Dictionary<Collider2D, FlockAgentJob> _agentColliderMap = new();
private Vector2 _alignmentDir, _cohesionDir, _separationDir;
private Transform _agentTransform;
private Vector3 _currentAgentPos;
private Vector2 _currentAgentMove;
private float _currentSqrdDistanceFromPlayer;
private void Awake()
{
// Get all behaviors attached as components
_behaviors = GetComponents<FlockBehaviorBase>();
}
// Start is called before the first frame update
void Start()
{
SetupFlockJobData();
InitializeAgents();
}
//Necessary setup for flock properties, meaning stuff all agents will share
private void SetupFlockJobData()
{
//initializing native arrays for job
_agentsDataArray = new NativeArray<BoidData>(numAgents, Allocator.Persistent);
_steeringOutputArray = new NativeArray<float2>(numAgents, Allocator.Persistent);
_speedMultiplierOutput = new NativeArray<float>(numAgents, Allocator.Persistent);
_currentSpeedMultiplier = new NativeArray<float>(numAgents, Allocator.Persistent);
_randomSeeds = new NativeArray<uint>(numAgents, Allocator.Persistent);
for (int i = 0; i < numAgents; i++)
{
_speedMultiplierOutput[i] = 1f;
_currentSpeedMultiplier[i] = 1f;
}
}
private void InitializeAgents()
{
//instantiate agents
for (int i = 0; i < numAgents; i++)
{
FlockAgentJob newAgent = Instantiate(
agentPrefab,
(Vector2)spawnPoint.position + (Random.insideUnitCircle * numAgents * 0.08f),
Quaternion.Euler(Vector3.forward * Random.Range(0f, 360f)),
transform
);
newAgent.name = agentPrefab.name + i;
newAgent.Initialize(this);
newAgent.orbitBias = Random.Range(-1f, 1f);
_agents.Add(newAgent);
_agentColliderMap[newAgent.GetComponent<Collider2D>()] = newAgent;
}
//cache the transforms for faster access
agentTransforms = _agents.Select(a => a.transform).ToArray();
//init behaviors
foreach (FlockBehaviorBase behavior in _behaviors)
{
behavior.Initialize(this);
}
}
// Update is called once per frame
void Update()
{
if (!isActive || !_agentsDataArray.IsCreated)
return;
if (isCulled)
return;
HandleFlockingUpdate();
}
private void HandleFlockingUpdate()
{
//1. Basic job data
for (int i = 0; i < numAgents; i++)
{
Transform tf = agentTransforms[i];
_agentsDataArray[i] = new BoidData
{
Position = new float2(tf.position.x, tf.position.y),
Forward = new float2(tf.up.x, tf.up.y)
};
}
//2. Create the Job with Common behavior data
var job = new FlockDirectionJob
{
Agents = _agentsDataArray,
Output = _steeringOutputArray,
SpeedMultiplierOutput = _speedMultiplierOutput,
TimeSeconds = Time.time,
};
//3. Calculate behaviors to use
foreach (FlockBehaviorBase behavior in _behaviors)
{
behavior.ApplyToJob(ref job);
}
JobHandle handle = job.Schedule(numAgents, 64);
handle.Complete();
//apply result back to agents
for (int i = 0; i < numAgents; i++)
{
float2 dir = _steeringOutputArray[i];
float targetSpeedMultiplier = _speedMultiplierOutput[i];
float currentMultiplier = _currentSpeedMultiplier[i];
float smoothingRate = targetSpeedMultiplier > currentMultiplier
? job.HardAvoidSpeedBoostInRate
: job.HardAvoidSpeedBoostOutRate;
currentMultiplier = Mathf.MoveTowards(currentMultiplier, targetSpeedMultiplier, smoothingRate * Time.deltaTime);
_currentSpeedMultiplier[i] = currentMultiplier;
float speed = acceleration * currentMultiplier;
FlockAgentJob agent = _agents[i];
//apply any external forces from the behaviors, like area containment
foreach (FlockBehaviorBase behavior in _behaviors)
{
dir += behavior.GetExternalDirection(ref agent);
}
dir = math.normalize(dir);
_agents[i].Move(dir * speed);
}
}
private void OnDestroy()
{
if (_agentsDataArray.IsCreated) _agentsDataArray.Dispose();
if (_steeringOutputArray.IsCreated) _steeringOutputArray.Dispose();
if (_speedMultiplierOutput.IsCreated) _speedMultiplierOutput.Dispose();
if (_currentSpeedMultiplier.IsCreated) _currentSpeedMultiplier.Dispose();
if (_randomSeeds.IsCreated) _randomSeeds.Dispose();
}
//to toggle the whole acitvity on and off
public void ToggleActivity(bool newActive)
{
this.isActive = newActive;
}
public bool ToggleGoal(bool newActive)
{
var goal = _behaviors.OfType<FlockGoal>().FirstOrDefault();
if (goal == null) return false;
goal.isActive = newActive;
return true;
}
public bool ToggleContainment(bool newActive)
{
var goal = _behaviors.OfType<FlockContainment>().FirstOrDefault();
if (goal == null) return false;
goal.isActive = newActive;
return true;
}
public bool ToggleGoalType(FlockGoalType newType)
{
var goal = _behaviors.OfType<FlockGoal>().FirstOrDefault();
if (goal == null) return false;
goal.goalType = newType;
return true;
}
public FlockContainment GetContainmentBehavior()
{
return _behaviors.OfType<FlockContainment>().FirstOrDefault();
}
#region Culling
public override Bounds GetCullBounds()
{
if (agentTransforms != null && agentTransforms.Length > 0)
{
Vector3 startPos = agentTransforms[0].position;
Bounds bounds = new Bounds(startPos, Vector3.one * 0.5f);
for (int i = 1; i < agentTransforms.Length; i++)
{
bounds.Encapsulate(agentTransforms[i].position);
}
return bounds;
}
return default;
}
public override void SetCulled(bool culled)
{
//for flock manager is only just changing a boolean no big deal
isCulled = culled;
}
protected override void OnDrawGizmosSelected()
{
//if they are the same it pretty much mean is visible
if (_cameraClosestPoint == Vector3.one)
return;
Bounds c = GetCullBounds();
Gizmos.color = Color.purple;
Gizmos.DrawWireCube(c.center, c.size);
Gizmos.color = isCulled ? Color.red : Color.purple;
Gizmos.DrawLine(c.center, _cameraClosestPoint);
Gizmos.DrawSphere(c.center, 1f);
Gizmos.DrawSphere(_cameraClosestPoint, 1f);
}
#endregion
}