Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Rendering;
- using System.Threading.Tasks;
- using Unity.Mathematics;
- using System.Diagnostics;
- using UnityEngine.UIElements;
- using Unity.VisualScripting;
- using Unity.Jobs;
- using Unity.Collections;
- using static UnityEngine.Mesh;
- public class MeshGenerator : MonoBehaviour
- {
- public static Vector2Int chunkDimensions = new Vector2Int(32, 192);
- public Material material;
- public ComputeShader voxelGridShader;
- public int brushSize;
- public float brushStrength;
- public int lod;
- public int maxLod;
- public int maxChunksProcessing;
- public float surfaceLevel;
- public bool hideMeshOnPlay;
- [Header("Noise Settings")]
- public float heightMultiplier;
- public int curveResolution;
- public AnimationCurve heightCurve;
- public float frequency;
- public float lacunarity;
- public float persistance;
- public int octaves;
- public float density;
- public float warpingStrength;
- public float warpingFrequency;
- public Vector2 offset;
- [Header("")]
- public bool autoUpdate;
- public string executionTime;
- Camera cam;
- VoxelGrid voxelGrid;
- List<ChunkData> chunksToProcess;
- int chunksProcessing;
- Stopwatch watch;
- private void Start()
- {
- Init();
- if (GameObject.Find("Mesh") != null)
- {
- GameObject.Find("Mesh").SetActive(!hideMeshOnPlay);
- }
- }
- private void Update()
- {
- if (Input.GetKeyDown(KeyCode.Space))
- {
- EditorMesh();
- }
- //Limit the number of chunks that can be processed at once, preventing lag spikes
- for (int i = 0; i < chunksToProcess.Count; i++)
- {
- if(chunksProcessing < maxChunksProcessing)
- {
- ProcessChunk(chunksToProcess[i]);
- chunksProcessing++;
- chunksToProcess.RemoveAt(i);
- }
- }
- }
- public GameObject ChunkObject(Vector2 position)
- {
- GameObject chunk = new GameObject("Chunk");
- chunk.AddComponent<MeshFilter>().mesh = ChunkMesh(position, 0);
- chunk.AddComponent<MeshRenderer>().material = material;
- chunk.GetComponent<MeshRenderer>().receiveShadows = false;
- chunk.GetComponent<MeshRenderer>().shadowCastingMode = ShadowCastingMode.Off;
- return chunk;
- }
- public Mesh ChunkMesh(Vector2 position, int lod)
- {
- Mesh mesh = new Mesh();
- mesh.indexFormat = IndexFormat.UInt32;
- lod = lod == 0 ? 1 : lod * 2;
- chunksToProcess.Add(new ChunkData
- {
- mesh = mesh,
- position = position,
- lod = lod
- });
- return mesh;
- }
- public void EditorMesh()
- {
- Init();
- Mesh mesh = ChunkMesh(offset / 10, lod);
- ProcessChunk(chunksToProcess[0]);
- chunksToProcess.Clear();
- if (GameObject.Find("Mesh") == null)
- {
- GameObject obj = new GameObject("Mesh");
- obj.transform.parent = transform;
- obj.AddComponent<MeshFilter>().mesh = mesh;
- obj.AddComponent<MeshRenderer>().material = material;
- obj.AddComponent<MeshCollider>();
- }
- else
- {
- var mf = GameObject.Find("Mesh").GetComponent<MeshFilter>();
- var collider = GameObject.Find("Mesh").GetComponent<MeshCollider>();
- mf.mesh = mesh;
- collider.sharedMesh = null;
- collider.sharedMesh = mesh;
- }
- }
- void Init()
- {
- chunksToProcess = new();
- cam = Camera.main;
- voxelGrid = new VoxelGrid(frequency, lacunarity, persistance, octaves, surfaceLevel, density, heightMultiplier, warpingFrequency, warpingStrength, curveResolution, heightCurve, voxelGridShader);
- }
- void ProcessChunk(ChunkData cd)
- {
- //Getting back data from the GPU is slow, so first the voxel grid is requested then
- //whenever the data has reached the CPU the mesh is constructed
- voxelGrid.RequestVoxelGrid(cd.position, cd.lod, out ShaderData shaderData);
- CompleteReadBack(shaderData, cd.mesh, cd.lod);
- }
- async void CompleteReadBack(ShaderData sd, Mesh mesh, int lod)
- {
- var request = AsyncGPUReadback.Request(sd.voxelGridBuffer);
- // Wait for the request to complete
- while (!request.done)
- {
- await Task.Yield();
- }
- if (request.hasError)
- {
- UnityEngine.Debug.LogWarning("GPU readback error detected.");
- }
- else
- {
- //Get voxelGrid after readback is complete
- sd.voxelGridBuffer.Release();
- sd.noiseMap2DBuffer.Release();
- sd.noiseMap2D.Dispose();
- float[] voxelGrid = request.GetData<float>().ToArray();
- ConstructMesh(voxelGrid, mesh, lod);
- }
- }
- async void ConstructMesh(float[] voxelGrid, Mesh mesh, int lod)
- {
- List<Vector3> vertices = new();
- List<int> indices = new();
- Dictionary<Vector3, int> vertDictionary = new();
- MeshData meshData = new MeshData
- {
- vertices = vertices,
- indices = indices,
- vertDictionary = vertDictionary,
- voxelGrid = voxelGrid,
- lod = lod
- };
- //Offloads mesh creation to another thread so the main thread is not halted
- await Task.Run(() =>
- {
- for (int z = 0, i = 0; z < chunkDimensions.x; z += lod)
- {
- for (int y = 0; y < chunkDimensions.y; y += lod)
- {
- for (int x = 0; x < chunkDimensions.x; x += lod, i++)
- {
- AddVertices(i, new Vector3Int(x, y, z), meshData);
- }
- }
- }
- });
- mesh.vertices = vertices.ToArray();
- mesh.triangles = indices.ToArray();
- mesh.RecalculateNormals();
- chunksProcessing--;
- }
- void AddVertices(int index, Vector3Int pos, MeshData md)
- {
- float[] voxelCornerValues = new float[8];
- for (int i = 0; i < 8; i++)
- {
- voxelCornerValues[i] = md.voxelGrid[(index * 8) + i];
- }
- int triCase = CalculateCase(voxelCornerValues);
- int[] edges = Tables.triTable[triCase];
- for (int j = 0, i = 0; j < Tables.caseToNumPolys[triCase]; j++, i += 3)
- {
- for (int h = 0; h < 3; h++)
- {
- Vector3 vertex = GetEdgePosition(edges[i + (2 - h)], voxelCornerValues, md.lod, pos);
- //Checks for duplicate vertices
- if(md.vertDictionary.TryGetValue(vertex, out int triIndex))
- {
- md.indices.Add(triIndex);
- }
- else
- {
- md.vertDictionary.Add(vertex, md.vertices.Count);
- md.vertices.Add(vertex);
- md.indices.Add(md.vertices.Count - 1);
- }
- }
- }
- }
- Vector3 GetEdgePosition(int edge, float[] voxelData, int lod, Vector3Int pos)
- {
- int x = pos.x;
- int y = pos.y;
- int z = pos.z;
- switch (edge)
- {
- case 0: return GetInterpolatedEdgePosition(x, y, z, voxelData[0], voxelData[1], 0, 1, 0);
- case 1: return GetInterpolatedEdgePosition(x, y + lod, z, voxelData[1], voxelData[2], 1, 0, 0);
- case 2: return GetInterpolatedEdgePosition(x + lod, y, z, voxelData[3], voxelData[2], 0, 1, 0);
- case 3: return GetInterpolatedEdgePosition(x, y, z, voxelData[0], voxelData[3], 1, 0, 0);
- case 4: return GetInterpolatedEdgePosition(x, y, z + lod, voxelData[4], voxelData[5], 0, 1, 0);
- case 5: return GetInterpolatedEdgePosition(x, y + lod, z + lod, voxelData[5], voxelData[6], 1, 0, 0);
- case 6: return GetInterpolatedEdgePosition(x + lod, y, z + lod, voxelData[7], voxelData[6], 0, 1, 0);
- case 7: return GetInterpolatedEdgePosition(x, y, z + lod, voxelData[4], voxelData[7], 1, 0, 0);
- case 8: return GetInterpolatedEdgePosition(x, y, z, voxelData[0], voxelData[4], 0, 0, 1);
- case 9: return GetInterpolatedEdgePosition(x, y + lod, z, voxelData[1], voxelData[5], 0, 0, 1);
- case 10: return GetInterpolatedEdgePosition(x + lod, y + lod, z, voxelData[2], voxelData[6], 0, 0, 1);
- case 11: return GetInterpolatedEdgePosition(x + lod, y, z, voxelData[3], voxelData[7], 0, 0, 1);
- default: throw new ArgumentOutOfRangeException(nameof(edge), "Invalid edge index: " + edge);
- }
- }
- public Vector3 GetInterpolatedEdgePosition(int x, int y, int z, float voxelA, float voxelB, int offsetX, int offsetY, int offsetZ)
- {
- float interpolation = (0 - voxelA) / (voxelB - voxelA);
- return new Vector3(x + offsetX * interpolation, y + offsetY * interpolation, z + offsetZ * interpolation);
- }
- public int CalculateCase(float[] voxelData)
- {
- int triCase = 0;
- for (int i = 0; i < 8; i++)
- {
- int bit = voxelData[i] < 0 ? 1 : 0;
- triCase |= bit << i;
- }
- return triCase;
- }
- struct MeshData
- {
- public List<Vector3> vertices;
- public List<int> indices;
- public Dictionary<Vector3, int> vertDictionary;
- public float[] voxelGrid;
- public int lod;
- }
- struct ChunkData
- {
- public Mesh mesh;
- public Vector2 position;
- public int lod;
- }
- }
- struct MeshJob : IJobParallelFor
- {
- [WriteOnly]
- public NativeList<float3>.ParallelWriter vertices;
- [ReadOnly]
- public NativeArray<float> voxelGrid;
- [ReadOnly]
- public int lod;
- [ReadOnly]
- public int2 chunkDimensions;
- [ReadOnly]
- public NativeArray<int> triTable;
- public NativeArray<int> caseToNumPolys;
- public void Execute(int i)
- {
- int z = i / (chunkDimensions.x / lod * chunkDimensions.y / lod) * lod;
- int y = (i / (chunkDimensions.x / lod) * lod) - z / lod * chunkDimensions.y;
- int x = i % (chunkDimensions.x / lod) * lod;
- AddVertices(i, x, y, z);
- }
- void AddVertices(int index, int x, int y, int z)
- {
- int triCase = CalculateCase(index);
- for (int j = 0, i = 0; j < caseToNumPolys[triCase]; j++, i += 3)
- {
- for (int h = 0; h < 3; h++)
- {
- int edge = triTable[(triCase * 15) + i + (2 - h)];
- float3 vertex = GetEdgePosition(edge, index, lod, x, y, z);
- vertices.AddNoResize(vertex);
- }
- }
- }
- float3 GetEdgePosition(int edge, int index, int lod, int x, int y, int z)
- {
- int i = index * 8;
- switch (edge)
- {
- case 0: return GetInterpolatedEdgePosition(x, y, z, voxelGrid[i], voxelGrid[i + 1], 0, 1, 0);
- case 1: return GetInterpolatedEdgePosition(x, y + lod, z, voxelGrid[i + 1], voxelGrid[i + 2], 1, 0, 0);
- case 2: return GetInterpolatedEdgePosition(x + lod, y, z, voxelGrid[i + 3], voxelGrid[i + 2], 0, 1, 0);
- case 3: return GetInterpolatedEdgePosition(x, y, z, voxelGrid[i], voxelGrid[i + 3], 1, 0, 0);
- case 4: return GetInterpolatedEdgePosition(x, y, z + lod, voxelGrid[i + 4], voxelGrid[i + 5], 0, 1, 0);
- case 5: return GetInterpolatedEdgePosition(x, y + lod, z + lod, voxelGrid[i + 5], voxelGrid[i + 6], 1, 0, 0);
- case 6: return GetInterpolatedEdgePosition(x + lod, y, z + lod, voxelGrid[i + 7], voxelGrid[i + 6], 0, 1, 0);
- case 7: return GetInterpolatedEdgePosition(x, y, z + lod, voxelGrid[i + 4], voxelGrid[i + 7], 1, 0, 0);
- case 8: return GetInterpolatedEdgePosition(x, y, z, voxelGrid[i], voxelGrid[i + 4], 0, 0, 1);
- case 9: return GetInterpolatedEdgePosition(x, y + lod, z, voxelGrid[i + 1], voxelGrid[i + 5], 0, 0, 1);
- case 10: return GetInterpolatedEdgePosition(x + lod, y + lod, z, voxelGrid[i + 2], voxelGrid[i + 6], 0, 0, 1);
- case 11: return GetInterpolatedEdgePosition(x + lod, y, z, voxelGrid[i + 3], voxelGrid[i + 7], 0, 0, 1);
- default: throw new ArgumentOutOfRangeException(nameof(edge), "Invalid edge index: " + edge);
- }
- }
- public float3 GetInterpolatedEdgePosition(int x, int y, int z, float voxelA, float voxelB, int offsetX, int offsetY, int offsetZ)
- {
- float interpolation = (0 - voxelA) / (voxelB - voxelA);
- return new float3(x + offsetX * interpolation, y + offsetY * interpolation, z + offsetZ * interpolation);
- }
- public int CalculateCase(int index)
- {
- int triCase = 0;
- for (int i = 0; i < 8; i++)
- {
- int bit = voxelGrid[(index * 8) + i] < 0 ? 1 : 0;
- triCase |= bit << i;
- }
- return triCase;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement