柏林噪声
关于柏林噪声的介绍http://www.cnblogs.com/Memo/archive/2008/09/08/1286963.html
//柏林噪声
float MathHelper::PerlinNoise(float x, float y)
{
float total = 0;
float p = 0.025f;
int n = 2;
for (int i = 0; i < n; i++)
{
float frequency = pow(2.0f, i);
float amplitude = pow(p, i);
total = total + InterpolatedNoise(x * frequency, y * frequency) * amplitude;
}
return total;
}
// 根据(x,y)获取一个初步噪声值
float MathHelper::Noise(int x, int y)
{
int n = x + y * 57;
n = (n << 13) ^ n;
return (1.0f - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0f);
}
//光滑噪声
float MathHelper::SmoothedNoise(int x, int y)
{
float corners = (Noise(x - 1, y - 1) + Noise(x + 1, y - 1) + Noise(x - 1, y + 1) + Noise(x + 1, y + 1)) / 16;
float sides = (Noise(x - 1, y) + Noise(x + 1, y) + Noise(x, y - 1) + Noise(x, y + 1)) / 8;
float center = Noise(x, y) / 4;
return corners + sides + center;
}
// 获取插值噪声
float MathHelper::InterpolatedNoise(float x, float y)
{
int integer_X = static_cast<int>(x);
float fractional_X = x - integer_X;
int integer_Y = static_cast<int>(y);
float fractional_Y = y - integer_Y;
float v1 = SmoothedNoise(integer_X, integer_Y);
float v2 = SmoothedNoise(integer_X + 1, integer_Y);
float v3 = SmoothedNoise(integer_X, integer_Y + 1);
float v4 = SmoothedNoise(integer_X + 1, integer_Y + 1);
float i1 = LinearInterpolate(v1, v2, fractional_X);
float i2 = LinearInterpolate(v3, v4, fractional_X);
return LinearInterpolate(i1, i2, fractional_Y);
}
//根据柏林噪声获取地形随机高度,生成自然的地形
float GetHeight(float x, float z, float frequency, float height)
{
return MathHelper::PerlinNoise(x * frequency, z *frequency) * height;
}
根据柏林噪声生成的地形高度。
项目Github地址