MeshGenerator.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using JetBrains.Annotations;
  2. using UnityEngine;
  3. public static class MeshGenerator
  4. {
  5. public static MeshData GenerateTerrainMesh(float[,] heightMap, float heightMultiplier, AnimationCurve _heightCurve, int levelOfDetail)
  6. {
  7. AnimationCurve heightCurve = new AnimationCurve(_heightCurve.keys);
  8. int width = heightMap.GetLength(0);
  9. int height = heightMap.GetLength(1);
  10. float topLeftX = (width - 1) / -2f;
  11. float topLeftZ = (height - 1) / 2f;
  12. int meshSimplficationIncrement = (levelOfDetail == 0) ? 1 : levelOfDetail * 2;
  13. int verticesPerLine = (width - 1) / meshSimplficationIncrement + 1;
  14. MeshData meshData = new(verticesPerLine, verticesPerLine);
  15. int vertexIndex = 0;
  16. for(int y=0; y<height; y += meshSimplficationIncrement)
  17. {
  18. for(int x=0; x<width; x += meshSimplficationIncrement)
  19. {
  20. meshData.vertices[vertexIndex] = new Vector3(topLeftX + x, heightCurve.Evaluate(heightMap[x, y]) * heightMultiplier, topLeftZ - y);
  21. meshData.uvs[vertexIndex] = new Vector2(x/(float)width, y/(float)height);
  22. if (x < width - 1 && y < height - 1)
  23. {
  24. meshData.AddTriangle(vertexIndex, vertexIndex + verticesPerLine + 1, vertexIndex + verticesPerLine);
  25. meshData.AddTriangle(vertexIndex + verticesPerLine + 1, vertexIndex, vertexIndex + 1);
  26. }
  27. vertexIndex++;
  28. }
  29. }
  30. return meshData;
  31. }
  32. }
  33. public class MeshData
  34. {
  35. public Vector3[] vertices;
  36. public int[] triangles;
  37. public Vector2[] uvs;
  38. int triangleIndex;
  39. public MeshData(int meshWidth, int meshHeight)
  40. {
  41. vertices = new Vector3[meshWidth * meshHeight];
  42. uvs = new Vector2[meshWidth * meshHeight];
  43. triangles = new int[(meshWidth - 1) * (meshHeight - 1) * 6];
  44. }
  45. public void AddTriangle(int a, int b, int c)
  46. {
  47. triangles[triangleIndex] = a;
  48. triangles[triangleIndex+1] = b;
  49. triangles[triangleIndex+2] = c;
  50. triangleIndex += 3;
  51. }
  52. public Mesh CreateMesh()
  53. {
  54. Mesh mesh = new();
  55. mesh.vertices = vertices;
  56. mesh.triangles = triangles;
  57. mesh.uv = uvs;
  58. mesh.RecalculateNormals();
  59. return mesh;
  60. }
  61. }