package projectzombie.util.math.random;

import java.util.Random;

import gl_engine.MathHelpers;

public class NoiseGeneratorSimplex implements NoiseGenerator
{
	private OpenSimplexNoise[] simplex;
	private double off_x, off_y, off_z;
	
	public NoiseGeneratorSimplex(Random rand, int octaves)
	{
		simplex = new OpenSimplexNoise[octaves];
		off_x = MathHelpers.map(rand.nextDouble(), 0, 1, -1024, 1024);
		off_y = MathHelpers.map(rand.nextDouble(), 0, 1, -1024, 1024);
		off_z = MathHelpers.map(rand.nextDouble(), 0, 1, -1024, 1024);
		
		for(int i=0;i<octaves;i++) {
			simplex[i] = new OpenSimplexNoise(rand.nextLong());
		}
	}
	
	public NoiseGeneratorSimplex(Random rand) {
		this(rand, 1);
	}
	
	@Override
	public double eval(double x, double y)
	{
		double v = 0;
		double t = 0;
		
		x += off_x;
		y += off_y;
		
		for(int i=0;i<simplex.length;i++)
		{
			double m = MathHelpers.squared(i + 1);
			
			v += simplex[i].eval(x * m, y * m) / m;
			t += 1 / m;
		}
		
		return v / t;
	}
	
	@Override
	public double eval(double x, double y, double z)
	{
		double v = 0;
		double t = 0;
		
		x += off_x;
		y += off_y;
		z += off_z;
		
		for(int i=0;i<simplex.length;i++)
		{
			double m = MathHelpers.squared(i + 1);
			
			v += simplex[i].eval(x * m, y * m, z * m) / m;
			t += 1 / m;
		}
		
		return v / t;
	}
}
