JA
games/rob-revisited / src / Revisited / Land / ZoneFactory.php · commit f9a1307
<?phpnamespace App\Revisited\Land;/** * Builds the five zones of Ysor from a seed (docs/reborn.md "Zones"): terrain (fractal noise, ridges, a lake and its * river, a canyon with mesas, a snowy plateau and its summit), cave networks (chambers joined by winding corridors, * with roofs and walls), biomes, the things on the ground and the exits that link the zones. Deterministic: the same * seed always gives the same zone (saves keep only a diff of the things). */final class ZoneFactory{    public const IDS = ['valley', 'caves1', 'caves2', 'canyon', 'plateau', 'jungle', 'marsh', 'coast', 'caves3'];    /** outdoor zones (the caves are the junctions between them) */    public const OUTDOOR = ['valley', 'canyon', 'jungle', 'marsh', 'plateau', 'coast'];    public const NAMES = [        'valley' => 'Forêt du Naufrage',        'jungle' => 'L\'Amazonie',        'marsh' => 'Marais des Brumes',        'coast' => 'Côte Volcanique',        'caves3' => 'Grottes des Jonctions',        'caves1' => 'Cavernes supérieures',        'caves2' => 'Cavernes profondes',        'canyon' => 'Canyon Rouge',        'plateau' => 'Plateau Gelé',    ];    /** Rise over run a walker can climb (45°). */    public const MAX_SLOPE = 1.0;    /** Where the player stands at the start of the game (valley, next to the pod). */    public const START = [190.0, 293.0];    public const POD = [184.0, 287.0];    public const MAST = [400.0, 110.0];    /** the Halde lander on the volcanic coast */    public const SHUTTLE = [300.0, 230.0];    /** islands of the jungle's river: v (0..1 down the river), radius (m) */    public const ISLANDS = [[0.24, 10.0], [0.5, 12.0], [0.78, 9.0]];    public const OUVI = [0.55, 58.0];   // the Ouvi village: v, metres west of the river    private const G = 128;    private Zone $z;    private Rng $rng;    private Noise $n;    private int $w;    private int $nextId = 1;    /** @var list<float> */    private array $h = [];    /** @var list<array{0: float, 1: float, 2: float}> places kept free of random things (x, z, r) */    private array $clear = [];    private function __construct(string $id, int $seed)    {        $index = array_search($id, self::IDS, true);        if ($index === false) {            throw new \InvalidArgumentException("Unknown zone '$id'");        }        $cave = $id === 'caves1' || $id === 'caves2' || $id === 'caves3';        $this->z = new Zone($id, self::NAMES[$id], self::G, $cave ? 2.0 : 4.0, $seed);        $this->z->cave = $cave;        $this->rng = new Rng($seed * 13 + $index * 101 + 7);        $this->n = new Noise($seed * 7 + $index);        $this->w = self::G + 1;        $this->h = array_fill(0, $this->w * $this->w, 0.0);    }    public static function make(string $id, int $seed): Zone    {        $f = new self($id, $seed);        match ($id) {            'valley' => $f->valley(),            'caves1' => $f->caves(1),            'caves2' => $f->caves(2),            'canyon' => $f->canyon(),            'plateau' => $f->plateau(),            'jungle' => $f->jungle(),            'marsh' => $f->marsh(),            'coast' => $f->coast(),            'caves3' => $f->caves(3),            default => null,        };        return $f->z;    }    /** The canyon's centre line: z (0..1) at x = u (0..1). Fixed at both ends (exits of other zones point there). */    public static function canyonZ(float $u, ?Noise $n = null): float    {        $c = 0.5 + 0.17 * sin(6.2832 * 1.1 * $u + 0.4);        if ($n !== null) {            $env = self::smooth(0.12, 0.25, $u) * (1 - self::smooth(0.75, 0.88, $u));            $c += 0.05 * $n->fbm($u * 3 + 5.5, 1.7, 2) * $env;        }        return $c;    }    /** The exits of a zone (doors to the others), the same for every seed. */    public static function exits(string $id): array    {        $cz = static fn (float $x): float => self::canyonZ($x / 512) * 512;        return match ($id) {            'valley' => [                ['x' => 256.0, 'z' => 66.0, 'r' => 5.0, 'to' => 'caves1', 'toX' => 32.0, 'toZ' => 128.0, 'label' => 'Entrer dans la grotte'],                // wave 2: added after the things of the zone (late), so the ids of an older save's things stay the same                ['x' => 497.0, 'z' => 330.0, 'r' => 6.0, 'to' => 'jungle', 'toX' => 30.0, 'toZ' => 256.0, 'label' => 'Suivre le vallon vers l\'est (l\'Amazonie)', 'late' => true],            ],            'jungle' => [                ['x' => 16.0, 'z' => 256.0, 'r' => 6.0, 'to' => 'valley', 'toX' => 486.0, 'toZ' => 330.0, 'label' => 'Remonter vers la Forêt du Naufrage', 'arriveLate' => true],                ['x' => 497.0, 'z' => 200.0, 'r' => 5.0, 'to' => 'caves3', 'toX' => 30.0, 'toZ' => 128.0, 'label' => 'Entrer dans la grotte de la rive est'],            ],            'caves3' => [                ['x' => 18.0, 'z' => 128.0, 'r' => 4.0, 'to' => 'jungle', 'toX' => 484.0, 'toZ' => 200.0, 'label' => 'Sortir vers le fleuve'],                ['x' => 128.0, 'z' => 18.0, 'r' => 4.0, 'to' => 'marsh', 'toX' => 256.0, 'toZ' => 482.0, 'label' => 'Monter vers l\'odeur de vase (marais)'],                ['x' => 238.0, 'z' => 128.0, 'r' => 4.0, 'to' => 'coast', 'toX' => 32.0, 'toZ' => 256.0, 'label' => 'Suivre le souffle chaud et salé (côte)'],            ],            'marsh' => [                ['x' => 256.0, 'z' => 497.0, 'r' => 6.0, 'to' => 'caves3', 'toX' => 128.0, 'toZ' => 30.0, 'label' => 'Descendre dans la grotte'],            ],            'coast' => [                ['x' => 16.0, 'z' => 256.0, 'r' => 6.0, 'to' => 'caves3', 'toX' => 226.0, 'toZ' => 128.0, 'label' => 'Rentrer dans la grotte'],            ],            'caves1' => [                ['x' => 18.0, 'z' => 128.0, 'r' => 4.0, 'to' => 'valley', 'toX' => 256.0, 'toZ' => 80.0, 'label' => 'Sortir vers la vallée'],                ['x' => 236.0, 'z' => 128.0, 'r' => 3.0, 'to' => 'caves2', 'toX' => 32.0, 'toZ' => 40.0, 'label' => 'Descendre l\'échelle'],            ],            'caves2' => [                ['x' => 18.0, 'z' => 40.0, 'r' => 3.0, 'to' => 'caves1', 'toX' => 224.0, 'toZ' => 128.0, 'label' => 'Remonter l\'échelle'],                ['x' => 238.0, 'z' => 222.0, 'r' => 4.0, 'to' => 'canyon', 'toX' => 38.0, 'toZ' => $cz(38.0), 'label' => 'Suivre la galerie vers la lumière'],            ],            'canyon' => [                ['x' => 18.0, 'z' => $cz(18.0), 'r' => 5.0, 'to' => 'caves2', 'toX' => 226.0, 'toZ' => 212.0, 'label' => 'Entrer dans la galerie'],                ['x' => 497.0, 'z' => $cz(497.0), 'r' => 7.0, 'to' => 'plateau', 'toX' => 40.0, 'toZ' => 470.0, 'label' => 'Franchir le col vers le plateau'],            ],            'plateau' => [                ['x' => 22.0, 'z' => 488.0, 'r' => 7.0, 'to' => 'canyon', 'toX' => 476.0, 'toZ' => $cz(476.0), 'label' => 'Redescendre vers le canyon'],            ],            default => [],        };    }    /** @return list<array> the exits of a zone made with its land (not the doors added after its things) */    public static function earlyExits(string $id): array    {        return array_values(array_filter(self::exits($id), fn (array $e): bool => empty($e['late'])));    }    /**     * Wave 2 doors of an older zone: added after its things (an older save's thing ids stay the same), opened, and a road     * cut from the arrival to $to if needed.     */    private function lateDoors(float $tx, float $tz): void    {        foreach (self::exits($this->z->id) as $e) {            if (empty($e['late'])) {                continue;            }            $this->z->exits[] = $e;            $this->open($e['x'], $e['z'], $e['r'] + 4);            foreach (self::IDS as $other) {                foreach (self::exits($other) as $b) {                    if ($b['to'] === $this->z->id && $other === $e['to']) {                        $this->ensurePath($b['toX'], $b['toZ'], $tx, $tz);                        $this->ensurePath($b['toX'], $b['toZ'], $e['x'], $e['z']);                    }                }            }        }    }    /** Can a walker go from one point to another (no wall, slopes it can climb)? For tests and checks. */    public static function reachable(Zone $z, float $x1, float $z1, float $x2, float $z2): bool    {        return self::bfs($z, $z->cellIndex($x1, $z1), $z->cellIndex($x2, $z2)) !== null;    }    // ------------------------------------------------------------------------------------------ the valley    private function valley(): void    {        $z = $this->z;        $z->water = 2.0;        $z->baseTemp = 27.0;        $n = $this->n;        $G = self::G;        $water = $z->water;        $S = $z->size;        $phase = $this->rng->range(0, 6.28);        for ($j = 0; $j <= $G; $j++) {            $v = $j / $G;            $ur = 0.6 + 0.06 * sin($v * 9 + $phase) + 0.03 * $n->value(3.1, $v * 6);            for ($i = 0; $i <= $G; $i++) {                $u = $i / $G;                $h = 7 + 6 * $n->fbm($u * 3, $v * 3, 5) + 2.5 * $n->fbm($u * 9 + 4, $v * 9 + 4, 3);                $h = max($h, $water + 0.5 + 0.6 * $n->value($u * 13, $v * 13));                $e = max(abs($u - 0.5) * 2, (0.5 - $v) * 2.4, ($v - 0.5) * 2);                $m = self::smooth(0.74, 1.0, $e);                $h += $m * (26 + 34 * $n->ridged($u * 5 + 11, $v * 5 + 3, 4));                // the lake                $dl = hypot($u - 0.64, $v - 0.62) / (0.11 + 0.03 * $n->value($u * 7, $v * 7));                if ($dl < 1.4) {                    $bed = $water - 0.3 - 3.5 * max(0.0, 1 - $dl);                    $h = $bed + ($h - $bed) * self::smooth(0.55, 1.35, $dl);                }                // the river, from its spring down to the lake                if ($v > 0.22 && $v < 0.56) {                    $dr = abs($u - $ur) * $S;                    if ($dr < 11) {                        $bed = $water - 0.7;                        $k = max(self::smooth(2.0, 11.0, $dr), self::smooth(0.26, 0.22, $v));                        $h = min($h, $bed + ($h - $bed) * $k);                    }                }                $this->h[$j * $this->w + $i] = $h;            }        }        // the crash site: flattened, a skid trench behind the pod        [$px, $pz] = self::POD;        $this->flatten($px, $pz, 14, null);        for ($k = 1; $k <= 8; $k++) {            $this->dent($px - $k * 4.5, $pz + $k * 1.2, 4.0, 0.5 - $k * 0.04);        }        // the cave mouth: a ledge in the northern mountains        $this->flatten(256, 74, 18, null);        // the waterfall: the brook falls off the foot of the northern mountains into a pool, its head        $fv = 0.205;        $fallX = (0.6 + 0.06 * sin($fv * 9 + $phase) + 0.03 * $n->value(3.1, $fv * 6)) * $S;        $fall = $this->carveFall($fallX, $fv * $S, 0.0, max($water + 9.0, min($water + 15.0, $this->heightRaw($fallX, $fv * $S - 8))), 7.0, $water);        $rv = 0.3;        $this->creek($fall[0], $fall[1] + 13, (0.6 + 0.06 * sin($rv * 9 + $phase) + 0.03 * $n->value(3.1, $rv * 6)) * $S, $rv * $S, $water - 0.75);        $this->commitHeights();        $this->classify(function (float $h, float $s, float $m, int $ci, int $cj) use ($water): string {            if ($h < $water + 0.35) {                return $m > 0.05 ? 'mud' : 'sand';            }            if ($s > 0.8 || $h > 30) {                return 'rock';            }            if ($h < $water + 1.2 && $m > 0.15) {                return 'mud';            }            if ($h < $water + 0.9) {                return 'sand';            }            return $m > -0.05 ? 'jungle' : 'grass';        }, 1.35);        [$sx, $sz] = self::START;        $this->ensurePath($sx, $sz, 256, 80);        $this->ensurePath(256, 80, 256, 66);        $this->ensurePath($sx, $sz, 0.64 * $S - 60, 0.62 * $S);        $this->connectDoors();        // special things        $this->clear = [[$px, $pz, 16], [256, 72, 12]];        $this->add('wreck_pod', $px, $pz, 0.6, 1.0, 1, ['label' => 'Nacelle de survie', 'log' => true, 'loot' => [            'ration' => 2, 'bandage' => 2, 'medkit' => 1, 'cloth' => 2, 'gourd_empty' => 1, 'helmet_pilot' => 1, 'purification_tablets' => 4,        ]]);        $this->add('crate', $px + 7, $pz + 5, 1.1, 1.0, 1, ['label' => 'Conteneur éjecté', 'loot' => [            'rope' => 1, 'wire' => 2, 'metal_scrap' => 2, 'torch' => 1, 'fiber' => 2, 'undershirt' => 1, 'gloves_pilot' => 1,        ]]);        $this->add('stick', $px + 4, $pz - 4);        $this->add('stone_small', $px - 3, $pz + 6);        $this->add('flint', $px + 9, $pz - 2);        $this->add('cave_entrance', 256, 62, 0.0, 1.2, 1, ['label' => 'Bouche de caverne']);        $this->add('bones', 262, 78, 1.0, 1.0, 1, ['label' => 'Squelette de bête', 'loot' => ['bone' => 3]]);        $sv = 0.23;        $srcX = (0.6 + 0.06 * sin($sv * 9 + $phase) + 0.03 * $n->value(3.1, $sv * 6)) * $S;        $this->add('water_spring', $srcX, $sv * $S + 2, 0.0, 1.0, 1, ['label' => 'Source du ruisseau']);        $this->clear[] = [$srcX, $sv * $S, 5];        for ($k = 0; $k < 2; $k++) {            [$x, $zz] = $this->findSpot(['jungle', 'grass'], 60);            $this->add('water_spring', $x, $zz, 0.0, 1.0, 1, ['label' => 'Source claire']);            $this->clear[] = [$x, $zz, 5];        }        $this->clear[] = [$fall[0], $fall[1] + 5, 10];        // an older wreck: a probe of the colony, half buried        [$x, $zz] = $this->findSpot(['grass', 'jungle'], 80);        $this->add('crate', $x, $zz, 0.3, 1.0, 1, ['label' => 'Sonde de la colonie', 'loot' => ['metal_scrap' => 2, 'wire' => 1, 'cloth' => 1]]);        $this->scatter([            'jungle' => [['tree_broad', 0.075], ['tree_palm', 0.035], ['vine', 0.02], ['bush_berry', 0.018], ['bush_red', 0.01], ['mushroom', 0.012], ['herb_heal', 0.006], ['herb_fever', 0.005], ['stick', 0.016], ['tree_dead', 0.004]],            'grass' => [['tree_broad', 0.02], ['bush_berry', 0.016], ['bush_red', 0.006], ['stick', 0.012], ['stone_small', 0.01], ['herb_heal', 0.004], ['rock', 0.006], ['tree_dead', 0.004], ['flint', 0.004]],            'sand' => [['tree_palm', 0.03], ['reed', 0.04], ['stone_small', 0.012], ['flint', 0.008]],            'mud' => [['reed', 0.07], ['mushroom', 0.018], ['tree_dead', 0.008], ['herb_fever', 0.01]],            'rock' => [['boulder', 0.025], ['rock', 0.03], ['flint', 0.014], ['stone_small', 0.018], ['tree_dead', 0.004], ['tree_conifer', 0.01]],        ]);        // added last (the ids of the older things stay the same for the saves)        $this->addFall($fall, 'Cascade du ruisseau', [            'note' => 'Le ruisseau tombe de la falaise dans un grondement continu. Derrière le rideau d\'eau, la roche est creusée : un abri sec, à demi caché.',        ]);        $this->add('crate', $fall[0] + 1.6, $fall[1] + 4.55, 0.4, 0.9, 1, ['label' => 'Cache derrière la cascade', 'secret' => true, 'loot' => [            'antenna_part' => 1, 'mittens_fur' => 1, 'purification_tablets' => 3, 'trade_amulet' => 1, 'pot' => 1,        ]]);        $this->add('bones', $fall[0] - 1.8, $fall[1] + 4.4, 1.2, 0.8, 1, ['label' => 'Restes d\'un colon', 'loot' => ['cloth' => 1, 'bone' => 1]]);        // wave 2: the way east to the jungle, a signpost of the colony        $this->lateDoors(self::START[0], self::START[1]);        $this->add('signpost', 486, 336, -1.5708, 1.0, 1, ['label' => 'Poteau de la colonie', 'note' => 'Une flèche de métal rouillée : « HALDE — PISTE DU FLEUVE — PORT OUVI ». Quelqu\'un a gravé dessous : « ILS ONT GARDÉ LES ÉCAILLES ».']);    }    /**     * Cuts a waterfall into the heights: a lip at $top facing $yaw (forward = (sin yaw, cos yaw)), the rock behind raised     * to it, a steep face (a wall cell), a dry ledge right at its foot (behind the falling water), then a pool.     * @return array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} x, z (the lip), top, bottom, width, yaw     */    private function carveFall(float $x, float $zz, float $yaw, float $top, float $width, float $water): array    {        $cell = $this->z->cell;        $x = round($x / $cell) * $cell;        $zz = round($zz / $cell) * $cell;        $fx = sin($yaw);        $fz = cos($yaw);        $r = 26.0;        for ($j = max(0, (int) (($zz - $r) / $cell)); $j <= min(self::G, (int) ceil(($zz + $r) / $cell)); $j++) {            for ($i = max(0, (int) (($x - $r) / $cell)); $i <= min(self::G, (int) ceil(($x + $r) / $cell)); $i++) {                $dx = $i * $cell - $x;                $dz = $j * $cell - $zz;                $a = $dx * $fx + $dz * $fz;                $b = abs($dx * $fz - $dz * $fx);                $k = $j * $this->w + $i;                $h = $this->h[$k];                if ($a <= 0.5 && $a >= -10 && $b <= $width / 2 + 5) {                    // the rock of the lip and the brook's bed behind it                    $level = $b <= $width / 2 + 0.5 ? $top - 0.25 + max(0.0, -$a - 2) * 0.12 : $top + 0.6;                    $h = $a > -4.5 ? max($h, $level) : ($b <= $width / 2 + 0.5 ? min($h, $level) : max($h, $level));                } elseif ($a > 0.5 && $a < 5.0 && $b <= $width / 2 + 1) {                    $h = $water + 0.25;            // the dry ledge behind the curtain of water                } elseif ($a >= 5.0 && $a <= 15.0 && $b <= $width / 2 + 3) {                    $bed = $water - 0.9 + max(0.0, $a - 11) * 0.05;                    $h = min($h, $bed + max(0.0, $b - $width / 2 - 1) * 0.4);                } elseif ($a > 0.5 && $a < 5.0 && $b <= $width / 2 + 5) {                    $h = max($h, $top - ($b > $width / 2 + 3 ? 2.0 : 0.0));   // the rock walls on both sides of the ledge                }                $this->h[$k] = $h;            }        }        return [$x, $zz, $top, $water, $width, $yaw];    }    /** @param array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float} $f */    private function addFall(array $f, string $label, array $data = []): Thing    {        [$x, $zz, $top, $bottom, $width, $yaw] = $f;        $t = $this->add('waterfall', $x, $zz, $yaw, 1.0, 1, ['label' => $label, 'top' => $top, 'bottom' => $bottom, 'w' => $width, 'reach' => 5.4] + $data);        $t->y = $top;        return $t;    }    // ------------------------------------------------------------------------------------------ the caves    private function caves(int $level): void    {        $z = $this->z;        $z->baseTemp = [1 => 12.0, 2 => 15.0, 3 => 19.0][$level];        $n = $this->n;        $G = self::G;        $cell = $z->cell;        $base = [1 => -18.0, 2 => -42.0, 3 => -24.0][$level];        $floor = [];        for ($j = 0; $j <= $G; $j++) {            for ($i = 0; $i <= $G; $i++) {                $u = $i / $G;                $v = $j / $G;                $floor[] = $base + 2.5 * $n->fbm($u * 4, $v * 4, 3) - 5 * $u + ($level === 2 ? 6 * self::smooth(0.7, 1.0, ($u + $v) / 2) : 0);            }        }        // chambers: [ci, cj, radius, dome]        $rooms = match ($level) {            1 => [[12, 64, 6.5, 6.0], [117, 64, 5.5, 5.0]],            2 => [[12, 20, 5.5, 5.0], [64, 70, 15.0, 11.0], [116, 108, 6.0, 6.0]],            default => [[12, 64, 6.0, 5.5], [64, 12, 6.0, 5.5], [117, 64, 6.0, 6.0], [70, 92, 10.0, 8.0]],        };        $count = $level === 1 ? 10 : 9;        for ($try = 0; $try < 400 && count($rooms) < $count + ($level === 1 ? 2 : ($level === 2 ? 3 : 4)); $try++) {            $r = $this->rng->range(4.0, $level === 1 ? 9.0 : 10.0);            $ci = $this->rng->range(10 + $r, $G - 10 - $r);            $cj = $this->rng->range(10 + $r, $G - 10 - $r);            $ok = true;            foreach ($rooms as $o) {                if (hypot($o[0] - $ci, $o[1] - $cj) < $o[2] + $r + 5) {                    $ok = false;                    break;                }            }            if ($ok) {                $rooms[] = [$ci, $cj, $r, $this->rng->range(4.5, 9.0)];            }        }        $open = array_fill(0, $G * $G, false);        $roof = array_fill(0, $G * $G, 0.0);        foreach ($rooms as $k => $o) {            [$ci, $cj, $r, $dome] = $o;            for ($j = max(1, (int) ($cj - $r * 1.3)); $j <= min($G - 2, (int) ($cj + $r * 1.3)); $j++) {                for ($i = max(1, (int) ($ci - $r * 1.3)); $i <= min($G - 2, (int) ($ci + $r * 1.3)); $i++) {                    $dx = $i + 0.5 - $ci;                    $dz = $j + 0.5 - $cj;                    $d = hypot($dx, $dz);                    $edge = $r * (1 + 0.2 * $n->value(atan2($dz, $dx) * 2 + $k * 5.3, $k * 1.7));                    if ($d < $edge) {                        $c = $j * $G + $i;                        $open[$c] = true;                        $roof[$c] = max($roof[$c], 3.2 + $dome * sqrt(max(0.0, 1 - ($d / $edge) ** 2)));                    }                }            }        }        // corridors: a spanning tree of the chambers (Prim) plus two loops        $links = [];        $in = [0];        $out = range(1, count($rooms) - 1);        while ($out !== []) {            $best = null;            foreach ($in as $a) {                foreach ($out as $ki => $b) {                    $d = hypot($rooms[$a][0] - $rooms[$b][0], $rooms[$a][1] - $rooms[$b][1]);                    if ($best === null || $d < $best[0]) {                        $best = [$d, $a, $b, $ki];                    }                }            }            $links[] = [$best[1], $best[2]];            $in[] = $best[2];            unset($out[$best[3]]);        }        for ($k = 0; $k < 2; $k++) {            $a = $this->rng->int(0, count($rooms) - 1);            $b = $this->rng->int(0, count($rooms) - 1);            if ($a !== $b) {                $links[] = [$a, $b];            }        }        foreach ($links as $k => [$a, $b]) {            $ax = $rooms[$a][0];            $az = $rooms[$a][1];            $bx = $rooms[$b][0];            $bz = $rooms[$b][1];            $len = hypot($bx - $ax, $bz - $az);            $px = -($bz - $az) / max(0.001, $len);            $pz = ($bx - $ax) / max(0.001, $len);            $steps = (int) ($len * 2) + 1;            $width = $this->rng->range(1.5, 2.3);            for ($s = 0; $s <= $steps; $s++) {                $t = $s / $steps;                $wob = sin($t * 3.1416) * 7 * $n->value($t * 3 + $k * 7.1, $k * 3.3);                $cx = $ax + ($bx - $ax) * $t + $px * $wob;                $cz = $az + ($bz - $az) * $t + $pz * $wob;                $rw = $width * (0.85 + 0.3 * $n->value($t * 9, $k + 0.5));                for ($j = max(1, (int) ($cz - $rw - 1)); $j <= min($G - 2, (int) ($cz + $rw + 1)); $j++) {                    for ($i = max(1, (int) ($cx - $rw - 1)); $i <= min($G - 2, (int) ($cx + $rw + 1)); $i++) {                        if (hypot($i + 0.5 - $cx, $j + 0.5 - $cz) < $rw) {                            $c = $j * $G + $i;                            $open[$c] = true;                            $roof[$c] = max($roof[$c], 3.0 + 1.4 * (0.5 + 0.5 * $n->value($t * 5 + $k, 9.1)));                        }                    }                }            }        }        // the gallery out to the canyon climbs (caves2)        if ($level === 2) {            for ($t = 0.0; $t <= 1.0; $t += 0.02) {                $cx = 116 + 4 * $t;                $cz = 108 + 4 * $t;                for ($j = (int) $cz - 3; $j <= (int) $cz + 3; $j++) {                    for ($i = (int) $cx - 3; $i <= (int) $cx + 3; $i++) {                        if ($i > 0 && $j > 0 && $i < $G - 1 && $j < $G - 1 && hypot($i + 0.5 - $cx, $j + 0.5 - $cz) < 2.6) {                            $open[$j * $G + $i] = true;                            $roof[$j * $G + $i] = max($roof[$j * $G + $i], 4.0);                        }                    }                }            }        }        // an underground pool in a chamber that is not a door        $poolRoom = $rooms[count($rooms) - 1];        $minFloor = min($floor);        $pool = [($poolRoom[0]) * $cell, ($poolRoom[1]) * $cell, $poolRoom[2] * $cell * 0.6];        for ($j = 0; $j <= $G; $j++) {            for ($i = 0; $i <= $G; $i++) {                $d = hypot($i * $cell - $pool[0], $j * $cell - $pool[1]);                if ($d < $pool[2]) {                    $k = $j * $this->w + $i;                    $floor[$k] = min($floor[$k], $minFloor - 1.6 * (1 - self::smooth($pool[2] * 0.5, $pool[2], $d)) - 0.1);                }            }        }        $z->water = $minFloor - 0.6;        $this->h = $floor;        $z->heights = $floor;        $ceil = [];        for ($j = 0; $j <= $G; $j++) {            for ($i = 0; $i <= $G; $i++) {                $sum = 0.0;                $cnt = 0;                foreach ([[$i - 1, $j - 1], [$i, $j - 1], [$i - 1, $j], [$i, $j]] as [$ci, $cj]) {                    if ($ci >= 0 && $cj >= 0 && $ci < $G && $cj < $G && $open[$cj * $G + $ci]) {                        $sum += $roof[$cj * $G + $ci];                        $cnt++;                    }                }                $f = $floor[$j * $this->w + $i];                $ceil[] = $cnt > 0 ? $f + $sum / $cnt : $f;            }        }        $z->ceilings = $ceil;        $solid = [];        $biomes = [];        for ($c = 0; $c < $G * $G; $c++) {            $solid[] = !$open[$c];            $biomes[] = 'cave';        }        // damp floors around the pool        for ($j = 0; $j < $G; $j++) {            for ($i = 0; $i < $G; $i++) {                if (hypot(($i + 0.5) * $cell - $pool[0], ($j + 0.5) * $cell - $pool[1]) < $pool[2] * 1.5) {                    $biomes[$j * $G + $i] = 'mud';                }            }        }        $z->solid = $solid;        $z->biomes = $biomes;        $z->exits = self::exits($z->id);        foreach ($z->exits as $e) {            $this->clear[] = [$e['x'], $e['z'], 6];        }        $this->connectDoors();        if ($level === 3) {            $this->ensurePath(30, 128, 226, 128);            $this->ensurePath(30, 128, 128, 30);            $this->ensurePath(30, 128, 140, 184);            $this->add('cave_entrance', 14, 128, 1.5708, 1.0, 1, ['label' => 'Lueur verte du fleuve']);            $this->add('cave_entrance', 128, 14, 0.0, 1.0, 1, ['label' => 'Brume du marais']);            $this->add('cave_entrance', 242, 128, -1.5708, 1.0, 1, ['label' => 'Souffle chaud et salé']);            // Jonas Merle's den: the wreck of the pod MR-4, three years ago            $this->add('crate', 140, 184, 0.3, 1.1, 1, ['label' => 'Épave de la nacelle MR-4', 'note' => 'jonas', 'loot' => [                'flare_gun' => 1, 'flare' => 3, 'wire' => 2, 'energy_cell' => 1,            ]]);            $this->add('campfire', 136, 188, 0.0, 0.8, 1, ['label' => 'Foyer de Jonas']);            $this->add('bones', 116, 176, 0.8, 1.0, 1, ['label' => 'Restes d\'un croco des rivières', 'loot' => ['bone' => 3, 'scale_hide' => 1]]);            $this->clear[] = [140, 184, 8];        } elseif ($level === 1) {            $this->ensurePath(32, 128, 224, 128);            $this->add('cave_entrance', 14, 128, 1.5708, 1.0, 1, ['label' => 'Lumière du jour']);            $this->add('ladder', 238, 128, -1.5708, 1.0, 1, ['label' => 'Vieille échelle de la colonie']);            // a colonist who never got out: the keycard of the base            $mid = $rooms[(int) (count($rooms) / 2)];            $this->add('bones', $mid[0] * $cell + 1, $mid[1] * $cell, 0.4, 1.0, 1, ['label' => 'Restes d\'un colon', 'note' => 'colonist', 'loot' => [                'keycard' => 1, 'torch' => 1, 'cloth' => 2, 'wire' => 1,            ]]);            $this->clear[] = [$mid[0] * $cell, $mid[1] * $cell, 5];            $r2 = $rooms[3 % count($rooms)];            $this->add('crate', $r2[0] * $cell, $r2[1] * $cell + 2, 0.2, 1.0, 1, ['label' => 'Cache de ravitaillement', 'loot' => [                'resin' => 3, 'rope' => 1, 'bandage' => 2, 'ration' => 1, 'metal_scrap' => 1,            ]]);        } else {            $this->ensurePath(32, 40, 226, 212);            $this->ensurePath(32, 40, 128, 150);            $this->add('ladder', 16, 40, 1.5708, 1.0, 1, ['label' => 'Échelle vers les cavernes supérieures']);            $this->add('cave_entrance', 240, 224, -0.7854, 1.0, 1, ['label' => 'Un souffle d\'air chaud']);            $this->add('wreck_colony', 128, 140, 0.3, 1.0, 1, ['label' => 'Base de la mission Halde', 'locked' => true, 'loot' => [                'power_cell' => 1, 'colony_log' => 1, 'antenna_part' => 1, 'medkit' => 1, 'wire' => 2,            ]]);            $this->clear[] = [128, 140, 14];            foreach ([[-12, -6], [11, -8], [-9, 10], [13, 9]] as $k => [$dx, $dz]) {                $loot = [['metal_scrap' => 2, 'wire' => 1], ['cloth' => 2, 'bandage' => 2], ['rope' => 1, 'ration' => 1, 'metal_scrap' => 1], ['resin' => 2, 'wire' => 1, 'splint' => 1]][$k];                $this->add('crate', 128 + $dx, 140 + $dz, $k * 0.7, 1.0, 1, ['label' => 'Caisse de la colonie', 'loot' => $loot]);            }            foreach ([[-5, 14], [7, 15], [18, -2]] as $k => [$dx, $dz]) {                $this->add('bones', 128 + $dx, 140 + $dz, $k, 1.0, 1, ['label' => 'Restes d\'un colon', 'loot' => $k === 0 ? ['cloth' => 1, 'trade_amulet' => 1] : ['bone' => 2]]);            }        }        $this->scatter([            'cave' => [['rock', 0.02], ['boulder', 0.012], ['stone_small', 0.02], ['flint', 0.02], ['mushroom', 0.025], ['bones', 0.003]],            'mud' => [['mushroom', 0.06], ['reed', 0.02], ['stone_small', 0.02]],        ]);    }    // ------------------------------------------------------------------------------------------ the canyon    private function canyon(): void    {        $z = $this->z;        $z->water = 2.6;        $z->baseTemp = 32.0;        $n = $this->n;        $G = self::G;        $S = $z->size;        $water = $z->water;        [$vx, $vz] = $this->village();        [$rx, $rz, $gx, $gz] = $this->camp();        $mesas = [];        foreach ([0.2, 0.3, 0.55, 0.63] as $k => $mu) {            $side = $k % 2 === 0 ? 1 : -1;            $mesas[] = [$mu * $S, self::canyonZ($mu, $n) * $S + $side * 13, 7.0, 13.0 + 4 * $k % 5];        }        for ($j = 0; $j <= $G; $j++) {            $v = $j / $G;            for ($i = 0; $i <= $G; $i++) {                $u = $i / $G;                $x = $u * $S;                $zz = $v * $S;                $rim = 46 + 8 * $n->fbm($u * 4, $v * 4, 4) + 14 * self::smooth(0.55, 0.8, $n->ridged($u * 3 + 2, $v * 3 + 7, 3));                $c = self::canyonZ($u, $n);                $dc = (self::canyonZ($u + 0.002, $n) - self::canyonZ($u - 0.002, $n)) / 0.004;                $d = abs($v - $c) * $S / sqrt(1 + $dc * $dc);                $w = 22 + 8 * $n->value($u * 6, 3.3);                $ramp = self::smooth(0.80, 0.965, $u);                $fl = 6 + 1.5 * $n->fbm($u * 8, $v * 8, 3);                $fl += $ramp * ($rim - 8 - $fl);                $prof = self::wall($d, $w);                // the village's wide bowl, the camp's side canyon                $prof = min($prof, self::wall(hypot($x - $vx, $zz - $vz), 62));                $prof = min($prof, self::wall(hypot($x - $rx, $zz - $rz), 38));                $prof = min($prof, self::wall(self::segment($x, $zz, $gx, $gz, $rx, $rz), 10));                $h = $fl + ($rim - $fl) * $prof;                // the stream in the middle of the floor                if ($u < 0.78 && $d < 5) {                    $bed = $water - 0.5;                    $h = min($h, $bed + ($h - $bed) * self::smooth(1.0, 5.0, $d));                }                foreach ($mesas as [$mx, $mz, $mr, $mh]) {                    $dm = hypot($x - $mx, $zz - $mz);                    if ($dm < $mr * 1.3) {                        $h = max($h, $fl + $mh * (1 - self::smooth($mr, $mr * 1.3, $dm)));                    }                }                $this->h[$j * $this->w + $i] = $h;            }        }        $this->flatten($vx, $vz, 44, max($this->heightRaw($vx, $vz), $water + 1.6));        $this->flatten($rx, $rz, 26, max($this->heightRaw($rx, $rz), $water + 1.6));        // a waterfall down the northern wall, its creek running to the stream (away from the camp)        $fu = hypot(0.26 * $S - $rx, self::canyonZ(0.26, $n) * $S - $rz) > 70 ? 0.26 : 0.68;        $fx = $fu * $S;        $cz = self::canyonZ($fu, $n) * $S;        $fz = $cz - 8;        while ($fz > $cz - 60 && $this->heightRaw($fx, $fz) < $water + 13) {            $fz -= 2;        }        $fall = $this->carveFall($fx, $fz, 0.0, min($water + 22.0, max($water + 11.0, $this->heightRaw($fx, $fz))), 6.0, $water);        $this->creek($fall[0], $fall[1] + 14, $fx, $cz, $water - 0.55);        $this->commitHeights();        $this->classify(function (float $h, float $s, float $m) use ($water): string {            if ($h < $water + 0.4) {                return 'mud';            }            if ($s > 0.6) {                return 'redrock';            }            if ($h < $water + 1.4) {                return 'sand';            }            if ($h > 30) {                return 'redrock';            }            return $m > 0.25 ? 'grass' : ($m > -0.3 ? 'sand' : 'redrock');        }, 1.3);        $ex = self::exits('canyon');        $this->ensurePath($ex[0]['x'] + 18, $ex[0]['z'], $vx, $vz);        $this->ensurePath($vx, $vz, $rx, $rz);        $this->ensurePath($vx, $vz, 476, self::canyonZ(476 / 512) * 512);        $this->connectDoors();        // the Haldi village        $this->clear = [[$vx, $vz, 46], [$rx, $rz, 22]];        foreach ($ex as $e) {            $this->clear[] = [$e['x'], $e['z'], 10];        }        $this->add('campfire', $vx, $vz, 0.0, 1.3, 1, ['label' => 'Feu du conseil', 'permanent' => true]);        $huts = ['Maëva', 'Sela', 'Bren', 'Ysa', 'Koru', 'Tilo'];        foreach ($huts as $k => $owner) {            $a = $k / count($huts) * 6.2832 + 0.3;            $x = $vx + sin($a) * 22;            $zz = $vz + cos($a) * 22;            $this->add('hut', $x, $zz, atan2($vx - $x, $vz - $zz), $k === 0 ? 1.3 : 1.0, 1, ['label' => 'Hutte de ' . $owner, 'owner' => $owner]);        }        foreach ([0.9, 2.6, 4.4] as $k => $a) {            $x = $vx + sin($a) * 34;            $zz = $vz + cos($a) * 34;            $this->add('tent', $x, $zz, atan2($vx - $x, $vz - $zz), 1.0, 1, ['label' => $k === 0 ? 'Tente d\'Oko' : 'Tente des chasseurs', 'owner' => $k === 0 ? 'Oko' : '']);        }        $this->add('crate', $vx + sin(0.9) * 30 + 2, $vz + cos(0.9) * 30, 0.9, 1.0, 1, ['label' => 'Étal d\'Oko', 'shop' => true]);        $this->add('skin_rack', $vx + 12, $vz - 8, 0.5);        $this->add('skin_rack', $vx - 10, $vz + 12, 2.0);        $this->add('water_spring', $vx - 14, $vz - 16, 0.0, 1.0, 1, ['label' => 'Source du village']);        for ($k = 0; $k < 7; $k++) {            $a = $k * 0.9 + 0.2;            $this->add('bush_berry', $vx + sin($a) * 40, $vz + cos($a) * 40, $a, 1.0, 3, ['label' => 'Jardin des Haldi']);        }        // the camp of the Rôdeurs        $this->add('campfire', $rx, $rz, 0.0, 1.0, 1, ['label' => 'Feu des Rôdeurs', 'permanent' => true]);        foreach ([0.4, 2.0, 3.6, 5.2] as $a) {            $x = $rx + sin($a) * 14;            $zz = $rz + cos($a) * 14;            $this->add('tent', $x, $zz, atan2($rx - $x, $rz - $zz), 1.0, 1, ['label' => 'Tente des Rôdeurs', 'loot' => ['dried_meat' => 1, 'arrow' => 2]]);        }        $this->add('crate', $rx + 6, $rz + 6, 0.8, 1.2, 1, ['label' => 'Coffre des Rôdeurs', 'chest' => true, 'loot' => [            'tuner' => 1, 'arrow' => 6, 'metal_scrap' => 2, 'trade_salt' => 2, 'dried_meat' => 2,        ]]);        $this->add('skin_rack', $rx - 7, $rz + 4, 1.2);        foreach ([[9, -8], [-11, -6], [3, 12]] as $k => [$dx, $dz]) {            $this->add('bones', $rx + $dx, $rz + $dz, $k, 1.0, 1, ['label' => 'Ossements', 'loot' => ['bone' => 2]]);        }        foreach ([[18, 0], [-18, 3], [0, -18]] as [$dx, $dz]) {            $this->add('boulder', $rx + $dx, $rz + $dz, 0.0, 1.4, 6);        }        $this->add('cave_entrance', $ex[0]['x'] - 4, $ex[0]['z'], -1.5708, 1.2, 1, ['label' => 'Galerie obscure']);        $this->scatter([            'redrock' => [['boulder', 0.03], ['rock', 0.04], ['flint', 0.025], ['stone_small', 0.03], ['tree_dead', 0.01]],            'sand' => [['rock', 0.02], ['stone_small', 0.03], ['tree_dead', 0.016], ['bush_red', 0.012], ['herb_heal', 0.014, ['item' => 'herb_antidote', 'label' => 'Herbe à venin']], ['stick', 0.02], ['bush_berry', 0.01], ['flint', 0.012]],            'grass' => [['tree_broad', 0.04], ['bush_berry', 0.025], ['herb_heal', 0.01], ['stick', 0.02], ['vine', 0.015], ['tree_palm', 0.02]],            'mud' => [['reed', 0.08], ['mushroom', 0.01]],        ], 28.0);        $this->addFall($fall, 'Cascade du canyon', [            'note' => 'Une source jaillit de la paroi rouge et tombe en cascade dans une vasque fraîche. L\'eau vive est bien plus sûre que celle du ruisseau.',        ]);        // wave 2 (added last: older saves keep their ids): the colony's money, the Rôdeurs' armoury, the Haldi forge, the totem        $this->add('terminal', $vx - 30, $vz - 20, 0.6, 1.0, 1, ['label' => 'Ancien comptoir de la colonie', 'loot' => ['credit' => 40, 'blueprint_crossbow' => 1]]);        $this->add('weapon_rack', $rx - 9, $rz - 5, 2.4, 1.0, 1, ['label' => 'Râtelier des Rôdeurs', 'loot' => ['pulse_rifle_broken' => 1, 'bolt' => 6, 'credit' => 25]]);        $this->add('forge', $vx + 16, $vz + 18, 0.9, 1.0, 1, ['label' => 'Forge de Koru']);        $this->add('totem', $vx - 6, $vz + 5, 0.0, 1.0, 1, ['label' => 'Totem des ancêtres']);        $this->add('market_stall', $vx + sin(0.9) * 30 - 3, $vz + cos(0.9) * 30 + 2, 0.9, 1.0, 1, ['label' => 'Étal d\'Oko', 'shop' => 'oko']);        // the lookout's cache on the tallest mesa: its walls only climbing stakes get up (added last: older saves keep their ids)        [$mx, $mz] = $mesas[1];        $this->add('crate', $mx + 1.5, $mz - 1.0, 0.4, 1.0, 1, ['label' => 'Cache du guetteur (sommet de la mesa)', 'climb' => true,            'loot' => ['credit' => 30, 'energy_cell' => 2, 'gun_parts' => 1, 'rope' => 2, 'ration' => 1]]);    }    /** A shallow creek bed from one point to another (a waterfall's pool down to the stream). */    private function creek(float $x1, float $z1, float $x2, float $z2, float $bed): void    {        $cell = $this->z->cell;        $r = 11.0;        $minX = min($x1, $x2) - $r;        $maxX = max($x1, $x2) + $r;        $minZ = min($z1, $z2) - $r;        $maxZ = max($z1, $z2) + $r;        for ($j = max(0, (int) floor($minZ / $cell)); $j <= min(self::G, (int) ceil($maxZ / $cell)); $j++) {            for ($i = max(0, (int) floor($minX / $cell)); $i <= min(self::G, (int) ceil($maxX / $cell)); $i++) {                $d = self::segment($i * $cell, $j * $cell, $x1, $z1, $x2, $z2);                if ($d < $r) {                    $k = $j * $this->w + $i;                    $this->h[$k] = min($this->h[$k], $bed + ($this->h[$k] - $bed) * self::smooth(3.0, $r, $d));                }            }        }    }    /** The centre of the Haldi village in the canyon (metres). */    public static function villageCentre(int $seed): array    {        $n = new Noise($seed * 7 + 3);        return [0.42 * 512, self::canyonZ(0.42, $n) * 512];    }    /** @return array{0: float, 1: float} */    private function village(): array    {        return [0.42 * 512, self::canyonZ(0.42, $this->n) * 512];    }    /** The Rôdeurs' camp (x, z) and where its side canyon leaves the main one (gx, gz). */    public static function campCentre(int $seed): array    {        $n = new Noise($seed * 7 + 3);        return self::campOf($n);    }    private function camp(): array    {        return self::campOf($this->n);    }    private static function campOf(Noise $n): array    {        $c = self::canyonZ(0.70, $n);        $side = $c > 0.5 ? -1 : 1;        $gc = self::canyonZ(0.66, $n);        return [0.72 * 512, ($c + $side * 0.2) * 512, 0.66 * 512, $gc * 512];    }    // ------------------------------------------------------------------------------------------ the plateau    private function plateau(): void    {        $z = $this->z;        $z->baseTemp = 1.0;        $n = $this->n;        $G = self::G;        [$mx, $mz] = self::MAST;        $S = $z->size;        for ($j = 0; $j <= $G; $j++) {            $v = $j / $G;            for ($i = 0; $i <= $G; $i++) {                $u = $i / $G;                $h = 96 + 10 * $n->fbm($u * 3, $v * 3, 5) + 3 * $n->fbm($u * 10, $v * 10, 3);                $basin = $n->fbm($u * 2.5 + 3, $v * 2.5 + 1, 3);                if ($basin < -0.25) {                    $h = min($h, 93 + 2 * self::smooth(-0.45, -0.25, $basin));                }                $dm = hypot($u - $mx / $S, $v - $mz / $S);                $h += 78 * exp(-($dm / 0.17) ** 2) * (0.8 + 0.2 * $n->ridged($u * 6, $v * 6, 3));                $h += 16 * $n->ridged($u * 4 + 5, $v * 4 + 9, 4) * self::smooth(0.15, 0.35, $dm);                $e = max(abs($u - 0.5), abs($v - 0.5)) * 2;                $h += 30 * self::smooth(0.86, 1.0, $e);                $this->h[$j * $this->w + $i] = $h;            }        }        $this->flatten(40, 470, 16, null);        $this->flatten(26, 486, 10, null);        // the summit: the mast stands on its highest rock        $top = $this->heightRaw($mx, $mz);        $this->flatten($mx, $mz, 10, $top);        $this->commitHeights();        $this->classify(function (float $h, float $s, float $m): string {            if ($s > 0.7) {                return 'rock';            }            if ($h < 95.2 && $s < 0.12) {                return 'ice';            }            if ($h < 102 && $m > 0.35 && $s < 0.3) {                return 'grass';            }            return 'snow';        }, 1.4);        $this->ensurePath(40, 470, $mx, $mz + 6);        $this->connectDoors();        $this->clear = [[$mx, $mz, 9], [40, 470, 10], [26, 486, 8]];        $this->add('relay_mast', $mx, $mz, 0.0, 1.0, 1, ['label' => 'Mât relais de la mission Halde']);        $this->add('crate', $mx + 5, $mz + 3, 0.4, 1.0, 1, ['label' => 'Caisse de maintenance', 'loot' => ['wire' => 2, 'metal_scrap' => 3, 'rope' => 1]]);        $this->add('bones', $mx - 6, $mz + 5, 0.2, 1.0, 1, ['label' => 'Restes d\'un technicien', 'loot' => ['cloth' => 2, 'boots' => 1]]);        [$x, $zz] = $this->findSpot(['snow', 'grass'], 120);        $this->add('tent', $x, $zz, 0.0, 1.0, 1, ['label' => 'Abri abandonné', 'loot' => ['fur' => 2, 'dried_meat' => 1]]);        $this->add('campfire', $x + 3, $zz + 2, 0.0, 0.8, 1, ['label' => 'Vieux foyer']);        $this->scatter([            'grass' => [['tree_conifer', 0.06], ['tree_dead', 0.01], ['stick', 0.015], ['herb_heal', 0.006], ['bush_berry', 0.006]],            'snow' => [['tree_conifer', 0.03], ['tree_dead', 0.012], ['boulder', 0.01], ['stone_small', 0.008], ['stick', 0.006]],            'rock' => [['boulder', 0.025], ['rock', 0.03], ['flint', 0.012], ['stone_small', 0.012]],            'ice' => [['stone_small', 0.004], ['bones', 0.002]],        ]);    }    // ------------------------------------------------------------------------------------------ the jungle (l'Amazonie)    /** The river's centre line in the jungle: x (0..1) at v (0..1, north to south). */    public static function riverX(float $v, Noise $n): float    {        return 0.56 + 0.11 * sin($v * 6.2832 * 1.25 + 0.7) + 0.035 * $n->fbm($v * 3 + 9.1, 2.2, 2);    }    /** Half the river's width (m) at v. */    public static function riverHalf(float $v, Noise $n): float    {        return 19.0 + 5.0 * $n->value($v * 5, 1.3);    }    /** The noise of a zone (the same the factory used), for the river's line in the game. */    public static function noiseOf(string $id, int $seed): Noise    {        return new Noise($seed * 7 + (int) array_search($id, self::IDS, true));    }    /** @return list<array{0: float, 1: float, 2: float}> the jungle's islands: x, z, radius */    public static function islands(int $seed): array    {        $n = self::noiseOf('jungle', $seed);        $out = [];        foreach (self::ISLANDS as [$v, $r]) {            $out[] = [self::riverX($v, $n) * 512, $v * 512, $r];        }        return $out;    }    /** The Ouvi village (x, z). */    public static function ouviCentre(int $seed): array    {        $n = self::noiseOf('jungle', $seed);        [$v, $west] = self::OUVI;        return [self::riverX($v, $n) * 512 - $west, $v * 512];    }    private function jungle(): void    {        $z = $this->z;        $z->water = 3.0;        $z->baseTemp = 30.0;        $n = $this->n;        $G = self::G;        $S = $z->size;        $water = $z->water;        $isl = self::islands($z->seed);        for ($j = 0; $j <= $G; $j++) {            $v = $j / $G;            $rx = self::riverX($v, $n) * $S;            $half = self::riverHalf($v, $n);            for ($i = 0; $i <= $G; $i++) {                $u = $i / $G;                $x = $u * $S;                $zz = $v * $S;                $h = $water + 3.5 + 4 * $n->fbm($u * 3, $v * 3, 4) + 1.6 * $n->fbm($u * 11 + 2, $v * 11 + 5, 2);                // the wide river: deep in its bed, low muddy banks                $d = abs($x - $rx);                if ($d < $half + 18) {                    $bed = $water - 0.6 - 2.4 * (1 - self::smooth($half * 0.55, $half, $d));                    $h = min($h, $bed + ($h - $bed) * self::smooth($half, $half + 18, $d));                }                foreach ($isl as [$ix, $iz, $ir]) {                    $di = hypot($x - $ix, $zz - $iz);                    if ($di < $ir) {                        $h = max($h, $water + 0.7 + 1.6 * (1 - self::smooth($ir * 0.35, $ir, $di)));                    }                }                // a ring of high ground on the borders, a cliff east where the cave opens                $e = max(abs($u - 0.5), abs($v - 0.5)) * 2;                $h += 24 * self::smooth(0.86, 1.0, $e) * (0.7 + 0.3 * $n->ridged($u * 5, $v * 5, 3));                $this->h[$j * $this->w + $i] = $h;            }        }        [$ox, $oz] = self::ouviCentre($z->seed);        $this->flatten($ox, $oz, 34, max($this->heightRaw($ox, $oz), $water + 1.4));        $this->flatten(36, 256, 12, null);        $this->flatten(476, 200, 12, null);        $this->commitHeights();        $this->classify(function (float $h, float $s, float $m) use ($water): string {            if ($h < $water + 0.3) {                return 'mud';            }            if ($s > 0.9) {                return 'rock';            }            if ($h < $water + 1.0) {                return $m > 0.1 ? 'mud' : 'sand';            }            return $m > 0.05 ? 'jungle_dense' : 'jungle';        }, 1.4);        // the west bank: valley door to the village; the east bank: the village's far side is reached by raft        $this->ensurePath(30, 256, $ox, $oz);        $this->ensurePath(30, 256, 30, 270);        $this->ensurePath(484, 200, 470, 260);        $this->clear = [[$ox, $oz, 32], [36, 256, 10], [476, 200, 10]];        foreach ($isl as [$ix, $iz, $ir]) {            $this->clear[] = [$ix, $iz, $ir * 0.6];        }        // the Ouvi village: huts on piles, the totem of the scales, the market, the fish racks        $this->add('campfire', $ox, $oz, 0.0, 1.2, 1, ['label' => 'Foyer des Ouvi', 'permanent' => true]);        foreach (['Aïka', 'Tamu', 'Nadjé', 'Oumi', 'Saro'] as $k => $owner) {            $a = $k / 5 * 6.2832 + 0.5;            $x = $ox + sin($a) * 19;            $zz = $oz + cos($a) * 19;            $this->add('stilt_hut', $x, $zz, atan2($ox - $x, $oz - $zz), $k === 0 ? 1.25 : 1.0, 1, ['label' => 'Case de ' . $owner, 'owner' => $owner]);        }        $this->add('totem', $ox + 6, $oz - 5, 0.4, 1.4, 1, ['label' => 'Totem des écailles', 'note' => 'plates']);        $this->add('market_stall', $ox - 9, $oz + 8, 2.2, 1.0, 1, ['label' => 'Étal de Nadjé', 'shop' => 'nadje']);        $this->add('skin_rack', $ox + 12, $oz + 10, 1.1, 1.0, 1, ['label' => 'Claie à poisson']);        $this->add('skin_rack', $ox - 13, $oz - 9, 2.6, 1.0, 1, ['label' => 'Claie à poisson']);        $this->add('water_spring', $ox - 22, $oz - 18, 0.0, 1.0, 1, ['label' => 'Source des Ouvi']);        $this->add('signpost', 44, 262, 1.5708, 1.0, 1, ['label' => 'Poteau de la colonie', 'note' => '« PORT OUVI — 300 M ». Plus bas, à la peinture fraîche : « NE PAS NAGER. LE FLEUVE MANGE. »']);        // the islands: a drone of the colony, a cache, a boat wreck (raft only)        [$i1, $i2, $i3] = $isl;        $this->add('drone_wreck', $i1[0], $i1[1], 0.8, 1.0, 1, ['label' => 'Drone de la colonie', 'loot' => ['gun_parts' => 2, 'energy_cell' => 2, 'blueprint_pulse' => 1, 'wire' => 2]]);        $this->add('crate', $i2[0] + 2, $i2[1], 0.2, 1.0, 1, ['label' => 'Cache des pêcheurs', 'loot' => ['smoked_fish' => 3, 'credit' => 15, 'harpoon' => 1]]);        $this->add('giant_tree', $i2[0] - 4, $i2[1] + 3, 1.0, 1.0, 1, ['label' => 'Arbre géant de l\'île']);        $this->add('boat_wreck', $i3[0], $i3[1], 2.0, 1.0, 1, ['label' => 'Barque échouée', 'loot' => ['fuel_canister' => 1, 'rope' => 2, 'flare' => 2]]);        // the cub's den, north on the west bank: Companions puts the wounded cub there        $this->add('bones', 150, 92, 0.4, 1.0, 1, ['label' => 'Tanière de rôdeur de nuit', 'note' => 'den', 'loot' => ['bone' => 2]]);        $this->clear[] = [150, 92, 8];        $this->add('cave_entrance', 503, 200, -1.5708, 1.2, 1, ['label' => 'Grotte de la rive est']);        for ($k = 0; $k < 3; $k++) {            $a = $k * 2.1 + 1.0;            $this->add('liana_bridge', $ox + sin($a) * 26, $oz + cos($a) * 26, $a, 1.0, 1, ['label' => 'Passerelle de lianes']);        }        $this->scatter([            'jungle_dense' => [['giant_tree', 0.03], ['tree_broad', 0.05], ['vine', 0.03], ['tree_palm', 0.015], ['mushroom', 0.012], ['herb_heal', 0.006], ['herb_fever', 0.006], ['bush_berry', 0.01], ['bush_red', 0.01]],            'jungle' => [['tree_broad', 0.04], ['tree_palm', 0.03], ['bush_berry', 0.016], ['vine', 0.015], ['stick', 0.016], ['reeds_tall', 0.01], ['herb_heal', 0.005], ['tree_dead', 0.004], ['stone_small', 0.008], ['flint', 0.004]],            'sand' => [['reeds_tall', 0.05], ['tree_palm', 0.02], ['stone_small', 0.015], ['flint', 0.01]],            'mud' => [['reeds_tall', 0.08], ['reed', 0.05], ['mangrove', 0.02], ['mushroom', 0.01]],            'rock' => [['boulder', 0.02], ['rock', 0.03], ['flint', 0.015]],        ]);    }    // ------------------------------------------------------------------------------------------ the marsh    /** Orsolo's hut and the stilt ruins of the marsh (x, z). */    public const HERMIT = [250.0, 180.0];    public const RUINS = [370.0, 300.0];    private function marsh(): void    {        $z = $this->z;        $z->water = 1.2;        $z->baseTemp = 23.0;        $n = $this->n;        $G = self::G;        $water = $z->water;        for ($j = 0; $j <= $G; $j++) {            $v = $j / $G;            for ($i = 0; $i <= $G; $i++) {                $u = $i / $G;                // hummocks and pools: most of the land a hand above or below the water                $h = $water + 0.15 + 0.9 * $n->fbm($u * 4, $v * 4, 4) + 0.35 * $n->fbm($u * 14 + 3, $v * 14 + 1, 2);                $deep = $n->fbm($u * 2 + 7, $v * 2 + 3, 2);                if ($deep < -0.3) {                    $h -= 1.2 * self::smooth(-0.3, -0.55, $deep);    // a few deep black pools                }                $e = max(abs($u - 0.5), abs($v - 0.5)) * 2;                $h += 18 * self::smooth(0.88, 1.0, $e) * (0.6 + 0.4 * $n->ridged($u * 6, $v * 6, 3));                $this->h[$j * $this->w + $i] = $h;            }        }        [$hx, $hz] = self::HERMIT;        [$rx, $rz] = self::RUINS;        $this->flatten($hx, $hz, 10, $water + 0.6);        $this->flatten($rx, $rz, 22, $water + 0.25);        $this->flatten(256, 480, 12, $water + 0.8);        $this->commitHeights();        $this->classify(function (float $h, float $s, float $m) use ($water): string {            if ($h < $water + 0.2) {                return 'marsh';            }            if ($s > 0.9) {                return 'rock';            }            if ($h < $water + 0.6) {                return $m > 0.0 ? 'marsh' : 'mud';            }            return $m > 0.2 ? 'jungle' : 'grass';        }, 1.5);        $this->ensurePath(256, 482, $hx, $hz);        $this->ensurePath(256, 482, $rx, $rz);        $this->connectDoors();        $this->clear = [[$hx, $hz, 9], [$rx, $rz, 20], [256, 482, 10]];        $this->add('stilt_hut', $hx, $hz, 2.6, 1.1, 1, ['label' => 'Cabane d\'Orsolo', 'owner' => 'Orsolo']);        $this->add('campfire', $hx + 4, $hz + 3, 0.0, 0.8, 1, ['label' => 'Feu fumant d\'Orsolo', 'permanent' => true]);        $this->add('terminal', $hx - 5, $hz + 2, 1.2, 1.0, 1, ['label' => 'Radio muette d\'Orsolo']);        for ($k = 0; $k < 6; $k++) {            $a = $k * 1.05 + 0.3;            $x = $rx + sin($a) * 14;            $zz = $rz + cos($a) * 14;            $this->add('stilt_hut', $x, $zz, atan2($rx - $x, $rz - $zz), 1.0, 1, ['label' => $k === 0 ? 'Maison de Kessa' : 'Ruine sur pilotis', 'owner' => $k === 0 ? 'Kessa' : '',                'loot' => $k === 0 ? [] : [['cloth' => 2], ['credit' => 12, 'bandage' => 1], ['metal_scrap' => 2], ['rope' => 1, 'credit' => 8], ['blueprint_forge' => 1, 'wire' => 1]][$k - 1]]);        }        $this->add('totem', $rx, $rz, 0.0, 0.9, 1, ['label' => 'Mât des noyés', 'note' => 'drowned']);        $this->add('signpost', 262, 470, 3.14, 1.0, 1, ['label' => 'Pancarte pourrie', 'note' => '« STATION HYDRO 2 — ACCÈS RESTREINT ». Quelqu\'un a ajouté au couteau : « IL VOUS ÉCOUTE ».']);        $this->add('drone_wreck', 120, 140, 0.4, 0.9, 1, ['label' => 'Sonde envasée', 'loot' => ['energy_cell' => 1, 'gun_parts' => 1, 'metal_scrap' => 2]]);        $this->scatter([            'marsh' => [['reeds_tall', 0.09], ['mangrove', 0.03], ['tree_dead', 0.01], ['reed', 0.04]],            'mud' => [['reeds_tall', 0.05], ['mangrove', 0.025], ['mushroom', 0.02], ['herb_fever', 0.01], ['tree_dead', 0.012], ['bones', 0.001]],            'grass' => [['tree_dead', 0.015], ['bush_berry', 0.01], ['herb_heal', 0.008], ['stick', 0.02], ['tree_broad', 0.01], ['stone_small', 0.01]],            'jungle' => [['tree_broad', 0.04], ['vine', 0.02], ['mushroom', 0.015], ['herb_heal', 0.006, ['item' => 'herb_antidote', 'label' => 'Herbe à venin']], ['stick', 0.015]],            'rock' => [['boulder', 0.02], ['rock', 0.02], ['flint', 0.01]],        ]);    }    // ------------------------------------------------------------------------------------------ the volcanic coast    private function coast(): void    {        $z = $this->z;        $z->water = 0.0;        $z->baseTemp = 29.0;        $n = $this->n;        $G = self::G;        $water = $z->water;        [$sx, $sz] = self::SHUTTLE;        for ($j = 0; $j <= $G; $j++) {            $v = $j / $G;            for ($i = 0; $i <= $G; $i++) {                $u = $i / $G;                // basalt heights in the west, sloping to a black beach, the sea in the east                $shore = 0.76 + 0.05 * sin($v * 7 + 1.2) + 0.03 * $n->fbm($v * 4, 3.3, 2);                $land = 10 + 5 * $n->fbm($u * 3, $v * 3, 4) + 4 * $n->ridged($u * 7 + 1, $v * 7 + 4, 3);                $h = $land * (1 - self::smooth($shore - 0.3, $shore - 0.02, $u)) + 1.2 * self::smooth($shore - 0.3, $shore - 0.02, $u);                $h -= 9 * self::smooth($shore, $shore + 0.12, $u);              // the sea floor                $e = max($u < 0.5 ? 0.5 - $u : 0, abs($v - 0.5)) * 2;                $h += 20 * self::smooth(0.86, 1.0, $e);                $this->h[$j * $this->w + $i] = $h;            }        }        $this->flatten($sx, $sz, 26, $this->heightRaw($sx, $sz) + 0.5);        $this->flatten(30, 256, 12, null);        $this->commitHeights();        $this->classify(function (float $h, float $s, float $m) use ($water): string {            if ($h < $water + 1.6) {                return 'beach';            }            if ($s > 0.55 || $h > 13) {                return 'basalt';            }            return $m > 0.3 ? 'grass' : ($m > -0.2 ? 'basalt' : 'burnt');        }, 1.4);        $this->ensurePath(32, 256, $sx, $sz);        $this->ensurePath($sx, $sz, $sx + 120, $sz + 40);        $this->connectDoors();        $this->clear = [[$sx, $sz, 22], [30, 256, 10]];        $this->add('shuttle', $sx, $sz, 1.2, 1.0, 1, ['label' => 'Navette Halde']);        $this->add('terminal', $sx - 14, $sz + 9, 0.6, 1.0, 1, ['label' => 'Console de la piste', 'note' => 'pad']);        $this->add('crate', $sx + 12, $sz - 10, 0.2, 1.0, 1, ['label' => 'Soute éventrée', 'loot' => ['fuel_canister' => 1, 'energy_cell' => 2, 'plasma_gun' => 1]]);        $this->add('boat_wreck', $sx + 150, $sz + 70, 2.4, 1.2, 1, ['label' => 'Coque de la barge', 'loot' => ['metal_scrap' => 3, 'rope' => 2, 'credit' => 20]]);        $this->add('bones', $sx + 30, $sz - 24, 1.0, 1.0, 1, ['label' => 'Restes d\'un pilote de la colonie', 'loot' => ['gun_parts' => 1, 'cloth' => 1, 'credit' => 10]]);        for ($k = 0; $k < 2; $k++) {            [$x, $zz] = $this->findSpot(['grass', 'basalt'], 70);            $this->add('water_spring', $x, $zz, 0.0, 1.0, 1, ['label' => $k === 0 ? 'Source chaude' : 'Suintement d\'eau douce']);            $this->clear[] = [$x, $zz, 5];        }        $this->scatter([            'beach' => [['palm_coast', 0.03], ['stone_small', 0.02], ['bones', 0.0015], ['basalt', 0.01]],            'basalt' => [['basalt', 0.04], ['fumarole', 0.012], ['boulder', 0.015], ['rock', 0.02], ['flint', 0.01], ['tree_dead', 0.004], ['geyser', 0.002]],            'burnt' => [['burnt_tree', 0.03], ['fumarole', 0.015], ['stone_small', 0.015]],            'grass' => [['palm_coast', 0.02], ['bush_berry', 0.012], ['herb_heal', 0.008], ['stick', 0.015], ['tree_broad', 0.01]],        ], 40.0);    }    // ------------------------------------------------------------------------------------------ helpers    private function commitHeights(): void    {        $this->z->heights = $this->h;    }    /** Biomes and walls from height, slope (rise / run) and moisture; cells steeper than $cliff are walls. */    private function classify(callable $biome, float $cliff): void    {        $z = $this->z;        $G = self::G;        $w = $this->w;        $cell = $z->cell;        $h = $z->heights;        $moist = new Noise($z->seed * 7 + 50);        $biomes = [];        $solid = [];        for ($j = 0; $j < $G; $j++) {            for ($i = 0; $i < $G; $i++) {                $a = $h[$j * $w + $i];                $b = $h[$j * $w + $i + 1];                $c = $h[($j + 1) * $w + $i];                $d = $h[($j + 1) * $w + $i + 1];                $s = max(abs($a - $b), abs($c - $d), abs($a - $c), abs($b - $d)) / $cell;                $m = $moist->fbm($i / 24, $j / 24, 3);                $biomes[] = $biome(($a + $b + $c + $d) / 4, $s, $m, $i, $j);                $solid[] = $i < 2 || $j < 2 || $i >= $G - 2 || $j >= $G - 2 || $s > $cliff;            }        }        $z->biomes = $biomes;        $z->solid = $solid;        $z->exits = self::earlyExits($z->id);        foreach ($z->exits as $e) {            // the doors are never walls            $this->open($e['x'], $e['z'], $e['r'] + 4);        }    }    /** Every arrival point of the zone can walk to every exit of the zone. */    private function connectDoors(): void    {        $arrivals = [];        foreach (self::IDS as $other) {            foreach (self::exits($other) as $e) {                if ($e['to'] === $this->z->id && empty($e['arriveLate'])) {                    $arrivals[] = [$e['toX'], $e['toZ']];                }            }        }        for ($pass = 0; $pass < 3; $pass++) {            $ok = true;            foreach ($this->z->exits as $e) {                foreach ($arrivals as [$ax, $az]) {                    if (!self::reachable($this->z, $ax, $az, $e['x'], $e['z'])) {                        $ok = false;                        $this->ensurePath($ax, $az, $e['x'], $e['z']);                    }                }            }            if ($ok) {                return;            }        }    }    private function open(float $x, float $zz, float $r): void    {        $z = $this->z;        $cell = $z->cell;        $G = self::G;        for ($j = max(1, (int) (($zz - $r) / $cell)); $j <= min($G - 2, (int) (($zz + $r) / $cell)); $j++) {            for ($i = max(1, (int) (($x - $r) / $cell)); $i <= min($G - 2, (int) (($x + $r) / $cell)); $i++) {                if (hypot(($i + 0.5) * $cell - $x, ($j + 0.5) * $cell - $zz) <= $r) {                    $z->solid[$j * $G + $i] = false;                }            }        }    }    private function heightRaw(float $x, float $zz): float    {        $cell = $this->z->cell;        $i = max(0, min(self::G, (int) round($x / $cell)));        $j = max(0, min(self::G, (int) round($zz / $cell)));        return $this->h[$j * $this->w + $i];    }    /** Levels the ground around a point (to its own height, or $to), blending out to the radius. */    private function flatten(float $x, float $zz, float $r, ?float $to): void    {        $cell = $this->z->cell;        $level = $to ?? $this->heightRaw($x, $zz);        for ($j = max(0, (int) (($zz - $r) / $cell)); $j <= min(self::G, (int) ceil(($zz + $r) / $cell)); $j++) {            for ($i = max(0, (int) (($x - $r) / $cell)); $i <= min(self::G, (int) ceil(($x + $r) / $cell)); $i++) {                $d = hypot($i * $cell - $x, $j * $cell - $zz);                if ($d < $r) {                    $k = $j * $this->w + $i;                    $this->h[$k] = $level + ($this->h[$k] - $level) * self::smooth($r * 0.55, $r, $d);                }            }        }    }    private function dent(float $x, float $zz, float $r, float $depth): void    {        $cell = $this->z->cell;        for ($j = max(0, (int) (($zz - $r) / $cell)); $j <= min(self::G, (int) ceil(($zz + $r) / $cell)); $j++) {            for ($i = max(0, (int) (($x - $r) / $cell)); $i <= min(self::G, (int) ceil(($x + $r) / $cell)); $i++) {                $d = hypot($i * $cell - $x, $j * $cell - $zz);                if ($d < $r) {                    $this->h[$j * $this->w + $i] -= $depth * (1 - $d / $r);                }            }        }    }    /**     * Makes sure a walker can go from one point to the other: if not, a road is cut along the gentlest way     * (Dijkstra over the cells, walls and steep steps cost a lot), levelled so that no step is too steep.     */    private function ensurePath(float $x1, float $z1, float $x2, float $z2): void    {        $z = $this->z;        $s = $z->cellIndex($x1, $z1);        $g = $z->cellIndex($x2, $z2);        if (self::bfs($z, $s, $g) !== null) {            return;        }        $G = self::G;        $cell = $z->cell;        $ch = self::cellHeights($z);        $dist = array_fill(0, $G * $G, INF);        $prev = array_fill(0, $G * $G, -1);        $dist[$s] = 0.0;        $q = new \SplPriorityQueue();        $q->insert($s, 0.0);        while (!$q->isEmpty()) {            $c = $q->extract();            if ($c === $g) {                break;            }            $ci = $c % $G;            $cj = intdiv($c, $G);            foreach ([[1, 0], [-1, 0], [0, 1], [0, -1]] as [$di, $dj]) {                $ni = $ci + $di;                $nj = $cj + $dj;                if ($ni < 1 || $nj < 1 || $ni >= $G - 1 || $nj >= $G - 1) {                    continue;                }                $nc = $nj * $G + $ni;                $sl = abs($ch[$nc] - $ch[$c]) / $cell;                $cost = 1 + ($sl > 0.5 ? ($sl - 0.5) * 25 : 0) + ($z->solid[$nc] ? 40 : 0);                $nd = $dist[$c] + $cost;                if ($nd < $dist[$nc]) {                    $dist[$nc] = $nd;                    $prev[$nc] = $c;                    $q->insert($nc, -$nd);                }            }        }        if ($prev[$g] === -1 && $g !== $s) {            return;        }        $path = [];        for ($c = $g; $c !== -1; $c = $prev[$c]) {            $path[] = $c;        }        $path = array_reverse($path);        $m = 0.6 * $cell;        $p = [];        foreach ($path as $k => $c) {            $hc = $ch[$c];            if ($k > 0) {                $hc = max($p[$k - 1] - $m, min($p[$k - 1] + $m, $hc));            }            $p[] = $hc;        }        $w = $this->w;        foreach ($path as $k => $c) {            $ci = $c % $G;            $cj = intdiv($c, $G);            foreach ([[0, 0], [1, 0], [0, 1], [1, 1]] as [$di, $dj]) {                $z->heights[($cj + $dj) * $w + $ci + $di] = $p[$k];            }            $z->solid[$c] = false;        }        if ($z->ceilings !== []) {            // a road cut in a cave keeps its roof above the new floor            foreach ($path as $k => $c) {                $ci = $c % $G;                $cj = intdiv($c, $G);                foreach ([[0, 0], [1, 0], [0, 1], [1, 1]] as [$di, $dj]) {                    $vi = ($cj + $dj) * $w + $ci + $di;                    $z->ceilings[$vi] = max($z->ceilings[$vi], $p[$k] + 3.2);                }            }        }        $this->h = $z->heights;    }    /** @return list<float> mean height of each cell */    private static function cellHeights(Zone $z): array    {        $G = $z->grid;        $w = $G + 1;        $h = $z->heights;        $out = [];        for ($j = 0; $j < $G; $j++) {            for ($i = 0; $i < $G; $i++) {                $out[] = ($h[$j * $w + $i] + $h[$j * $w + $i + 1] + $h[($j + 1) * $w + $i] + $h[($j + 1) * $w + $i + 1]) / 4;            }        }        return $out;    }    /** Breadth-first walk between two cells (4 neighbours, no wall, steps of at most 0.7 × the cell); null: none. */    private static function bfs(Zone $z, int $s, int $g): ?int    {        $G = $z->grid;        $cell = $z->cell;        $ch = self::cellHeights($z);        $seen = [$s => true];        $queue = new \SplQueue();        $queue->enqueue($s);        $max = 0.7 * $cell;        $caveRoom = $z->ceilings !== [];        $w = $G + 1;        while (!$queue->isEmpty()) {            $c = $queue->dequeue();            if ($c === $g) {                return count($seen);            }            $ci = $c % $G;            $cj = intdiv($c, $G);            foreach ([[1, 0], [-1, 0], [0, 1], [0, -1]] as [$di, $dj]) {                $ni = $ci + $di;                $nj = $cj + $dj;                if ($ni < 0 || $nj < 0 || $ni >= $G || $nj >= $G) {                    continue;                }                $nc = $nj * $G + $ni;                if (isset($seen[$nc]) || $z->solid[$nc] || abs($ch[$nc] - $ch[$c]) > $max) {                    continue;                }                if ($caveRoom) {                    $vi = $nj * $w + $ni;                    if ($z->ceilings[$vi] - $z->heights[$vi] < 1.3 && $z->ceilings[$vi + $w + 1] - $z->heights[$vi + $w + 1] < 1.3) {                        continue;                    }                }                $seen[$nc] = true;                $queue->enqueue($nc);            }        }        return null;    }    /** A random walkable spot of one of the biomes, at least $margin metres from the borders. */    private function findSpot(array $biomes, float $margin): array    {        $z = $this->z;        for ($k = 0; $k < 300; $k++) {            $x = $this->rng->range($margin, $z->size - $margin);            $zz = $this->rng->range($margin, $z->size - $margin);            if (!$z->solidAt($x, $zz) && in_array($z->biomeAt($x, $zz), $biomes, true) && $z->heightAt($x, $zz) > $z->water + 0.5) {                return [$x, $zz];            }        }        return [$z->size / 2, $z->size / 2];    }    /** One chance per cell for each biome's things (kind, probability per cell, optional data). */    private function scatter(array $table, float $maxHeight = INF): void    {        $z = $this->z;        $G = self::G;        $cell = $z->cell;        $water = $z->water;        $clump = new Noise($z->seed * 7 + 77);        for ($j = 2; $j < $G - 2; $j++) {            for ($i = 2; $i < $G - 2; $i++) {                $c = $j * $G + $i;                if ($z->solid[$c]) {                    continue;                }                $list = $table[$z->biomes[$c]] ?? null;                if ($list === null) {                    continue;                }                // things grow in clumps: denser where the clump noise is high                $k = 0.4 + 1.2 * max(0.0, $clump->value($i / 6, $j / 6) + 0.5);                $r = $this->rng->next();                $x = ($i + $this->rng->next()) * $cell;                $zz = ($j + $this->rng->next()) * $cell;                $acc = 0.0;                foreach ($list as $entry) {                    $acc += $entry[1] * $k;                    if ($r >= $acc) {                        continue;                    }                    $kind = $entry[0];                    $h = $z->heightAt($x, $zz);                    if (($kind === 'reed' ? $h < $water - 0.6 : $h < $water + 0.15) || $h > $maxHeight) {                        break;                    }                    foreach ($this->clear as [$cx, $cz, $cr]) {                        if (abs($x - $cx) < $cr && abs($zz - $cz) < $cr && hypot($x - $cx, $zz - $cz) < $cr) {                            break 2;                        }                    }                    $tree = str_starts_with($kind, 'tree_');                    $scale = $tree ? $this->rng->range(0.75, 1.35) : $this->rng->range(0.85, 1.15);                    $this->add($kind, $x, $zz, $this->rng->range(0, 6.2832), $scale, self::leftOf($kind), $entry[2] ?? []);                    break;                }            }        }    }    /** How many times a thing of this kind can be used before it is spent. */    public static function leftOf(string $kind): int    {        return match ($kind) {            'bush_berry', 'bush_red', 'reed', 'tree_broad', 'tree_palm', 'tree_conifer' => 3,            'tree_dead', 'vine', 'reeds_tall', 'mangrove', 'basalt' => 2,            'giant_tree' => 5,            'rock' => 4,            'boulder' => 6,            default => 1,        };    }    private function add(string $kind, float $x, float $zz, float $yaw = 0.0, float $scale = 1.0, ?int $left = null, array $data = []): Thing    {        $t = new Thing($this->nextId++, $kind, $x, $this->z->heightAt($x, $zz), $zz, $yaw, $scale, $left ?? self::leftOf($kind), $data);        $this->z->things[] = $t;        return $t;    }    /** 0 inside the floor (d < w), rising steeply to 1 on the rim. */    private static function wall(float $d, float $w): float    {        if ($d <= $w) {            return 0.0;        }        $t = ($d - $w) / (0.55 * $w);        return $t >= 1 ? 1.0 : $t * $t * (3 - 2 * $t);    }    private static function segment(float $x, float $z, float $ax, float $az, float $bx, float $bz): float    {        $dx = $bx - $ax;        $dz = $bz - $az;        $l = $dx * $dx + $dz * $dz;        $t = $l > 0 ? max(0.0, min(1.0, (($x - $ax) * $dx + ($z - $az) * $dz) / $l)) : 0.0;        return hypot($x - $ax - $dx * $t, $z - $az - $dz * $t);    }    public static function smooth(float $a, float $b, float $x): float    {        if ($a === $b) {            return $x < $a ? 0.0 : 1.0;        }        $t = ($x - $a) / ($b - $a);        $t = $t < 0 ? 0.0 : ($t > 1 ? 1.0 : $t);        return $t * $t * (3 - 2 * $t);    }}