So I'm trying to generate perlin noise and save it to an image file. I've got the image being saved correctly but the noise doesn't really look like perlin noise.
Here's my code:
package com.egs.survivalsim.util;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.egs.survivalsim.MainComponent;
public class Noise {
MainComponent main;
public double noise(int x,int y){
x = x + y * 57;
x = ((x << 13) ^ x);
double t = (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff;
return 1 - t * 0.000000000931322574615478515625;
}
public double sNoise(int x, int y){
double corners = (noise(x - 1, y - 1) + noise(x + 1, y - 1) + noise(x - 1, y + 1) + noise(x + 1, y + 1)) * 0.0625;
double sides = (noise(x - 1, y) + noise(x + 1, y) + noise(x, y - 1) + noise(x, y + 1)) * 0.125;
double center = noise(x, y) * 0.25;
return corners + sides + center;
}
public double lInterpoleLin(double a, double b, double x){
return a * (1 - x) + b * x;
}
public double lInterpoleCos(double a, double b, double x){
double ft = x * 3.1415927;
double f = (1 - Math.cos(ft)) * 0.001;
return a * (1 - f) + b * f;
}
public double iNoise(double x, double y){
int iX = (int) x;
int iY = (int) y;
double dX = x - iX;
double dY = y - iY;
double p1 = sNoise(iX, iY);
double p2 = sNoise(iX + 1, iY);
double p3 = sNoise(iX, iY + 1);
double p4 = sNoise(iX + 1, iY + 1);
double i1 = lInterpoleCos(p1 ,p2 ,dX);
double i2 = lInterpoleCos(p3, p4, dX);
return lInterpoleCos(i1, i2, dY);
}
public double pNoise(double x, double y, double persistence, int octave){
double result;
double amplitude = 1;
int frequence = 1;
result = 0;
for(int n = 0; n < octave; n++){
frequence <<= 1;
amplitude *= persistence;
result += iNoise(x * frequence, y * frequence) * amplitude;
}
return result;
}
public void startNoise(MainComponent main){
System.out.println("Generating noise map");
this.main = main;
System.out.println("Width: " + main.worldWidth);
System.out.println("Height: " + main.worldHeight);
BufferedImage image = new BufferedImage(main.worldWidth, main.worldHeight, BufferedImage.TYPE_INT_RGB);
for(int y = 0; y < main.worldHeight; y++){
for(int x = 0; x < main.worldWidth; x++){
double c = pNoise((double) x - main.worldWidth, (double) y - main.worldHeight, 0.2, 2);
c *= 128.0;
c += 127.0;
if(c > 255.0){
c = 255.0;
}
if(c < 0.0){
c = 0.0;
}
int r = (int) c;
int g = (int) c;
int b = (int) c;
if(c>128)
r>>=1;
if(c>128)
b>>=1;
int color = new Color(r, g, b).getRGB();
image.setRGB(x, y, color);
main.noiseArray[x][y] = (int) c;
}
}
File fileImage = new File("noise.png");
try {
ImageIO.write(image, "png", fileImage);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Noise map generated");
}
}