using UnityEngine;

namespace Generators
{
    public class PerlinNoiseGenerator : IGenerator
    {
        public float Scale { get; set; } = 0.001f;
        public Vector2 Offset { get; set; } = new Vector2(.0f, .0f);
        public int Iterations { get; set; } = 8;
        public float Decay { get; set; } = .7f;
        public float Lacunarity { get; set; } = 1.71f;

        public double GetValue(Vector2 position)
        {
            var amplitude = 1.0;
            var scale     = Scale;
            var result    = 0.0;

            for (int i = 0; i < Iterations; i++) {
                result += amplitude * Calculate(position, scale);

                amplitude *= Decay;
                scale     *= Lacunarity;
            }

            return result / ((1 - System.Math.Pow(Decay, Iterations)) / (1 - Decay));
        }

        private double Calculate(Vector2 position, float scale)
        {
            var final = (position + Offset) * scale;

            return Mathf.PerlinNoise(final.x, final.y);
        }
    }
}