PL
games/rob-revisited / src / Revisited / Land / Noise.php · commit f9a1307
<?phpnamespace App\Revisited\Land;/** Seeded value noise (smooth, -1..1), fractal sums and ridges, for the zones' terrains. */final class Noise{    /** @var list<int> 512 entries */    private array $perm = [];    /** @var list<float> 256 lattice values -1..1 */    private array $val = [];    public function __construct(int $seed)    {        $rng = new Rng($seed);        $p = range(0, 255);        for ($i = 255; $i > 0; $i--) {            $j = $rng->int(0, $i);            [$p[$i], $p[$j]] = [$p[$j], $p[$i]];        }        $this->perm = array_merge($p, $p);        for ($i = 0; $i < 256; $i++) {            $this->val[] = $rng->next() * 2 - 1;        }    }    public function value(float $x, float $y): float    {        $xf = floor($x);        $yf = floor($y);        $xi = ((int) $xf) & 255;        $yi = ((int) $yf) & 255;        $fx = $x - $xf;        $fy = $y - $yf;        $fx = $fx * $fx * (3 - 2 * $fx);        $fy = $fy * $fy * (3 - 2 * $fy);        $p = $this->perm;        $v = $this->val;        $a = $p[$xi] + $yi;        $b = $p[$xi + 1] + $yi;        $v00 = $v[$p[$a]];        $v10 = $v[$p[$b]];        $v01 = $v[$p[$a + 1]];        $v11 = $v[$p[$b + 1]];        $top = $v00 + ($v10 - $v00) * $fx;        $bot = $v01 + ($v11 - $v01) * $fx;        return $top + ($bot - $top) * $fy;    }    /** Fractal sum of octaves, about -1..1. */    public function fbm(float $x, float $y, int $octaves = 4, float $gain = 0.5): float    {        $sum = 0.0;        $amp = 1.0;        $norm = 0.0;        for ($o = 0; $o < $octaves; $o++) {            $sum += $amp * $this->value($x, $y);            $norm += $amp;            $amp *= $gain;            $x = $x * 2.03 + 17.1;            $y = $y * 2.03 + 9.7;        }        return $sum / $norm;    }    /** Ridged fractal (sharp crests), 0..1. */    public function ridged(float $x, float $y, int $octaves = 4): float    {        $sum = 0.0;        $amp = 1.0;        $norm = 0.0;        $weight = 1.0;        for ($o = 0; $o < $octaves; $o++) {            $n = 1 - abs($this->value($x, $y));            $n *= $n * $weight;            $weight = min(1.0, $n * 2);            $sum += $n * $amp;            $norm += $amp;            $amp *= 0.5;            $x = $x * 2.1 + 31.7;            $y = $y * 2.1 + 3.3;        }        return $sum / $norm;    }}