Monday, February 17, 2014

Interpolated Noise Generation

And now we come to the generation of interpolated noise. Interpolated Noise looks much smoother and more natural than raw noise. The basic steps of interpolating noise are simple: to find the value of a coordinate, find the nearest neighbors in the base noise array, and interpolate between them. Here are the steps are visually:



So in layman's terms:
find four closest values in base noise
interpolate between opposite pairs
interpolate between calculated values
set pixel

Now one thing more we need to cover before we get to the code is periods. Periods are the number of interpolated values between every value from the base noise function. Longer periods result in a more smooth and uniform result.

The code looks like this:
for(int x = 0; x < noise.length; x++)
{
    int bottomX = (int)(x / periodX);//calculate bottom value for x
    int topX = Util.wrap(bottomX + 1, 0, baseNoise.length - 1);//calculate top value for x (wrapping so as to not get an OutOfBounds exception)
    double blendX = (x % periodX) / (double)periodX;//the mu values for x
    
    for(int y = 0; y < noise[0].length; y++)
    {
        int bottomY = (int)(y / periodY);//calculate bottom value for x
        int topY = Util.wrap(bottomY + 1, 0, baseNoise[0].length - 1);//calculate top value for x (wrapping so as to not get an OutOfBounds exception)
        double blendY = (y % periodY) / (double)periodY;//the mu values for x
     
        double xBotInterp = interp.interpolate(baseNoise[bottomX][bottomY], baseNoise[bottomX][topY], blendY);//interpolate between x bottom values
        double xTopInterp = interp.interpolate(baseNoise[topX][bottomY], baseNoise[topX][topY], blendY);//interpolate between x top values
     
        noise[x][y] = interp.interpolate(xBotInterp, xTopInterp, blendX);//interpolate between calculated values
    }
}

This code is for linear or cosine interpolation, if you want cubic or higher, you need to calculate past and future values for both x and y. The included sources have methods to calculate smooth noise functions for any given interpolation function as well as some other cool features. See for more details.

If you want to play around with what interpolated noise looks like with various interpolation functions, here is an applet that will let you get your feet wet.
Controls:
Space = next interpolation function
Q = increase x period
E = decrease x period
A = increase y period
D = decrease y period
S = new random seed
Shift = toggle color mode
Enter (downloadable version only) = save screenshot


If the applet doesn't load, trying refreshing the webpage. May not work on mobiles.

Demos: https://drive.google.com/folderview?id=0B_jXYEquMamINGVGQTM0cTJzdmM&usp=sharing
Source Code: https://github.com/f4113nb34st/Println/

No comments:

Post a Comment