import java.util.Random;
public class PerlinNoise {
private final int[] permutation;
public PerlinNoise(int seed) {
permutation = new int[256];
Random random = new Random(seed);
for (int i = 0; i < permutation.length; i++) {
permutation[i] = i;
}
// Shuffle using the Fisher-Yates algorithm
for (int i = 0; i < permutation.length; i++) {
int j = random.nextInt(permutation.length);
int temp = permutation[i];
permutation[i] = permutation[j];
permutation[j] = temp;
}
}
private double fade(double t) {
// Fade function as defined by Ken Perlin. This eases coordinate values so that they will ease towards integral values.
// This eases the curves and provides a smoother transition.
return t * t * t * (t * (t * 6 - 15) + 10);
}
private double lerp(double t, double a, double b) {
// Linear interpolate between a and b
return a + t * (b - a);
}
private double grad(int hash, double x, double y, double z) {
// Convert lower 4 bits of hash into 12 gradient directions
int h = hash & 15;
double u = h < 8 ? x : y,
v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
public double noise(double x, double y, double z) {
int X = (int) Math.floor(x) & 255, // FIND UNIT CUBE THAT
Y = (int) Math.floor(y) & 255, // CONTAINS POINT.
Z = (int) Math.floor(z) & 255;
x -= Math.floor(x); // FIND RELATIVE X,Y,Z
y -= Math.floor(y); // OF POINT IN CUBE.
z -= Math.floor(z);
double u = fade(x), // COMPUTE FADE CURVES
v = fade(y), // FOR EACH OF X,Y,Z.
w = fade(z);
int A = permutation[X ]+Y, AA = permutation[A]+Z, AB = permutation[A+1]+Z, // HASH COORDINATES OF
B = permutation[X+1]+Y, BA = permutation[B]+Z, BB = permutation[B+1]+Z; // THE 8 CUBE CORNERS,
return lerp(w, lerp(v, lerp(u, grad(permutation[AA ], x , y , z), // AND ADD
grad(permutation[BA ], x-1, y , z)), // BLENDED
lerp(u, grad(permutation[AB ], x , y-1, z), // RESULTS
grad(permutation[BB ], x-1, y-1, z))),// FROM 8
lerp(v, lerp(u, grad(permutation[AA+1], x , y , z-1), // CORNERS
grad(permutation[BA+1], x-1, y , z-1)), // OF CUBE
lerp(u, grad(permutation[AB+1], x , y-1, z-1),
grad(permutation[BB+1], x-1, y-1, z-1))));
}
public static void main(String[] args) {
PerlinNoise perlin = new PerlinNoise(100); // seed can be any integer
double value = perlin.noise(0.1, 0.1, 0.1);
System.out.println("Noise value: " + value);
}
}