-
Notifications
You must be signed in to change notification settings - Fork 3
/
HeartPromoManager5.cs
400 lines (344 loc) · 11.9 KB
/
HeartPromoManager5.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
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
using System;
using System.Collections.Generic;
using Random = UnityEngine.Random;
using UnityEngine;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
public class HeartPromoManager5 : MonoBehaviour
{
public GameObject heartPrefab;
public Bounds bounds;
public int virtualHeartCount = 100000;
public int realHeartCount = 3000;
private List<GameObject> heartPool = new List<GameObject>();
private void OnEnable()
{
foreach (var heart in heartPool)
{
heart.SetActive(true);
}
}
private void OnDisable()
{
foreach (var heart in heartPool)
{
//Check exists to avoid error when exiting playmode.
if (heart != null)
heart.SetActive(false);
}
}
struct HeartData : IComparable<HeartData>
{
public float3 position;
public float distanceToCamera;
public int poolIndex;
public bool visible;
public int CompareTo(HeartData other)
{
int result = -visible.CompareTo(other.visible);
if (result == 0)
{
return distanceToCamera.CompareTo(other.distanceToCamera);
}
else
{
return result;
}
}
}
struct PoolRecord
{
public float3 position;
public bool writeThisFrame;
}
// This is new!
struct HeartPromoLogicData
{
public float oscilationSpeed;
public float oscilationHeight;
public float rotationSpeed;
}
// And so is this!
struct HeartPromoLogicTransformValues
{
public float3 position;
public quaternion rotation;
}
[BurstCompile]
struct PoolRecordResetJob : IJobFor
{
public NativeArray<PoolRecord> poolRecords;
public void Execute(int i)
{
var record = poolRecords[i];
record.writeThisFrame = false;
poolRecords[i] = record;
}
}
[BurstCompile]
struct HeartCullJob : IJobFor
{
[ReadOnly] public NativeArray<float4> planes;
public NativeArray<HeartData> hearts;
public float3 camPos;
public void Execute(int i)
{
var heart = hearts[i];
heart.distanceToCamera = math.distancesq(camPos, heart.position); //Optimization: distanceSq is good enough for our needs
heart.visible = TestPlanes(heart.position);
hearts[i] = heart;
}
bool TestPlanes(float3 position)
{
float4 p = new float4(position, 1f);
bool inside = true;
for (int i = 0; i < 6; i++)
{
inside &= math.dot(planes[i], p) > -6f;
}
return inside;
}
}
[BurstCompile]
struct HeartSortJob : IJob
{
public NativeArray<HeartData> hearts;
public int poolCount;
public void Execute()
{
Sort(hearts);
}
void Sort<T>(NativeArray<T> array) where T : struct, IComparable<T>
{
Sort(array, 0, array.Length - 1);
}
void Sort<T>(NativeArray<T> array, int left, int right) where T : struct, IComparable<T>
{
//Only the prioritized elements need to be sorted.
if (left >= poolCount && right >= poolCount)
return;
if (left < poolCount && right < poolCount)
return;
int i = left;
int j = right;
var pivot = array[(left + right) / 2];
while (i <= j)
{
while (array[i].CompareTo(pivot) < 0)
{
i++;
}
while (array[j].CompareTo(pivot) > 0)
{
j--;
}
if (i <= j)
{
var temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
if (left < j)
{
Sort(array, left, j);
}
if (right > i)
{
Sort(array, i, right);
}
}
}
[BurstCompile]
struct HeartSwapJob : IJob
{
public NativeArray<HeartData> hearts;
public NativeArray<PoolRecord> poolRecords;
public void Execute()
{
int j = poolRecords.Length;
for (int i = 0; i < poolRecords.Length; i++)
{
var heart = hearts[i];
if (heart.poolIndex == -1)
{
while (j < hearts.Length)
{
var otherHeart = hearts[j];
if (otherHeart.poolIndex != -1)
{
heart.poolIndex = otherHeart.poolIndex;
otherHeart.poolIndex = -1;
poolRecords[heart.poolIndex] = new PoolRecord
{
position = heart.position,
writeThisFrame = true
};
hearts[i] = heart;
hearts[j] = otherHeart;
j++;
break;
}
j++;
}
}
}
}
}
[BurstCompile]
struct HeartPromoLogicJob : IJobFor
{
[ReadOnly] public NativeArray<HeartPromoLogicData> data;
public NativeArray<HeartPromoLogicTransformValues> transforms;
public float time;
public float deltaTime;
public void Execute(int i)
{
float y = data[i].oscilationHeight * math.sin(data[i].oscilationSpeed * time);
var tf = transforms[i];
tf.position = new float3(0f, y, 0f);
tf.rotation = math.mul(quaternion.Euler(0f, math.radians(data[i].rotationSpeed * deltaTime), 0f), tf.rotation);
transforms[i] = tf;
}
}
private Camera mainCam;
private NativeArray<HeartData> hearts;
private NativeArray<PoolRecord> poolRecords;
private Plane[] camPlanes = new Plane[6];
private NativeArray<float4> planes;
private NativeArray<HeartPromoLogicData> promoLogicData;
private NativeArray<HeartPromoLogicTransformValues> promoLogicTransformValues;
// Caching the children is a massive optimization.
// Iterating through all the real Transforms is slow.
// That's why the writeThisFrame bool in past iterations
// was so important.
private Transform[] childTransforms;
// We have two independent job chains now.
JobHandle jobHandleVirtual; // Virtual mapping of hearts to GameObjects
JobHandle jobHandlePool; // Updating transforms of child GameObjects in pool
private void Awake()
{
hearts = new NativeArray<HeartData>(virtualHeartCount, Allocator.Persistent);
poolRecords = new NativeArray<PoolRecord>(realHeartCount, Allocator.Persistent);
planes = new NativeArray<float4>(6, Allocator.Persistent);
promoLogicData = new NativeArray<HeartPromoLogicData>(poolRecords.Length, Allocator.Persistent);
promoLogicTransformValues = new NativeArray<HeartPromoLogicTransformValues>(poolRecords.Length, Allocator.Persistent);
childTransforms = new Transform[poolRecords.Length];
for (int i = 0; i < poolRecords.Length; i++)
{
heartPool.Add(Instantiate(heartPrefab));
}
for (int i = 0; i < hearts.Length; i++)
{
Vector3 position;
position.x = Random.Range(bounds.min.x, bounds.max.x);
position.y = Random.Range(bounds.min.y, bounds.max.y);
position.z = Random.Range(bounds.min.z, bounds.max.z);
hearts[i] = new HeartData
{
position = position,
distanceToCamera = 0f,
poolIndex = i < heartPool.Count ? i : -1,
visible = false
};
}
// There's a lot more to do now, since we are now replacing the HeartPromoLogic's Update method with a job.
// We now need to copy that script's data and disable it.
for (int i = 0; i < heartPool.Count; i++)
{
heartPool[i].transform.position = hearts[i].position;
var logic = heartPool[i].transform.GetChild(0).GetComponent<HeartPromoLogic>();
promoLogicData[i] = new HeartPromoLogicData
{
oscilationHeight = logic.oscilationHeight,
oscilationSpeed = logic.oscilationSpeed,
rotationSpeed = logic.rotationSpeed
};
promoLogicTransformValues[i] = new HeartPromoLogicTransformValues
{
position = float3.zero,
rotation = logic.transform.localRotation
};
childTransforms[i] = logic.transform;
logic.enabled = false;
}
mainCam = Camera.main;
}
private void Update()
{
GeometryUtility.CalculateFrustumPlanes(mainCam, camPlanes);
var camPos = mainCam.transform.position;
for (int i = 0; i < 6; i++)
{
planes[i] = new float4(camPlanes[i].normal, camPlanes[i].distance);
}
var resetJobHandle = new PoolRecordResetJob
{
poolRecords = poolRecords
}.Schedule(poolRecords.Length, default);
var cullingSortingJobHandle = new HeartCullJob
{
camPos = camPos,
hearts = hearts,
planes = planes
}.ScheduleParallel(hearts.Length, 16, default);
//Reuse handles
cullingSortingJobHandle = new HeartSortJob
{
hearts = hearts,
poolCount = poolRecords.Length
}.Schedule(cullingSortingJobHandle);
jobHandleVirtual = JobHandle.CombineDependencies(resetJobHandle, cullingSortingJobHandle);
jobHandleVirtual = new HeartSwapJob
{
hearts = hearts,
poolRecords = poolRecords
}.Schedule(jobHandleVirtual);
jobHandlePool = new HeartPromoLogicJob
{
data = promoLogicData,
transforms = promoLogicTransformValues,
time = Time.unscaledTime,
deltaTime = Time.unscaledDeltaTime
}.ScheduleParallel(promoLogicData.Length, 8, default);
JobHandle.ScheduleBatchedJobs();
}
private void LateUpdate()
{
jobHandlePool.Complete();
ApplyChildTransforms();
jobHandleVirtual.Complete();
ApplyRecords();
}
void ApplyRecords()
{
for (int i = 0; i < poolRecords.Length; i++)
{
if (poolRecords[i].writeThisFrame)
{
heartPool[i].transform.position = poolRecords[i].position;
}
}
}
void ApplyChildTransforms()
{
for (int i = 0; i < poolRecords.Length; i++)
{
var tf = childTransforms[i];
tf.localPosition = promoLogicTransformValues[i].position;
tf.localRotation = promoLogicTransformValues[i].rotation;
}
}
private void OnDestroy()
{
hearts.Dispose();
poolRecords.Dispose();
planes.Dispose();
promoLogicData.Dispose();
promoLogicTransformValues.Dispose();
}
}