1
0

Noise.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using UnityEngine;
  2. using System.Collections;
  3. public static class Noise
  4. {
  5. public enum NormalizeMode { Local, Global };
  6. public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset, NormalizeMode normalizeMode)
  7. {
  8. float[,] noiseMap = new float[mapWidth, mapHeight];
  9. System.Random prng = new System.Random(seed);
  10. Vector2[] octaveOffsets = new Vector2[octaves];
  11. float maxPossibleHeight = 0;
  12. float amplitude = 1;
  13. float frequency = 1;
  14. for (int i = 0; i < octaves; i++)
  15. {
  16. float offsetX = prng.Next(-100000, 100000) + offset.x;
  17. float offsetY = prng.Next(-100000, 100000) - offset.y;
  18. octaveOffsets[i] = new Vector2(offsetX, offsetY);
  19. maxPossibleHeight += amplitude;
  20. amplitude *= persistance;
  21. }
  22. if (scale <= 0)
  23. {
  24. scale = 0.0001f;
  25. }
  26. float maxLocalNoiseHeight = float.MinValue;
  27. float minLocalNoiseHeight = float.MaxValue;
  28. float halfWidth = mapWidth / 2f;
  29. float halfHeight = mapHeight / 2f;
  30. for (int y = 0; y < mapHeight; y++)
  31. {
  32. for (int x = 0; x < mapWidth; x++)
  33. {
  34. amplitude = 1;
  35. frequency = 1;
  36. float noiseHeight = 0;
  37. for (int i = 0; i < octaves; i++)
  38. {
  39. float sampleX = (x - halfWidth + octaveOffsets[i].x) / scale * frequency;
  40. float sampleY = (y - halfHeight + octaveOffsets[i].y) / scale * frequency;
  41. float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
  42. noiseHeight += perlinValue * amplitude;
  43. amplitude *= persistance;
  44. frequency *= lacunarity;
  45. }
  46. if (noiseHeight > maxLocalNoiseHeight)
  47. {
  48. maxLocalNoiseHeight = noiseHeight;
  49. }
  50. else if (noiseHeight < minLocalNoiseHeight)
  51. {
  52. minLocalNoiseHeight = noiseHeight;
  53. }
  54. noiseMap[x, y] = noiseHeight;
  55. }
  56. }
  57. for (int y = 0; y < mapHeight; y++)
  58. {
  59. for (int x = 0; x < mapWidth; x++)
  60. {
  61. if (normalizeMode == NormalizeMode.Local)
  62. {
  63. noiseMap[x, y] = Mathf.InverseLerp(minLocalNoiseHeight, maxLocalNoiseHeight, noiseMap[x, y]);
  64. }
  65. else
  66. {
  67. float normalizedHeight = (noiseMap[x, y] + 1) / (maxPossibleHeight / 0.9f);
  68. noiseMap[x, y] = Mathf.Clamp(normalizedHeight, 0, int.MaxValue);
  69. }
  70. }
  71. }
  72. return noiseMap;
  73. }
  74. }