-
Notifications
You must be signed in to change notification settings - Fork 12
/
ChunkManager.cs
441 lines (400 loc) · 21.1 KB
/
ChunkManager.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
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
using System;
using System.Collections;
using System.Collections.Generic;
using Swihoni.Components;
using Swihoni.Util.Math;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.SceneManagement;
using Voxels.Map;
using Random = UnityEngine.Random;
namespace Voxels
{
public delegate void MapProgressCallback(in MapProgressInfo mapProgressInfoCallback);
public enum MapLoadingStage
{
Waiting,
CleaningUp,
SettingUp,
Generating,
UpdatingMesh,
Completed,
Failed
}
public struct MapProgressInfo
{
public MapLoadingStage stage;
public float progress;
}
public enum ChunkActionType
{
Commission,
Generate,
UpdateMesh
}
public class ChunkManager : MonoBehaviour
{
[SerializeField] private GameObject m_ChunkPrefab = default;
[SerializeField] private int m_ChunkSize = default;
private readonly Stack<Chunk> m_ChunkPool = new();
private int m_PoolSize;
private MapContainer m_LoadedMap;
public int ChunkSize => m_ChunkSize;
public MapContainer Map { get; private set; }
public Dictionary<Position3Int, Chunk> Chunks { get; } = new();
public MapProgressInfo ProgressInfo { get; set; } = new() {stage = MapLoadingStage.Completed};
public IEnumerator LoadMap(MapContainer map)
{
Map = map;
m_LoadedMap = map.Clone();
SetPoolSize(map);
// Decommission all current chunks
yield return DecommissionAllChunks();
if (map.terrainHeight.WithoutValue) yield break;
yield return ManagePoolSize();
yield return ChunkActionForAllStaticMapChunks(map, ChunkActionType.Commission);
yield return ChunkActionForAllStaticMapChunks(map, ChunkActionType.Generate);
yield return ChunkActionForAllStaticMapChunks(map, ChunkActionType.UpdateMesh);
ProgressInfo = new MapProgressInfo {stage = MapLoadingStage.Completed};
}
private IEnumerator DecommissionAllChunks()
{
var progress = 0.0f;
int commissionedChunks = Chunks.Count;
var chunksInPositionToRemove = new List<Position3Int>(Chunks.Keys);
foreach (Position3Int chunkPosition in chunksInPositionToRemove)
{
DecommissionChunkInPosition(chunkPosition);
progress += 1.0f / commissionedChunks;
ProgressInfo = new MapProgressInfo {stage = MapLoadingStage.CleaningUp, progress = progress};
yield return null;
}
}
private IEnumerator ChunkActionForAllStaticMapChunks(MapContainer map, ChunkActionType actionType)
{
var progress = 0.0f;
Position3Int lower = map.dimension.lowerBound, upper = map.dimension.upperBound;
for (int x = lower.x; x <= upper.x; x++)
for (int y = lower.y; y <= upper.y; y++)
for (int z = lower.z; z <= upper.z; z++)
{
var chunkPosition = new Position3Int(x, y, z);
progress += 1.0f / m_PoolSize;
var progressInfo = new MapProgressInfo {progress = progress};
switch (actionType)
{
case ChunkActionType.Commission:
{
CommissionChunkFromPoolIntoPosition(chunkPosition);
progressInfo.stage = MapLoadingStage.SettingUp;
break;
}
case ChunkActionType.Generate:
{
GetChunkFromPosition(chunkPosition).CreateTerrainFromSave(map);
progressInfo.stage = MapLoadingStage.Generating;
break;
}
case ChunkActionType.UpdateMesh:
{
UpdateChunkMesh(GetChunkFromPosition(chunkPosition));
progressInfo.stage = MapLoadingStage.UpdatingMesh;
break;
}
default:
{
Debug.LogWarning($"Unrecognized chunk action type: {actionType}");
break;
}
}
ProgressInfo = progressInfo;
yield return null;
}
if (actionType == ChunkActionType.Generate)
foreach (VoxelChange change in map.voxelChanges.List)
ApplyVoxelChanges(change, false, TouchedChunks);
}
/// <summary>
/// Manage the size of the pool, commission chunks if there are too little,
/// and decommission if there are too much.
/// This will only change things if chunk pool and the chunks are free.
/// </summary>
private IEnumerator ManagePoolSize()
{
var adjust = true;
while (adjust)
{
int totalAmountOfChunks = m_ChunkPool.Count + Chunks.Count;
if (totalAmountOfChunks < m_PoolSize)
{
GameObject chunkInstance = Instantiate(m_ChunkPrefab);
SceneManager.MoveGameObjectToScene(chunkInstance, gameObject.scene);
chunkInstance.name = "DecommissionedChunk";
// chunkInstance.hideFlags = HideFlags.HideInHierarchy;
var chunk = chunkInstance.GetComponent<Chunk>();
chunk.Initialize(this, m_ChunkSize);
m_ChunkPool.Push(chunk);
}
else
{
// if (totalAmountOfChunks > m_PoolSize)
// Destroy(m_ChunkPool.Pop().gameObject);
adjust = false;
}
yield return null;
}
}
private static readonly TouchedChunks TouchedChunks = new();
private static readonly ProfilerMarker ApplyVoxelChangeMarker = new("Apply Voxel Change");
/// <summary>
/// Change the data of a chunk in the array.
/// </summary>
/// <param name="change">Data to change on voxel</param>
/// <param name="updateSave">Whether or not to update map save component</param>
/// <param name="existingTouched"></param>
/// <param name="overrideBreakable"></param>
public void ApplyVoxelChanges(in VoxelChange change, bool updateSave = true, TouchedChunks existingTouched = null, bool overrideBreakable = false)
{
using (ApplyVoxelChangeMarker.Auto())
{
TouchedChunks touched = existingTouched ?? TouchedChunks;
if (change.isUndo)
{
foreach ((Chunk chunk, Position3Int position, Voxel voxel) in change.undo)
{
chunk.SetVoxelDataRawNoCheck(position, voxel);
AddChunksToUpdateFromVoxel(position, chunk, touched);
}
if (updateSave) Map.voxelChanges.RemoveEnd();
}
else
{
Position3Int worldPosition = change.position.Value;
Random.InitState(worldPosition.GetHashCode());
VoxelChange GetEvaluated(in VoxelChange originalChange, Chunk chunk, in Position3Int voxelChunkPosition, bool mergeOriginal = true)
{
VoxelChange evaluatedChange = originalChange.revert.GetValueOrDefault() ? chunk.GetChangeFromMap(voxelChunkPosition, Map) : default;
if (mergeOriginal) evaluatedChange.Merge(originalChange);
return evaluatedChange;
}
void SetEvaluatedVoxel(in VoxelChange originalChange, in VoxelChange evaluatedChange, Chunk chunk, in Position3Int voxelChunkPosition)
{
// ReSharper disable once PossibleInvalidOperationException
originalChange.undo?.Add((chunk, voxelChunkPosition, chunk.GetVoxelNoCheck(voxelChunkPosition)));
chunk.SetVoxelDataNoCheck(voxelChunkPosition, evaluatedChange);
AddChunksToUpdateFromVoxel(voxelChunkPosition, chunk, touched);
}
VoxelVolumeForm form = change.form.Value;
switch (form)
{
case VoxelVolumeForm.Single:
{
Chunk chunk = GetChunkFromWorldPosition(worldPosition);
if (!chunk) return;
Position3Int voxelChunkPosition = WorldVoxelToChunkVoxel(worldPosition, chunk);
VoxelChange evaluatedChange = GetEvaluated(change, chunk, voxelChunkPosition);
SetEvaluatedVoxel(change, evaluatedChange, chunk, voxelChunkPosition);
break;
}
case VoxelVolumeForm.Prism:
{
Position3Int l = worldPosition, u = change.upperBound.Value;
int lx = Math.Min(l.x, u.x), ly = Math.Min(l.y, u.y), lz = Math.Min(l.z, u.z);
for (int x = lx; x <= Math.Max(l.x, u.x); x++)
for (int y = ly; y <= Math.Max(l.y, u.y); y++)
for (int z = lz; z <= Math.Max(l.z, u.z); z++)
{
var voxelWorldPosition = new Position3Int(x, y, z);
Chunk chunk = GetChunkFromWorldPosition(voxelWorldPosition);
if (!chunk) continue;
Position3Int voxelChunkPosition = WorldVoxelToChunkVoxel(voxelWorldPosition, chunk);
ref Voxel voxel = ref chunk.GetVoxelNoCheck(voxelChunkPosition);
/* Evaluated Change */
VoxelChange evaluatedChange = GetEvaluated(change, chunk, voxelChunkPosition);
evaluatedChange.form = VoxelVolumeForm.Single;
if (change.density.HasValue && (x == lx || y == ly || z == lz))
evaluatedChange.density = null;
else if (evaluatedChange.density is { } density && !change.noRandom.GetValueOrDefault())
evaluatedChange.density = checked((byte) Mathf.RoundToInt(density * Random.Range(0.75f, 1.0f)));
if (!change.modifiesBlocks.GetValueOrDefault() && voxel.HasBlock)
{
evaluatedChange.color = null;
evaluatedChange.texture = null;
}
SetEvaluatedVoxel(change, evaluatedChange, chunk, voxelChunkPosition);
}
break;
}
case VoxelVolumeForm.Spherical:
case VoxelVolumeForm.Cylindrical:
{
float radius = change.magnitude.Value;
bool isAdditive = radius > 0.0f;
float absoluteRadius = Mathf.Abs(radius);
int roundedRadius = Mathf.CeilToInt(absoluteRadius);
for (int ix = -roundedRadius; ix <= roundedRadius; ix++)
for (int iy = -roundedRadius; iy <= roundedRadius; iy++)
for (int iz = -roundedRadius; iz <= roundedRadius; iz++)
{
Position3Int voxelWorldPosition = worldPosition + new Position3Int(ix, iy, iz);
Chunk chunk = GetChunkFromWorldPosition(voxelWorldPosition);
if (!chunk) continue;
Position3Int voxelChunkPosition = WorldVoxelToChunkVoxel(voxelWorldPosition, chunk);
ref Voxel voxel = ref chunk.GetVoxelNoCheck(voxelChunkPosition);
static float GetDistance(VoxelVolumeForm _form, in Vector3 _center, in Vector3 _voxel) => _form == VoxelVolumeForm.Cylindrical
? Mathf.Sqrt((_center.x - _voxel.x).Square() + (_center.z - _voxel.z).Square())
: Vector3.Distance(_center, _voxel);
float distance = GetDistance(form, worldPosition, voxelWorldPosition),
floatDensity = distance / absoluteRadius * 0.5f;
if (!change.noRandom.GetValueOrDefault()) floatDensity *= Random.Range(0.85f, 1.0f);
byte newDensity = checked((byte) Mathf.RoundToInt(Mathf.Clamp01(floatDensity) * byte.MaxValue)),
currentDensity = voxel.density;
if (!overrideBreakable && voxel.IsUnbreakable) continue;
/* Evaluated Change */
VoxelChange evaluatedChange = GetEvaluated(change, chunk, voxelChunkPosition, false);
var changedDensity = false;
if (isAdditive)
{
newDensity = checked((byte) (byte.MaxValue - newDensity));
if (newDensity > currentDensity)
{
evaluatedChange.density = newDensity;
changedDensity = true;
}
}
else
{
if (newDensity < currentDensity)
{
evaluatedChange.density = newDensity;
changedDensity = true;
}
}
if (changedDensity && voxel.OnlySmooth)
{
evaluatedChange.Merge(change);
if (change.color is { } color)
evaluatedChange.color = Color32.Lerp(color, voxel.color, Mathf.Clamp01(distance / absoluteRadius) * 0.1f);
evaluatedChange.natural = false;
}
bool isInside = GetDistance(form, worldPosition, voxelWorldPosition + new Vector3(0.5f, 0.5f, 0.5f)) < absoluteRadius * 1.5f;
if (isInside && !isAdditive && change.modifiesBlocks.GetValueOrDefault() && voxel.HasBlock)
{
evaluatedChange.Merge(change);
if (change.color is { } color)
evaluatedChange.color = Color32.Lerp(color, voxel.color, Mathf.Clamp01(distance / absoluteRadius) * 0.1f);
evaluatedChange.natural = false;
evaluatedChange.hasBlock = false;
}
evaluatedChange.form = VoxelVolumeForm.Single;
SetEvaluatedVoxel(change, evaluatedChange, chunk, voxelChunkPosition);
}
break;
}
case VoxelVolumeForm.Wall:
break;
default:
throw new ArgumentOutOfRangeException(nameof(form), form, null);
}
if (updateSave) Map.voxelChanges.Append(change);
}
if (existingTouched is null) TouchedChunks.UpdateMesh();
}
}
public VoxelChange? GetMapSaveVoxel(in Position3Int worldPosition)
{
Chunk chunk = GetChunkFromWorldPosition(worldPosition);
if (!chunk) return null;
Position3Int voxelChunkPosition = WorldVoxelToChunkVoxel(worldPosition, chunk);
VoxelChange change = chunk.GetChangeFromMap(voxelChunkPosition, m_LoadedMap);
change.position = worldPosition;
return change;
}
/// <summary>
/// Given a world position, find the chunk and then the voxel in that chunk.
/// </summary>
/// <param name="worldPosition">Position of voxel in world space</param>
/// <param name="chunk">Chunk we know it is in. If it is null, we will try to find it</param>
/// <returns>Voxel in that chunk, or null if it does not exist</returns>
public Voxel? GetVoxel(in Position3Int worldPosition, Chunk chunk = null)
{
if (!chunk) chunk = GetChunkFromWorldPosition(worldPosition);
// ReSharper disable once PossibleNullReferenceException
if (chunk) return chunk.GetVoxelNoCheck(WorldVoxelToChunkVoxel(worldPosition, chunk));
return null;
}
/// <summary>
/// Given a world position, determine if a chunk is there.
/// </summary>
/// <param name="worldPosition">World position of chunk</param>
/// <returns>Chunk instance, or null if it doe not exist</returns>
public Chunk GetChunkFromWorldPosition(in Position3Int worldPosition)
{
Position3Int chunkPosition = WorldToChunk(worldPosition);
return GetChunkFromPosition(chunkPosition);
}
public static void UpdateChunkMesh(Chunk chunk) => chunk.UpdateAndApply();
public void AddChunksToUpdateFromVoxel(in Position3Int voxelChunkPosition, Chunk originatingChunk, ICollection<Chunk> chunksToUpdate)
{
chunksToUpdate.Add(originatingChunk);
void AddIfNeeded(int voxelChunkPositionSingle, in Position3Int axis)
{
int sign;
if (voxelChunkPositionSingle == 0) sign = -1;
else if (voxelChunkPositionSingle == m_ChunkSize - 1) sign = 1;
else return;
Chunk chunk = GetChunkFromPosition(originatingChunk.Position + axis * sign);
if (chunk) chunksToUpdate.Add(chunk);
}
AddIfNeeded(voxelChunkPosition.x, new Position3Int {x = 1});
AddIfNeeded(voxelChunkPosition.y, new Position3Int {y = 1});
AddIfNeeded(voxelChunkPosition.z, new Position3Int {z = 1});
}
private static readonly HashSet<Chunk> UpdateAdjacentChunks = new();
private void UpdateChunkMesh(Chunk chunk, in Position3Int voxelChunkPosition)
{
AddChunksToUpdateFromVoxel(voxelChunkPosition, chunk, UpdateAdjacentChunks);
foreach (Chunk chunkToUpdate in UpdateAdjacentChunks)
UpdateChunkMesh(chunkToUpdate);
UpdateAdjacentChunks.Clear();
}
public Chunk GetChunkFromPosition(in Position3Int chunkPosition)
{
Chunks.TryGetValue(chunkPosition, out Chunk containerChunk);
return containerChunk;
}
private void SetPoolSize(MapContainer save)
{
Position3Int upper = save.dimension.upperBound, lower = save.dimension.lowerBound;
m_PoolSize = (upper.x - lower.x + 1) * (upper.y - lower.y + 1) * (upper.z - lower.z + 1);
}
private void CommissionChunkFromPoolIntoPosition(in Position3Int newChunkPosition)
{
if (Chunks.ContainsKey(newChunkPosition)) return;
Chunk chunk = m_ChunkPool.Pop();
Chunks.Add(newChunkPosition, chunk);
chunk.Commission(newChunkPosition);
}
private void DecommissionChunkInPosition(in Position3Int chunkPosition)
{
Chunk chunk = GetChunkFromPosition(chunkPosition);
if (!chunk) return;
chunk.Decommission();
Chunks.Remove(chunk.Position);
m_ChunkPool.Push(chunk);
}
public Position3Int WorldVoxelToChunkVoxel(in Position3Int worldPosition, Chunk chunk) => worldPosition - chunk.Position * m_ChunkSize;
/// <summary>
/// Given a world position, return the position of the chunk that would contain it.
/// </summary>
/// <param name="worldPosition">World position inside of chunk</param>
/// <returns>Position of chunk in respect to chunks dictionary</returns>
private Position3Int WorldToChunk(in Vector3 worldPosition)
{
float chunkSize = m_ChunkSize;
return new Position3Int(Mathf.FloorToInt(worldPosition.x / chunkSize),
Mathf.FloorToInt(worldPosition.y / chunkSize),
Mathf.FloorToInt(worldPosition.z / chunkSize));
}
}
}