PL
games/rob-revisited / src / Scene / RevisitedScene.php · commit f9a1307
<?phpnamespace App\Scene;use App\Revisited\Audio\Soundscape;use App\Revisited\Land\Chests;use App\Revisited\Land\Escape;use App\Revisited\Land\Game;use App\Revisited\Land\Wildfire;use App\Revisited\Land\Wildlife;use App\Revisited\Land\Intent;use App\Revisited\Land\Zone;use App\Revisited\Render\AdaptiveQuality;use App\Revisited\Render\Graphics;use App\Revisited\Render\Quality;use App\Revisited\Render\View;use App\Revisited\Sim\Inventory;use App\Revisited\Sim\Items;use App\Revisited\Ui\Canvas;use App\Revisited\Ui\ChestView;use App\Revisited\Ui\Controls;use App\Revisited\Ui\Guide;use App\Revisited\Ui\Hints;use App\Revisited\Ui\Hud;use App\Revisited\Ui\HudData;use App\Revisited\Ui\MapView;use App\Revisited\I18n\Translator;use App\Revisited\Ui\MenuList;use App\Revisited\Ui\SavePreview;use App\Revisited\Ui\SaveScreen;use App\Revisited\Ui\SaveStore;use App\Revisited\Ui\Screens;use App\Revisited\Ui\SleepView;use App\Revisited\Ui\UiInput;use App\Revisited\Ui\VitalMenu;use JumPHP\Kernel\Platform;use JumPHP\Renderer\Renderer;use JumPHP\Scene\AbstractScene;/** * "Experience - Rob revisited" (docs/reborn.md): an original first-person survival adventure. Rob Calder's pod crashed * on the moon Ysor; survive (water, food, fire, wounds, cold), find the lost colony's power cell, help the Haldi, and * call the station from the old relay mast. * * The scene ties the modules together: Land\Game (the state, pure logic), Render\Graphics (the 3D, drawn from a View * built each frame), Ui (the dashboard and the screens, drawn at the window's resolution in a Renderer overlay). * * Keys (Controls): arrows / WASD (ZQSD) walk and turn, the mouse looks (a click in the view captures it, Escape frees * it; right button held also looks), Shift run, C crouch, Space jump, E / Return the context action, F (or a click, * mouse captured) attack, I inventory, K crafting, B body, Tab / N scanner, M map, J journal, T sleep, 1-4 quick slots, * H / F1 the controls, Escape pause. Pad: left stick, right stick look, A jump, X action, RT attack, Y inventory, B back, * LB run, RB crouch, LT journal, Select map, Start pause. Phones: the page's stick (walk) and A = ACTION, a drag on the * view looks around, the scene's own buttons (attack, jump, run, crouch, bag, scanner, map, pause). * * Audio: Revisited\Audio\Soundscape, updated while playing only (no footsteps behind the title card, the pause or the * screens), plus the UI's own events (click, open, close, craft, swing, chop...). Option "Musique". * * Saves (Ui\SaveStore, docs/reborn.md "Saves"): 20 named slots + "Sauvegarde automatique" (each game hour, when leaving), * each with a preview picture (SavePreview: the 3D view read back, else the map); screens "Charger une partie" and * "Sauvegarder la partie" (Ui\SaveScreen) from the title, the pause and the death screen. * * Test params: ['seed' => 7, 'new' => true] (straight into a new game), 'continue' => true (the latest save), 'zone' => * 'canyon' (a new game started there), 'quality' => auto|ultra|low|medium|high (not saved), 'start' => the level Auto starts at, * 'fov' => 80 (the field of view, degrees), 'eye' => 0.15 (metres added to the eye), 'bob' => normal|reduced|none, * 'adaptive' => true (Auto adapts headless too: off by default there), 'frame_ms' => 30 (the governor sees frames of that * length: a slow computer), 'gpu' => 'Google SwiftShader' (the renderer's name instead of the detected one), 'fps' => true, 'touch' => true (the phone buttons), 'help' => * false (no controls panel at the start), 'uiscale' => 0.54 (draw the dashboard as on a phone's small screen), 'weather' * => 'storm' + 'amount' (the sky turns into it, smoothly), 'minutes' (game minutes since day 1, 07:00), 'at' => 'waterfall' + * 'dist' (Rob stands in front of the first thing of that kind, looking at it), 'x' / 'z' / 'yaw' / 'pitch', 'level' => 5 + * 'talents' => 'power,frugal' (experience and talents learnt). */final class RevisitedScene extends AbstractScene{    /** the single save of older versions (moved into slot 1 by SaveStore::migrate()) */    public const SAVE = SaveStore::OLD;    /** the software-rendering panel (Chrome on SwiftShader, a missing GPU driver) */    public const SOFT_TEXT = 'Ton navigateur n\'utilise pas ta carte graphique (rendu logiciel) : le jeu sera lent. '        . 'Dans Chrome : Paramètres → Système → active « Utiliser l\'accélération graphique si disponible », puis relance. '        . 'Vérifie aussi chrome://gpu (WebGL doit être « Hardware accelerated ») et mets à jour le pilote de ta carte graphique.';    private ?Game $game = null;    private SaveStore $saves;    private ?SaveScreen $saveScreen = null;    /** where the save / load screen goes back to: title | pause | dead */    private string $savesFrom = 'title';    /** seconds played in this game (saved with it) */    private float $played = 0.0;    /** the game's minutes at the last save or load: more progress than that is "unsaved" */    private float $savedMinutes = 0.0;    /** the last 3D view read back (PNG) and the game minute it shows */    private ?string $snapshot = null;    private float $snapshotAt = -1.0;    private string $snapshotZone = '';    /** read the 3D view back in the next overlay (and give it to that slot) */    private bool $shotWanted = false;    private ?string $shotFor = null;    /** test bench ('demo_saves' => n, 'saves' => load|save): slots made from this game and other zones, then the screen */    private int $demoSaves = 0;    private string $demoScreen = 'load';    /** where the game goes once saved ("Sauvegarder avant de quitter ?" → Oui) */    private ?\Closure $pendingLeave = null;    /** SDL's text input is on (the save's name being typed) */    private bool $textOn = false;    private ?Soundscape $audio = null;    private ?Graphics $gfx = null;    /** the zone Graphics has built (the same object: a loaded save has new Zone objects) */    private ?Zone $loadedZone = null;    private float $titleYaw = 0.0;    private View $view;    private Intent $intent;    private ?Canvas $canvas = null;    private Hud $hud;    private HudData $data;    private ?Screens $screens = null;    private ?MapView $map = null;    private Guide $guide;    private UiInput $ui;    private MenuList $menu;    private VitalMenu $vitals;    private SleepView $sleepView;    /** the transfer screen of a chest (mode "chest") */    private ChestView $chestView;    /** seconds since a gauge's menu pointed the compass at a place */    private float $pointerAge = 0.0;    private ?int $overlay = null;    private ?\Closure $onClose = null;    /** title | loading | play | screen | pause | options | dead | won | controls | sleep | vitals | chest */    private string $mode = 'title';    /** where options go back to */    private string $optionsFrom = 'title';    /** the mode after the loading card */    private string $afterLoading = 'play';    private int $loadStep = 0;    /** the quality level drawn (Quality::LEVELS) */    private string $quality = 'medium';    /** the option: auto or a forced level */    private string $qualityPref = 'auto';    private AdaptiveQuality $adaptive;    /** test bench: the governor sees frames of this length (seconds) instead of the wall clock */    private ?float $fakeDt = null;    private float $lastFrameAt = 0.0;    /** the GL renderer's name (Quality::renderer()) and whether it draws on the CPU */    private string $gpu = '';    private bool $software = false;    /** the "rendu logiciel" panel is shown */    private bool $softPanel = false;    private bool $softShown = false;    private bool $showFps = false;    private string $toast = '';    /** comfort (motion sickness): the horizontal field of view (wheel / pinch / option), the eye raised, the view's sway */    public const FOV_MIN = 45.0;    public const FOV_MAX = 105.0;    public const FOV_DEFAULT = 80.0;    public const EYE_LIFTS = ['0' => 'Normale', '0.15' => '+15 cm', '0.3' => '+30 cm'];    public const BOBS = ['normal' => 'Normal', 'reduced' => 'Réduit', 'none' => 'Aucun'];    private const BOB_SCALE = ['normal' => 1.0, 'reduced' => 0.4, 'none' => 0.0];    private float $fov = self::FOV_DEFAULT;    private float $eyeLift = 0.0;    private string $bobMode = 'reduced';    /** the eye's height above Rob's feet, eased (critically damped) toward standing / crouching, and its speed */    private float $eyeH = 1.7;    private float $eyeV = 0.0;    private float $toastAge = 99.0;    private bool $mouseLook = true;    private bool $touch = false;    private int $seed = 7;    private float $clock = 0.0;    private int $savedHour = -1;    private bool $crouch = false;    private float $promptTimer = 0.0;    private float $slowTimer = 0.0;    private int $logCount = 0;    private ?string $logLast = null;    private float $lastMx = 0.0;    private float $lastMy = 0.0;    private ?float $dragX = null;    /** the left button went down on the view (not on a button of the HUD): its drag looks */    private bool $leftLook = false;    /** a click without a drag (a press and release moving under CLICK_SLOP pixels): button => [x, y, travel, t0] */    private array $clickTrack = [];    /** this frame: the left button clicked on the view (attack, right hand) / the right one (the left hand's action) */    private bool $clickAttack = false;    private bool $clickLeft = false;    /** window pixels a click may move and still be a click (more: it is a look drag) */    public const CLICK_SLOP = 6.0;    /** "Quitter le jeu" was chosen (tests; the browser page takes over) */    private bool $quitting = false;    private ?float $dragY = null;    private int $dialogueSel = 0;    private Hints $hints;    private Controls $controls;    /** where the controls panel goes back to: play | pause */    private string $controlsFrom = 'play';    private bool $controlsFirst = false;    /** show the controls at the start of a new game (once per player, option rv_controls_seen) */    private bool $autoHelp = true;    private ?string $promptId = null;    /** seconds since the player turned the view himself (mouse, finger, pad, keys): the combat camera assist waits for 0.6 s */    private float $lookAge = 9.0;    private string $lastSleepPhase = '';    /** desktop: the mouse is captured (relative mode) and turns the view */    private bool $captured = false;    private float $sensitivity = 1.0;    private bool $invertY = false;    /** phones: a finger dragging on the view looks around */    private bool $touchLook = false;    private float $touchX = 0.0;    private float $touchY = 0.0;    /** 1 → 0: the picture comes out of black after a loading (zone change) */    private float $fade = 0.0;    private string $lastMode = 'title';    /** @var list<object> creatures + people, refilled each frame */    private array $entities = [];    private string $saveNote = '';    private float $saveNoteAge = 9.0;    private float $frameMs = 0.0;    private float $renderMs = 0.0;    private float $uiMs = 0.0;    /** @var list<array{0: string, 1: float, 2: float}> sounds the game asked for, played when their time comes (thunder after the flash) */    private array $sounds = [];    /** the victory: seconds since the launch (the ending text scrolls in) */    private float $wonTime = 0.0;    /** test bench: a screen tab to open once the zone is loaded */    private ?string $pendingScreen = null;    /** test bench: a menu / panel to open once the zone is loaded (title, pause, options, controls, sleep, vital:<key>, body:<view>) */    private ?string $pendingMenu = null;    public function enter(array $params = []): void    {        // the language: the saved choice, else the page's / the system's (src/Revisited/I18n, docs/i18n-plan.md)        Translator::boot($this->engine);        if (isset($params['lang']) && isset(Translator::LANGS[(string) $params['lang']])) {            Translator::setLang((string) $params['lang']);     // test bench: this language, not saved        }        $this->view = new View();        $this->intent = new Intent();        $this->hud = new Hud();        $this->data = new HudData();        $this->guide = new Guide();        $this->ui = new UiInput();        $this->menu = new MenuList('menu');        $this->vitals = new VitalMenu();        $this->sleepView = new SleepView();        $this->chestView = new ChestView();        $this->map = new MapView($this->sdl());        $this->screens = new Screens($this->map, $this->sdl());        $this->hints = new Hints();        $this->audio?->stop();        $this->audio = new Soundscape($this->engine);        $this->audio->music = (bool) $this->engine->options->get('rv_music', true);        $this->controls = new Controls();        $this->captured = false;        $this->touchLook = false;        $this->fade = 0.0;        $this->canvas ??= new Canvas($this->engine->config->path('assets/fonts/hd.ttf'), $this->sdl());        $this->overlay = $this->sdl()->getRenderer()->addOverlay(fn (Renderer $r) => $this->drawUi($r));        $this->game = null;        $this->gfx = null;        $this->loadedZone = null;        $this->clock = 0.0;        $this->crouch = false;        $this->dialogueSel = 0;        $this->savedHour = -1;        $this->logCount = 0;        $this->logLast = null;        $this->saveNote = '';        $this->dragX = $this->dragY = null;        $this->quitting = false;        $this->leftLook = $this->touchLook = false;        $opts = $this->engine->options;        $this->setupQuality($params);        $this->fov = max(self::FOV_MIN, min(self::FOV_MAX, (float) ($params['fov'] ?? $opts->get('rv_fov', self::FOV_DEFAULT))));        $lift = (float) ($params['eye'] ?? $opts->get('rv_eye_lift', 0.0));        $this->eyeLift = max(0.0, min(0.3, $lift));        $bob = (string) ($params['bob'] ?? $opts->get('rv_bob', 'reduced'));        $this->bobMode = isset(self::BOBS[$bob]) ? $bob : 'reduced';        $this->eyeH = Game::EYE;        $this->eyeV = 0.0;        $this->mouseLook = (bool) $opts->get('rv_mouse_look', true);        $this->sensitivity = max(0.25, min(3.0, (float) $opts->get('rv_sensitivity', 1.0)));        $this->invertY = (bool) $opts->get('rv_invert_y', false);        $mode = (string) $opts->get('rv_hints', 'auto');        $this->hints->mode = isset(Hints::MODES[$mode]) ? $mode : 'auto';        $this->autoHelp = ($params['help'] ?? true) !== false;        $this->setTouch((bool) ($params['touch'] ?? Platform::isMobile()));        $this->canvas->forceScale = isset($params['uiscale']) ? (float) $params['uiscale'] : null;        $this->seed = (int) ($params['seed'] ?? random_int(1, 99999));        $this->saves = new SaveStore($this->engine->storage);        $this->saves->migrate();        $this->saveScreen?->dispose();        $this->saveScreen = new SaveScreen($this->saves, $this->sdl());        $this->played = 0.0;        $this->savedMinutes = 0.0;        $this->snapshot = null;        $this->snapshotAt = -1.0;        $this->shotWanted = false;        $this->shotFor = null;        $this->engine->bridge->send('touch', ['labels' => ['a' => 'ACTION'], 'hide' => ['start', 'select']]);        $this->onClose = function (): void {            $this->save(SaveStore::AUTO);        };        $this->engine->lifecycle()->on('close', $this->onClose);        if (!empty($params['continue']) && $this->hasSave()) {            $this->continueGame();        } elseif (!empty($params['new']) || isset($params['zone'])) {            $this->newGame(isset($params['zone']) ? (string) $params['zone'] : null);            if (isset($params['minutes']) && $this->game !== null) {                $this->game->minutes = (float) $params['minutes'];     // tests: the time since the crash (0 = day 1, 07:00)            }            if (isset($params['at']) && $this->game !== null) {                $this->placeAt($this->game, (string) $params['at'], (float) ($params['dist'] ?? 22.0));            }            if (isset($params['x'], $params['z']) && $this->game !== null) {                $this->game->x = (float) $params['x'];                $this->game->z = (float) $params['z'];                $this->game->y = $this->game->zone->heightAt($this->game->x, $this->game->z);            }            if (isset($params['yaw']) && $this->game !== null) {                $this->game->yaw = (float) $params['yaw'];            }            if (isset($params['pitch']) && $this->game !== null) {                $this->game->pitch = (float) $params['pitch'];            }            $this->pendingScreen = isset($params['screen']) ? (string) $params['screen'] : null;            $this->pendingMenu = isset($params['menu']) ? (string) $params['menu'] : null;            if (isset($params['endurance']) && $this->game !== null) {                $this->game->body->setFitness((float) $params['endurance'], (float) ($params['force'] ?? 0.0));   // test bench            }            $this->demoSaves = max(0, min(SaveStore::SLOTS, (int) ($params['demo_saves'] ?? 0)));            $this->demoScreen = ($params['saves'] ?? 'load') === 'save' ? 'save' : 'load';            if (isset($params['talk']) && $this->game !== null) {                // test bench: a conversation open with a named person of the zone (People key)                foreach ($this->game->npcs as $n) {                    if (($n->data['key'] ?? null) === $params['talk']) {                        $this->game->x = $n->x - sin($n->yaw + 3.1416) * -1.6;                        $this->game->z = $n->z - cos($n->yaw + 3.1416) * -1.6;                        $this->game->y = $this->game->zone->heightAt($this->game->x, $this->game->z);                        $this->game->yaw = atan2($n->x - $this->game->x, $n->z - $this->game->z);                        $this->game->talkTo($n);                    }                }            }            if (isset($params['weather']) && $this->game !== null) {                // test bench: the weather turns (smoothly) into this one                $this->game->setWeatherTarget((string) $params['weather'], (float) ($params['amount'] ?? 1.0));            }            if (isset($params['hold']) && $this->game !== null) {                // test bench: items given and taken in hand, in order ("torch,spear": the torch left, the spear right)                foreach (explode(',', (string) $params['hold']) as $id) {                    if (Items::exists($id)) {                        $this->game->give($id);                        if (\App\Revisited\Sim\Inventory::holdable($id)) {                            $this->game->useItem($id);                        }                    }                }            }            if (isset($params['chest']) && $this->game !== null) {                // test bench: a chest of that kind put down in front of Rob, with a few things in it ('chest_fill' => false: empty)                $this->benchChest($this->game, (string) $params['chest'], ($params['chest_fill'] ?? true) !== false);            }            if (isset($params['level']) && $this->game !== null) {                // test bench: experience up to that level, 'talents' => "power,power,frugal" learnt                $this->game->talents->gain(\App\Revisited\Sim\Talents::total((int) $params['level']));                foreach (array_filter(explode(',', (string) ($params['talents'] ?? ''))) as $id) {                    $this->game->talents->learn($id);                }            }            if (isset($params['beast']) && $this->game !== null) {                // test bench: a beast of that species in front of Rob, at 'beast_dist' metres (the others gone)                $g0 = $this->game;                $d = (float) ($params['beast_dist'] ?? 4.0);                $c = Wildlife::make($g0, (string) $params['beast'], $g0->x + sin($g0->yaw) * $d, $g0->z + cos($g0->yaw) * $d);                $c->y = $g0->zone->heightAt($c->x, $c->z);                $c->yaw = $g0->yaw + M_PI;                $g0->creatures = [$c];            }        } else {            // the title card, over the valley seen from the crash site            $this->game = Game::newGame($this->seed);            $this->titleYaw = $this->game->yaw;            $this->beginLoading('title');        }    }    public function exit(): void    {        $this->save(SaveStore::AUTO);        $this->textInput(false);        $this->saveScreen?->dispose();        $this->capture(false);        $this->audio?->stop();        if ($this->overlay !== null) {            $this->sdl()->getRenderer()->removeOverlay($this->overlay);            $this->overlay = null;        }        if ($this->onClose !== null) {            $this->engine->lifecycle()->removeListener('close', $this->onClose);            $this->onClose = null;        }        $this->gfx?->dispose();        $this->gfx = null;        $this->engine->gl()->disable();        $this->engine->bridge->send('touch', ['show' => ['start', 'select'], 'labels' => ['a' => 'OK']]);    }    // ------------------------------------------------------------------------------------------ games, saves    private function newGame(?string $zone = null): void    {        if ($zone !== null && $zone !== 'valley') {            $this->game = Game::fromArray(['seed' => $this->seed, 'zone' => $zone, 'inv' => Game::newGame($this->seed)->inv->toArray()]);            $this->game->x = $this->game->zone->exits[0]['x'] + 6;            $this->game->z = $this->game->zone->exits[0]['z'];            $this->game->y = $this->game->zone->heightAt($this->game->x, $this->game->z);        } else {            $this->game ??= Game::newGame($this->seed);            if ($this->game->seed !== $this->seed || $this->game->minutes > 0.01 || $this->game->dead()) {                $this->game = Game::newGame($this->seed);            } else {                // the game of the title card: the camera turned, nothing else happened                $this->game->yaw = $this->titleYaw;                $this->game->pitch = 0.0;            }        }        $this->data->slots = [1 => null, 2 => null, 3 => null, 4 => null];        $this->autoSlots();        $this->played = 0.0;        $this->savedMinutes = $this->game->minutes;        $this->savedHour = (int) floor($this->game->minutes / 60);        $this->resetFeed();        $this->hints->load([]);        $first = $this->autoHelp && !(bool) $this->engine->options->get('rv_controls_seen', false);        $this->beginLoading($first ? 'controls' : 'play');        $this->controlsFirst = $first;        $this->controlsFrom = 'play';    }    /** Test bench: a chest put down in front of Rob (and filled with a few things). */    private function benchChest(Game $g, string $kind, bool $fill): void    {        if (!isset(Chests::KINDS[$kind])) {            return;        }        $g->give($kind);        Chests::place($g, $kind);        $t = Chests::inZone($g)[count(Chests::inZone($g)) - 1] ?? null;        if ($t === null || !$fill) {            return;        }        foreach (['meat_cooked' => 2, 'rope' => 3, 'stick' => 6, 'flint' => 2, 'bandage' => 2, 'berries_blue' => 5, 'hide' => 1, 'arrow' => 8] as $id => $n) {            $g->inv->add($id, $n);            Chests::put($g, $t, $id, $n);        }        $g->give('fiber', 6);        $g->give('gourd_clean', 1);        // a step back, looking down at it        $back = [$g->x - sin($g->yaw) * 1.0, $g->z - cos($g->yaw) * 1.0];        if (\App\Revisited\Land\Solids::free($g->zone, $back[0], $back[1], 0.3)) {            [$g->x, $g->z] = $back;            $g->y = $g->zone->heightAt($g->x, $g->z);        }        $g->pitch = -0.38;    }    /** Test bench: Rob stands $dist metres in front of a thing of that kind (the first one), looking at it. */    private function placeAt(Game $g, string $kind, float $dist): void    {        foreach ($g->zone->things as $t) {            if ($t->kind === $kind) {                $g->x = $t->x + sin($t->yaw) * $dist;                $g->z = $t->z + cos($t->yaw) * $dist;                $g->y = $g->zone->heightAt($g->x, $g->z);                $g->yaw = atan2($t->x - $g->x, $t->z - $g->z);                $g->pitch = 0.12;                return;            }        }    }    private function setTouch(bool $on): void    {        $this->touch = $on;        $this->data->touch = $on;        $this->data->actKey = $on ? 'ACTION' : 'E';        if ($this->screens !== null) {            $this->screens->touch = $on;        }        if ($this->canvas !== null) {            // phones: much bigger text everywhere (the layouts wrap and measure with the boost)            $this->canvas->minPx = $on ? 13 : 7;            $this->canvas->boost = $on ? 1.25 : 1.0;        }    }    private function openControls(string $from, bool $first = false): void    {        $this->capture(false);        $this->controlsFrom = $from;        $this->controlsFirst = $first;        $this->mode = 'controls';    }    private function closeControls(): void    {        if ($this->controlsFirst) {            $this->engine->options->set('rv_controls_seen', true);            $this->controlsFirst = false;        }        if ($this->controlsFrom === 'pause') {            $this->pauseMenu();        } else {            $this->mode = 'play';        }    }    /** Desktop: the mouse captured (hidden, relative motion) turns the view; released for the menus and screens. */    private function capture(bool $on): void    {        if ($on && ($this->touch || !$this->mouseLook)) {            return;        }        if ($this->captured === $on) {            return;        }        $this->captured = $on;        if (function_exists('SDL_SetRelativeMouseMode')) {            @\SDL_SetRelativeMouseMode($on ? 1 : 0);            $dx = $dy = 0;            @\SDL_GetRelativeMouseState($dx, $dy);     // forget the motion of before        }    }    private function hasSave(): bool    {        return $this->saves->any();    }    /** Loads the most recent save. */    private function continueGame(): bool    {        $key = $this->saves->latest();        return $key !== null && $this->loadSlot($key);    }    /** Loads a slot: the game, the quick slots, the hints, the play time; then the zone is built behind the loading card. */    private function loadSlot(string $key): bool    {        $a = $this->saves->read($key);        if ($a === null) {            return false;        }        try {            $game = Game::fromArray($a['game']);        } catch (\Throwable) {            return false;        }        $this->game = $game;        $this->seed = $this->game->seed;        $this->data->slots = [1 => null, 2 => null, 3 => null, 4 => null];        foreach ((array) ($a['slots'] ?? []) as $k => $id) {            if ((int) $k >= 1 && (int) $k <= 4 && is_string($id) && Items::exists($id)) {                $this->data->slots[(int) $k] = $id;            }        }        $this->played = (float) ($a['played'] ?? 0.0);        $this->savedMinutes = $this->game->minutes;        $this->savedHour = (int) floor($this->game->minutes / 60);        $this->snapshot = null;        $this->resetFeed();        $this->hints->load($a['hints'] ?? []);        $this->beginLoading('play');        return true;    }    /** Can the game be saved now (playing, alive, not won)? */    private function canSave(): bool    {        $g = $this->game;        return !($g === null || !in_array($this->mode, ['play', 'screen', 'pause', 'options', 'loading', 'controls', 'vitals', 'saves', 'askleave'], true) || $g->dead() || $g->won()            || ($this->mode === 'loading' && $this->afterLoading !== 'play') || ($this->mode === 'options' && $this->optionsFrom !== 'pause')            || ($this->mode === 'saves' && $this->savesFrom !== 'pause'));    }    /** Progress since the last save (a load from the pause asks first). */    private function unsaved(): bool    {        return $this->game !== null && $this->game->minutes - $this->savedMinutes > 0.25;    }    /**     * Writes the game into a slot (SaveStore::AUTO: the autosave). Its preview: the 3D view read back when the pause     * opened (the same moment), else drawn from the map now and replaced by the 3D view in the next frame.     */    private function save(string $key = SaveStore::AUTO, ?string $name = null): bool    {        $g = $this->game;        if ($g === null || !$this->canSave()) {            return false;        }        $fresh = $this->snapshot !== null && abs($this->snapshotAt - $g->minutes) < 0.01 && $this->snapshotZone === $g->zone->id;        $png = $fresh ? $this->snapshot : SavePreview::fromMap($g);        $old = $this->saves->metaOf($key);        $name ??= $key === SaveStore::AUTO ? SaveStore::AUTO_NAME : (string) ($old['name'] ?? SaveStore::defaultName($g));        $payload = ['v' => 2, 'game' => $g->toArray(), 'slots' => $this->data->slots, 'hints' => $this->hints->toArray(), 'played' => round($this->played, 1), 'at' => date('c')];        $ok = $this->saves->write($key, $payload, SaveStore::meta($g, $name, $this->played), $png);        $explicit = $key !== SaveStore::AUTO;        if ($ok && !$fresh && $this->gfx !== null && in_array($this->mode, ['play', 'pause', 'saves', 'screen', 'vitals'], true)) {            $this->shotWanted = true;     // the real view, read back in the next overlay            $this->shotFor = $key;        }        $this->savedHour = (int) floor($g->minutes / 60);        if ($ok && $explicit) {            $this->savedMinutes = $g->minutes;      // the autosave does not count as the player's save        }        return $ok;    }    /** Test bench: $demoSaves slots (the game played, then other zones and hours, previews from their maps), then the screen. */    private function makeDemoSaves(Game $g): void    {        $n = $this->demoSaves;        $this->demoSaves = 0;        $names = ['Le camp de la cascade', 'Avant la grotte', 'Village haldi — troc avec Oko', 'Le plateau gelé, sans feu', 'Jungle : le fleuve',            'Marais, la nuit', 'Côte volcanique : la navette !', 'Grottes des Jonctions', 'Juste avant le lancement'];        $zones = ['valley', 'caves1', 'canyon', 'plateau', 'jungle', 'marsh', 'coast', 'caves3', 'coast'];        $this->save('1', $names[0]);        $at = time();        for ($i = 1; $i < $n; $i++) {            $zone = $zones[$i % count($zones)];            $h = Game::fromArray(['seed' => $g->seed, 'zone' => $zone, 'inv' => $g->inv->toArray(), 'minutes' => 300.0 + $i * 900.0,                'flags' => ['q_fire' => true, 'q_sleep' => true, 'fit_nav_core' => $i > 4, 'fit_heat_plates' => $i > 6]]);            $h->x = $h->zone->exits[0]['x'] + 6;            $h->z = $h->zone->exits[0]['z'];            $meta = SaveStore::meta($h, $names[$i % count($names)] . ($i >= count($names) ? ' (' . $i . ')' : ''), 600.0 + $i * 1500.0, $at - $i * 86000);            $this->saves->write((string) ($i + 1), ['v' => 2, 'game' => $h->toArray(), 'played' => 600.0 + $i * 1500.0], $meta, SavePreview::fromMap($h));        }        $this->openSaves($this->demoScreen, 'pause');    }    /** Opens "Charger une partie" / "Sauvegarder la partie". */    private function openSaves(string $mode, string $from): void    {        $this->savesFrom = $from;        $this->saveScreen?->open($mode, $from === 'pause', $from === 'pause' && $this->unsaved());        if ($this->saveScreen !== null) {            $this->saveScreen->touch = $this->touch;        }        $this->mode = 'saves';    }    private function closeSaves(): void    {        $this->textInput(false);        $this->pendingLeave = null;        match ($this->savesFrom) {            'pause' => $this->pauseMenu(),            'dead' => $this->deathMenu(),            default => $this->titleMenu(),        };    }    /** SDL's text input (the keyboard's layout, accents) and, in a browser on a phone, its on-screen keyboard. */    private function textInput(bool $on): void    {        if ($on === $this->textOn) {            return;        }        $this->textOn = $on;        if (function_exists('SDL_StartTextInput')) {            $on ? \SDL_StartTextInput() : \SDL_StopTextInput();        }        $this->engine->bridge->send('textinput', ['on' => $on]);    }    private function updateSaves(float $dt): void    {        $screen = $this->saveScreen;        if ($screen === null) {            $this->closeSaves();            return;        }        $kb = $this->engine->input->getKeyboard();        $cmd = $screen->update($this->ui, $kb, !$screen->editing() && $this->actions()->isPressed('rv_rest'), $dt);        $this->textInput($screen->editing());        if ($cmd === null) {            return;        }        $this->audio?->event('click');        switch ($cmd[0]) {            case 'close':                $this->closeSaves();                return;            case 'save':                $key = (string) ($cmd[1] ?? '');                $new = !$this->saves->has($key);                if ($this->save($key)) {                    if ($this->pendingLeave !== null) {                        $leave = $this->pendingLeave;                        $this->pendingLeave = null;                        $this->textInput(false);                        $this->save(SaveStore::AUTO);                        $leave();                        return;                    }                    $screen->dirty = false;                    $screen->refresh($key);                    $screen->say('Partie sauvegardée.');                    if ($new) {                        $screen->startRename($key);      // a new save: its name, at once (Entrée keeps the one proposed)                    }                } else {                    $screen->say('Impossible de sauvegarder.');                }                return;            case 'load':                $this->textInput(false);                if (!$this->loadSlot((string) ($cmd[1] ?? ''))) {                    $screen->say('Cette sauvegarde ne peut pas être lue.');                }                return;        }    }    /** The first quick slots: food, water, a bandage, the torch, from what the bag holds. */    private function autoSlots(): void    {        $g = $this->game;        if ($g === null) {            return;        }        $want = [1 => ['spear', 'axe_stone', 'knife_flint', 'bow'], 2 => ['ration', 'meat_cooked', 'fruit', 'berries_blue'], 3 => ['bandage', 'medkit'], 4 => ['torch', 'gourd_clean']];        foreach ($want as $k => $ids) {            if ($this->data->slots[$k] !== null) {                continue;            }            foreach ($ids as $id) {                if ($g->inv->has($id)) {                    $this->data->slots[$k] = $id;                    break;                }            }        }    }    private function resetFeed(): void    {        $this->data->feed = [];        $log = $this->game?->messages() ?? [];        // the last messages of the game come back as fresh ones (the story's first lines at a new game)        foreach (array_slice($log, -4) as $m) {            $this->data->feed[] = [$m, 0.0];        }        $this->logCount = count($log);        $this->logLast = $log === [] ? null : $log[count($log) - 1];    }    // ------------------------------------------------------------------------------------------ 3D    private function beginLoading(string $then): void    {        $this->mode = 'loading';        $this->afterLoading = $then;        $this->loadStep = 0;        // building a zone blocks the page for a moment, and in the browser the sound is fed by that same thread: what        // was playing would repeat in a loop. Silence first (the ambience of the new zone comes back by itself), then        // the build once the audio has played some of that silence        $this->audio?->stop();        $this->loadAt = microtime(true);    }    /** when the loading card came (the build waits a little: the sound has gone quiet) */    private float $loadAt = 0.0;    /** Builds the zone's meshes (a frame after the "Chargement" card is shown). */    private function loadStep(): void    {        if ($this->loadStep++ < 1 || (Platform::isWasm() && $this->loadStep < 30 && microtime(true) - $this->loadAt < 0.15)) {            return;        }        $g = $this->game;        if ($g === null) {            return;        }        $gl = $this->engine->gl();        if ($gl->isAvailable() && ($this->gfx === null || $this->loadedZone !== $g->zone)) {            $this->gfx ??= new Graphics($gl, $this->quality);            $this->gfx->loadZone($g->zone);        }        $this->loadedZone = $g->zone;        $this->mode = $this->afterLoading;        if ($this->mode === 'play' || $this->mode === 'controls') {            $this->fade = 1.0;        }        if ($this->mode === 'play' && $this->demoSaves > 0) {            $this->pauseMenu();        // the 3D view read back in this frame: the first demo slot's preview        }        if ($this->mode === 'title') {            $this->titleMenu();        } elseif ($this->mode === 'options') {            $this->optionsMenu($this->optionsFrom);        }    }    // ------------------------------------------------------------------------------------------ quality    /** The option, the renderer, the level to start at, the governor. */    private function setupQuality(array $params): void    {        $opts = $this->engine->options;        $headless = Platform::isHeadless();        $pref = (string) ($params['quality'] ?? $opts->get('rv_quality', 'auto'));        $this->qualityPref = in_array($pref, Quality::CHOICES, true) ? $pref : 'auto';        $gl = $this->engine->gl();        // headless runs draw with Mesa's llvmpipe (software): not a player's computer, unless a test says so        $this->gpu = isset($params['gpu']) ? (string) $params['gpu'] : (!$headless && $gl->isAvailable() ? Quality::renderer() : '');        $this->software = Quality::isSoftware($this->gpu);        $this->quality = $this->qualityPref !== 'auto' ? $this->qualityPref : $this->autoStart($params);        if ($this->software && $this->qualityPref === 'auto') {            $this->quality = 'ultra';        }        $this->adaptive = new AdaptiveQuality($this->quality, $this->qualityPref === 'auto' && (bool) ($params['adaptive'] ?? !$headless));        $this->fakeDt = isset($params['frame_ms']) ? max(0.001, (float) $params['frame_ms'] / 1000) : null;        $this->lastFrameAt = 0.0;        $this->showFps = (bool) ($params['fps'] ?? $opts->get('rv_fps', false));        $this->softShown = false;        $this->softPanel = false;        if ($this->software) {            $this->showSoftPanel();        }        $this->toast = '';        $this->toastAge = 99.0;    }    /** Auto starts where it settled last time, else medium on a computer, low on a phone. */    private function autoStart(array $params): string    {        $start = (string) ($params['start'] ?? $this->engine->options->get('rv_quality_auto', Platform::isMobile() ? 'low' : 'medium'));        return Quality::valid($start) ? $start : 'medium';    }    private function showSoftPanel(): void    {        if (!$this->softShown && !(bool) $this->engine->options->get('rv_soft_dismissed', false)) {            $this->softPanel = true;            $this->softShown = true;        }    }    /** Each frame: the wall-clock time since the last one goes to the governor, which may change the level. */    private function measure(): void    {        $now = microtime(true);        $dt = $this->lastFrameAt > 0.0 ? $now - $this->lastFrameAt : 0.0;        $this->lastFrameAt = $now;        // only while the 3D shows as in play: not behind the loading card, a screen, a menu, a hidden tab        if (!in_array($this->mode, ['play', 'title'], true) || $this->softPanel || $this->gfx === null && $this->fakeDt === null            || !$this->engine->lifecycle()->isVisible() || $this->game?->dialogue() !== null) {            $this->adaptive->pause();            return;        }        $new = $this->adaptive->frame($this->fakeDt ?? $dt);        if ($this->adaptive->hopeless) {            $this->showSoftPanel();        }        if ($new === null) {            return;        }        $this->engine->options->set('rv_quality_auto', $new);        $down = array_search($new, Quality::LEVELS, true) < array_search($this->quality, Quality::LEVELS, true);        $this->toastNote(sprintf($down ? 'Qualité graphique abaissée à %s pour garder le jeu fluide (%d i/s).'            : 'Qualité graphique relevée à %s : le jeu tourne bien (%d i/s).', Quality::LABELS[$new], (int) round($this->adaptive->fps)));        $this->applyLevel($new, $this->mode);    }    /** Draws at another level: Graphics is made again and the zone rebuilt behind the loading card. */    private function applyLevel(string $level, string $then): void    {        if ($level === $this->quality && $this->gfx !== null) {            return;        }        $this->quality = $level;        if ($this->gfx === null && $this->loadedZone === null) {            return;         // nothing built yet: the next loading builds it at this level        }        $this->gfx?->dispose();        $this->gfx = null;        $this->engine->gl()->disable();        $this->beginLoading($then);    }    /** The option "Qualité": auto or a forced level (saved). */    private function setQuality(string $pref): void    {        $this->qualityPref = $pref;        $this->engine->options->set('rv_quality', $pref);        $level = $pref === 'auto' ? ($this->software ? 'ultra' : $this->autoStart([])) : $pref;        $this->adaptive->set($level, $pref === 'auto' && ($this->adaptive->auto || !Platform::isHeadless()));        if ($level !== $this->quality) {            $this->applyLevel($level, 'options');        }    }    // ------------------------------------------------------------------------------------------ comfort    /**     * The eye's height eases toward standing / crouching: a critically damped spring (no overshoot), ~0.25 s, solved     * exactly for any frame length (no snap, steady at 30 or 144 i/s).     */    private function easeEye(Game $g, float $dt): void    {        $target = $g->crouching ? Game::CROUCH_EYE : Game::EYE;        $w = 18.0;        $x0 = $this->eyeH - $target;        $k = exp(-$w * $dt);        $tmp = ($this->eyeV + $w * $x0) * $dt;        $this->eyeH = $target + ($x0 + $tmp) * $k;        $this->eyeV = ($this->eyeV - $w * $tmp) * $k;        if (abs($this->eyeH - $target) < 0.0005 && abs($this->eyeV) < 0.001) {            $this->eyeH = $target;            $this->eyeV = 0.0;        }    }    /** Zoom: the field of view, in steps, within FOV_MIN .. FOV_MAX, saved. */    private function zoom(float $by): void    {        $fov = max(self::FOV_MIN, min(self::FOV_MAX, round(($this->fov + $by) * 2) / 2));        if ($fov !== $this->fov) {            $this->fov = $fov;            $this->engine->options->set('rv_fov', $fov);        }    }    private function toastNote(string $text): void    {        $this->toast = $text;        $this->toastAge = 0.0;    }    private function qualityLabel(): string    {        return $this->qualityPref === 'auto' ? 'Auto (' . Quality::LABELS[$this->quality] . ')' : Quality::LABELS[$this->quality];    }    // ------------------------------------------------------------------------------------------ menus    private function titleMenu(): void    {        $this->mode = 'title';        // a save exists: "Reprendre" (the latest) is the row selected; else "Nouvelle partie"        $this->menu->sel = 0;        $any = $this->hasSave();        $this->menu->set([            ['Reprendre', fn () => $this->continueGame(), $any],            ['Charger une partie…', fn () => $this->openSaves('load', 'title'), $any],            ['Nouvelle partie', fn () => $this->newGame()],            ['Options', fn () => $this->optionsMenu('title')],            $this->langRow(fn () => $this->titleMenu()),            ...$this->leaveRows(false),        ]);    }    /**     * "Langue : Français / English": switches at once (every text is translated when drawn), saved as rv_lang.     * @return array{0: string, 1: \Closure, 2: bool, 3: \Closure}     */    private function langRow(\Closure $again): array    {        return ['Langue', function () use ($again): void {            $sel = $this->menu->sel;            Translator::choose($this->engine, Translator::next());            $again();            $this->menu->sel = $sel;        }, true, fn () => Translator::LANGS[Translator::lang()]];    }    /**     * The way out: inside the ALIS project its list of games (App\Scene\TitleScene); the standalone game     * (rob-revisited) has no such list: back to this game's title card, or quit on the desktop.     * @return list<array<int, mixed>>     */    private function leaveRows(bool $toTitle, bool $saveFirst = false): array    {        // from a game (the pause): the autosave slot keeps where Rob was; with progress not saved in a slot of the player's,        // "Sauvegarder avant de quitter ?" first        $wrap = function (\Closure $leave) use ($saveFirst): \Closure {            return function () use ($leave, $saveFirst): void {                if ($saveFirst && $this->unsaved()) {                    $this->askLeave($leave);                    return;                }                if ($saveFirst) {                    $this->save(SaveStore::AUTO);                }                $leave();            };        };        if (class_exists(TitleScene::class)) {            return [[$toTitle && $saveFirst ? 'Quitter vers la liste des jeux' : 'Retour à la liste des jeux', $wrap(function (): void {                $this->scenes()->switchTo(TitleScene::class);            })], $this->quitRow($wrap)];        }        $rows = [];        if ($toTitle) {            $rows[] = [$saveFirst ? 'Revenir au titre' : 'Écran titre', $wrap(function (): void {                $this->titleMenu();            })];        }        $rows[] = $this->quitRow($wrap);        return $rows;    }    /**     * "Quitter le jeu", everywhere (an installed game needs a way out): the desktop closes the window; in a browser the     * engine hands it to the page (Engine::quit(): the ?back= address, the portal frame, else "thanks for playing").     * @return array{0: string, 1: \Closure}     */    private function quitRow(\Closure $wrap): array    {        return ['Quitter le jeu', $wrap(function (): void {            $this->quitting = true;            $this->engine->quit();        })];    }    /** "Sauvegarder avant de quitter ?": Oui (the save screen, then away), Non (away: the autosave only), Annuler. */    private function askLeave(\Closure $leave): void    {        $this->mode = 'askleave';        $this->menu->sel = 0;        $this->menu->set([            ['Oui, sauvegarder', function () use ($leave): void {                $this->pendingLeave = $leave;                $this->openSaves('save', 'pause');            }],            ['Non, quitter sans sauvegarder', function () use ($leave): void {                $this->save(SaveStore::AUTO);                $leave();            }],            ['Annuler', fn () => $this->pauseMenu()],        ]);    }    private function pauseMenu(): void    {        if ($this->mode === 'play') {            $this->shotWanted = true;      // the view as it is: the preview of a save made from this pause        }        $this->mode = 'pause';        $this->menu->sel = 0;        $this->menu->set([            ['Reprendre', fn () => $this->mode = 'play'],            ['Sauvegarder…', fn () => $this->openSaves('save', 'pause')],            ['Charger une partie…', fn () => $this->openSaves('load', 'pause'), $this->hasSave()],            ['Commandes', fn () => $this->openControls('pause')],            ['Options', fn () => $this->optionsMenu('pause')],            ...$this->leaveRows(true, true),        ]);    }    private function optionsMenu(string $from): void    {        $this->optionsFrom = $from;        $this->mode = 'options';        $this->menu->sel = 0;        $this->menu->set([            ['Qualité graphique', function (): void {                $order = Quality::CHOICES;                $i = (int) array_search($this->qualityPref, $order, true);                $dir = $this->ui->left ? -1 : 1;                $this->setQuality($order[($i + $dir + count($order)) % count($order)]);            }, true, fn () => $this->qualityLabel()],            ['Afficher les images par seconde', function (): void {                $this->showFps = !$this->showFps;                $this->engine->options->set('rv_fps', $this->showFps);            }, true, fn () => $this->showFps ? 'Oui' : 'Non'],            ['Champ de vision (molette)', function (): void {                if (!$this->ui->left && !$this->ui->right && $this->fov >= self::FOV_MAX) {                    $this->zoom(self::FOV_MIN - self::FOV_MAX);      // Enter at the widest: back to the narrowest                } else {                    $this->zoom($this->ui->left ? -5.0 : 5.0);                }            }, true, fn () => sprintf('%d°', (int) round($this->fov))],            ['Hauteur des yeux', function (): void {                $keys = array_keys(self::EYE_LIFTS);                $i = 0;                foreach ($keys as $k => $v) {                    if (abs((float) $v - $this->eyeLift) < 0.01) {                        $i = $k;                    }                }                $dir = $this->ui->left ? -1 : 1;                $this->eyeLift = (float) $keys[($i + $dir + count($keys)) % count($keys)];                $this->engine->options->set('rv_eye_lift', $this->eyeLift);            }, true, fn () => self::EYE_LIFTS[(string) $this->eyeLift] ?? sprintf('+%d cm', (int) round($this->eyeLift * 100))],            ['Balancement de la vue', function (): void {                $keys = array_keys(self::BOBS);                $i = (int) array_search($this->bobMode, $keys, true);                $dir = $this->ui->left ? -1 : 1;                $this->bobMode = $keys[($i + $dir + count($keys)) % count($keys)];                $this->engine->options->set('rv_bob', $this->bobMode);            }, true, fn () => self::BOBS[$this->bobMode]],            ['Regard libre à la souris', function (): void {                $this->mouseLook = !$this->mouseLook;                $this->engine->options->set('rv_mouse_look', $this->mouseLook);            }, true, fn () => $this->mouseLook ? 'Oui' : 'Non'],            ['Sensibilité du regard', function (): void {                $steps = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5];                $i = 0;                foreach ($steps as $k => $v) {                    if (abs($v - $this->sensitivity) < 0.01) {                        $i = $k;                    }                }                $dir = $this->ui->left ? -1 : 1;                $this->sensitivity = $steps[($i + $dir + count($steps)) % count($steps)];                $this->engine->options->set('rv_sensitivity', $this->sensitivity);            }, true, fn () => rtrim(rtrim(Translator::num($this->sensitivity, 2), '0'), ',.')],            ['Inverser le regard vertical', function (): void {                $this->invertY = !$this->invertY;                $this->engine->options->set('rv_invert_y', $this->invertY);            }, true, fn () => $this->invertY ? 'Oui' : 'Non'],            ['Aides à l\'écran', function (): void {                $order = array_keys(Hints::MODES);                $i = (int) array_search($this->hints->mode, $order, true);                $this->hints->mode = $order[($i + 1) % count($order)];                $this->engine->options->set('rv_hints', $this->hints->mode);            }, true, fn () => Hints::MODES[$this->hints->mode]],            ['Musique', function (): void {                if ($this->audio !== null) {                    $this->audio->music = !$this->audio->music;                    $this->engine->options->set('rv_music', $this->audio->music);                }            }, true, fn () => ($this->audio->music ?? true) ? 'Oui' : 'Non'],            ['Boutons tactiles', function (): void {                $this->setTouch(!$this->touch);            }, true, fn () => $this->touch ? 'Oui' : 'Non'],            $this->langRow(fn () => $this->optionsMenu($from)),            ['Retour', fn () => $from === 'pause' ? $this->pauseMenu() : $this->titleMenu()],        ]);    }    private function deathMenu(): void    {        $this->mode = 'dead';        $this->menu->sel = 0;        $this->menu->set([            ['Reprendre la dernière sauvegarde', fn () => $this->continueGame(), $this->hasSave()],            ['Charger une partie…', fn () => $this->openSaves('load', 'dead'), $this->hasSave()],            ['Nouvelle partie', function (): void {                $this->seed = random_int(1, 99999);                $this->newGame();            }],            ...$this->leaveRows(true),        ]);    }    private function victoryMenu(): void    {        $this->mode = 'won';        $this->wonTime = 0.0;        $this->audio?->event('win');        $this->menu->sel = 0;        $this->menu->set([            ['Nouvelle partie', function (): void {                $this->seed = random_int(1, 99999);                $this->newGame();            }],            ...$this->leaveRows(true),        ]);    }    // ------------------------------------------------------------------------------------------ update    public function update(float $dt): void    {        $t0 = microtime(true);        $this->clock += $dt;        $this->saveNoteAge += $dt;        if (in_array($this->mode, ['play', 'screen', 'vitals', 'sleep', 'controls', 'chest'], true)) {            $this->played += $dt;        }        $this->toastAge += $dt;        $this->readUi();        $this->measure();        $g = $this->game;        if ($this->softPanel && $this->mode !== 'loading') {            // the software-rendering panel waits for "Compris" (Enter, Escape, a click on its button)            $this->capture(false);            if ($this->ui->ok || $this->ui->back || $this->ui->hit === 'soft:ok') {                $this->softPanel = false;                $this->engine->options->set('rv_soft_dismissed', true);                $this->audio?->event('click');            }            $this->frameMs = $this->frameMs * 0.9 + (microtime(true) - $t0) * 100;            return;        }        switch ($this->mode) {            case 'loading':                $this->loadStep();                break;            case 'title':                if ($g !== null) {                    $g->yaw += $dt * 0.06;     // the camera turns slowly over the valley                }                $this->menuUpdate();                break;            case 'pause':                if ($this->demoSaves > 0 && $g !== null) {                    $this->makeDemoSaves($g);                    break;                }                if ($this->ui->back || ($this->actions()->isPressed('pause') && !$this->actions()->isPressed('rv_close'))) {                    $this->mode = 'play';                    break;                }                $this->menuUpdate();                break;            case 'options':                if ($this->ui->back) {                    $this->optionsFrom === 'pause' ? $this->pauseMenu() : $this->titleMenu();                    break;                }                $this->menuUpdate();                break;            case 'dead':            case 'won':                $this->menuUpdate();                break;            case 'saves':                $this->updateSaves($dt);                break;            case 'askleave':                if ($this->ui->back) {                    $this->pauseMenu();                    break;                }                $this->menuUpdate();                break;            case 'controls':                if ($this->ui->ok || $this->ui->back || $this->ui->click || $this->actions()->isPressed('rv_help')                    || $this->actions()->isPressed('pause') || $this->actions()->isPressed('rv_jump')) {                    $this->closeControls();                }                break;            case 'sleep':                if ($g !== null && !$this->sleepView->update($this->ui, $g, $dt)) {                    if ($g->sleeping !== null) {                        $g->wake();                    }                    $this->mode = 'play';                }                if ($g !== null && $this->sleepView->phase === 'woke' && $this->lastSleepPhase !== 'woke' && $this->sleepView->rude()) {                    $this->audio?->event('stinger');                }                $this->lastSleepPhase = $this->sleepView->phase;                break;            case 'chest':                if ($g === null || !$this->chestView->update($this->ui, $g, $dt)) {                    if ($g !== null) {                        Chests::close($g);                    }                    $this->mode = 'play';                } elseif ($this->chestView->sound !== '') {                    $this->audio?->event($this->chestView->sound);                }                break;            case 'vitals':                if ($g !== null && !$this->vitals->update($this->ui, $g)) {                    $this->vitals->close();                    // a row may have opened another screen (the body, the sleep): keep it                    if ($this->vitalsKeep()) {                        $this->mode = 'play';                    }                }                break;            case 'screen':                if ($g !== null && !$this->screens?->update($this->ui, $g, $this->data, $dt)) {                    $this->mode = 'play';                }                if ($g !== null && $this->mode === 'screen' && $this->screenKey() === $this->screens?->tab) {                    $this->mode = 'play';                }                break;            default:                if ($g !== null) {                    $this->play($g, $dt);                }        }        if ($g !== null && $this->mode !== 'title' && $this->mode !== 'loading') {            $this->follow($g, $dt);        }        if ($g !== null) {            $this->easeEye($g, $dt);        }        if ($this->mode !== 'play' || ($g !== null && $g->dialogue() !== null)) {            $this->capture(false);            // a click on a menu, a choice, a panel never becomes a look drag once back in the game (the button still held)            $this->leftLook = $this->touchLook = false;            $this->dragX = $this->dragY = null;        }        if ($g !== null) {            foreach ($g->takeEvents() as [$name, $delay, $vol]) {                $this->sounds[] = [$name, $this->clock + $delay, $vol];            }            $keep = [];            foreach ($this->sounds as $snd) {                if ($snd[1] <= $this->clock) {                    $name = ['zap' => 'hit', 'flare' => 'fire', 'flash' => '', 'engage' => ''][$snd[0]] ?? $snd[0];                    if ($name === 'brandish') {                        $keep[] = ['fire', $this->clock + 0.12, 0.8];   // the flame roars as it sweeps                    }                    if ($name !== '') {                        $this->audio?->event($name);                    }                } else {                    $keep[] = $snd;                }            }            $this->sounds = $keep;        }        if ($this->mode === 'won') {            $this->wonTime += $dt;        }        $this->fade = max(0.0, $this->fade - $dt * 2.2);        $this->data->captured = $this->captured;        $this->data->captureHint = $this->mode === 'play' && !$this->touch && $this->mouseLook && $g !== null && $g->minutes < 7 * 60 + 45;        $this->data->crouchToggle = $this->crouch;        $this->data->hasScanner = $g !== null && $g->inv->has('scanner');        $leftItem = $g !== null && $g->inv->handLeft !== null && $g->inv->has($g->inv->handLeft) ? $g->inv->handLeft : null;        $this->data->leftButton = $leftItem === null ? ($g !== null && $g->torchLit() ? 'TORCHE' : null)            : ($leftItem === 'torch' ? 'TORCHE' : (Inventory::isShield($leftItem) ? 'PARER' : 'MAIN G.'));        $this->data->shieldKey = $leftItem !== null && Inventory::isShield($leftItem) ? ($this->engine->input->getGamepad()->count() > 0 ? 'LT' : 'V') : null;        if ($this->mode !== $this->lastMode) {            if ($this->mode === 'screen' || $this->mode === 'controls' || $this->mode === 'chest') {                $this->audio?->event('open');            } elseif ($this->lastMode === 'screen' || $this->lastMode === 'controls' || $this->lastMode === 'chest') {                $this->audio?->event('close');            }            if ($this->mode === 'dead') {                $this->audio?->event('death');            }            $this->lastMode = $this->mode;        }        $this->frameMs = $this->frameMs * 0.9 + (microtime(true) - $t0) * 100;    }    private function menuUpdate(): void    {        if ($this->menu->update($this->ui)) {            $this->audio?->event('click');        }    }    /** The tab whose key was pressed this frame (I K B M J), null: none. */    private function screenKey(): ?string    {        $a = $this->actions();        return match (true) {            $a->isPressed('rv_inventory') => 'inventory',            $a->isPressed('rv_craft') => 'craft',            $a->isPressed('rv_body') => 'body',            $a->isPressed('rv_scanner') => 'scanner',            $a->isPressed('rv_map') => 'map',            $a->isPressed('rv_journal') => 'journal',            $this->engine->input->getKeyboard()->isKeyPressed(\SDLK_l) && !$this->engine->input->getKeyboard()->ctrlHeld() => 'talents',            default => null,        };    }    private function readUi(): void    {        $a = $this->actions();        $u = $this->ui;        $u->reset();        $u->up = $a->isPressed('up') || $a->isPressed('rv_forward');        $u->down = $a->isPressed('down');        $u->left = $a->isPressed('left') || $a->isPressed('rv_turn_left');        $u->right = $a->isPressed('right');        $u->ok = $a->isPressed('rv_act') || $a->isPressed('confirm');        $u->back = $a->isPressed('rv_close');        $u->prev = $a->isPressed('rv_prev');        $u->next = $a->isPressed('rv_next');        $u->drop = $a->isPressed('rv_drop');        for ($i = 1; $i <= 6; $i++) {            if ($a->isPressed('rv_' . $i)) {                $u->digit = $i;            }        }        $m = $this->engine->input->getMouse();        [$u->mx, $u->my] = $this->canvas?->toUnits($m->x, $m->y, $this->width(), $this->height())            ?? [$m->x * Canvas::W / max(1, $this->width()), $m->y * Canvas::H / max(1, $this->height())];        $u->moved = abs($u->mx - $this->lastMx) + abs($u->my - $this->lastMy) > 0.5;        $u->wheel = $m->wheelY;        $u->hover = $this->canvas?->hitAt($u->mx, $u->my);        // only a real move of the pointer takes the selection: a menu opening under a resting mouse keeps its keyboard        // default (Enter runs it), a click still runs the row clicked        if ($m->isPressed(1)) {            $u->click = true;            $u->hit = $u->hover;        }        $u->held = $m->isHeld(1);        $this->lastMx = $u->mx;        $this->lastMy = $u->my;    }    private function play(Game $g, float $dt): void    {        if ($this->ui->wheel != 0.0 && $g->dialogue() === null) {            $this->zoom(-$this->ui->wheel * 4.0);      // wheel up: zoom in (narrower), down: wider (motion sickness)        }        if ($this->loadedZone !== $g->zone) {            $this->beginLoading('play');            return;        }        if ($g->over() !== null) {            $this->deathMenu();            return;        }        if ($g->won()) {            $this->victoryMenu();            return;        }        if ($this->pendingMenu !== null) {            $m = $this->pendingMenu;            $this->pendingMenu = null;            match (true) {                $m === 'title' => $this->titleMenu(),                $m === 'pause' => $this->pauseMenu(),                $m === 'options' => $this->optionsMenu('pause'),                $m === 'controls' => $this->openControls('pause'),                $m === 'sleep' => $this->openSleep($g),                $m === 'chest' => $this->openChestAhead($g),                str_starts_with($m, 'vital:') || isset(VitalMenu::COND_KEY[$m]) => $this->openVitals($g, $m, 300.0),                str_starts_with($m, 'body:') => (function () use ($m): void {                    $this->screens?->openBody(substr($m, 5));                    $this->mode = 'screen';                })(),                default => null,            };            return;        }        if ($this->pendingScreen !== null) {            $this->screens?->open($this->pendingScreen);            $this->pendingScreen = null;            $this->mode = 'screen';            return;        }        foreach ($g->takeNotices() as $note) {            $this->toastNote($note);       // the fitness steps ("Tu te sens plus endurant : +5 %")        }        $a = $this->actions();        $u = $this->ui;        $in = $this->intent;        $in->forward = $in->turn = $in->strafe = $in->look = 0.0;        $in->attack = false;        $in->dodge = null;        $in->assist = false;        if ($g->dialogue() !== null) {            $this->dialogue($g);            $g->update($dt, $in);            $this->audio?->update($g, $dt);            return;        }        // the mouse: a button held on the view and dragged turns it (mouseLook()); never captured: the browser's pointer        // lock locked the cursor without giving its motion to the game        if ($a->isPressed('pause') && !$u->click) {            $this->pauseMenu();            return;        }        if ($a->isPressed('rv_help')) {            $this->openControls('play');            return;        }        if ($u->click && $u->hit === 'btn:pause') {            $this->pauseMenu();            return;        }        $tab = $this->screenKey();        if ($u->click && $u->hit !== null) {            $tab = match ($u->hit) {                'btn:inventory', 'hand' => 'inventory',                'btn:map' => 'map',                'btn:scanner' => 'scanner',                default => $tab,            };        }        if ($tab !== null) {            $this->screens?->open($tab);            $this->mode = 'screen';            return;        }        // a gauge or a condition badge: its menu of actions        if ($u->click && $u->hit !== null && (str_starts_with($u->hit, 'vital:') || str_starts_with($u->hit, 'cond:'))) {            $this->openVitals($g, $u->hit, $u->mx - 40);            return;        }        $this->data->tooltip = null;        if (!$this->touch && $u->hover !== null && (str_starts_with($u->hover, 'vital:') || str_starts_with($u->hover, 'cond:'))) {            $key = str_starts_with($u->hover, 'vital:') ? substr($u->hover, 6) : (VitalMenu::COND_KEY[substr($u->hover, 5)] ?? 'health');            $this->data->tooltip = VitalMenu::tooltip($g, $key) . '  (clic : actions)';        }        if ($this->data->pointer !== null) {            $this->pointerAge += $dt;            if ($this->pointerAge > 180 || hypot($this->data->pointer[0] - $g->x, $this->data->pointer[1] - $g->z) < 4) {                $this->data->pointer = null;            }        }        if ($a->isPressed('rv_rest')) {            $this->openSleep($g, true);            return;        }        // actions        if (($a->isPressed('rv_act') || ($u->click && $u->hit === 'prompt')) && $this->promptId === 'sleep') {            $this->hints->done($this->promptId);            $this->openSleep($g);            return;        }        $kb = $this->engine->input->getKeyboard();        if (($kb->isKeyPressed(\SDLK_g) && !$kb->ctrlHeld()) || $this->engine->input->getGamepad()->isPressed('pad0:rs') || ($u->click && $u->hit === 'prompt:next')) {            // the next thing within reach for the context action            $g->cycleFocus();            $this->promptTimer = 0.0;            $this->audio?->event('click');        }        if ($a->isPressed('rv_act') || ($u->click && $u->hit === 'prompt')) {            $this->hints->done($this->promptId);            $g->act();            $this->promptTimer = 0.0;            if ($g->chestOpen !== null) {                $this->openChest($g);                return;            }            $sound = ['chop' => 'chop', 'mine' => 'mine', 'fire' => 'fire', 'sleep' => 'sleep', 'fish' => 'splash'][$this->promptId ?? ''] ?? null;            if ($sound !== null) {                $this->audio?->event($sound);            }        }        if ($a->isPressed('rv_sleep')) {            $this->openSleep($g);            return;        }        if ($a->isPressed('rv_crouch') || ($u->click && $u->hit === 'btn:crouch')) {            $this->crouch = !$this->crouch;        }        $in->jump = $a->isPressed('rv_jump') || ($u->click && $u->hit === 'btn:jump');        if ($in->jump && $this->crouch) {            // a jump stands up first            $this->crouch = false;            $in->jump = false;        }        $slot = $u->digit >= 1 && $u->digit <= 4 ? $u->digit : 0;        if ($u->click && $u->hit !== null && str_starts_with($u->hit, 'slot:')) {            $slot = (int) substr($u->hit, 5);        }        if ($slot > 0) {            $this->useSlot($g, $slot);        }        if ($u->click && $u->hit === 'btn:run') {            $this->data->runToggle = !$this->data->runToggle;        }        // movement        $in->forward = (float) ($a->axis('down', 'up') ?: ($a->isHeld('rv_forward') ? 1 : 0));        $in->turn = (float) ($a->axis('left', 'right') ?: ($a->isHeld('rv_turn_left') ? -1 : 0));        $pad = $this->engine->input->getGamepad();        $in->turn = max(-1.0, min(1.0, $in->turn + $pad->axis(0, 'rx')));        $in->look = -$pad->axis(0, 'ry');        $in->run = $a->isHeld('rv_run') || $this->data->runToggle;        $in->crouch = $this->crouch;        $yaw0 = $g->yaw;        $pitch0 = $g->pitch;        $this->mouseLook($g);        $this->touchLook($g);        // the combat camera assist: only while the player does not turn the view himself        $this->lookAge = $g->yaw !== $yaw0 || $g->pitch !== $pitch0 || abs($in->turn) > 0.05 || abs($in->look) > 0.05 ? 0.0 : $this->lookAge + $dt;        $in->assist = $this->lookAge > 0.6;        if ($in->jump && $g->combat->active && $in->forward < 0.3) {            // combat mode: the jump key dodges (a step back, or aside with a turn held); forward + jump still jumps            $in->dodge = $in->turn > 0.3 ? 1.0 : ($in->turn < -0.3 ? -1.0 : 0.0);            $in->jump = false;        }        // attack (right hand): F, a click on the view without a drag, the pad's RT, the phone's ATTAQUE (the sounds come        // from the game at the strike); the left hand: V, a right click without a drag, the pad's LT, the phone's TORCHE        $in->attack = $a->isHeld('rv_attack') || $a->isPressed('rv_attack') || $this->clickAttack || ($u->click && $u->hit === 'btn:attack') || ($this->touch && $this->held('btn:attack'));        $in->left = $a->isHeld('rv_left') || $a->isPressed('rv_left') || $this->clickLeft || ($u->click && $u->hit === 'btn:left') || ($this->touch && $this->held('btn:left'))            || ($g->inv->shield() !== null && $this->mouseLook && !$this->touch && $this->engine->input->getMouse()->isHeld(3));        if ($a->isPressed('rv_swap')) {            $g->swapHands();        }        $g->update($dt, $in);        $this->audio?->update($g, $dt);        $this->observe($g, $dt);    }    /** The transfer screen of the chest Game::$chestOpen names (Chests::open() was just run). */    private function openChest(Game $g): void    {        if (Chests::opened($g) === null) {            $g->chestOpen = null;            return;        }        $this->capture(false);        $this->chestView->open($g, $this->touch);        $this->mode = 'chest';    }    /** Test bench: opens the nearest chest of the zone (menu "chest"). */    private function openChestAhead(Game $g): void    {        $best = null;        foreach (Chests::inZone($g) as $t) {            if ($best === null || hypot($t->x - $g->x, $t->z - $g->z) < hypot($best->x - $g->x, $best->z - $g->z)) {                $best = $t;            }        }        if ($best !== null) {            Chests::open($g, $best);            $this->openChest($g);        }    }    /** Still in the gauge's menu after its action (no other screen opened by it)? */    private function vitalsKeep(): bool    {        return $this->mode === 'vitals';    }    /** The Dormir screen (or straight into a short rest). */    private function openSleep(Game $g, bool $rest = false): void    {        $this->capture(false);        $this->sleepView->open($g, $rest);        $this->lastSleepPhase = $this->sleepView->phase;        if ($rest && $this->sleepView->phase !== 'sleep') {            $g->say($this->sleepView->refused);            return;        }        $this->mode = 'sleep';    }    /** The menu of a gauge or a condition badge, with the scene's hooks (open the body, sleep, rest, point at a place). */    private function openVitals(Game $g, string $hit, float $x): void    {        $key = str_starts_with($hit, 'vital:') ? substr($hit, 6) : $hit;        $this->vitals->open($g, $key, $x, [            'body' => function (string $view, string $part): void {                $this->screens?->openBody($view, $part);                $this->mode = 'screen';            },            'sleep' => function () use ($g): void {                $this->openSleep($g);            },            'rest' => function () use ($g): void {                $this->openSleep($g, true);            },            'point' => function (float $px, float $pz, string $label): string {                $this->data->pointer = [$px, $pz, $label];                $this->pointerAge = 0.0;                return 'La boussole montre : ' . $label . '.';            },        ]);        $this->data->tooltip = null;        $this->mode = 'vitals';    }    /** Is the pointer held on that touch button (phones keep a finger on it)? */    private function held(string $id): bool    {        $m = $this->engine->input->getMouse();        return $m->isHeld(1) && $this->ui->hover === $id;    }    /** Phones: a finger that comes down on the view (not on a button) and drags turns the view, both ways. */    private function touchLook(Game $g): void    {        if (!$this->touch) {            $this->touchLook = false;            return;        }        $m = $this->engine->input->getMouse();        $u = $this->ui;        if ($m->isPressed(1)) {            $this->touchLook = $u->hit === null;            $this->touchX = $u->mx;            $this->touchY = $u->my;            return;        }        if (!$m->isHeld(1) || !$this->touchLook) {            $this->touchLook = false;            return;        }        $dx = $u->mx - $this->touchX;        $dy = $u->my - $this->touchY;        $this->touchX = $u->mx;        $this->touchY = $u->my;        $k = 0.0062 * $this->sensitivity;        $g->yaw -= $dx * $k;        $g->pitch = max(-1.25, min(1.25, $g->pitch - $dy * $k * 0.8 * ($this->invertY ? -1 : 1)));    }    /** Desktop: the left button pressed on the view (not on the HUD) or the right one, held and dragged, turns the view. */    private function mouseLook(Game $g): void    {        $m = $this->engine->input->getMouse();        $this->clickAttack = $this->clickLeft = false;        if (!$this->mouseLook || $this->touch) {            $this->dragX = $this->dragY = null;            $this->clickTrack = [];            return;        }        // a click (not a drag): the left button strikes, the right one is the left hand's action        foreach ([1, 3] as $b) {            if ($m->isPressed($b) && ($b === 3 || $this->ui->hit === null)) {                $this->clickTrack[$b] = [$m->x, $m->y, 0.0, $this->clock];            }            if (!isset($this->clickTrack[$b])) {                continue;            }            [$px, $py, $travel, $t0] = $this->clickTrack[$b];            $travel += abs($m->x - $px) + abs($m->y - $py);            $this->clickTrack[$b] = [$m->x, $m->y, $travel, $t0];            if ($m->isReleased($b) || !$m->isHeld($b)) {                if ($travel < self::CLICK_SLOP && $this->clock - $t0 < 0.5) {                    if ($b === 1) {                        $this->clickAttack = true;                    } else {                        $this->clickLeft = true;                    }                }                unset($this->clickTrack[$b]);            }        }        if ($m->isPressed(1)) {            $this->leftLook = $this->ui->hit === null;        }        // with a shield on the left arm the right button holds it up (Game::guard()) instead of turning the view        $shield = $g->inv->shield() !== null;        $look = ($m->isHeld(1) && $this->leftLook) || ($m->isHeld(3) && !$shield);        if (!$look) {            $this->dragX = $this->dragY = null;            return;        }        if ($this->dragX !== null) {            $k = 0.012 * $this->sensitivity;            $g->yaw -= ($m->x - $this->dragX) * $k;            $g->pitch = max(-1.25, min(1.25, $g->pitch - ($m->y - (float) $this->dragY) * $k * 0.85 * ($this->invertY ? -1 : 1)));        }        $this->dragX = $m->x;        $this->dragY = $m->y;    }    private function useSlot(Game $g, int $slot): void    {        $id = $this->data->slots[$slot] ?? null;        if ($id === null) {            $g->say('Raccourci ' . $slot . ' vide : choisis un objet dans l\'inventaire (I) et appuie sur ' . $slot . '.');            return;        }        if (!$g->inv->has($id)) {            $g->say('Plus de ' . mb_strtolower(Items::name($id)) . ' dans ton sac.');            return;        }        if (Screens::isLocalCare($id)) {            $this->screens?->open('body');            $this->mode = 'screen';            return;        }        $slot = $g->inv->heldSlot($id);        if ($slot !== null) {            $g->say($g->unequip($slot));            return;        }        $g->useItem($id);    }    private function dialogue(Game $g): void    {        $d = $g->dialogue();        if ($d === null) {            return;        }        $u = $this->ui;        $n = count($d['choices']);        $this->dialogueSel = max(0, min($this->dialogueSel, $n - 1));        if ($u->up) {            $this->dialogueSel = ($this->dialogueSel - 1 + $n) % max(1, $n);        }        if ($u->down) {            $this->dialogueSel = ($this->dialogueSel + 1) % max(1, $n);        }        if ($u->moved && $u->hover !== null && str_starts_with($u->hover, 'choice:')) {            $this->dialogueSel = (int) substr($u->hover, 7);        }        $pick = null;        if ($u->digit >= 1 && $u->digit <= $n) {            $pick = $u->digit - 1;        } elseif ($u->ok) {            $pick = $this->dialogueSel;        } elseif ($u->click && $u->hit !== null && str_starts_with($u->hit, 'choice:')) {            $pick = (int) substr($u->hit, 7);        }        if ($u->back) {            $g->closeDialogue();            return;        }        if ($pick !== null && $pick < $n) {            $g->choose($pick);            $this->dialogueSel = 0;        }    }    /** What the dashboard needs from the game: new messages, the prompt, the body's state, the objective, autosave. */    private function observe(Game $g, float $dt): void    {        $this->promptTimer -= $dt;        if ($this->promptTimer <= 0) {            $this->promptTimer = 0.12;            $first = $g->actions()[0] ?? null;            $this->data->prompt = $first['label'] ?? null;            $this->promptId = $first['id'] ?? null;            $this->data->focusCount = count($g->thingsAhead());            $this->data->focusIndex = $this->data->focusCount > 0 ? $g->focusPick % $this->data->focusCount + 1 : 0;        }        $this->data->hint = $this->hints->update($this->promptId, $dt);        $this->data->combat = $g->combat->info($g);        $this->data->aim = $g->aiming() ? $g->aimPos() : null;        $this->data->sweet = $g->talents->sweetWidth();        $this->data->popups = $g->combat->popups;        $this->data->hitMark = max(0.0, 1 - ($g->clock - $g->hitAt) / 0.18);        $this->data->dodgeKey = $this->engine->input->getGamepad()->count() > 0 ? 'A' : 'Espace';        $this->data->attackKey = $this->engine->input->getGamepad()->count() > 0 ? 'RT' : 'F';        $this->slowTimer -= $dt;        if ($this->slowTimer <= 0) {            $this->slowTimer = 0.4;            $this->data->conditions = array_slice($g->body->conditions(), 0, 5);            $f = $g->body->feelings();            $this->data->feeling = $f[0] ?? null;            $this->data->target = $this->guide->target($g);            $q = $g->quest();            $this->data->quest = 'Chapitre ' . $q['chapter'] . ' — ' . $q['title'];            $this->data->objective = $q['objective'];            $this->autoSlots();        }        if ((int) floor($g->minutes / 60) !== $this->savedHour) {            $this->save(SaveStore::AUTO);     // every game hour: the autosave slot        }    }    /** New messages of the game into the feed; ages; the red flash. */    private function follow(Game $g, float $dt): void    {        $log = $g->messages();        $n = count($log);        $last = $n > 0 ? $log[$n - 1] : null;        if ($n !== $this->logCount || $last !== $this->logLast) {            $start = 0;            if ($this->logLast !== null) {                for ($i = $n - 1; $i >= 0; $i--) {                    if ($log[$i] === $this->logLast) {                        $start = $i + 1;                        break;                    }                }            }            for ($i = max($start, $n - 5); $i < $n; $i++) {                $this->data->feed[] = [$log[$i], 0.0];                if (str_starts_with($log[$i], 'Tu as fabriqué')) {                    $this->audio?->event('craft');                }            }            $this->logCount = $n;            $this->logLast = $last;        }        $feed = [];        foreach ($this->data->feed as [$text, $age]) {            $age += $dt;            if ($age < 9.0) {                $feed[] = [$text, $age];            }        }        $this->data->feed = array_slice($feed, -6);        $this->data->time = $this->clock;        $this->data->flash = $g->hurt;    }    // ------------------------------------------------------------------------------------------ render    public function render(Renderer $r): void    {        $g = $this->game;        $gl = $this->engine->gl();        if ($g === null || $this->mode === 'loading') {            $r->clear([8, 10, 14]);            return;        }        if ($this->gfx !== null && $gl->isAvailable() && $this->loadedZone === $g->zone) {            $r->clear(Graphics::KEY);            $v = $this->view;            $v->x = $g->x;            $v->z = $g->z;            $v->y = $g->y + $this->eyeH + $this->eyeLift;            $v->fov = $this->fov;            $v->yaw = $g->yaw;            $v->pitch = $this->mode === 'title' ? 0.05 : $g->pitch;            $v->minutes = $g->minutes + Game::START_HOUR * 60;            $v->weather = $g->weather;            $v->light = $g->lightLevel();            $v->torch = $g->torchLit();            $v->fires = $g->blazes === [] ? $g->fires : array_merge($g->fires, Wildfire::viewFires($g));            // wave 2 (Render adds these to View): lightning, the raft, burnt ground            // the strike's time in the view's clock (the game counts its own seconds of play)            $v->lightning = $g->lightning === null ? null : ['x' => (float) $g->lightning['x'], 'z' => (float) $g->lightning['z'],                't' => $this->clock - ($g->clock - (float) $g->lightning['t'])];            $v->raft = $g->raft === null ? null : ['x' => $g->raft['x'], 'z' => $g->raft['z'], 'yaw' => $g->raft['yaw']];            $list = [];            foreach ($g->burnt[$g->zone->id] ?? [] as [$bx, $bz, $br]) {                $list[] = ['x' => $bx, 'z' => $bz, 'r' => $br];            }            $v->burnt = $list;            $this->entities = $g->creatures;            foreach ($g->npcs as $n) {                $this->entities[] = $n;            }            $v->entities = $this->entities;            $hand = $g->inv->hand !== null && $g->inv->has($g->inv->hand) ? $g->inv->hand : null;            $left = $g->inv->handLeft !== null && $g->inv->has($g->inv->handLeft) ? $g->inv->handLeft : null;            $shown = fn (?string $id): bool => $id !== null && $this->mode !== 'title' && (Items::get($id)['kind'] === 'weapon' || $id === 'torch' || $id === 'raft_pole' || Inventory::isShield($id));            $v->held = $shown($hand) ? $hand : null;            $v->heldLeft = $shown($left) ? $left : null;            // the blow under way and the torch's sweep (their poses: Render\HeldPose)            $sw = $this->mode === 'title' ? null : $g->swing;            $v->attackPhase = $sw === null ? 0.0 : $g->swingPhase();            $v->attackKind = $sw['kind'] ?? 'swing';            $v->attackStrike = $sw === null ? 0.4 : $sw['at'] / max(0.01, $sw['dur']);            $v->attackSide = $sw['side'] ?? 'right';            $v->brandish = $this->mode === 'title' ? 0.0 : $g->brandishPhase();            $v->guard = $this->mode === 'title' ? 0.0 : $g->guardPhase();            // a blow that lands nudges the view; a shot kicks it up            $since = $g->clock - $g->hitAt;            if ($since >= 0 && $since < 0.25) {                $k = 1 - $since / 0.25;                $v->yaw += sin($since * 55.0) * 0.008 * $k;                $v->pitch -= 0.018 * $k;            }            if ($sw !== null && $sw['done'] && in_array($sw['kind'], ['gun', 'crossbow'], true)) {                $a = ($sw['t'] - $sw['at']) / 0.35;                if ($a >= 0 && $a < 1) {                    $v->pitch += ($sw['kind'] === 'gun' ? 0.045 : 0.025) * (1 - $a) * (1 - $a);                }            }            if ($g->raft !== null && $hand === null && $g->inv->has('raft_pole')) {                $v->held = 'raft_pole';            }            $v->hurt = $g->hurt;            $v->time = $this->clock;            $v->bob = ($g->running ? 1.0 : ($g->moving ? ($g->crouching ? 0.25 : 0.5) : 0.0)) * self::BOB_SCALE[$this->bobMode];            $t0 = microtime(true);            $this->gfx->render($v);            $this->renderMs = $this->renderMs * 0.9 + (microtime(true) - $t0) * 100;            return;        }        $this->fallback($r, $g);    }    /** Without OpenGL: the land seen from above, around Rob (headless tests, old machines). */    private function fallback(Renderer $r, Game $g): void    {        $r->clear($g->zone->cave ? [22, 20, 18] : [40, 62, 38]);        $w = $this->width();        $h = $this->height();        $cx = $w / 2;        $cy = $h / 2 - 10;        $k = 2.0;        $z = $g->zone;        foreach ($z->thingsNear($g->x, $g->z, 80) as $t) {            $px = $cx + ($t->x - $g->x) * $k;            $py = $cy + ($t->z - $g->z) * $k;            if ($px < 0 || $py < 0 || $px >= $w || $py >= $h) {                continue;            }            $col = match (true) {                str_starts_with($t->kind, 'tree') => [30, 90, 40],                str_starts_with($t->kind, 'bush') => [60, 120, 50],                in_array($t->kind, ['rock', 'boulder', 'flint', 'stone_small'], true) => [120, 116, 110],                $t->kind === 'water_spring' => [80, 150, 220],                default => [200, 180, 120],            };            $r->fillRect($px - 1.5, $py - 1.5, 3, 3, $col);        }        if ($z->water > -999) {            for ($dz = -50; $dz <= 50; $dz += 4) {                for ($dx = -70; $dx <= 70; $dx += 4) {                    if ($z->waterDepth($g->x + $dx, $g->z + $dz) > 0) {                        $r->fillRect($cx + $dx * $k - 4, $cy + $dz * $k - 4, 8, 8, [50, 100, 150, 160]);                    }                }            }        }        foreach ($g->creatures as $c) {            $r->fillRect($cx + ($c->x - $g->x) * $k - 2, $cy + ($c->z - $g->z) * $k - 2, 4, 4, [220, 70, 60]);        }        foreach ($g->npcs as $n) {            $r->fillRect($cx + ($n->x - $g->x) * $k - 2, $cy + ($n->z - $g->z) * $k - 2, 4, 4, $n->hostile ? [230, 80, 40] : [120, 200, 240]);        }        foreach ($g->fires as $f) {            $r->fillCircle($cx + ($f['x'] - $g->x) * $k, $cy + ($f['z'] - $g->z) * $k, 3, [255, 150, 40]);        }        $fx = sin($g->yaw);        $fz = cos($g->yaw);        $r->drawLine($cx, $cy, $cx + $fx * 10, $cy + $fz * 10, [255, 255, 255]);        $r->fillRect($cx - 2, $cy - 2, 4, 4, [255, 255, 255]);    }    /** The overlay: the dashboard and the screens at the window's resolution. */    private function drawUi(Renderer $r): void    {        $c = $this->canvas;        if ($c === null) {            return;        }        $t0 = microtime(true);        if ($this->shotWanted) {            // the 3D view, before the dashboard is drawn over it: a save's preview            $this->shotWanted = false;            $png = $this->gfx !== null && $this->game !== null ? SavePreview::capture($r) : null;            if ($png !== null) {                $this->snapshot = $png;                $this->snapshotAt = $this->game->minutes;                $this->snapshotZone = $this->game->zone->id;                if ($this->shotFor !== null) {                    $this->saves->setPreview($this->shotFor, $png);                }            }            $this->shotFor = null;        }        $c->begin($r);        $g = $this->game;        switch ($this->mode) {            case 'loading':                $this->drawLoading($c);                break;            case 'title':                $this->drawTitle($c);                break;            case 'options':                if ($this->optionsFrom === 'pause' && $g !== null) {                    $this->hud->draw($c, $g, $this->data);                } else {                    $this->drawTitleBack($c);                }                $this->drawMenuCard($c, 'Options', null);                break;            case 'pause':                if ($g !== null) {                    $this->hud->draw($c, $g, $this->data);                }                $this->drawMenuCard($c, 'Pause', $g?->clock());                break;            case 'dead':                $this->drawDeath($c);                break;            case 'askleave':                if ($g !== null) {                    $this->hud->draw($c, $g, $this->data, true);                }                $this->drawMenuCard($c, 'Sauvegarder avant de quitter ?', 'Ta progression depuis ta dernière sauvegarde n\'est pas dans tes parties.');                break;            case 'saves':                if ($this->savesFrom === 'pause' && $g !== null) {                    $this->hud->draw($c, $g, $this->data, true);                } elseif ($this->savesFrom === 'title') {                    $this->drawTitleBack($c);                }                $this->saveScreen?->draw($c);                break;            case 'controls':                if ($g !== null) {                    $this->hud->draw($c, $g, $this->data, true);                }                $this->controls->draw($c, $this->touch, $this->controlsFirst, $this->clock);                break;            case 'won':                $this->drawVictory($c);                break;            case 'screen':                if ($g !== null) {                    $this->screens?->draw($c, $g, $this->data);                }                break;            case 'sleep':                if ($g !== null) {                    if ($this->sleepView->phase === 'choose') {                        $this->hud->draw($c, $g, $this->data, true);                    }                    $this->sleepView->draw($c, $g);                }                break;            case 'vitals':                if ($g !== null) {                    $this->hud->draw($c, $g, $this->data, true);                    $this->vitals->draw($c);                }                break;            case 'chest':                if ($g !== null) {                    if (!$this->touch) {                        $this->hud->draw($c, $g, $this->data, true);                    }                    $this->chestView->draw($c, $g);                }                break;            default:                if ($g !== null) {                    $talking = $g->dialogue() !== null;                    $this->hud->draw($c, $g, $this->data, $talking);                    if ($talking) {                        $this->drawDialogue($c, $g);                    }                }        }        if ($this->fade > 0.01 && $this->mode !== 'controls') {            $c->rect(0, 0, Canvas::W, Canvas::H, [0, 0, 0, (int) (255 * min(1.0, $this->fade))]);        }        if ($this->saveNote !== '' && $this->saveNoteAge < 2.5) {            $c->panel(380, 120, 200, 36, 200);            $c->text($this->saveNote, 480, 128, 16, [230, 255, 236], 'center');        }        if ($this->toast !== '' && $this->toastAge < 5.0) {            $w = min(900.0, $c->measure($this->toast, 15) + 36);            $c->panel(480 - $w / 2, 164, $w, 34, 210, [255, 196, 90]);            $c->text($this->toast, 480, 172, 15, [255, 240, 214], 'center');        }        if ($this->showFps) {            $fps = $this->adaptive->fps;            $label = ($fps > 0 ? sprintf('%d i/s', (int) round($fps)) : '… i/s') . '  ·  ' . $this->qualityLabel();            $c->text($label, 944, 6, 12, $fps > 0 && $fps < AdaptiveQuality::SLOW_FPS ? [255, 170, 120] : [200, 255, 200], 'right');        }        if ($this->softPanel) {            $this->drawSoftPanel($c);        }        if ($this->quitting) {            // the browser's page takes over (back link, portal, "thanks for playing"): meanwhile, a word            $c->rect(0, 0, Canvas::W, Canvas::H, [0, 0, 0, 160]);            $c->text('À bientôt !', 480, 340, 26, [236, 240, 244], 'center');        }        $c->end();        $this->uiMs = $this->uiMs * 0.9 + (microtime(true) - $t0) * 100;        if ((bool) Platform::setting('JUMPHP_DEBUG', false)) {            $c->text(sprintf('PHP  update %.2f ms  ·  3D %.2f ms  ·  HUD %.2f ms', $this->frameMs, $this->renderMs, $this->uiMs), 950, 100, 12, [255, 255, 0], 'right');        }    }    /** "Rendu logiciel": why the game is slow and how to turn the graphics card on. */    private function drawSoftPanel(Canvas $c): void    {        $c->rect(0, 0, Canvas::W, Canvas::H, [0, 0, 0, 150]);        $x = 150.0;        $w = 660.0;        $lines = $c->wrap(self::SOFT_TEXT, 17, $w - 60);        $h = 128 + count($lines) * 26;        $y = (Canvas::H - $h) / 2;        $c->panel($x, $y, $w, $h, 235, [255, 170, 80]);        $c->text('Le jeu va être lent sur ce navigateur', $x + $w / 2, $y + 18, 22, [255, 214, 150], 'center');        foreach ($lines as $i => $line) {            $c->text($line, $x + 30, $y + 62 + $i * 26, 17, [236, 240, 244]);        }        $by = $y + $h - 52;        $hover = $this->ui->hover === 'soft:ok';        $c->pill($x + $w / 2 - 80, $by, 160, 36, $hover ? [255, 190, 100] : [210, 140, 60]);        $c->text('Compris', $x + $w / 2, $by + 8, 18, [20, 14, 8], 'center', false);        $c->hit($x + $w / 2 - 80, $by, 160, 36, 'soft:ok');        if ($this->gpu !== '') {            $c->text('Rendu : ' . $this->gpu, $x + $w - 14, $by + 40, 11, [150, 160, 170], 'right');        }    }    private function drawLoading(Canvas $c): void    {        $c->rect(0, 0, Canvas::W, Canvas::H, [8, 10, 14]);        $c->panel(330, 320, 300, 80, 200);        $c->text('Chargement…', 480, 334, 24, [240, 244, 248], 'center');        $name = $this->game?->zone->name ?? '';        $c->text($name, 480, 368, 15, [160, 176, 190], 'center');        $p = 0.25 + 0.5 * (0.5 + 0.5 * sin($this->clock * 4));        $c->rect(350, 392, 260, 3, [255, 255, 255, 30]);        $c->rect(350, 392, 260 * $p, 3, [150, 210, 255, 200]);    }    private function drawTitleBack(Canvas $c): void    {        if ($this->gfx === null) {            $c->rect(0, 0, Canvas::W, Canvas::H, [10, 18, 22]);        }        $c->rect(0, 0, Canvas::W, 260, [0, 0, 0, 70]);        $c->rect(0, 0, Canvas::W, 120, [0, 0, 0, 60]);    }    private function drawTitle(Canvas $c): void    {        $this->drawTitleBack($c);        $c->text('EXPÉRIENCE', 480, 52, 22, [190, 214, 230], 'center');        $c->text('ROB REVISITED', 480, 80, 56, [255, 255, 255], 'center');        $c->rect(380, 150, 200, 2, [255, 196, 80, 220]);        $story = 'Rob Calder, pilote de reconnaissance de la station Meridian, s\'écrase sur Ysor, une lune que personne n\'a cartographiée. '            . 'Sa balise est morte, et aucune navette du Meridian ne peut descendre. Quelque part sur la côte volcanique dort la navette de la mission Halde, '            . 'disparue il y a soixante ans, dépouillée par ses propres colons. Il faudra survivre — l\'eau, le feu, les bêtes, le froid — '            . 'puis gagner la confiance, ou la crainte, de leurs descendants pour s\'évader.';        $lines = $c->wrap($story, 16, 624);        $lh = $c->lineH(16, 1.2);        $c->panel(150, 170, 660, 24 + $lh * count($lines), 150);        foreach ($lines as $i => $line) {            $c->text($line, 168, 182 + $i * $lh, 16, [226, 232, 238]);        }        $top = min(200 + $lh * count($lines) + 20, Canvas::H - 8 - (24 + 44 * count($this->menu->rows)));        [$mx, $mw] = $this->menuFrame(360.0);        $c->panel($mx, $top, $mw, 24 + 44 * count($this->menu->rows), 190);        $this->menu->draw($c, $mx + 12, $top + 12, $mw - 24);        if (!$this->touch) {            $c->text('Qualité : ' . $this->qualityLabel() . '   ·   ↑ ↓ et Entrée, ou la souris', 480, 690, 12, [170, 184, 196], 'center');        }    }    /**     * Where the menu panels stand: centred, $w units wide; on a phone (bigger text) much wider.     * @return array{0: float, 1: float} x, width     */    private function menuFrame(float $w = 380.0): array    {        $w = $this->touch ? 700.0 : $w;        return [(Canvas::W - $w) / 2, $w];    }    private function drawMenuCard(Canvas $c, string $title, ?string $sub): void    {        $c->rect(0, 0, Canvas::W, Canvas::H, [4, 8, 12, 130]);        [$mx, $mw] = $this->menuFrame();        // the subtitle: up to two lines (a question explained), the rows below it        $subText = (string) $sub;        $sub = $subText !== '' ? $c->fit($subText, 14, $mw - 32 - 2 * Canvas::PAD, 2) : null;        $subH = $sub === null ? 0.0 : max(0.0, (count($sub['lines']) - 1) * $sub['size'] * 1.3 * $c->boost);        $h = 96 + $subH + 44 * count($this->menu->rows);        $y = 360 - $h / 2;        $c->panel($mx, $y, $mw, $h, 215);        $c->text($title, 480, $y + 18, 28, [255, 255, 255], 'center');        if ($sub !== null) {            $c->textBox($subText, $mx + 16, $y + 54, $mw - 32, 14, [170, 186, 200], 'center', 2, 1.3);        }        $this->menu->draw($c, $mx + 16, $y + 80 + $subH, $mw - 32);    }    /** the colour tag of an answer's tone (the player sees how it sounds before choosing) */    private const TONES = [        'kind' => ['gentil', [130, 220, 150]], 'honest' => ['franc', [150, 200, 255]], 'lie' => ['mensonge', [230, 160, 255]],        'threat' => ['menace', [255, 120, 100]], 'gift' => ['cadeau', [255, 214, 120]], 'joke' => ['plaisanterie', [255, 190, 230]],        'flatter' => ['flatterie', [240, 230, 140]], 'trade' => ['commerce', [180, 220, 200]],    ];    private function drawDialogue(Canvas $c, Game $g): void    {        $d = $g->dialogue();        if ($d === null) {            return;        }        $phone = $this->touch;        // phones: the whole width, tall rows for the fingers        [$x0, $w] = $phone ? [16.0, 928.0] : [140.0, 680.0];        $rowH = $phone ? 52.0 : 30.0;        $gap = $phone ? 6.0 : 4.0;        $ts = $phone ? 18.0 : 17.0;        $lines = $c->wrap($d['text'], $ts, $w - 40);        $lh = $ts * ($phone ? 1.75 : 1.3) * $c->boost;        $n = count($d['choices']);        $tones = $d['tones'] ?? [];        $head = isset($d['who']) ? ($phone ? 104.0 : 72.0) : ($phone ? 64.0 : 50.0);        $h = $head + 12 + $lh * count($lines) + ($rowH + $gap) * $n + 10;        $h = min($h, 712.0);        $y = max(4.0, ($phone ? 714 : 610) - $h);        $c->rect(0, 0, Canvas::W, Canvas::H, [0, 0, 0, $phone ? 120 : 70]);        $c->panel($x0, $y, $w, $h, 225, [255, 196, 80, 230]);        $c->text($d['npc'], $x0 + 20, $y + 12, 20, [255, 204, 110]);        if (isset($d['attitude'])) {            $c->text($d['attitude'], $x0 + $w - 20, $y + 14, 14, match ($d['attitude']) {                'hostile' => [255, 110, 100], 'méfiant' => [255, 170, 110], 'réservé' => [210, 214, 220], 'amical' => [150, 220, 160], default => [120, 230, 200],            }, 'right');        }        if (isset($d['who'])) {            $c->text($d['who'], $x0 + 20, $y + ($phone ? 54 : 40), 12, [160, 172, 184]);        }        foreach ($lines as $i => $line) {            $c->text($line, $x0 + 20, $y + $head + $i * $lh, $ts, [236, 240, 244]);        }        $cy = $y + $head + 12 + $lh * count($lines);        foreach ($d['choices'] as $i => $choice) {            if ($cy + $rowH > $y + $h) {                break;            }            $on = $i === $this->dialogueSel;            $c->rect($x0 + 12, $cy, $w - 24, $rowH, $on ? [120, 190, 255, 60] : [255, 255, 255, $phone ? 14 : 0]);            if ($on) {                $c->rect($x0 + 12, $cy, 3, $rowH, [150, 210, 255, 230]);            }            $ty = $cy + ($rowH - 16 * $c->boost) / 2 - 1;            $c->text(($i + 1) . '.', $x0 + 26, $ty, 16, [150, 210, 255]);            $tag = self::TONES[$tones[$i] ?? ''] ?? null;            $tx = $x0 + 52;            if ($tag !== null) {                $tx += $c->text(Translator::keep('[' . Translator::t($tag[0]) . ']'), $tx, $ty + 2, 12, $tag[1]) + 8;            }            $c->text($choice, $tx, $ty, 16, $on ? [255, 255, 255] : [206, 214, 222]);            $c->hit($x0 + 12, $cy, $w - 24, $rowH, 'choice:' . $i);            $cy += $rowH + $gap;        }    }    private function drawDeath(Canvas $c): void    {        $g = $this->game;        $c->rect(0, 0, Canvas::W, Canvas::H, [40, 0, 0, 170]);        $c->text('ROB CALDER EST MORT', 480, 150, 40, [255, 210, 200], 'center');        $c->text($g !== null ? 'Jour ' . $g->day() . ' sur Ysor' : '', 480, 206, 18, [230, 170, 160], 'center');        $cause = $g?->over() ?? '';        foreach ($c->wrap($cause, 18, 620) as $i => $line) {            $c->text($line, 480, 246 + $i * 24, 18, [240, 230, 226], 'center');        }        [$mx, $mw] = $this->menuFrame();        $c->panel($mx, 360, $mw, 24 + 44 * count($this->menu->rows), 200);        $this->menu->draw($c, $mx + 16, 372, $mw - 32);    }    private function drawVictory(Canvas $c): void    {        $g = $this->game;        $c->rect(0, 0, Canvas::W, Canvas::H, [0, 8, 24, 190]);        $escaped = $g !== null && !empty($g->flags['q_launch']);        $c->text($escaped ? 'ÉVADÉ' : 'SAUVÉ', 480, 34, 46, [255, 255, 255], 'center');        $paras = $escaped ? Escape::ending($g) : ['Rob Calder rentre chez lui, avec le dernier journal de la mission Halde.'];        $y = 104.0;        $shown = (int) floor($this->wonTime / 2.2) + 1;     // the ending comes paragraph by paragraph        foreach (array_slice($paras, 0, $shown) as $p) {            foreach ($c->wrap($p, 15, 760) as $line) {                $c->text($line, 480, $y, 15, [226, 236, 246], 'center');                $y += 20 * $c->boost;            }            $y += 8;        }        if ($g !== null) {            $c->text(sprintf('%d jours sur Ysor  ·  %d nuits  ·  %d feux  ·  %d bêtes abattues', $g->day(), (int) ($g->flags['nights'] ?? 0),                (int) ($g->flags['fires'] ?? 0), (int) ($g->flags['kills'] ?? 0)), 480, max($y + 6, 470), 13, [180, 200, 220], 'center');        }        if ($shown > count($paras)) {            foreach (Escape::credits() as $i => $line) {                $c->text($line, 480, 500 + $i * 18, $i === 0 ? 14 : 12, $i === 0 ? [255, 214, 140] : [150, 166, 182], 'center');            }        }        $mh = 24 + 44 * count($this->menu->rows);        [$mx, $mw] = $this->menuFrame();        $c->panel($mx, 712 - $mh - 4, $mw, $mh, 200);        $this->menu->draw($c, $mx + 16, 712 - $mh + 8, $mw - 32);    }}