ChunkTerrainGenerator.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using NavMeshSurface = UnityEngine.AI.NavMeshSurface;
  5. using KairoEngine.Core;
  6. using KairoEngine.Chunks;
  7. using KairoEngine.NoiseUtilities;
  8. using Utilities = KairoEngine.Utility.Utilities;
  9. using Sirenix.OdinInspector;
  10. using UniRx;
  11. namespace KairoEngine.TerrainEngine
  12. {
  13. [HideMonoScript]
  14. public class ChunkTerrainGenerator : MonoBehaviour
  15. {
  16. [BoxGroup("Configurations")] public Vector3 voxelSize = new Vector3(1f, 1f, 1f);
  17. [BoxGroup("Configurations")] public Vector3Int chunkSize = new Vector3Int(16, 16, 16);
  18. [BoxGroup("Configurations")] public Vector3Int chunkLimit = new Vector3Int(2, 1, 2);
  19. [BoxGroup("Configurations")] public StartConfig startConfiguration = StartConfig.DoNothing;
  20. [BoxGroup("Configurations"), ShowIf("@startConfiguration == StartConfig.WaitForEvent")] public string generateWorldEvent = "GenerateWorld";
  21. [BoxGroup("Configurations")] public int dataProcessLimit = 4;
  22. [BoxGroup("Configurations")] public int parallelMeshJobs = 4;
  23. [HorizontalGroup("Configurations/NavMesh")] public bool processNavMesh = false;
  24. [HorizontalGroup("Configurations/NavMesh"), ShowIf("@processNavMesh"), HideLabel] public NavMeshSurface navMeshSurface;
  25. [HorizontalGroup("Configurations/OnChunkGeneratedEvent")] public bool triggerOnChunkGeneratedEvent = true;
  26. [HorizontalGroup("Configurations/OnChunkGeneratedEvent"), ShowIf("@triggerOnChunkGeneratedEvent"), HideLabel] public string onChunkGeneratedEvent;
  27. [HorizontalGroup("Configurations/OnTerrainGeneratedEvent")] public bool triggerOnTerrainGeneratedEvent = true;
  28. [HorizontalGroup("Configurations/OnTerrainGeneratedEvent"), ShowIf("@triggerOnTerrainGeneratedEvent"), HideLabel] public string onTerrainGeneratedEvent;
  29. [BoxGroup("Configurations")] public bool showChunkData = false;
  30. [BoxGroup("Configurations")] public bool showDebug = false;
  31. [InlineProperty, HideLabel, BoxGroup("Marching Cubes")] public MarchingCubes4 marchingCubes = new();
  32. [BoxGroup("Map Data Generator"), InlineProperty, HideLabel, SerializeReference] public IMapDataGenerator mapDataGenerator;
  33. [ShowIf("@showChunkData"), BoxGroup("Chunk System"), InlineProperty, HideLabel] public ChunkSystem<BlockBase> chunkSystem;
  34. public Dictionary<Vector3, GameObject> terrainMeshes = new Dictionary<Vector3, GameObject>();
  35. [ShowInInspector] private List<Vector3> chunkDataBuffer = new List<Vector3>(); // Store list of chunks for populating with data
  36. [ShowInInspector] private List<Vector3> chunkMeshBuffer = new List<Vector3>(); // Store list of chunks for generating the mesh
  37. [ShowInInspector] private List<Vector3> chunkMeshProcessBuffer = new List<Vector3>(); // Store list of chunks that are waiting for their meshes
  38. private bool initialized = false;
  39. private bool buildingNavmesh = false;
  40. public class VoxelUpdateData
  41. {
  42. public Vector3 position;
  43. public BlockBase block;
  44. public VoxelUpdateData(Vector3 position, BlockBase block)
  45. {
  46. this.position = position;
  47. this.block = block;
  48. }
  49. }
  50. private Dictionary<Vector3,List<VoxelUpdateData>> chunkUpdates = new Dictionary<Vector3, List<VoxelUpdateData>>();
  51. private void Start()
  52. {
  53. if(startConfiguration == StartConfig.GenerateOnStart) GenerateWorld();
  54. else if(startConfiguration == StartConfig.WaitForEvent) GenericEvents.StartListening(generateWorldEvent, GenerateWorld);
  55. }
  56. private void Update()
  57. {
  58. marchingCubes.UpdateFinishedJobs();
  59. }
  60. private void OnDisable()
  61. {
  62. if(startConfiguration == StartConfig.WaitForEvent) GenericEvents.StopListening(generateWorldEvent, GenerateWorld);
  63. }
  64. private void OnDestroy()
  65. {
  66. marchingCubes.OnDestroy();
  67. }
  68. public void Initialize ()
  69. {
  70. chunkSystem = new ChunkSystem<BlockBase>(chunkSize,voxelSize, true);
  71. initialized = true;
  72. }
  73. public bool IsInitialized() => initialized;
  74. [Button("Generate World"), ButtonGroup("Buttons")]
  75. void GenerateWorld()
  76. {
  77. if(mapDataGenerator == null)
  78. {
  79. Debug.LogError("Missing planet template", this.gameObject);
  80. return;
  81. }
  82. DestroyTerrain();
  83. Debug.Log("Starting chunk generation");
  84. Initialize();
  85. for (int x = 0; x < chunkLimit.x; x++) {
  86. for (int z = 0; z < chunkLimit.z; z++) {
  87. for (int y = 0; y < chunkLimit.y; y++) {
  88. Vector3 chunkGlobalPos = new Vector3(x * chunkSize.x * voxelSize.x, y * chunkSize.y * voxelSize.y, z * chunkSize.z * voxelSize.z);
  89. Vector3Int chunkPos = new Vector3Int(x * chunkSize.x, y * chunkSize.y, z * chunkSize.z);
  90. chunkSystem.CreateChunk(chunkGlobalPos, chunkPos, (Chunk<BlockBase> c, Vector3Int pos) => new BlockBase(0, 0));
  91. PopulateChunkData(chunkGlobalPos);
  92. }
  93. }
  94. }
  95. for (int x = 0; x < chunkLimit.x; x++) {
  96. for (int z = 0; z < chunkLimit.z; z++) {
  97. for (int y = 0; y < chunkLimit.y; y++) {
  98. //Vector3Int chunkPos = new Vector3Int(x * chunkSize.x, y * chunkSize.y, z * chunkSize.z);
  99. Vector3 chunkPos = new Vector3(x * chunkSize.x * voxelSize.x, y * chunkSize.y * voxelSize.y, z * chunkSize.z * voxelSize.z);
  100. GenerateTerrainMesh(chunkPos);
  101. //else if(marchingCubes2 != null) marchingCubes2.Generate(chunkSystem, chunkPos);
  102. }
  103. }
  104. }
  105. #if UNITY_EDITOR
  106. UpdateEditor ();
  107. #endif
  108. }
  109. public void GenerateChunk(Vector3 position)
  110. {
  111. position = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(position);
  112. bool buffered = false;
  113. for (int i = 0; i < chunkDataBuffer.Count; i++)
  114. {
  115. if(chunkDataBuffer[i] == position) buffered = true;
  116. }
  117. for (int i = 0; i < chunkMeshBuffer.Count; i++)
  118. {
  119. if(chunkMeshBuffer[i] == position) buffered = true;
  120. }
  121. //if(chunkSystem.ChunkExists(position)) buffered = true;
  122. //bool meshGenerated = terrainMeshes.TryGetValue(position, out GameObject obj);
  123. //if(meshGenerated) buffered = true;
  124. if(buffered) return;
  125. chunkDataBuffer.Add(position);
  126. }
  127. void PopulateChunkData(Vector3 initialPos)
  128. {
  129. float width = (float)(chunkLimit.x * chunkSize.x * voxelSize.x);
  130. float height = (float)(chunkLimit.y * chunkSize.y * voxelSize.y);
  131. float length = (float)(chunkLimit.z * chunkSize.z * voxelSize.z);
  132. for (int x = 0; x < chunkSize.x; x++) {
  133. for (int z = 0; z < chunkSize.z; z++) {
  134. for (int y = 0; y < chunkSize.y; y++) {
  135. // Get a terrain height using regular old Perlin noise.
  136. Vector3 pos = initialPos + new Vector3(x * voxelSize.x, y * voxelSize.y, z * voxelSize.z);
  137. // Old example noise:
  138. //float thisHeight = height * Mathf.PerlinNoise((float)pos.x / width * noiseMultiplier + 0.001f, (float)pos.z / length * noiseMultiplier + 0.001f);
  139. float elevation = mapDataGenerator.SamplePoint((float)pos.x / width, (float)pos.z / length);
  140. float thisHeight = height * elevation;
  141. uint code = mapDataGenerator.SamplePointColor((float)pos.x / width, (float)pos.z / length, elevation);
  142. BlockBase block = new BlockBase(code, (uint)Mathf.FloorToInt(thisHeight * 1000));
  143. chunkSystem.SetBlock(pos, block);
  144. }
  145. }
  146. }
  147. chunkUpdates.TryGetValue(initialPos, out List<VoxelUpdateData> updates);
  148. if(updates == null) return;
  149. for (int i = 0; i < updates.Count; i++)
  150. {
  151. chunkSystem.SetBlock(updates[i].position, updates[i].block);
  152. }
  153. }
  154. public void GenerateChunkData(Vector3 position)
  155. {
  156. position = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(position);
  157. Vector3Int chunkPos = chunkSystem.GetChunkPositionFromGlobalPosition(position);
  158. if(!chunkSystem.ChunkExists(position))
  159. {
  160. //Debug.Log($"Generating Terrain Data ({position} | {chunkPos})");
  161. chunkSystem.CreateChunk(position, chunkPos, (Chunk<BlockBase> c, Vector3Int pos) => new BlockBase(0, 0));
  162. PopulateChunkData(position);
  163. }
  164. }
  165. public void GenerateTerrainMesh(Vector3 position, bool overwrite = false)
  166. {
  167. bool meshExists = terrainMeshes.TryGetValue(position, out GameObject obj);
  168. if(meshExists && !overwrite && obj != null) return;
  169. if(!overwrite) terrainMeshes.Add(position, null);
  170. if(marchingCubes != null)
  171. {
  172. chunkMeshProcessBuffer.Add(position);
  173. marchingCubes.Generate(chunkSystem, this, position);
  174. }
  175. }
  176. public void UpdateGenerator()
  177. {
  178. if(marchingCubes.GetJobCount() == 0) ProcessChunkDataBuffer();
  179. ProcessChunkMeshBuffer();
  180. }
  181. public void UpdateEditor ()
  182. {
  183. Timer.ExecuteRealTime(50, () => {
  184. if(marchingCubes != null)
  185. {
  186. UpdateGenerator();
  187. if(!marchingCubes.IsGeneratorDone()) UpdateEditor();
  188. }
  189. });
  190. }
  191. private void ProcessChunkDataBuffer()
  192. {
  193. int limit = chunkDataBuffer.Count < dataProcessLimit ? chunkDataBuffer.Count : dataProcessLimit;
  194. for (int i = 0; i < limit; i++)
  195. {
  196. Vector3 position = chunkDataBuffer[i];
  197. List<Vector3> positions = new List<Vector3>{
  198. new Vector3( 0, 0, 0),
  199. new Vector3( 1, 0, 0),
  200. new Vector3( 1, 0, -1),
  201. new Vector3( 0, 0, -1),
  202. new Vector3(-1, 0, -1),
  203. new Vector3(-1, 0, 0),
  204. new Vector3(-1, 0, 1),
  205. new Vector3( 0, 0, 1),
  206. new Vector3( 1, 0, 1),
  207. new Vector3( 0, 1, 0),
  208. new Vector3( 1, 1, 0),
  209. new Vector3( 1, 1, -1),
  210. new Vector3( 0, 1, -1),
  211. new Vector3(-1, 1, -1),
  212. new Vector3(-1, 1, 0),
  213. new Vector3(-1, 1, 1),
  214. new Vector3( 0, 1, 1),
  215. new Vector3( 1, 1, 1),
  216. new Vector3( 0, -1, 0),
  217. new Vector3( 1, -1, 0),
  218. new Vector3( 1, -1, -1),
  219. new Vector3( 0, -1, -1),
  220. new Vector3(-1, -1, -1),
  221. new Vector3(-1, -1, 0),
  222. new Vector3(-1, -1, 1),
  223. new Vector3( 0, -1, 1),
  224. new Vector3( 1, -1, 1),
  225. };
  226. for (int a = 0; a < positions.Count; a++)
  227. {
  228. //position = new Vector3(position.x + chunkSize.x * voxelSize.x, position.y, position.z);
  229. Vector3 chunkPos = new Vector3(
  230. position.x + (positions[a].x * chunkSize.x * voxelSize.x),
  231. position.y + (positions[a].y * chunkSize.y * voxelSize.y),
  232. position.z + (positions[a].z * chunkSize.z * voxelSize.z)
  233. );
  234. GenerateChunkData(chunkPos);
  235. }
  236. chunkMeshBuffer.Add(chunkDataBuffer[i]);
  237. }
  238. chunkDataBuffer.RemoveRange(0, limit);
  239. }
  240. private void ProcessChunkMeshBuffer()
  241. {
  242. marchingCubes.UpdateFinishedJobs();
  243. int limit = marchingCubes.GetJobCount() < parallelMeshJobs ? parallelMeshJobs - marchingCubes.GetJobCount() : 0;
  244. limit = limit < chunkMeshBuffer.Count ? limit : chunkMeshBuffer.Count;
  245. for (int i = 0; i < limit; i++)
  246. {
  247. GenerateTerrainMesh(chunkMeshBuffer[i]);
  248. }
  249. chunkMeshBuffer.RemoveRange(0, limit);
  250. }
  251. public void DestroyChunk(Vector3 position)
  252. {
  253. DestroyChunkData(position);
  254. DestroyChunkMesh(position);
  255. }
  256. public void DestroyChunkData(Vector3 position)
  257. {
  258. chunkSystem.DestroyChunk(position);
  259. }
  260. public void DestroyChunkMesh(Vector3 position)
  261. {
  262. terrainMeshes.TryGetValue(position, out GameObject obj);
  263. if(obj != null)
  264. {
  265. Destroy(obj);
  266. #if UNITY_EDITOR
  267. DestroyImmediate(obj);
  268. #endif
  269. }
  270. terrainMeshes.Remove(position);
  271. }
  272. public void ClearChunkDataBuffer() => chunkDataBuffer.Clear();
  273. [Button("Destroy"), ButtonGroup("Buttons")]
  274. public void DestroyTerrain()
  275. {
  276. var childTransforms = this.gameObject.transform.GetComponentsInChildren<Transform>();
  277. if(childTransforms.Length > 0) Debug.Log($"Destroying {childTransforms.Length} terrain objects");
  278. for (int i = 0; i < childTransforms.Length; i++)
  279. {
  280. if(childTransforms[i] == this.transform) continue;
  281. #if UNITY_EDITOR
  282. DestroyImmediate(childTransforms[i].gameObject);
  283. #else
  284. Destroy(childTransforms[i].gameObject);
  285. #endif
  286. }
  287. terrainMeshes = new Dictionary<Vector3, GameObject>();
  288. chunkDataBuffer = new List<Vector3>();
  289. chunkMeshBuffer = new List<Vector3>();
  290. chunkSystem.chunks = new Dictionary<Vector3Int, Chunk<BlockBase>>();
  291. chunkSystem.chunkList = new List<Vector3>();
  292. }
  293. public enum VoxelOperation
  294. {
  295. Add,
  296. Remove,
  297. Level
  298. }
  299. public void ChangeVoxels(Vector3 pos, uint code, VoxelOperation operation, int radius = 3)
  300. {
  301. int startHeigth = 0, endHeigth = 0, targetHeigth = 0, updatedVoxels = 0;
  302. switch (operation)
  303. {
  304. case VoxelOperation.Add:
  305. startHeigth = -1;
  306. endHeigth = radius;
  307. targetHeigth = (int)(((chunkSystem.GetBlock(pos).value/1000) + (radius * voxelSize.y)) * 1000);
  308. break;
  309. case VoxelOperation.Remove:
  310. startHeigth = -1 * (radius + 1);
  311. endHeigth = radius + 1;
  312. targetHeigth = (int)(Mathf.Clamp((chunkSystem.GetBlock(pos).value/1000) - (radius * voxelSize.y), 0, 10000) * 1000);
  313. break;
  314. case VoxelOperation.Level:
  315. startHeigth = -1 * radius;
  316. endHeigth = radius;
  317. targetHeigth = (int)chunkSystem.GetBlock(pos).value;
  318. break;
  319. default:
  320. return;
  321. }
  322. Vector3 chunkPosition = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(pos);
  323. List<Vector2Int> points = Utilities.GetPointsInRadius(radius, true);
  324. List<Vector3> chunkPositions = new List<Vector3>();
  325. for (int j = 0; j < points.Count; j++)
  326. {
  327. for (int y = startHeigth; y < endHeigth + 1; y++)
  328. {
  329. updatedVoxels += 1;
  330. Vector3 voxelPos = new Vector3(pos.x + points[j].x * voxelSize.x, pos.y + y * voxelSize.y, pos.z + points[j].y * voxelSize.z);
  331. BlockBase block = chunkSystem.GetBlock(voxelPos);
  332. block.code = code;
  333. block.value = (uint)targetHeigth;
  334. chunkSystem.SetBlock(voxelPos, block);
  335. // Get positions
  336. Vector3Int localVoxelPos = chunkSystem.GetVoxelFromGlobalPosition(voxelPos);
  337. Vector3 chunkPos = chunkSystem.GetChunkGlobalPositionFromGlobalPosition(voxelPos);
  338. // Save data update
  339. VoxelUpdateData updateData = new VoxelUpdateData(voxelPos, block);
  340. chunkUpdates.TryGetValue(chunkPos, out List<VoxelUpdateData> chunkUpdate);
  341. if(chunkUpdate != null)
  342. {
  343. bool exists = false;
  344. for (int h = 0; h < chunkUpdate.Count; h++)
  345. {
  346. if(chunkUpdate[h].position.Equals(updateData.position))
  347. {
  348. exists = true;
  349. chunkUpdate[h].block = updateData.block;
  350. }
  351. }
  352. if(!exists) chunkUpdate.Add(updateData);
  353. }
  354. else chunkUpdates.Add(chunkPos, new List<VoxelUpdateData>{updateData});
  355. // Check if changed voxels are in the edge of the chunk and if true add the neightboring chunk to the update list
  356. List<Vector3> chunks = new List<Vector3>();
  357. chunks.Add(chunkPos);
  358. if(localVoxelPos.x == 0) chunks.Add(new Vector3(chunkPos.x - chunkSize.x * voxelSize.x, chunkPos.y, chunkPos.z));
  359. if(localVoxelPos.x == 16) chunks.Add(new Vector3(chunkPos.x + chunkSize.x * voxelSize.x, chunkPos.y, chunkPos.z));
  360. if(localVoxelPos.y == 0) chunks.Add(new Vector3(chunkPos.x, chunkPos.y - chunkSize.y * voxelSize.y, chunkPos.z));
  361. if(localVoxelPos.y == 16) chunks.Add(new Vector3(chunkPos.x, chunkPos.y + chunkSize.y * voxelSize.y, chunkPos.z));
  362. if(localVoxelPos.z == 0) chunks.Add(new Vector3(chunkPos.x, chunkPos.y, chunkPos.z - chunkSize.z * voxelSize.z));
  363. if(localVoxelPos.z == 16) chunks.Add(new Vector3(chunkPos.x , chunkPos.y, chunkPos.z + chunkSize.z * voxelSize.z));
  364. for (int i = 0; i < chunks.Count; i++)
  365. {
  366. bool duplicate = false;
  367. for (int k = 0; k < chunkPositions.Count; k++)
  368. {
  369. if(chunkPositions[k].Equals(chunks[i]))
  370. {
  371. duplicate = true;
  372. break;
  373. }
  374. }
  375. if(!duplicate) chunkPositions.Add(chunks[i]);
  376. }
  377. }
  378. }
  379. for (int c = 0; c < chunkPositions.Count; c++) GenerateTerrainMesh(chunkPositions[c], true);
  380. Debug.Log($"Changing voxel at {pos}, updated {updatedVoxels} voxels and {chunkPositions.Count} chunks");
  381. }
  382. public void AddGeneratedTerrainMesh(Vector3 chunkPosition, GameObject meshObj)
  383. {
  384. chunkMeshProcessBuffer.Remove(chunkPosition);
  385. bool meshExists = terrainMeshes.TryGetValue(chunkPosition, out GameObject currentMesh);
  386. if(currentMesh != null)
  387. {
  388. //Debug.Log($"Updating chunk mesh at {chunkPosition}");
  389. DestroyChunkMesh(chunkPosition);
  390. terrainMeshes[chunkPosition] = meshObj;
  391. }
  392. else
  393. {
  394. //Debug.Log($"Adding chunk mesh at {chunkPosition}");
  395. //terrainMeshes.Add(chunkPosition, meshObj);
  396. terrainMeshes[chunkPosition] = meshObj;
  397. }
  398. if(triggerOnChunkGeneratedEvent) GenericEvents.Trigger(onChunkGeneratedEvent, chunkPosition);
  399. if(!buildingNavmesh && chunkMeshProcessBuffer.Count == 0 && chunkMeshBuffer.Count == 0 && chunkDataBuffer.Count == 0)
  400. {
  401. buildingNavmesh = true;
  402. Timer.ExecuteRealTime(50, () => {
  403. if(processNavMesh && navMeshSurface != null)
  404. {
  405. var cron = new Cronometer();
  406. navMeshSurface.BuildNavMesh();
  407. //navMeshSurface.UpdateNavMesh(navMeshSurface.navMeshData);
  408. cron.Stop();
  409. if(showDebug) Debug.Log($"Generated Navmesh in {cron.Print()}");
  410. buildingNavmesh = false;
  411. }
  412. if(triggerOnTerrainGeneratedEvent) GenericEvents.Trigger(onTerrainGeneratedEvent);
  413. });
  414. }
  415. }
  416. [Button("Save"), ButtonGroup("Buttons")]
  417. public void SaveChunkUpdateData()
  418. {
  419. }
  420. public enum StartConfig
  421. {
  422. DoNothing,
  423. GenerateOnStart,
  424. WaitForEvent
  425. }
  426. }
  427. }