IT
games/alis / src / Alis / fn / sys.php · commit 9c722cf
<?phpnamespace App\Alis;// Host layer of the ALIS port: what alis/src/sys/sys.c + sys_sdl2.c do with SDL, done with JumPHP.// Never blocks: the VM runs one frame per call of Machine::frame() (see Machine.php); delays are no-ops,// input is a snapshot taken by the scene before each frame, the screen is turned into a BMP image// that the scene draws.// ---------------------------------------------------------------------------------------------// Dirty rectangles (only used by the C SDL backend to limit uploads: kept for the callers)// ---------------------------------------------------------------------------------------------function dirty_all(): void{    SysVars::$dirty_len = 0xff;}function dirty_add(int $x, int $y, int $w, int $h): void{    if (SysVars::$dirty_len >= 0xfe) {        dirty_all();        return;    }    SysVars::$dirty_len++;}// ---------------------------------------------------------------------------------------------// Timing// ---------------------------------------------------------------------------------------------/** VM pace (the original VBL rate): 50 Hz on European machines, 60 Hz on the Mac and PC VGA (C sys_pace_hz). */function sys_pace_hz(): int{    return 50;}function sys_music_hz(): int{    return 50;}function sys_init_timers(): void{}function sys_delay_loop(): void{}/** C: sleeps until the next frame. The port paces frames in Machine::frame(). */function sys_delay_frame(): void{}/** C: interruptible delay during loads (cosmetic): no delay in the port. */function sys_sleep_interactive(int &$loop, int $intr): void{    $loop = 0;}function sys_sleep_until_music_stops(): void{}function sys_msec(): int{    return SysVars::$msec;}function sys_ticks(): int{    return SysVars::$msec;}function sys_delay(int $ms): void{}function sys_set_time(int $h, int $m, int $s): void{}function sys_get_time(): int{    return 0;}function sys_random(): int{    // C: rand() & 0xffff, never seeded (srand is not called): the same numbers at every start. PHP's mt_rand()    // is seeded at random by PHP, which made two identical runs diverge (crandom with D7 = 0 at the first frame).    // The C library's classic generator (ANSI C example: next = next * 1103515245 + 12345, 15 bits), kept in    // SysVars and reset at each boot; 32-bit safe for the browser.    SysVars::$randSeed = s32(mul32(SysVars::$randSeed, 1103515245) + 12345);    return (SysVars::$randSeed >> 16) & 0x7fff;}function sys_lock_renderer(): void{}function sys_unlock_renderer(): void{}function sys_isr_pause(int $on): void{}function sys_free_bytes(string $path, int $cap): int{    return $cap;}/** C sys_get_model(): the machine model the scripts test (memory / video class). */function sys_get_model(): int{    $pl = Alis::$platform;    switch ($pl->kind) {        case C::EPlatformAtari:            return Alis::$memclass ? (Alis::$memclass + ($pl->version < 20 ? 0 : 100)) : ($pl->version < 20 ? 1010 : 1120);        case C::EPlatformPC:            return $pl->version > 11 && $pl->version < 30 ? 2004 : 2000;        case C::EPlatformAmiga:            return 3000;        case C::EPlatformMac:            return 4001;        case C::EPlatformFalcon:            return 5000;        case C::EPlatformAmigaAGA:            return 6000;        default:            return 4000;    }}// ---------------------------------------------------------------------------------------------// Lifecycle// ---------------------------------------------------------------------------------------------function sys_init(Platform $pl, int $fullscreen, int $mutesound): void{}function sys_start(): int{    return 1;}function sys_deinit(): void{}function sys_restore_desktop(): void{}function sys_errors_init(): void{}function sys_errors_deinit(): void{}/** C: renders, reads the mouse and drains the event queue. Input is already a snapshot of this frame. */function sys_poll_event(): void{    sys_render(Host::$pixelbuf);}// ---------------------------------------------------------------------------------------------// Screen// ---------------------------------------------------------------------------------------------/** * C sys_render(): converts the 8-bit frame (host.pixelbuf.data, palette image.mpalet) to an image. * Here: an 8-bit BMP (header + palette + the pixel bytes, no per-pixel loop) kept in SysVars::$frameBmp; * the scene uploads it as a texture. Per-line palettes (image.flinepal) use a 24-bit BMP built with strtr. */function sys_render(PixelBuf $buffer): void{    SysVars::$dirty_len = 0;    $w = $buffer->w;    $h = $buffer->h;    if ($w <= 0 || $h <= 0) {        return;    }    if (SysVars::$dirty_mouse) {        SysVars::$dirty_mouse = false;        sys_dirty_mouse();    }    $pixels = substr(Alis::$mem, $buffer->data, $w * $h);    $palette = Img::$mpalet;    if ($buffer->rgb) {        // true colour (3DO): host.pixelbuf.rgb = image.rgbphysic, 3 bytes B, G, R per pixel (image_v6.php)        $data = substr(Alis::$mem, $buffer->rgb, $w * $h * 3);        $padn = (4 - ($w * 3) % 4) % 4;        if ($padn) {            $data = implode(str_repeat("\0", $padn), str_split($data, $w * 3)) . str_repeat("\0", $padn);        }        SysVars::$frameBmp = sys_bmp_header($w, $h, 24, strlen($data)) . $data;    } elseif (($film = film_render_rgb()) !== null) {        SysVars::$frameBmp = $film;    // HAM6 / Spectrum 512 film frame (video.php)    } elseif (Img::$flinepal) {        SysVars::$frameBmp = sys_bmp24($pixels, $w, $h, sys_line_palettes($h));    } else {        $pal = '';        for ($i = 0; $i < 256; $i++) {            $c = $palette[$i] ?? 0;            $pal .= chr($c & 0xff) . chr(($c >> 8) & 0xff) . chr(($c >> 16) & 0xff) . "\0";        }        SysVars::$frameBmp = sys_bmp_header($w, $h, 8, strlen($pixels)) . $pal . $pixels;    }    SysVars::$frameW = $w;    SysVars::$frameH = $h;    SysVars::$frameCount++;    if (SysVars::$hdText) {        hd_glyphs_shown($pixels, $w, $h, $palette);    }    if (HdSprites::$on && !$buffer->rgb && !Img::$flinepal) {        HdSprites::shown($pixels, $w, $h, $palette);    }    // HD edition: the land at twice the resolution, where the screen shows it (fn/hd3d.php)    SysVars::$hdLand = null;    if (Hd3d::$on && Hd3d::$pending !== null) {        hd3d_deferred();    }    if (Hd3d::$on && !$buffer->rgb && !Img::$flinepal && ($shown = hd3d_shown($pixels, $w, $h)) !== null) {        [$lx, $ly, $lw, $lh, $ls, $lpix, $lkey] = $shown;        $pal = '';        for ($i = 0; $i < 256; $i++) {            $c = $palette[$i] ?? 0;            $pal .= chr($c & 0xff) . chr(($c >> 8) & 0xff) . chr(($c >> 16) & 0xff) . "\0";        }        SysVars::$hdLand = ['x' => $lx, 'y' => $ly, 'w' => $lw, 'h' => $lh, 'key' => $lkey,            'bmp' => sys_bmp_header($lw * $ls, $lh * $ls, 8, strlen($lpix)) . $pal . $lpix];    }    if (Trace::on()) {        Trace::picture($pixels, $w, $h, $buffer->data);    }    if (Hd3d::$on && Trace::on()) {        $why = $buffer->rgb ? 'rgb' : (Img::$flinepal ? 'linepal' : Hd3d::$why);        Trace::shown(SysVars::$hdLand !== null, $why, Hd3d::$differ, Hd3d::$land);    }}/** BMP file + info header, top-down rows (negative height). */function sys_bmp_header(int $w, int $h, int $bpp, int $dataSize): string{    $palSize = $bpp === 8 ? 1024 : 0;    return 'BM' . pack('VvvV', 54 + $palSize + $dataSize, 0, 0, 54 + $palSize)        . pack('VVVvvVVVVVV', 40, $w, -$h, 1, $bpp, 0, $dataSize, 2835, 2835, $bpp === 8 ? 256 : 0, 0);}/** * The palette offset of each line (C image.firstpal list, see sys_render of sys_sdl2.c): a list of * [first line, palette offset] sorted by line, returned as offset per line. * @return int[] */function sys_line_palettes(int $h): array{    $offsets = array_fill(0, $h, 0);    $list = image_line_palettes(); // [[y, paloff], ...] from image.php (C firstpal walk)    $cur = 0;    $n = count($list);    $k = 0;    for ($y = 0; $y < $h; $y++) {        while ($k < $n && $y >= $list[$k][0]) {            $cur = $list[$k][1];            $k++;        }        $offsets[$y] = $cur;    }    return $offsets;}/** 24-bit BMP of an 8-bit frame with a palette offset per line (rows padded to 4 bytes). */function sys_bmp24(string $pixels, int $w, int $h, array $lineOffsets): string{    $palette = Img::$mpalet;    $maps = [];    $pad = str_repeat("\0", (4 - ($w * 3) % 4) % 4);    $data = '';    for ($y = 0; $y < $h; $y++) {        $off = $lineOffsets[$y];        if (!isset($maps[$off])) {            $map = [];            for ($i = 0; $i < 256; $i++) {                $c = $palette[$i + $off] ?? 0; // C: index + paloff, no mask                $map[chr($i)] = chr($c & 0xff) . chr(($c >> 8) & 0xff) . chr(($c >> 16) & 0xff);            }            $maps[$off] = $map;        }        $data .= strtr(substr($pixels, $y * $w, $w), $maps[$off]) . $pad;    }    return sys_bmp_header($w, $h, 24, strlen($data)) . $data;}function sys_get_framebuffer(int $index): int{    return $index ? Img::$physic : Img::$logic;}function sys_blit_frame_sync(): void{}// ---------------------------------------------------------------------------------------------// Mouse// ---------------------------------------------------------------------------------------------function sys_get_mouse(): MouseT{    return clone SysVars::$mouse;}function sys_consume_mouse(): MouseT{    $snap = clone SysVars::$mouse;    SysVars::$mouse->lb_clicked = 0;    SysVars::$mouse->rb_clicked = 0;    return $snap;}function sys_set_mouse(int $x, int $y): void{    SysVars::$mouse->x = $x & 0xffff;    SysVars::$mouse->y = $y & 0xffff;}/** The v3 DOS VM (Robinson's Requiem: version 30..59, PC, little endian), checked against the original executable. */function sys_is_dos_v3(): bool{    return Alis::$platform->kind == C::EPlatformPC && Alis::$platform->version >= 30        && Alis::$platform->version < 60 && Alis::$platform->is_little_endian;}/** * v3 DOS setmouse (0x28f1): the hardware mouse never moves; a negative x resets the offset, otherwise the * offset makes cmouse report (x, y) from now on and then follow the real moves. */function sys_set_mouse_offset(int $x, int $y): void{    if (s16($x) < 0) {        SysVars::$mouseOffX = SysVars::$mouseOffY = 0;        return;    }    SysVars::$mouseOffX = s16(s16($x) - SysVars::$mouse->x);    SysVars::$mouseOffY = s16(s16($y) - SysVars::$mouse->y);}function sys_enable_mouse(int $enable): void{    SysVars::$mouse->enabled = $enable & 0xff;    // The v3 DOS mousoff (0x98b1) only hides the cursor: its descriptor lives until the next defmouse,    // so a mousoff / mouson pair brings the same cursor back.    if (!SysVars::$mouse->enabled && Alis::$platform->version < 60 && !sys_is_dos_v3()) {        Alis::$desmouse = 0;    }    SysVars::$dirty_mouse = true;}function set_update_cursor(): void{    SysVars::$dirty_mouse = true;}/** * C sys_dirty_mouse(): builds the cursor image from alis.desmouse (a sprite descriptor in memory). * The port decodes it into SysVars::$cursor (a list of rows of palette indexes, -1 = transparent); * the scene draws it over the frame. */function sys_dirty_mouse(): void{    SysVars::$cursorVersion++;    if (Alis::$desmouse === 0) {        SysVars::$cursor = null;        return;    }    SysVars::$cursor = image_mouse_cursor(Alis::$desmouse); // image.php: decode like sys_dirty_mouse of sys_sdl2.c}function sys_mouse_erase(): void{}function sys_mouse_uncopy(): void{}function sys_mouse_draw(): void{}function sys_flip_wait(): void{}// ---------------------------------------------------------------------------------------------// Keyboard / joystick (C io_* of sys.c, SDL key codes)// ---------------------------------------------------------------------------------------------function sys_key_held(int $sym): bool{    return isset(SysVars::$held[$sym]);}/** C io_inkey(): the last key pressed while it is still held, as an ALIS key code (0 = none). */function io_inkey(): int{    if (!sys_key_held(SysVars::$button)) {        SysVars::$button = 0;        // (not in the C) another arrow still held takes over: a diagonal of the phone's stick (up + left, then        // left let go) keeps walking instead of stopping        foreach (array_reverse(array_keys(SysVars::$held)) as $held) {            if ($held === \SDLK_UP || $held === \SDLK_DOWN || $held === \SDLK_LEFT || $held === \SDLK_RIGHT) {                SysVars::$button = $held;                break;            }        }    }    $sym = SysVars::$button;    switch ($sym) {        case 0:            return 0;        case \SDLK_ESCAPE:            return 0x1b;        case \SDLK_UP:            return 0xc8;        case \SDLK_DOWN:            return 0xd0;        case \SDLK_LEFT:            return 0xcb;        case \SDLK_RIGHT:            return 0xcd;        case \SDLK_KP_0:            return 0x30;        case \SDLK_KP_1:            return 0x31;        case \SDLK_KP_2:            return 0x32;        case \SDLK_KP_3:            return 0x33;        case \SDLK_KP_4:            return 0x34;        case \SDLK_KP_5:            return 0x35;        case \SDLK_KP_6:            return 0x36;        case \SDLK_KP_7:            return 0x37;        case \SDLK_KP_8:            return 0x38;        case \SDLK_KP_9:            return 0x39;        case \SDLK_KP_PLUS:            return 0x2b;        case \SDLK_KP_MINUS:            return 0x2d;        case \SDLK_KP_ENTER:            return 0x0d;        case \SDLK_LSHIFT:        case \SDLK_RSHIFT:        case \SDLK_LCTRL:        case \SDLK_RCTRL:        case \SDLK_LALT:        case \SDLK_RALT:        case \SDLK_CAPSLOCK:            return 0;    }    if ($sym >= \SDLK_F1 && $sym <= \SDLK_F10) {        return 0xbb + ($sym - \SDLK_F1);    }    if (sys_key_held(\SDLK_LSHIFT) || sys_key_held(\SDLK_RSHIFT)) {        $shifted = [\SDLK_1 => '!', \SDLK_2 => '@', \SDLK_3 => '#', \SDLK_4 => '$', \SDLK_5 => '%', \SDLK_6 => '^',            \SDLK_7 => '&', \SDLK_8 => '*', \SDLK_9 => '(', \SDLK_0 => ')', \SDLK_MINUS => '_', \SDLK_EQUALS => '+'];        if (isset($shifted[$sym])) {            return ord($shifted[$sym]);        }    }    return $sym & 0xff; // C returns (u8)button.sym}/** * C io_getkey() blocks until a key is pressed (then released). Non-blocking port: without a key, the * current opcode is restarted at the next frame (vm_yield_retry); with one, the key is consumed so the * next call waits for a new press (the C waits for the release). */function io_getkey(): int{    $k = io_inkey();    if ($k === 0) {        vm_yield_retry();    }    SysVars::$button = 0;    return $k;}/** Shift, Ctrl, Alt, Caps Lock: keys that change the others (shiftkey()), never the key inkey() reads. */function sys_is_modifier(int $sym): bool{    return in_array($sym, [\SDLK_LSHIFT, \SDLK_RSHIFT, \SDLK_LCTRL, \SDLK_RCTRL, \SDLK_LALT, \SDLK_RALT, \SDLK_CAPSLOCK, \SDLK_LGUI, \SDLK_RGUI], true);}function io_shiftkey(): int{    $s = SysVars::$shift;    // BIOS bits: 1 = right Shift, 2 = left Shift. Robinson's Requiem runs with left Shift only (yoda.als:    // shiftkey() & 2): either Shift gives both bits, as a player expects    $shift = sys_key_held(\SDLK_RSHIFT) || sys_key_held(\SDLK_LSHIFT);    $s = $shift ? $s | 3 : $s & 0xfc;    $s = (sys_key_held(\SDLK_LCTRL) || sys_key_held(\SDLK_RCTRL)) ? $s | 4 : $s & 0xfb;    $s = (sys_key_held(\SDLK_LALT) || sys_key_held(\SDLK_RALT)) ? $s | 8 : $s & 0xf7;    $s &= 0xef;    SysVars::$shift = $s;    return $s;}/** Atari joystick byte: bit0 up, bit1 down, bit2 left, bit3 right, bit7 fire. */function sys_joy_compose(int $with_mouse_fire, int $with_keys): int{    $b = SysVars::$pad; // gamepad / touch directions + fire, set by the scene    if ($with_keys) {        $a = 0;        if (sys_key_held(\SDLK_UP) || sys_key_held(\SDLK_KP_8) || sys_key_held(\SDLK_KP_7) || sys_key_held(\SDLK_KP_9)) {            $a |= 0x01;        }        if (sys_key_held(\SDLK_DOWN) || sys_key_held(\SDLK_KP_2) || sys_key_held(\SDLK_KP_1) || sys_key_held(\SDLK_KP_3)) {            $a |= 0x02;        }        if (sys_key_held(\SDLK_LEFT) || sys_key_held(\SDLK_KP_4) || sys_key_held(\SDLK_KP_7) || sys_key_held(\SDLK_KP_1)) {            $a |= 0x04;        }        if (sys_key_held(\SDLK_RIGHT) || sys_key_held(\SDLK_KP_6) || sys_key_held(\SDLK_KP_9) || sys_key_held(\SDLK_KP_3)) {            $a |= 0x08;        }        $b |= $a;    } else {        $b &= 0x80;    }    if ($with_mouse_fire && SysVars::$mouse->lb) {        $b |= 0x80;    }    return $b;}function sys_joy_refresh(): void{    SysVars::$joystick0 = sys_joy_compose(0, 1);    SysVars::$joystick1 = sys_joy_compose(1, 1);}/** C io_keyon(code): is the key of this ALIS code held. */function io_keyon(int $code): int{    $h = fn (int $sym) => sys_key_held($sym);    switch ($code) {        case 0x1b:            return (int) $h(\SDLK_ESCAPE);        case 0x0d:            return (int) ($h(\SDLK_RETURN) || $h(\SDLK_KP_ENTER));        case 0x20:            return (int) $h(\SDLK_SPACE);        case 0x08:            return (int) $h(\SDLK_BACKSPACE);        case 0x09:            return (int) $h(\SDLK_TAB);        case 0xc8:            return (int) ($h(\SDLK_UP) || $h(\SDLK_KP_8));        case 0xd0:            return (int) ($h(\SDLK_DOWN) || $h(\SDLK_KP_2));        case 0xcb:            return (int) ($h(\SDLK_LEFT) || $h(\SDLK_KP_4));        case 0xcd:            return (int) ($h(\SDLK_RIGHT) || $h(\SDLK_KP_6));        case 0xc7:            return (int) $h(\SDLK_HOME);        case 0xc9:            return (int) $h(\SDLK_PAGEUP);        case 0xcf:            return (int) $h(\SDLK_END);        case 0xd1:            return (int) $h(\SDLK_PAGEDOWN);        case 0xd2:            return (int) $h(\SDLK_INSERT);        case 0xd3:            return (int) $h(\SDLK_DELETE);        case 0xe0:            return (int) $h(\SDLK_LSHIFT);        case 0xe1:            return (int) $h(\SDLK_RSHIFT);        case 0xe2:            return (int) ($h(\SDLK_LCTRL) || $h(\SDLK_RCTRL));        case 0xe3:            return (int) ($h(\SDLK_LALT) || $h(\SDLK_RALT));        case 0xe4:            return (int) $h(\SDLK_CAPSLOCK);    }    if ($code >= 0xbb && $code <= 0xc6) {        return (int) $h(\SDLK_F1 + ($code - 0xbb));    }    if ($code >= 0x61 && $code <= 0x7a) {        return (int) $h($code); // SDLK_a..SDLK_z are the ASCII codes    }    if ($code >= 0x30 && $code <= 0x39) {        $kp = $code === 0x30 ? \SDLK_KP_0 : \SDLK_KP_1 + ($code - 0x31);        return (int) ($h($code) || $h($kp));    }    return 0;}function io_joy_raw(): int{    return sys_joy_compose(1, 0);}function io_joy(int $port): int{    sys_joy_refresh();    return $port ? SysVars::$joystick0 : SysVars::$joystick1;}function io_joykey(int $test): int{    sys_joy_refresh();    $result = 0;    if ($test === 0) {        $result = (SysVars::$joystick1 & 0x80) !== 0 ? 1 : 0;        if ((SysVars::$shift & 4) !== 0) {            $result |= 2;        }        if ((SysVars::$shift & 8) !== 0) {            $result |= 4;        }    }    return $result;}// ---------------------------------------------------------------------------------------------// Files: game data (read-only) in the data folder; files written by the game (saves) go to the// JumPHP storage (var/, IndexedDB in the browser) and are read back from there first.// ---------------------------------------------------------------------------------------------/** Storage name of a file written by the game: its base name in lower case. */function sys_save_name(string $path): string{    return 'alis-' . strtolower(basename(str_replace('\\', '/', $path)));}/** Finds a data file whatever the case of its name (C tries as is, lower case, upper case). */function sys_find_file(string $path): ?string{    if (is_file($path)) {        return $path;    }    $dir = dirname($path);    $name = basename($path);    foreach ([strtolower($name), strtoupper($name)] as $n) {        if (is_file("$dir/$n")) {            return "$dir/$n";        }    }    // case-insensitive scan (cached per folder)    if (!isset(SysVars::$dirIndex[$dir])) {        SysVars::$dirIndex[$dir] = [];        foreach (@scandir($dir) ?: [] as $f) {            SysVars::$dirIndex[$dir][strtolower($f)] = $f;        }    }    $real = SysVars::$dirIndex[$dir][strtolower($name)] ?? null;    if ($real !== null) {        return "$dir/$real";    }    return sys_lazy_file($dir, strtolower($name));}/** * A data file loaded on demand (catalog/<game>.json "lazy": the big films and maps): in the folder of a * developer's full copy (SysVars::$lazyDev), or downloaded from the playground (private files lazy/<game>/) * in the background — then null with SysVars::$lazyPending set, and sys_fopen() makes the VM wait for it. */function sys_lazy_file(string $dir, string $name): ?string{    if (!isset(SysVars::$lazy[$name])) {        return null;    }    // debugging (tools/run.php --lazy-delay): the developer's copy answers like a network, a while after the request    if (SysVars::$lazyDev !== '' && SysVars::$lazyDelay !== null && SysVars::$inLoop && preg_match('/' . (SysVars::$lazyDelay[2] ?? '.') . '/', $name)) {        $at = SysVars::$lazyReadyAt[$name] ??= SysVars::$msec / 1000 + SysVars::$lazyDelay[0] + (int) SysVars::$lazy[$name][0] / 1048576 / SysVars::$lazyDelay[1];        if (SysVars::$msec / 1000 < $at) {            SysVars::$lazyPending = $name;            SysVars::$fetching[$name] = true;            return null;        }        unset(SysVars::$fetching[$name]);    }    if (SysVars::$lazyDev !== '' && is_file(SysVars::$lazyDev . '/' . $name)) {        return SysVars::$lazyDev . '/' . $name;    }    if (SysVars::$lazyDev !== '' && is_file(SysVars::$lazyDev . '/src/' . $name)) {        return SysVars::$lazyDev . '/src/' . $name;        // the ALIS sources of a developer's copy    }    if (isset(SysVars::$lazyFailed[$name]) || SysVars::$http === null) {        return null;    }    SysVars::$lazyPending = $name;    if (!isset(SysVars::$fetching[$name])) {        SysVars::$fetching[$name] = true;        [$size, $hash] = SysVars::$lazy[$name];        @mkdir($dir, 0777, true);        sys_lazy_download($dir, $name, (int) $size, (string) $hash);    }    return null;}/** * Downloads a file by parts of SysVars::LAZY_PART bytes (HTTP Range, SysVars::LAZY_PARALLEL at a time), written * at their place in <name>.part, renamed when whole. In the browser PHP never gets back the memory of a string of * 2 MB or more once freed (Emscripten cannot unmap what Zend's allocator maps), and an answer reaches PHP in base64 * inside the page's events: a film downloaded whole grew the page at each download, and the game slowed down. */function sys_lazy_download(string $dir, string $name, int $size, string $hash): void{    // the playground's externals first (no limits of the private files, blocks cached by the extension)    if (SysVars::$externals !== null && !SysVars::$externalsOff) {        sys_lazy_external($dir, $name, $size, $hash);        return;    }    sys_lazy_private($dir, $name, $size, $hash);}/** * A file of the externals (alis/<game>/<name>, jumphp/externals): read by parts of SysVars::LAZY_PART bytes * (SysVars::LAZY_PARALLEL at a time) into <name>.part, renamed when whole. Not shared, missing, a server that * answers no: the private files, for this file and the next ones. */function sys_lazy_external(string $dir, string $name, int $size, string $hash): void{    $part = "$dir/$name.part";    $fallback = static function (\Throwable $e) use ($dir, $name, $size, $hash, $part): void {        @unlink($part);        if (!SysVars::$externalsOff) {            SysVars::$externalsOff = true;            error_log('ALIS: externals unavailable (' . $e->getMessage() . '): the private files are used');        }        sys_lazy_private($dir, $name, $size, $hash);    };    SysVars::$externals->open(SysVars::$externalsDir . '/' . $name)->then(        static function ($file) use ($dir, $name, $part, $fallback): void {            $total = $file->size();            @unlink($part);            touch($part);            $state = new class {                public int $next = 0;                public int $left = 0;                public bool $failed = false;            };            $state->left = max(1, (int) ceil($total / SysVars::LAZY_PART));            $ask = null;            $ask = static function () use (&$ask, $file, $dir, $name, $part, $total, $state, $fallback): void {                if ($state->failed || $state->next >= $total) {                    return;                }                $from = $state->next;                $want = min(SysVars::LAZY_PART, $total - $from);                $state->next += $want;                $file->read($from, $want)->then(                    static function (string $bytes) use (&$ask, $dir, $name, $part, $total, $from, $want, $state, $fallback): void {                        if ($state->failed) {                            return;                        }                        if (strlen($bytes) !== $want) {                            $state->failed = true;                            $fallback(new \RuntimeException("$name: " . strlen($bytes) . " bytes instead of $want"));                            return;                        }                        $fp = fopen($part, 'c+b');                        fseek($fp, $from);                        fwrite($fp, $bytes);                        fclose($fp);                        unset($bytes);                        if (--$state->left > 0) {                            $ask();                            return;                        }                        rename($part, "$dir/$name");                        unset(SysVars::$fetching[$name]);                        unset(SysVars::$dirIndex[$dir]);                        sys_lazy_evict("$dir/$name", $total);                    },                    static function (\Throwable $e) use ($state, $fallback): void {                        if (!$state->failed) {                            $state->failed = true;                            $fallback($e);                        }                    }                );            };            if ($total === 0) {                rename($part, "$dir/$name");                unset(SysVars::$fetching[$name], SysVars::$dirIndex[$dir]);                return;            }            for ($i = 0; $i < SysVars::LAZY_PARALLEL; $i++) {                $ask();            }        },        $fallback    );}/** A file of the private files (lazy/<game>/<name>), by parts (see sys_lazy_download()). */function sys_lazy_private(string $dir, string $name, int $size, string $hash): void{    $part = "$dir/$name.part";    @unlink($part);    touch($part);    $state = new class {        public int $next = 0;        // the first byte not asked yet        public int $left = 0;        // parts still to come        public bool $failed = false;    };    $state->left = max(1, (int) ceil($size / SysVars::LAZY_PART));    $url = SysVars::$lazyBase . rawurlencode($name) . '?v=' . $hash;    $fail = static function (string $why) use ($name, $part, $state): void {        if (!$state->failed) {            $state->failed = true;            unset(SysVars::$fetching[$name]);            @unlink($part);            SysVars::$lazyFailed[$name] = $why;        }    };    $ask = null;    $ask = static function () use (&$ask, $dir, $name, $size, $url, $part, $state, $fail): void {        if ($state->failed || $state->next >= $size) {            return;        }        $from = $state->next;        $to = min($size, $from + SysVars::LAZY_PART) - 1;        $state->next = $to + 1;        $whole = $from === 0 && $to === $size - 1;        SysVars::$http->request('GET', $url, null, $whole ? [] : ['Range' => "bytes=$from-$to"], 120.0)->then(            static function ($r) use (&$ask, $dir, $name, $size, $from, $to, $part, $state, $fail): void {                if ($state->failed) {                    return;                }                $want = $to - $from + 1;                $body = $r->body;                // a server that ignores Range sends the whole file (200): keep the part asked for                if ($r->status === 200 && strlen($body) === $size && $want !== $size) {                    $body = substr($body, $from, $want);                }                if (!$r->ok() || strlen($body) !== $want) {                    $fail($r->ok() ? 'size ' . strlen($body) : 'HTTP ' . $r->status);                    return;                }                $fp = fopen($part, 'c+b');                fseek($fp, $from);                fwrite($fp, $body);                fclose($fp);                unset($body, $r);                if (--$state->left > 0) {                    $ask();                    return;                }                rename($part, "$dir/$name");                unset(SysVars::$fetching[$name]);                unset(SysVars::$dirIndex[$dir]);                sys_lazy_evict("$dir/$name", $size);            },            static fn (\Throwable $e) => $fail($e->getMessage())        );    };    for ($i = 0; $i < SysVars::LAZY_PARALLEL; $i++) {        $ask();    }}/** Keeps the downloaded files under SysVars::LAZY_CACHE bytes (memory of the browser): the oldest leave first. */function sys_lazy_evict(string $path, int $size): void{    SysVars::$lazyLoaded[$path] = $size;    while (array_sum(SysVars::$lazyLoaded) > SysVars::LAZY_CACHE && count(SysVars::$lazyLoaded) > 1) {        $old = array_key_first(SysVars::$lazyLoaded);        unset(SysVars::$lazyLoaded[$old]);        @unlink($old);        unset(SysVars::$dirIndex[dirname($old)]);    }}/** @return resource|null a PHP stream */function sys_fopen(string $path, string $mode){    $write = strpbrk($mode, 'wa+') !== false;    $storage = SysVars::$storage;    $saveName = sys_save_name($path);    if ($write) {        $fp = fopen('php://memory', 'w+b');        if (str_contains($mode, 'a') || str_contains($mode, '+') && !str_contains($mode, 'w')) {            $old = $storage?->read($saveName) ?? (($f = sys_find_file($path)) !== null ? file_get_contents($f) : null);            if ($old !== null && $old !== false) {                fwrite($fp, $old);                if (!str_contains($mode, 'a')) {                    rewind($fp);                }            } elseif (str_contains($mode, 'r')) {                // "r+" of a missing file fails like fopen                if (!str_contains($mode, 'w')) {                    fclose($fp);                    return null;                }            }        }        SysVars::$writeStreams[(int) $fp] = $saveName;        return $fp;    }    if (($io = sys_source_io($path)) !== null) {        $fp = fopen('php://memory', 'w+b');        fwrite($fp, $io);        rewind($fp);        return $fp;    }    if ($storage !== null && $storage->exists($saveName)) {        $fp = fopen('php://memory', 'w+b');        fwrite($fp, (string) $storage->read($saveName));        rewind($fp);        return $fp;    }    SysVars::$lazyPending = null;    $real = sys_find_file($path);    if ($real === null && SysVars::$lazyPending !== null && SysVars::$inLoop) {        // a file still downloading: run this opcode again at a later frame (the VM waits, the screen stays)        vm_yield_retry();    }    SysVars::$opened[] = $real ?? "(missing) $path";    if ($real === null) {        return null;    }    $fp = fopen($real, 'rb');    return $fp === false ? null : $fp;}/** C sys_fopen_b(path, ALIS open mode): 0x100 create, 0x200 truncate, 0x400 append. */function sys_fopen_b(string $path, int $mode){    $flag = 'rb';    if ($mode & 0x100) {        $flag = 'r+b';    }    if ($mode & 0x200) {        $flag = 'wb';    }    if ($mode & 0x400) {        $flag = 'ab';    }    $fp = sys_fopen($path, $flag);    if ($fp === null && $flag === 'r+b') {        $fp = sys_fopen($path, 'w+b');    }    return $fp;}function sys_fclose($fp): int{    if (!is_resource($fp)) {        return -1;    }    $id = (int) $fp;    if (isset(SysVars::$writeStreams[$id])) {        rewind($fp);        SysVars::$storage?->write(SysVars::$writeStreams[$id], (string) stream_get_contents($fp));        unset(SysVars::$writeStreams[$id]);    }    fclose($fp);    return 0;}function sys_fexists(string $path): int{    if (SysVars::$storage !== null && SysVars::$storage->exists(sys_save_name($path))) {        return 1;    }    return sys_find_file($path) !== null || isset(SysVars::$lazy[strtolower(basename($path))]) || sys_source_io($path) !== null ? 1 : 0;}/** * Source edition (SysVars::$sourceDir): a script X.io is made from the ALIS source X.als (+ its resources file), * compiled once (App\Alis\Lang\Assembler, docs/language.md). Null when there is no source for $path. */function sys_source_io(string $path): ?string{    if (SysVars::$sourceDir === '' || !preg_match('~([^/\\\\]+)\.io$~i', $path, $m)) {        return null;    }    $name = strtolower($m[1]);    if (isset(SysVars::$sourceCache[$name])) {        return SysVars::$sourceCache[$name];    }    // the player's version of the script (the ALIS editor, docs/editor.md), else the original    $mine = SysVars::$sourceGame !== '' ? SysVars::$storage?->read(\App\Editor\SourceStore::key(SysVars::$sourceGame, $name)) : null;    SysVars::$lazyPending = null;    $als = $mine === null ? sys_find_file(SysVars::$sourceDir . '/' . $name . '.als') : '';    if ($als === null) {        if (SysVars::$lazyPending !== null && SysVars::$inLoop) {            vm_yield_retry();       // the source is downloading: the VM waits for it (not the original script)        }        return null;    }    $source = $mine ?? (string) file_get_contents($als);    // its resources too, before compiling (a download in the browser)    if (preg_match('/^\s*resources\s+"([^"]+)"/m', $source, $rm)) {        SysVars::$lazyPending = null;        if (sys_find_file(SysVars::$sourceDir . '/' . $rm[1]) === null && SysVars::$lazyPending !== null && SysVars::$inLoop) {            vm_yield_retry();        }    }    $read = function (string $file) use ($name): string {        $f = sys_find_file(SysVars::$sourceDir . '/' . $file);        if ($f === null) {            throw new \RuntimeException("ALIS source $name.als: missing $file");        }        return (string) file_get_contents($f);    };    try {        $script = \App\Alis\Lang\Human::compile($source, $read);   // either form (docs/language.md)    } catch (\App\Alis\Lang\CompileError $e) {        throw new \RuntimeException("ALIS source $name.als, " . $e->getMessage());    }    SysVars::$sourcePack[$name] = s8($script->pack & 0xfe);    return SysVars::$sourceCache[$name] = $script->ioFile();}/** Deletes a file written by the game (C remove()). */function sys_fdelete(string $path): int{    SysVars::$storage?->delete(sys_save_name($path));    return 0;}