ChunkTerrainGenerator.cs 19 KB

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