86 lines
No EOL
2 KiB
C++
86 lines
No EOL
2 KiB
C++
|
|
#include "noise.hpp"
|
|
|
|
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
|
|
{
|
|
return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
|
|
}
|
|
|
|
|
|
//using the algorithm from http://freespace.virgin.net/hugo.elias/models/m_perlin.html
|
|
// thanks to hugo elias
|
|
float Noise2(float x, float y)
|
|
{
|
|
long noise;
|
|
noise = x + y * 57;
|
|
//noise = pow(noise << 13,noise);
|
|
noise = (noise << 13)*noise;
|
|
return ( 1.0 - ( long(noise * (noise * noise * 15731L + 789221L) + 1376312589L) & 0x7fffffff) / 1073741824.0);
|
|
}
|
|
|
|
float SmoothNoise2(float x, float y)
|
|
{
|
|
float corners, sides, center;
|
|
corners = ( Noise2(x-1, y-1)+Noise2(x+1, y-1)+Noise2(x-1, y+1)+Noise2(x+1, y+1) ) / 16;
|
|
sides = ( Noise2(x-1, y) +Noise2(x+1, y) +Noise2(x, y-1) +Noise2(x, y+1) ) / 8;
|
|
center = Noise2(x, y) / 4;
|
|
return (corners + sides + center);
|
|
}
|
|
|
|
float InterpolatedNoise2(float x, float y)
|
|
{
|
|
float v1,v2,v3,v4,i1,i2,fractionX,fractionY;
|
|
long longX,longY;
|
|
|
|
longX = long(x);
|
|
fractionX = x - longX;
|
|
|
|
longY = long(y);
|
|
fractionY = y - longY;
|
|
|
|
v1 = SmoothNoise2(longX, longY);
|
|
v2 = SmoothNoise2(longX + 1, longY);
|
|
v3 = SmoothNoise2(longX, longY + 1);
|
|
v4 = SmoothNoise2(longX + 1, longY + 1);
|
|
|
|
i1 = Interpolate(v1 , v2 , fractionX);
|
|
i2 = Interpolate(v3 , v4 , fractionX);
|
|
|
|
|
|
return(Interpolate(i1 , i2 , fractionY));
|
|
}
|
|
|
|
float Interpolate(float a, float b, float x)
|
|
{
|
|
//cosine interpolations
|
|
return(CosineInterpolate(a, b, x));
|
|
}
|
|
|
|
float LinearInterpolate(float a, float b, float x)
|
|
{
|
|
return(a*(1-x) + b*x);
|
|
}
|
|
|
|
float CosineInterpolate(float a, float b, float x)
|
|
{
|
|
float ft = x * 3.1415927;
|
|
float f = (1 - cos(ft)) * .5;
|
|
|
|
return(a*(1-f) + b*f);
|
|
}
|
|
|
|
float PerlinNoise2(float x, float y, float persistance, int octaves)
|
|
{
|
|
float frequency, amplitude;
|
|
float total = 0.0;
|
|
|
|
for (int i = 0; i <= octaves - 1; i++)
|
|
{
|
|
frequency = pow(2,i);
|
|
amplitude = pow(persistance,i);
|
|
|
|
total = total + InterpolatedNoise2(x * frequency, y * frequency) * amplitude;
|
|
}
|
|
|
|
return(total);
|
|
} |