60 lines
2.1 KiB
C#
60 lines
2.1 KiB
C#
using UnityEngine;
|
|
using Random = System.Random;
|
|
|
|
namespace LandmassGeneration {
|
|
public static class Noise {
|
|
|
|
public static float[,] GenerateNoiseMap(int width, int height, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset) {
|
|
var noiseMap = new float[width, height];
|
|
|
|
var prng = new Random(seed);
|
|
var octaveOffsets = new Vector2[octaves];
|
|
for (int i = 0; i < octaves; i++) {
|
|
float offsetX = prng.Next(-100000, 100000) + offset.x;
|
|
float offsetY = prng.Next(-100000, 100000) + offset.y;
|
|
octaveOffsets[i] = new Vector2(offsetX, offsetY);
|
|
}
|
|
|
|
if (scale <= 0) scale = 0.0001f;
|
|
|
|
var maxNoise = float.MinValue;
|
|
var minNoise = float.MaxValue;
|
|
|
|
var centerX = width / 2f;
|
|
var centerY = height / 2f;
|
|
|
|
for (int y = 0; y < height; y++) {
|
|
for (int x = 0; x < width; x++) {
|
|
var amplitute = 1.0f;
|
|
var frequency = 1.0f;
|
|
var noiseHeight = 0.0f;
|
|
|
|
for (int i = 0; i < octaves; i++) {
|
|
float sampleX = (x - centerX) / scale * frequency + octaveOffsets[i].x;
|
|
float sampleY = (y - centerY) / scale * frequency + octaveOffsets[i].y;
|
|
|
|
var perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1;
|
|
noiseHeight += perlinValue * amplitute;
|
|
|
|
amplitute *= persistance;
|
|
frequency += lacunarity;
|
|
}
|
|
|
|
noiseMap[x, y] = noiseHeight;
|
|
|
|
if (noiseHeight > maxNoise) maxNoise = noiseHeight;
|
|
if (noiseHeight < minNoise) minNoise = noiseHeight;
|
|
}
|
|
}
|
|
|
|
for (int y = 0; y < height; y++) {
|
|
for (int x = 0; x < width; x++) {
|
|
noiseMap[x, y] = Mathf.InverseLerp(minNoise, maxNoise, noiseMap[x, y]);
|
|
}
|
|
}
|
|
|
|
return noiseMap;
|
|
}
|
|
|
|
}
|
|
} |