PL
games/alis / src / Alis / fn / image.php · commit 9c722cf
<?phpnamespace App\Alis;// Port of alis/src/image.c (MIT, Olivier Huguenot, Vadim Kindl).// Part 1: palettes, sprite lists, put, screen composition, draw(). Part 2 (image2.php): blitters, maps.// Dropped: v6 (put chain, v6x renderer, v6 dirty list), 3DO (cel/rgb), RRQ 3D land, FLI video,// enhanced 32-bit renderer. See docs/porting.md.//// PORT: palette pointers: Img::$atpalet / Img::$ampalet are int ELEMENT OFFSETS into Img::$tpalet / Img::$mpalet// (the C pointers always point into those two arrays, moved by thepalet * 64 in selpalet()).// Palette entries are packed 0xRRGGBB ints whatever image.pal_format says.// ---------------------------------------------------------------------------------------------// image.h / alis.h / screen.h helpers// ---------------------------------------------------------------------------------------------// PL_CGA() is in alis.php; the screen.h getters (get_scr_state, ...) in accessors.php./** sRect "constructor" (C compound literal). */function image_rect(int $x1, int $y1, int $x2, int $y2): sRect{    $r = new sRect();    $r->x1 = s16($x1);    $r->y1 = s16($y1);    $r->x2 = s16($x2);    $r->y2 = s16($y2);    return $r;}/** image.h boxf_clip(): clamp a filled box (x1 <= x2, y2 inclusive) to the screen, 0 when nothing is left. */function boxf_clip(int &$x1, int &$y1, int &$x2, int &$y2): int{    // x2 is inclusive in the originals    if (Alis::$platform->kind != C::EPlatformMac) {        $x2 = s16($x2 + 1);    }    if ($y1 > $y2) {        $t = $y1;        $y1 = $y2;        $y2 = $t;    }    if ($x1 < 0) {        $x1 = 0;    }    if ($y1 < 0) {        $y1 = 0;    }    if ($x2 > Alis::$platform->width) {        $x2 = s16(Alis::$platform->width);    }    if ($y2 >= Alis::$platform->height) {        $y2 = s16(Alis::$platform->height - 1);    }    return (int) ($x1 < $x2 && $y1 <= $y2);}/** PAL_WRITE_RGB / PAL_WRITE_DISPATCH: palette entry = packed 0xRRGGBB (pal = 'tpalet', 'mpalet', ...). */function image_pal_write(string $pal, int $idx, int $r, int $g, int $b): void{    Img::${$pal}[$idx] = (($r & 0xff) << 16) | (($g & 0xff) << 8) | ($b & 0xff);}/** PAL_DELTA_LOOP(mpalet -> tpalet, duration) */function image_pal_delta(int $duration): void{    $dur = s32($duration);    if ($dur == 0) {        $dur = 1;    }    for ($i = 0; $i < 256; $i++) {        $s = Img::$mpalet[$i] ?? 0;        $d = Img::$tpalet[$i] ?? 0;        Img::$dpalet[$i * 3 + 0] = cdiv(((($s >> 16) & 0xff) - (($d >> 16) & 0xff)) * 65536, $dur);        Img::$dpalet[$i * 3 + 1] = cdiv(((($s >> 8) & 0xff) - (($d >> 8) & 0xff)) * 65536, $dur);        Img::$dpalet[$i * 3 + 2] = cdiv((($s & 0xff) - ($d & 0xff)) * 65536, $dur);    }}/** Bytes of Alis::$mem as an int array (for C helpers that take a u8 * which may also be a local array). */function image_bytes(int $p, int $n): array{    if ($n <= 0) {        return [];    }    $s = substr(Alis::$mem, $p, $n);    $a = array_values(unpack('C*', $s) ?: []);    for ($i = count($a); $i < $n; $i++) {        $a[] = 0;    }    return $a;}// ---------------------------------------------------------------------------------------------// Robinsons Requiem// ---------------------------------------------------------------------------------------------// save_bitmap_as_bmp(): debug helper writing a BMP file to disk, never called. Dropped.// ---------------------------------------------------------------------------------------------// Palette management// ---------------------------------------------------------------------------------------------// Entries one palette bank spans: banks are 64 apart for <8bpp data (thepalet*64), one bank for 8bpp.function pal_bank_len(): int{    return Alis::$platform->bpp < 8 ? 64 : 256;}function topalet(): void{    Img::$ftopal = 0;    // Fades always run over the fixed base (all banks), as the original: the selected bank    // pointers can move under this (it runs from the timer thread / ISR).    if (Img::$palc == 1) {        for ($i = 0; $i < 256; $i++) {            Img::$mpalet[$i] = Img::$tpalet[$i] ?? 0;        }    } else {        // TOPALET_INTERP_LOOP        $palc = Img::$palc;        for ($i = 0; $i < 256; $i++) {            $a = Img::$mpalet[$i] ?? 0;            $t = Img::$tpalet[$i] ?? 0;            if ($a != $t) {                $r = (($t >> 16) & 0xff) + (mul32(Img::$dpalet[$i * 3 + 0], $palc) >> 16);                $g = (($t >> 8) & 0xff) + (mul32(Img::$dpalet[$i * 3 + 1], $palc) >> 16);                $b = ($t & 0xff) + (mul32(Img::$dpalet[$i * 3 + 2], $palc) >> 16);                Img::$mpalet[$i] = (($r & 0xff) << 16) | (($g & 0xff) << 8) | ($b & 0xff);            }        }    }    Img::$ftopal = 1;    set_update_cursor();}function topalette(int $paldata, int $duration): void{    if (Alis::$platform->kind == C::EPlatformMac) {        // Entry 0 = black, entries 1..255 = white        image_pal_write('tpalet', Img::$atpalet + 0, 0, 0, 0);        image_pal_write('mpalet', Img::$ampalet + 0, 0, 0, 0);        for ($i = 1; $i < 256; $i++) {            image_pal_write('tpalet', Img::$atpalet + $i, 255, 255, 255);            image_pal_write('mpalet', Img::$ampalet + $i, 255, 255, 255);        }        Img::$ftopal = 0xff;    } elseif (PL_CGA()) {        // PAL_WRITE(..., RGB32(cga_palette))        for ($c = 0; $c < 4; $c++) {            $p = ImageVars::$cga_palette;            image_pal_write('tpalet', Img::$atpalet + $c, $p[$c * 4], $p[$c * 4 + 1], $p[$c * 4 + 2]);        }        for ($c = 0; $c < 4; $c++) {            $p = ImageVars::$cga_palette;            image_pal_write('mpalet', Img::$ampalet + $c, $p[$c * 4], $p[$c * 4 + 1], $p[$c * 4 + 2]);        }    } else {        selpalet();        $colors = Alis::$platform->version == 10 ? 0 : xread8($paldata + 1);        if (Alis::$platform->version >= 60) {            topalette_v6($paldata); // image_v6.php        } elseif ($colors == 0) { // 4 bit palette            Img::$palc = 0;            $palptr = $paldata + 2;            // Manhattan Amiga keeps the Atari 3-bit palettes            if (Alis::$platform->kind == C::EPlatformAmiga || Alis::$platform->kind == C::EPlatformAmigaAGA) {                for ($c = 0; $c < 16; $c++) {                    // RGB12                    $r = (xread8($palptr) & 0b00001111) << 4;                    $palptr++;                    $g = (xread8($palptr) >> 4) << 4;                    $b = (xread8($palptr) & 0b00001111) << 4;                    $palptr++;                    image_pal_write('tpalet', Img::$atpalet + $c, $r, $g, $b);                }            } else {                for ($c = 0; $c < 16; $c++) {                    // RGB9                    $r = (xread8($palptr) & 0b00000111) << 5;                    $palptr++;                    $g = (xread8($palptr) >> 4) << 5;                    $b = (xread8($palptr) & 0b00000111) << 5;                    $palptr++;                    image_pal_write('tpalet', Img::$atpalet + $c, $r, $g, $b);                }            }        } else { // 8 bit palette            if (Alis::$platform->kind == C::EPlatformAmiga) {                Img::$palc = 0;                $palptr = $paldata + 2;                for ($c = 0; $c < 32; $c++) {                    // RGB12                    $r = (xread8($palptr) & 0b00001111) << 4;                    $palptr++;                    $g = (xread8($palptr) >> 4) << 4;                    $b = (xread8($palptr) & 0b00001111) << 4;                    $palptr++;                    image_pal_write('tpalet', Img::$atpalet + $c, $r, $g, $b);                }            } else {                Img::$palc = 0;                $offset = xread8($paldata + 2);                $paldata += 4;                for ($c = 0; $c < $colors + 1; $c++) {                    // RGB24                    $r = xread8($paldata++);                    $g = xread8($paldata++);                    $b = xread8($paldata++);                    image_pal_write('tpalet', Img::$atpalet + $offset + $c, $r, $g, $b);                }            }        }        if (Img::$fdarkpal && Img::$thepalet == 0) {            $dk = 0; // u16 *dkpalptr = (u16 *)image.dkpalet            $colors = Alis::$platform->bpp <= 4 ? 16 : 256;            for ($i = 0; $i < $colors; $i++, $dk += 3) {                $c = Img::$tpalet[Img::$atpalet + $i] ?? 0;                $_r = ($c >> 16) & 0xff;                $_g = ($c >> 8) & 0xff;                $_b = $c & 0xff;                image_pal_write('tpalet', Img::$atpalet + $i,                    (int) ($_r * ((Img::$dkpalet[$dk] & 0xffff) / 256.0)),                    (int) ($_g * ((Img::$dkpalet[$dk + 1] & 0xffff) / 256.0)),                    (int) ($_b * ((Img::$dkpalet[$dk + 2] & 0xffff) / 256.0)));            }        }        if ($duration == 0) {            // only the written bank            $n = pal_bank_len();            for ($i = 0; $i < $n; $i++) {                Img::$mpalet[Img::$ampalet + $i] = Img::$tpalet[Img::$atpalet + $i] ?? 0;            }        }        Img::$thepalet = 0;        Img::$defpalet = 0;        selpalet();        if ($duration != 0) {            image_pal_delta($duration);            Img::$palt = 1;            Img::$palt0 = 1;            Img::$palc = $duration & 0xff;        } else {            Img::$ftopal = 0xff;        }    }    set_update_cursor();}function toblackpal(int $duration): void{    $duration = s16($duration);    selpalet();    // Black only the selected bank (the original clears 16 colours of addr_tpalet).    $n = pal_bank_len();    for ($i = 0; $i < $n; $i++) {        Img::$tpalet[Img::$atpalet + $i] = 0;    }    if ($duration == 0) {        for ($i = 0; $i < $n; $i++) {            Img::$mpalet[Img::$ampalet + $i] = 0;        }    }    Img::$thepalet = 0;    Img::$defpalet = 0;    selpalet();    if ($duration == 0) {        Img::$ftopal = 0xff;        Img::$palc = 0;    } else {        image_pal_delta($duration);        Img::$palt = 1;        Img::$palt0 = 1;        Img::$palc = $duration & 0xff;    }}function savepal(int $mode): void{    $mode = s16($mode);    if ($mode < 0 && -3 < $mode) {        if ($mode != -1) {            Img::$svpalet2 = Img::$tpalet;        } else {            Img::$svpalet = Img::$tpalet;        }    }}function restorepal(int $mode, int $duration): void{    $mode = s16($mode);    // not used in some games (Metal Mutant, ...)    if (Alis::$platform->uid == ImageConst::EGameMetalMutant) {        return;    }    $src = ($mode != -1) ? Img::$svpalet2 : Img::$svpalet;    Img::$tpalet = $src;    Img::$thepalet = 0;    Img::$defpalet = 0;    selpalet();    if ($duration == 0) {        Img::$mpalet = $src;        Img::$ftopal = 0xff;        Img::$palc = 0;    } else {        image_pal_delta($duration);        topalet();        Img::$palt = 1;        Img::$palt0 = 1;        Img::$palc = $duration & 0xff;    }}// ============================================================================// DOS palette model (PC data, version >= 12): the originals keep a 6-bit target (tpal) and a// live palette (mpal) and fade by chasing mpal toward tpal on the vblank tick. m68k games// never come here. Families differ in a few opcode details (see dos_pal_family).// ============================================================================// Colorado: 16 colours, no fades. Bunny Bricks / Ishar 1, 2 (Transarctica assumed): the// 16-bit driver. RRQ / Ishar 3: the 32-bit driver. Other PC games keep the generic path.function dos_pal_family(): int{    if (Alis::$platform->kind != C::EPlatformPC) {        return ImageConst::DPAL_NONE;    }    switch (Alis::$platform->uid) {        case C::EGameColorado:            return ImageConst::DPAL_C16;        case C::EGameBunnyBricks:            return ImageConst::DPAL_BUNNY;        case C::EGameIshar_1:        case C::EGameIshar_2:        case C::EGameTransarctica:            return ImageConst::DPAL_ISHAR;        case C::EGameIshar_3:        case C::EGameRobinsonsRequiem0:        case C::EGameRobinsonsRequiem1:            return ImageConst::DPAL_B32;        default:            return ImageConst::DPAL_NONE;    }}function dos_pal_active(): int{    return (int) (dos_pal_family() != ImageConst::DPAL_NONE);}function dpal_expand(int $v): int{    $v &= 0x3f;    return (($v << 2) | ($v >> 4)) & 0xff;}// The DAC write: the live 6-bit palette becomes the host palette.function dpal_upload(): void{    $n = dos_pal_family() == ImageConst::DPAL_C16 ? 16 : 256;    $mp = ImageVars::$dpal_mpal;    for ($i = 0; $i < $n; $i++) {        image_pal_write('mpalet', $i, dpal_expand($mp[$i * 3]), dpal_expand($mp[$i * 3 + 1]), dpal_expand($mp[$i * 3 + 2]));    }    set_update_cursor();   // the host cursor image is built from the palette}// image.tpalet mirrors the target so save states keep it.function dpal_mirror_target(): void{    $tp = ImageVars::$dpal_tpal;    for ($i = 0; $i < 256; $i++) {        image_pal_write('tpalet', $i, dpal_expand($tp[$i * 3]), dpal_expand($tp[$i * 3 + 1]), dpal_expand($tp[$i * 3 + 2]));    }}function dpal_chase(): void{    ImageVars::$dpal_ftopal = 0;    $step = ImageVars::$dpal_step;    for ($i = 0; $i < 768; $i++) {        $t = ImageVars::$dpal_tpal[$i];        $m = ImageVars::$dpal_mpal[$i];        if ($t == $m) {            continue;        }        ImageVars::$dpal_ftopal = 1;        if ($t > $m) {            ImageVars::$dpal_mpal[$i] = ($m + $step < $t ? $m + $step : $t) & 0xff;        } else {            ImageVars::$dpal_mpal[$i] = ($m - $step > $t ? $m - $step : $t) & 0xff;        }    }}// Fade speed from a duration. Returns 0 when the set is immediate.function dpal_steps(int $dur, int $inc): int{    $dur = s16($dur);    ImageVars::$dpal_step = 1;    if ($dur == 0) {        return 0;    }    if ($dur < 63) {        $cl = $dur & 0xff;        if ($cl == 0) {            return 0;   // the original divides by zero here        }        ImageVars::$dpal_step = (intdiv(63, $cl) + 1) & 0xff;        ImageVars::$dpal_reload = 1;        ImageVars::$dpal_counter = 1;    } else {        $q = intdiv($dur, 63) + $inc;        if ($q > 127) {            $q = 127;        }        ImageVars::$dpal_reload = $q & 0xff;        ImageVars::$dpal_counter = s8($q);    }    return 1;}// Immediate set or the first fade step; the 16-bit driver writes the DAC at once.function dpal_apply(int $fade): void{    ImageVars::$dpal_lock = 1;    if ($fade) {        dpal_chase();        ImageVars::$dpal_ftopal = 1;    } else {        ImageVars::$dpal_counter = ImageVars::$dpal_reload = 0;        ImageVars::$dpal_mpal = ImageVars::$dpal_tpal;        ImageVars::$dpal_ftopal = 0xff;        if (dos_pal_family() != ImageConst::DPAL_B32) {            dpal_upload();        }    }    ImageVars::$dpal_lock = 0;    dpal_mirror_target();}/** @param int[] $words bytes (C u8 *words: 16 big-endian words) */function dpal_load16(array $words, int $first): void{    $fam = dos_pal_family();    for ($i = 0; $i < 16 && $first + $i < 256; $i++) {        // PORT: dos_cdefcolor passes a 2-byte array; the C reads stack garbage past it, here 0.        $hi = ($words[$i * 2] ?? 0) & 0xff;        $lo = ($words[$i * 2 + 1] ?? 0) & 0xff;        $c = [(($hi & 0x0f) << 3) & 0xff, (($lo & 0xf0) >> 1) & 0xff, (($lo & 0x0f) << 3) & 0xff];        for ($k = 0; $k < 3; $k++) {            if ($fam == ImageConst::DPAL_B32) {    // expanded to 8 bits, then the normal >>2 load                $c[$k] = $c[$k] ? (((($c[$k] >> 3) << 5) | 0x1f) >> 2) & 0xff : 0;            } elseif ($fam != ImageConst::DPAL_C16 && $c[$k]) {                $c[$k] |= 7;            }            ImageVars::$dpal_tpal[($first + $i) * 3 + $k] = $c[$k];        }    }}// RRQ's dark palette applied while loading (8-bit source).function dpal_dark(int $c8, int $dk): int{    $p = ($c8 & 0xff) * ($dk & 0xffff);    return (($p > 0xffff ? 0xffff : $p) >> 10) & 0xff;}/** @param int[] $rgb8 bytes */function dpal_load_dark(array $rgb8, int $first, int $n): void{    $dk = Img::$dkpalet; // u16 *dk = (u16 *)image.dkpalet    for ($i = 0; $i < $n; $i++) {        $e = $first + $i;        $r = $rgb8[$i * 3] ?? 0;        $g = $rgb8[$i * 3 + 1] ?? 0;        $b = $rgb8[$i * 3 + 2] ?? 0;        $d0 = ($dk[$e * 3] ?? 0) & 0xffff;        $d1 = ($dk[$e * 3 + 1] ?? 0) & 0xffff;        $d2 = ($dk[$e * 3 + 2] ?? 0) & 0xffff;        if (!$r && !$g && !$b && ($d0 > 0x100 || $d1 > 0x100 || $d2 > 0x100)) {            $r = $g = $b = 2;        }        ImageVars::$dpal_tpal[$e * 3] = dpal_dark($r, $d0);        ImageVars::$dpal_tpal[$e * 3 + 1] = dpal_dark($g, $d1);        ImageVars::$dpal_tpal[$e * 3 + 2] = dpal_dark($b, $d2);    }}// topalette of a 0xFE resource (0 = NULL: keep the target, as the restore path).function dpal_topalette(int $res, int $dur): void{    $fam = dos_pal_family();    $fade = dpal_steps($dur, (int) ($fam != ImageConst::DPAL_BUNNY));    if ($fam == ImageConst::DPAL_C16) {        if ($res) {            dpal_load16(image_bytes($res + 2, 32), 0);        }        dpal_apply(0);        return;    }    if ($res) {        $n = xread8($res + 1) + 1;        $first = xread8($res + 2);        if ($n == 1) {            dpal_load16(image_bytes($res + 2, 32), $first);            if ($fam != ImageConst::DPAL_B32) {                $fade = 1;   // the 16-bit driver always takes the fade path here            }        } else {            if ($first + $n > 256) {                $n = 256 - $first;            }            if ($fam == ImageConst::DPAL_B32 && Img::$fdarkpal) {                dpal_load_dark(image_bytes($res + 4, $n * 3), $first, $n);            } else {                for ($k = 0; $k < $n * 3; $k++) {                    ImageVars::$dpal_tpal[$first * 3 + $k] = xread8($res + 4 + $k) >> 2;                }            }        }    }    dpal_apply($fade);    ImageVars::$dpal_skip = 0;}function dpal_ctopalsav(int $idx, int $dur): void{    $src = s16($idx) == -1 ? ImageVars::$dpal_sav1 : ImageVars::$dpal_sav2;    if (dos_pal_family() == ImageConst::DPAL_B32 && Img::$fdarkpal) {        $rgb8 = [];        for ($k = 0; $k < 768; $k++) {            $rgb8[$k] = ($src[$k] << 2) & 0xff;        }        dpal_load_dark($rgb8, 0, 256);    } else {        ImageVars::$dpal_tpal = $src;    }    dpal_topalette(0, $dur);}function dos_pal_reset(): void{    // memset(&dpal, 0, sizeof(dpal))    ImageVars::$dpal_tpal = array_fill(0, 768, 0);    ImageVars::$dpal_mpal = array_fill(0, 768, 0);    ImageVars::$dpal_sav1 = array_fill(0, 768, 0);    ImageVars::$dpal_sav2 = array_fill(0, 768, 0);    ImageVars::$dpal_step = 0;    ImageVars::$dpal_reload = 0;    ImageVars::$dpal_skip = 0;    ImageVars::$dpal_counter = 0;    ImageVars::$dpal_ftopal = 0;    ImageVars::$dpal_lock = 0;    ImageVars::$dpal_acc = 0;}function dos_cpalette(int $idx, int $res): void{    $idx = s16($idx);    $fam = dos_pal_family();    if ($idx < 0) {        if (($fam == ImageConst::DPAL_ISHAR || $fam == ImageConst::DPAL_B32) && $idx >= -2) {            ImageVars::$dpal_counter = ImageVars::$dpal_reload = 0;            dpal_ctopalsav($idx, 0);        }    } elseif (($fam == ImageConst::DPAL_BUNNY || $fam == ImageConst::DPAL_C16 || !ImageVars::$dpal_skip) && xread8($res) == 0xfe) {        ImageVars::$dpal_counter = ImageVars::$dpal_reload = 0;        dpal_topalette($res, 0);        if ($fam != ImageConst::DPAL_B32 && $fam != ImageConst::DPAL_C16) {            ImageVars::$dpal_ftopal = 1;        }    }    ImageVars::$dpal_skip = 0;}function dos_ctopalet(int $idx, int $dur, int $res): void{    $idx = s16($idx);    $fam = dos_pal_family();    if ($fam == ImageConst::DPAL_BUNNY || $fam == ImageConst::DPAL_C16) {        if ($idx >= 0 && xread8($res) == 0xfe) {            dpal_topalette($res, $fam == ImageConst::DPAL_C16 ? 0 : $dur);        }    } elseif (!ImageVars::$dpal_skip) {        if ($idx < 0) {            if ($idx >= -2) {                dpal_ctopalsav($idx, $dur);            }        } elseif (xread8($res) == 0xfe) {            dpal_topalette($res, $dur);        }    }    ImageVars::$dpal_skip = 0;}function dos_ctoblack(int $dur): void{    if (dos_pal_family() == ImageConst::DPAL_C16) {        ImageVars::$dpal_tpal = array_fill(0, 768, 0);        dpal_apply(0);        return;    }    $fade = dpal_steps($dur, 0);    ImageVars::$dpal_tpal = array_fill(0, 768, 0);    ImageVars::$dpal_lock = 1;    if (!$fade) {        ImageVars::$dpal_counter = ImageVars::$dpal_reload = 0;        ImageVars::$dpal_mpal = array_fill(0, 768, 0);    }    dpal_chase();    ImageVars::$dpal_ftopal = 1;    ImageVars::$dpal_lock = 0;    dpal_mirror_target();    ImageVars::$dpal_skip = 0;}function dos_cselpalet(int $val): void{    if (dos_pal_family() != ImageConst::DPAL_C16) {        ImageVars::$dpal_skip = $val & 0xff;    }}function dos_cdefcolor(int $idx, int $val): void{    $idx = s16($idx);    $val &= 0xffff;    switch (dos_pal_family()) {        case ImageConst::DPAL_C16:            if ($idx >= 0 && $idx < 16) {                $w = [($val >> 8) & 0xff, $val & 0xff];                dpal_load16($w, $idx);                for ($k = 0; $k < 3; $k++) {                    ImageVars::$dpal_mpal[$idx * 3 + $k] = ImageVars::$dpal_tpal[$idx * 3 + $k];                }                dpal_upload();            }            break;        case ImageConst::DPAL_BUNNY:        case ImageConst::DPAL_ISHAR:            // The original indexes the 3-byte entries by 2 (its bug).            if ($idx >= 0 && $idx * 2 + 1 < 768) {                ImageVars::$dpal_mpal[$idx * 2] = ($val >> 8) & 0xff;                ImageVars::$dpal_mpal[$idx * 2 + 1] = $val & 0xff;                dpal_upload();            }            break;        default:            break;    }}function dos_csavepal(int $idx): void{    $idx = s16($idx);    $fam = dos_pal_family();    if ($fam != ImageConst::DPAL_ISHAR && $fam != ImageConst::DPAL_B32) {        return;    }    if ($idx == -1) {        ImageVars::$dpal_sav1 = ImageVars::$dpal_tpal;    } elseif ($idx == -2) {        ImageVars::$dpal_sav2 = ImageVars::$dpal_tpal;    }}// 0xFE resource drawn with put: unreachable in the originals (their path crashes); set it now.function dos_putin_palette(int $res): void{    ImageVars::$dpal_counter = ImageVars::$dpal_reload = 0;    dpal_topalette($res, 0);}// RRQ/Ishar 3 film colour chunk: written straight into the live palette, entry 0 black.function dos_film_palette(int $addr): int{    if (dos_pal_family() != ImageConst::DPAL_B32) {        return 0;    }    $packets = read16le($addr);    $index = 0;    $addr += 2;    ImageVars::$dpal_lock = 1;    do {        $index = ($index + xread8($addr++)) & 0xffff;        $len = xread8($addr++);        if ($len == 0) {            $len = 256;        }        if ($index + $len > 256) {            $len = (256 - $index) & 0xffff;            $packets = 1;        }        for ($k = 0; $k < $len * 3; $k++) {            ImageVars::$dpal_mpal[$index * 3 + $k] = xread8($addr + $k) & 0x3f;        }        $addr += $len * 3;        $index = ($index + $len) & 0xffff;        $packets = ($packets - 1) & 0xffff;    } while ($packets);    ImageVars::$dpal_mpal[0] = ImageVars::$dpal_mpal[1] = ImageVars::$dpal_mpal[2] = 0;    ImageVars::$dpal_lock = 0;    dpal_upload();    return 1;}// One vblank of the original timer: upload what is live, then step the fade.function dpal_tick(): void{    if (ImageVars::$dpal_lock) {        return;    }    dpal_upload();    if (dos_pal_family() == ImageConst::DPAL_B32 && ImageVars::$dpal_ftopal == 0xff) {        ImageVars::$dpal_ftopal = 0;        return;    }    ImageVars::$dpal_counter = s8(ImageVars::$dpal_counter - 1);    if (ImageVars::$dpal_counter >= 0) {        return;    }    ImageVars::$dpal_counter = s8(ImageVars::$dpal_reload);    dpal_chase();}// Called from itroutine; fade steps follow the pace rate (the DOS originals: VGA refresh).function dos_pal_tick(): void{    $hz = SysVars::$sys_timeclock_hz ? SysVars::$sys_timeclock_hz : 60;    for (ImageVars::$dpal_acc += sys_pace_hz(); ImageVars::$dpal_acc >= $hz; ImageVars::$dpal_acc -= $hz) {        if (ImageVars::$dpal_ftopal) {            dpal_tick();        }    }}// After a save state load: rebuild the 6-bit state from the restored host palettes.function dos_pal_sync_from_image(): void{    if (!dos_pal_active()) {        return;    }    for ($i = 0; $i < 256; $i++) {        $c = Img::$mpalet[$i] ?? 0;        ImageVars::$dpal_mpal[$i * 3] = (($c >> 16) & 0xff) >> 2;        ImageVars::$dpal_mpal[$i * 3 + 1] = (($c >> 8) & 0xff) >> 2;        ImageVars::$dpal_mpal[$i * 3 + 2] = ($c & 0xff) >> 2;        $c = Img::$tpalet[$i] ?? 0;        ImageVars::$dpal_tpal[$i * 3] = (($c >> 16) & 0xff) >> 2;        ImageVars::$dpal_tpal[$i * 3 + 1] = (($c >> 8) & 0xff) >> 2;        ImageVars::$dpal_tpal[$i * 3 + 2] = ($c & 0xff) >> 2;    }    ImageVars::$dpal_counter = ImageVars::$dpal_reload = 0;    ImageVars::$dpal_step = 1;    ImageVars::$dpal_ftopal = 1;}function selpalet(): void{    if (Alis::$platform->bpp < 8) {        $offset = s16(Img::$thepalet * 64);        Img::$ampalet = $offset;        Img::$atpalet = $offset;        // Only the write bank moves: the display stays on bank 0 (other banks show through        // clinepalet), as the original. Flag a pal16/CLUT refresh.    }}function linepal(): void{    $begline = 0xc6;    $endline = 0x2f;    $tl = 0;   // s16 *tlinepal_ptr = image.tlinepal    $pe = 0;   // s16 *palentry = image.firstpal    for ($i = 0; $i < 4; $i++) {        $line = Img::$tlinepal[$tl] ?? 0;        if (Alis::$platform->height < $line) {            break;        }        $dummy = s16($line == 0 ? $line : ((($line * $begline) & 0xffff) >> 8) + $endline);        Img::$firstpal[$pe + 0] = $dummy;        Img::$firstpal[$pe + 1] = $line;        Img::$firstpal[$pe + 2] = s16((Img::$tlinepal[$tl + 1] ?? 0) * 64);        $tl += 2;        $pe += ImageConst::LINEPAL_STRIDE;   // 2 + (sizeof(u8 *) >> 1)    }    Img::$firstpal[$pe + 0] = 0xff;    Img::$firstpal[$pe + 1] = 0;    Img::$firstpal[$pe + 2] = 0;}// Native-planar clinepal: stamp the per-row bank into planes 4-5 (PLANAR_LINEPAL_ENABLE/DISABLE: no-ops).function setlinepalet(): void{    if (Alis::$varD7 < 0) {        Img::$flinepal = 0;        Img::$tlinepal[0] = 0;        Img::$tlinepal[1] = 0;        Img::$tlinepal[2] = 0xff;        Img::$tlinepal[3] = 0;        linepal();        return;    }    if (Img::$logy2 <= Alis::$varD7) {        Alis::$varD7 = Img::$logy2;    }    $cur = 0;   // tlinepal_ptr    $prev = 0;  // prevtlpal_ptr    do {        $prev = $cur;        if (Alis::$varD7 == (Img::$tlinepal[$prev] ?? 0)) {            if (Alis::$varD6 == (Img::$tlinepal[$prev + 1] ?? 0)) {                return;            }            Img::$tlinepal[$prev + 1] = s16(Alis::$varD6);            Img::$flinepal = 1;            linepal();            return;        }        $cur = $prev + 2;    } while ((Img::$tlinepal[$prev] ?? 0) < Alis::$platform->height);    // check whether we are not using too many palettes    if ($prev - 8 < 0) {        do {            $prev = $cur;            Img::$tlinepal[$prev] = Img::$tlinepal[$prev - 2] ?? 0;            Img::$tlinepal[$prev + 1] = Img::$tlinepal[$prev - 1] ?? 0;            $cur = $prev - 2;        } while (s16(Alis::$varD7 - Img::$tlinepal[$prev]) < 0);        Img::$tlinepal[$prev] = s16(Alis::$varD7);        Img::$tlinepal[$prev + 1] = s16(Alis::$varD6);        Img::$flinepal = 1;        linepal();    }}function setmpalet(): void{    Img::$ftopal = 0xff;    Img::$thepalet = 0;    Img::$defpalet = 0;    // Direct palette write (cdefcolor): rebuild pal16 / CLUT.}// ---------------------------------------------------------------------------------------------// Sprite management// ---------------------------------------------------------------------------------------------function printelem(): void{    $cursprit = Img::$debsprit;    $cursprit += 0x78;    $cursprit += 0x60;    do {        $cursprit += 0x30;    } while ($cursprit < Img::$debsprit + 16 * 0x30);}function inisprit(): void{    Img::$debsprit = 0;    Img::$finsprit = 0xffff;    $cursprit = Img::$debsprit;    Img::$tvsprite = 0x8000;    Img::$basesprite = Img::$debsprit + 0x8000;    // PORT: the C writes logx1/logx2/logy2/logy1, 0 and 0xfe into raw spritemem bytes 0x0c..0x5c    // (below basesprite, never reached through SPRITE_VAR). The port keeps sprites as objects only:    // those writes are dropped (only a raw save state would see them).    Img::$backsprite = 0x000e; // 0x8028;    Img::$texsprite = 0x0042; // 0x8050;    Alis::$mousflag = 0;    Img::$atexsprite = 0x78;    Img::$libsprit = 0xa8;    $cursprit += 0xa8;    for (; $cursprit + C::SPRITE_SZ < Img::$finsprit; $cursprit += C::SPRITE_SZ) {        sprite_var($cursprit)->to_next = ($cursprit + C::SPRITE_SZ) & 0xffff;    }    sprite_var($cursprit)->to_next = 0;}function searchelem(int &$curidx, int &$previdx): int{    $curidx = get_0x18_unknown(Alis::$script->vram_org);    if ($curidx != 0) {        do {            $cursprvar = sprite_var($curidx);            $screen_id = $cursprvar->screen_id;            if ($screen_id <= get_0x16_screen_id(Alis::$script->vram_org)) {                if (get_0x16_screen_id(Alis::$script->vram_org) != $screen_id) {                    break;                }                $num = $cursprvar->numelem;                if ($num <= Img::$numelem) {                    if (Img::$numelem == $num) {                        return 1;                    }                    break;                }            }            $previdx = $curidx;            $curidx = $cursprvar->to_next;        } while ($curidx != 0);    }    return 0;}function searchtete(int &$curidx, int &$previdx): int{    $previdx = 0;    $curidx = get_0x18_unknown(Alis::$script->vram_org);    if ($curidx != 0) {        $screenid = s16(get_0x16_screen_id(Alis::$script->vram_org));        do {            $sprite = sprite_var($curidx);            $sprscid = $sprite->screen_id;            if ($sprscid <= $screenid) {                if ($screenid == $sprscid) {                    return (int) ($screenid == $sprscid);                }                break;            }            $previdx = $curidx;            $curidx = $sprite->to_next;        } while ($curidx != 0);    }    return 0;}function testnum(int &$curidx): int{    $cursprvar = sprite_var($curidx);    return ($cursprvar !== null && $cursprvar->screen_id == get_0x16_screen_id(Alis::$script->vram_org) && $cursprvar->numelem == Img::$numelem) ? 1 : 0;}function nextnum(int &$curidx, int &$previdx): int{    $previdx = $curidx;    $curidx = sprite_var($curidx)->to_next;    $cursprvar = sprite_var($curidx);    return ($cursprvar !== null && $cursprvar->screen_id == get_0x16_screen_id(Alis::$script->vram_org) && $cursprvar->numelem == Img::$numelem) ? 1 : 0;}function createlem(int &$curidx, int &$previdx): void{    $cursprvar = sprite_var(Img::$libsprit);    if (Img::$libsprit != 0) {        $sprit = Img::$libsprit;        $nextsprit = $cursprvar->to_next;        if ($previdx == 0) {            set_0x18_unknown(Alis::$script->vram_org, Img::$libsprit);            Img::$libsprit = $nextsprit;        } else {            $prevsprvar = sprite_var($previdx);            $prevsprvar->to_next = Img::$libsprit;            Img::$libsprit = $nextsprit;        }        $scrnidx = s16(get_scr_screen_id(get_0x16_screen_id(Alis::$script->vram_org)));        $scrnsprvar = sprite_var($scrnidx);        $cursprvar->state = -1;        $cursprvar->numelem = s8(Img::$numelem);        $cursprvar->screen_id = s16(get_0x16_screen_id(Alis::$script->vram_org));        if (Alis::$ftextfield) {            $cursprvar->unknown0x30 = Alis::$textfx & 0xffff;            $cursprvar->unknown0x32 = Alis::$textfy & 0xffff;        } else {            $cursprvar->unknown0x30 = 0x8000;            $cursprvar->unknown0x32 = 0x8000;        }        $cursprvar->to_next = $curidx & 0xffff;        $cursprvar->link = $scrnsprvar->link;        $cursprvar->prev = $scrnidx & 0xffff;        if ($cursprvar->link != 0) {            sprite_var($cursprvar->link)->prev = $sprit;        }        $scrnsprvar->link = $sprit;        $curidx = $sprit;    }}function delprec(int $elemidx): void{    $elemidx &= 0xffff;    $cursprvar = sprite_var($elemidx);    $scridx = $cursprvar->screen_id;    if ($elemidx == get_scr_screen_id($scridx)) {        // Deleting the list head: new head is the sprite's link (not its screen_id).        set_scr_screen_id($scridx, $cursprvar->link);        return;    }    $spridx = get_scr_screen_id($scridx);    $tmpsprvar = sprite_var($spridx);    while ($tmpsprvar !== null && $elemidx != $tmpsprvar->link) {        $spridx = $tmpsprvar->link;        $tmpsprvar = sprite_var($spridx);    }    if ($tmpsprvar !== null) {        $tmpsprvar->link = $cursprvar->link;        if ($cursprvar->link != 0) {            sprite_var($cursprvar->link)->prev = $spridx & 0xffff;        }    }}function killelem(int &$curidx, int &$previdx): void{    $cursprvar = sprite_var($curidx);    if (Alis::$ferase == 0 && -1 < $cursprvar->state) {        $cursprvar->state = 1;        if ($previdx == 0) {            set_0x18_unknown(Alis::$script->vram_org, $cursprvar->to_next);        } else {            sprite_var($previdx)->to_next = $cursprvar->to_next;        }    } else {        if ($previdx == 0) {            set_0x18_unknown(Alis::$script->vram_org, $cursprvar->to_next);        } else {            sprite_var($previdx)->to_next = $cursprvar->to_next;        }        $cursprvar->to_next = Img::$libsprit;        Img::$libsprit = $curidx & 0xffff;        delprec($curidx);    }    if ($previdx == 0) {        $curidx = get_0x18_unknown(Alis::$script->vram_org);        return;    }    $curidx = sprite_var($previdx)->to_next;}function textfield_match(int $idx): int{    if (!Alis::$ftextfield) {        return 1;    }    $s = sprite_var($idx);    return (int) (s16($s->unknown0x30) == Alis::$textfx && s16($s->unknown0x32) == Alis::$textfy);}function getelem(int &$newidx, int &$oldidx): void{    $ret = searchelem($newidx, $oldidx);    if ($ret) {        do {            if (sprite_var($newidx)->state == 0 && textfield_match($newidx)) {                sprite_var($newidx)->state = 2;                return;            }            $ret = nextnum($newidx, $oldidx);        } while ($ret);    }    createlem($newidx, $oldidx);}function put(int $idx): void{    Alis::$fmuldes = 0;    putin($idx);}function putfin(): void{    if (Alis::$fmuldes == 0) {        $newidx = 0;        $oldidx = 0;        if (searchelem($newidx, $oldidx) != 0) {            do {                while (sprite_var($newidx)->state == 0 && textfield_match($newidx)) {                    killelem($newidx, $oldidx);                    if ($newidx == 0) {                        Alis::$fadddes = 0;                        return;                    }                    if (!testnum($newidx)) {                        Alis::$fadddes = 0;                        return;                    }                }            } while (nextnum($newidx, $oldidx));        }    }    Alis::$fadddes = 0;}function scalaire_v10(int $scene, int &$x, int &$y, int &$z): void{    $scene = s16($scene);    $m = Alis::$basemain + $scene + 0x1a;    $x0 = $x;    $y0 = $y;    $z0 = $z;    if (get_scr_numelem($scene) < 0) {        $x = s16(s8(xread8($m + 0)) * $x0 + s8(xread8($m + 2)) * $z0);        if (Alis::$platform->kind == C::EPlatformPC) {            $x = s16($x + s8(xread8($m + 1)) * $y0);        }        $y = s16(s8(xread8($m + 3)) * $x0 + s8(xread8($m + 4)) * $y0 + s8(xread8($m + 5)) * $z0);        $z = s16(s8(xread8($m + 6)) * $x0 + s8(xread8($m + 7)) * $y0 + s8(xread8($m + 8)) * $z0);    } else {        $y = s16($y0 * s8(xread8($m + 4)) - $z0);        $z = s16($y0);    }}function topix_v10(int $scene, int &$x, int &$y, int &$z): void{    $scene = s16($scene);    $m = Alis::$basemain + $scene;    $x = s16(Img::$oldcx - xread16($m + 0x12));    $y = s16(Img::$oldcy - xread16($m + 0x14));    $z = s16(Img::$oldcz - xread16($m + 0x16));    scalaire_v10($scene, $x, $y, $z);    $sh = xread8($m + 0x18) & 0x3f;    $x = s16(($x >> $sh) + xread16($m + 0xa));    $y = s16(($y >> $sh) + xread16($m + 0xc));    $z = s16($z >> $sh);}function picture_v10(int $idx): void{    $addr = adresdes($idx & 0xffff);    $res = $addr;    if (xread8($res) == 0xfe) {        if (Alis::$platform->kind != C::EPlatformPC) {            topalette($res, 0);        }        return;    }    if (!(xread8($res) == 0 || (Alis::$platform->kind == C::EPlatformPC && xread8($res) <= 2))) {        $x = Img::$depx;        $y = Img::$depy;        $z = Img::$depz;        $invx = Img::$invert_x;        for ($cur = $res + 2, $end = $cur + xread8($res + 1) * 8; $cur < $end; $cur += 8) {            $elem = s16(read16($cur));            Img::$depx = s16(Img::$depx + (Img::$invert_x ? -read16($cur + 2) : read16($cur + 2)));            Img::$depy = s16(Img::$depy + read16($cur + 4));            Img::$depz = s16(Img::$depz + read16($cur + 6));            if ($elem < 0) {                $elem &= 0x7fff;                Img::$invert_x ^= 1;            }            picture_v10($elem);            Img::$depx = $x;            Img::$depy = $y;            Img::$depz = $z;            Img::$invert_x = $invx;        }        return;    }    $pic = new Sprite(0);   // sSprite pic = {0}    $pic->data = $pic->newad = $addr & 0xffffff;    $pic->newf = s8(Img::$invert_x);    $pic->width = s16(read16($res + 2));    $pic->height = s16(read16($res + 4));    $pic->newx = s16(Alis::$poldx + Img::$depx - ($pic->width >> 1));    $pic->newy = s16(Alis::$poldy + Img::$depy - ($pic->height >> 1));    $cx1 = Img::$clipx1;    $cy1 = Img::$clipy1;    $cx2 = Img::$clipx2;    $cy2 = Img::$clipy2;    Img::$clipx1 = 0;    Img::$clipy1 = 0;    Img::$clipx2 = s16(Alis::$platform->width - 1);    Img::$clipy2 = s16(Alis::$platform->height - 1);    destofen($pic);    Img::$clipx1 = $cx1;    Img::$clipy1 = $cy1;    Img::$clipx2 = $cx2;    Img::$clipy2 = $cy2;}function putin(int $idx): void{    $idx &= 0xffff;    // if there is no scene opened, there is nowhere to add sprite    $scrnidx = s16(get_scr_screen_id(get_0x16_screen_id(Alis::$script->vram_org)));    if ($scrnidx == 0) {        return;    }    $x = Img::$depx;    $z = Img::$depz;    $y = Img::$depy;    $addr = adresdes($idx);    if (Alis::$platform->version == 10) {        $resourcedata = $addr;        if (Alis::$platform->kind == C::EPlatformPC) {            $compositimg = (int) (xread8($resourcedata) > 2);            if ($compositimg && xread8($resourcedata) == 0xfe) {                return;            }        } else {            $compositimg = xread8($resourcedata);        }    } else {        $addr = s32($addr + xread32($addr));        $resourcedata = $addr;        $compositimg = (int) (xread8($resourcedata) > 0x80);    }    if (Alis::$platform->version >= 60 && xread8($resourcedata) == 2) {        putin_v6composite($resourcedata, $x, $y, $z); // image_v6.php        putfin();        return;    }    if ($compositimg) {        if (xread8($resourcedata) == 0xfe) {            if (dos_pal_active()) {                dos_putin_palette($resourcedata);            } else {                topalette($resourcedata, 0);            }            return;        }        // handle composit images        $rsrccount = xread8($resourcedata + 1);        $currsrc = $resourcedata + 2;        for ($i = 0; $i < $rsrccount; $i++) {            $invx = Img::$invert_x;            $muldes = Alis::$fmuldes;            $curelem = s16(read16($currsrc + 0));            $curdepx = s16(read16($currsrc + 2));            if (Img::$invert_x != 0) {                $curdepx = s16(-$curdepx);            }            Img::$depx = s16(Img::$depx + $curdepx);            $curdepy = s16(read16($currsrc + 4));            Img::$depy = s16($curdepy + $y);            $curdepz = s16(read16($currsrc + 6));            Img::$depz = s16($curdepz + $z);            if ($curelem < 0) {                $curelem = $curelem & 0x7fff;                Img::$invert_x ^= 1;            }            Alis::$fmuldes = 1;            putin($curelem);            Img::$depx = $x;            Img::$depy = $y;            Img::$depz = $z;            Img::$invert_x = $invx;            Alis::$fmuldes = $muldes;            $currsrc += 8;        }        Alis::$fmuldes = 0;    } else {        $newidx = 0;        $oldidx = 0;        if (Alis::$fadddes == 0) {            if (Alis::$fmuldes) {                getelem($newidx, $oldidx);            } else {                if (searchelem($newidx, $oldidx) == 0) {                    createlem($newidx, $oldidx);                }                if (-1 < sprite_var($newidx)->state) {                    sprite_var($newidx)->state = 2;                }            }        } else {            getelem($newidx, $oldidx);        }        $addr = adresdes($idx);        putmapin($newidx, $addr);        return;    }    putfin();}function putmapin(int $spridx, int $bitmap): void{    sprite_var($spridx)->hdChar = SysVars::$hdChar;   // HD edition: a character of the font (fn/hd.php)    $sprite = sprite_var($spridx);    $sprite->data = $bitmap & 0xffffff;    $sprite->newad = 0;    $sprite->flaginvx = Img::$invert_x & 0xff;    if (Alis::$platform->version == 10) {        $x = 0;        $y = 0;        $z = 0;        topix_v10(get_0x16_screen_id(Alis::$script->vram_org), $x, $y, $z);        $sprite->script_ent = get_0x0e_script_ent(Alis::$script->vram_org) & 0xffff;        $sprite->clinking = -1;        $sprite->cordspr = 0;        $sprite->chsprite = 0xff;        $sprite->creducing = 0;        $sprite->credon_off = -1;        $sprite->depx = s16($x + Img::$depx);        $sprite->depy = s16($y + Img::$depy);        $sprite->depz = s16($z + Img::$depz);        putfin();        return;    }    $sprite->sprite_0x28 = s32(get_0x28_unknown(Alis::$script->vram_org));    if (Alis::$fochar && Alis::$focolor && sys_is_dos_v3()) {        // v3 DOS put (0x5627): a character in a text colour; word +0x26 (the high word here) = 0x8000 | colour        $sprite->sprite_0x28 = s32(($sprite->sprite_0x28 & 0xffff) | ((0x8000 | Alis::$focolor) << 16));    }    $sprite->script_ent = get_0x0e_script_ent(Alis::$script->vram_org) & 0xffff;    $sprite->clinking = s16(get_0x2a_clinking(Alis::$script->vram_org));    $sprite->cordspr = get_0x2b_cordspr(Alis::$script->vram_org) & 0xff;    $sprite->creducing = get_0x27_creducing(Alis::$script->vram_org) & 0xff;    $sprite->credon_off = s8(get_0x25_credon_credoff(Alis::$script->vram_org));    $contextsize = get_context_size();    if ($contextsize > 0x2e) {        $sprite->chsprite = get_0x2f_chsprite(Alis::$script->vram_org) & 0xff;        if (s8($sprite->credon_off) == -0x80) {            $sprite->newzoomx = get_0x38_unknown(Alis::$script->vram_org) & 0xffff;            $sprite->newzoomy = get_0x36_unknown(Alis::$script->vram_org) & 0xffff;            $sprite->creducing = 0;        }    }    if (Alis::$platform->kind == C::EPlatformPC && Alis::$platform->uid == C::EGameColorado) {        // Colorado DOS: its credon test never branches, so the context values are always taken.        $sprite->creducing = get_0x27_creducing(Alis::$script->vram_org) & 0xff;        $sprite->credon_off = s8(get_0x26_creducing(Alis::$script->vram_org));    } elseif (s8($sprite->credon_off) >= 0) {        $sprite->creducing = get_0x27_creducing(Alis::$script->vram_org) & 0xff;        $sprite->credon_off = s8(get_0x26_creducing(Alis::$script->vram_org));        if (s8($sprite->credon_off) < 0) {            $sprite->creducing = 0;            $sprite->credon_off = s8(xread8(Alis::$basemain + get_0x16_screen_id(Alis::$script->vram_org) + 0x1f));        }    }    $sprite->depx = s16(Img::$oldcx + Img::$depx);    $sprite->depy = s16(Img::$oldcy + Img::$depy);    $sprite->depz = s16(Img::$oldcz + Img::$depz);    putfin();}// v6 put chain (v6_elemhead ... killallelem_v6, put_v6, putin_v6...): fn/image_v6.php./** * v3 DOS: the text colour a character sprite carries (byte +0x27 == 0x80, colour in byte +0x26: the high word * of sprite_0x28, set by putmapin while put_char puts it), or -1. */function dos_v3_text_colour(Sprite $sprite): int{    if (!sys_is_dos_v3() || (($sprite->sprite_0x28 >> 24) & 0xff) != 0x80) {        return -1;    }    return ($sprite->sprite_0x28 >> 16) & 0xff;}function put_char(int $character): void{    $character = s8($character);    if (Alis::$charmode == 0) {        // PORT: the C printf()s the character to stdout (debug console text mode): dropped.        return;    }    if (Alis::$charmode != 1) {        if (Alis::$charmode != 2) {            return;        }        if ($character == 0x0a) { // '\n'            Img::$depz = s16(Img::$depz - Alis::$fohaut);        } elseif ($character == 0x0d) { // '\r'            Img::$depx = 0;        } else {            if ($character != 0x20) {                if (Alis::$fonum < 0) {                    return;                }                if (sys_is_dos_v3()) {                    // 0x3f0b: the unsigned character byte, js on the subtraction, then an unsigned compare                    $charidx = s16(($character & 0xff) - Alis::$foasc);                    $inrange = $charidx >= 0 && $charidx < (Alis::$fomax & 0xffff);                } else {                    $charidx = s16($character - Alis::$foasc);                    $inrange = (-1 < $charidx) && (s16($charidx - Alis::$fomax) < 0);                }                if ($inrange) {                    Alis::$flagmain = (Alis::$platform->version >= 60) ? Alis::$fomain : 1;                    Img::$invert_x = 0;                    Alis::$fadddes = 1;                    SysVars::$hdChar = $character & 0xff;                    Alis::$fochar = 1;                    put($charidx + Alis::$fonum);                    Alis::$fochar = 0;                    SysVars::$hdChar = -1;                }            }            Img::$depx = s16(Img::$depx + Alis::$folarg);        }    }}function put_string(): void{    $saved_ftext = Alis::$ftextfield;    if (Alis::$platform->version >= 60 && Alis::$charmode == 2) {        put_string_v6_align(); // image_v6.php    }    for ($strptr = Alis::$sd7; ($c = ord(Alis::$mem[$strptr])) != 0; $strptr++) {        put_char($c);    }    Alis::$ftextfield = $saved_ftext;}function valtostr(int $string, int $value): void{    $value = s16($value);    $strptr = $string;    $tmpval = $value;    if ($tmpval < 0) {        $strptr = $string + 1;        Alis::$mem[$string] = chr(0x2d);        $tmpval = -$tmpval;    }    $tabptr = 0;    $length = 9;    $res = 0;    $c = 0;    do {        $tprintv = ImageVars::$tprintd0[$tabptr++];        $cw = -0x30;        do {            $tmpval -= $tprintv;            if ($tmpval < 0) {                break;            }            $cw = s16($cw - 1);        } while ($cw != -1);        $c = s8(-s8($cw));        if ($c != 0x30) {            $res = 1;            $tmpptr = $strptr + 1;            Alis::$mem[$strptr] = chr($c & 0xff);        } elseif ($res) {            $tmpptr = $strptr + 1;            Alis::$mem[$strptr] = chr($c & 0xff);        } else {            $tmpptr = $strptr;        }        $tmpval += $tprintv;        $length--;        $strptr = $tmpptr;        if ($length == -1) {            if (!$res) {                Alis::$mem[$strptr++] = chr($c & 0xff);            }            Alis::$mem[$strptr] = "\0";            return;        }    } while (true);}// ---------------------------------------------------------------------------------------------// calculate what to draw and where// ---------------------------------------------------------------------------------------------// u16: the free list runs past 0x7fff; an s16 index sign-flips in SPRITE_VAR math.function inilink(int $elemidx): int{    Img::$blocx1 = 0x7fff;    Img::$blocy1 = 0x7fff;    Img::$blocx2 = -0x8000;    Img::$blocy2 = -0x8000;    return sprite_var($elemidx)->clinking;}function calcfen(int $elemidx1, int $elemidx3): int{    if (Img::$joints == 0) {        $idx1sprvar = sprite_var($elemidx1);        if ($idx1sprvar->newd < 0) {            return 0;        }        // Inclusive bounds (width is stored as w-1), as the original.        Img::$blocx1 = $idx1sprvar->newx;        Img::$blocy1 = $idx1sprvar->newy;        Img::$blocx2 = s16(Img::$blocx1 + $idx1sprvar->width);        Img::$blocy2 = s16(Img::$blocy1 + $idx1sprvar->height);    }    $idx3sprvar = sprite_var($elemidx3);    $tmpx = $idx3sprvar->newx;    $tmpy = $idx3sprvar->newy;    $tmpw = $idx3sprvar->depx;    $tmph = $idx3sprvar->depy;    if (Img::$blocx1 <= $tmpw && Img::$blocy1 <= $tmph && $tmpx <= Img::$blocx2 && $tmpy <= Img::$blocy2) {        Img::$fenx1 = Img::$blocx1;        if (Img::$blocx1 < $tmpx) {            Img::$fenx1 = $tmpx;        }        Img::$feny1 = Img::$blocy1;        if (Img::$blocy1 < $tmpy) {            Img::$feny1 = $tmpy;        }        Img::$fenx2 = Img::$blocx2;        if ($tmpw < Img::$blocx2) {            Img::$fenx2 = $tmpw;        }        Img::$feny2 = Img::$blocy2;        if ($tmph < Img::$blocy2) {            Img::$feny2 = $tmph;        }        // 16px-align X after clamping, as the original. clrvga_68k needs odd width,        // clrvga_dos width % 4 == 0, skytofen constant clipx1 parity; planar blits whole chunks.        // (DOS original aligns bloc before clamping.)        $ax1 = s16(Img::$fenx1 & ~15);        $ax2 = s16(Img::$fenx2 | 15);        if ($ax1 < 0) {            $ax1 = 0;        }        if ($ax2 > Alis::$platform->width - 1) {            $ax2 = s16(Alis::$platform->width - 1);        }        Img::$fenx1 = $ax1;        Img::$fenx2 = $ax2;        Img::$fenlargw = s16((((Img::$fenx2 - Img::$fenx1) + 1) & 0xffff) >> 2);        return 1;    }    return 0;}function clipfen(Sprite $sprite): int{    Img::$fclip = 0;    $spritex1 = $sprite->newx;    if (Img::$fenx2 < $spritex1) {        return Img::$fclip;    }    $spritey1 = $sprite->newy;    if (Img::$feny2 < $spritey1) {        return Img::$fclip;    }    $spritex2 = $sprite->depx;    if ($spritex2 < Img::$fenx1) {        return Img::$fclip;    }    $spritey2 = $sprite->depy;    if ($spritey2 < Img::$feny1) {        return Img::$fclip;    }    if ($spritex1 < Img::$fenx1) {        $spritex1 = Img::$fenx1;    }    if ($spritey1 < Img::$feny1) {        $spritey1 = Img::$feny1;    }    if (Img::$fenx2 < $spritex2) {        $spritex2 = Img::$fenx2;    }    if (Img::$feny2 < $spritey2) {        $spritey2 = Img::$feny2;    }    Img::$clipx1 = $spritex1;    Img::$clipy1 = $spritey1;    Img::$clipx2 = $spritex2;    Img::$clipy2 = $spritey2;    Img::$clipl = s16((Img::$clipx2 - Img::$clipx1) + 1);    Img::$cliph = s16((Img::$clipy2 - Img::$clipy1) + 1);    Img::$fclip = 1;    return Img::$fclip;}function rangesprite(int $elemidx1, int $elemidx2, int $elemidx3): int{    $elemidx1 &= 0xffff;    $elemidx2 &= 0xffff;    $elemidx3 &= 0xffff;    $sprite1 = sprite_var($elemidx1);    $newd1 = $sprite1->newd;    $cordspr1 = s8($sprite1->cordspr);    $numelem1 = $sprite1->numelem;    if (Img::$wback != 0 && $elemidx1 != Img::$backsprite && Img::$backprof <= $newd1) {        Img::$pback = 1;    }    $sprite3 = sprite_var($elemidx3);    while ($sprite3->link != 0) {        $linksprite = sprite_var($sprite3->link);        // Signed compare: cscback sets the backsprite's cordspr to 0x80 (-128) so it        // sorts first at equal depth.        if (-1 < $linksprite->state && $linksprite->newd <= $newd1 && ($linksprite->newd < $newd1 || (s8($linksprite->cordspr) <= $cordspr1 && (s8($linksprite->cordspr) < $cordspr1 || ($linksprite->numelem <= $numelem1 && ($linksprite->numelem < $numelem1 || -1 == $sprite1->state)))))) {            break;        }        $elemidx3 = $sprite3->link;        $sprite3 = $linksprite;    }    $sprite1->state = 0;    $sprite1->link = $sprite3->link;    $sprite3->link = $elemidx1;    return ($elemidx2 == $elemidx3) ? $elemidx1 : $elemidx2;}// rangesprite_v6(): fn/image_v6.php.function tstjoints(int $elemidx): void{    $sprvar = sprite_var($elemidx);    $tmpx = s16($sprvar->newx + $sprvar->width);    $tmpy = s16($sprvar->newy + $sprvar->height);    if (-1 < $sprvar->newd && -1 < Img::$newd && $sprvar->newx <= Img::$newx + Img::$newl && $sprvar->newy <= Img::$newy + Img::$newh && Img::$newx <= $tmpx && Img::$newy <= $tmpy) {        Img::$blocx1 = $sprvar->newx;        if (Img::$newx < $sprvar->newx) {            Img::$blocx1 = Img::$newx;        }        Img::$blocy1 = $sprvar->newy;        if (Img::$newy < $sprvar->newy) {            Img::$blocy1 = Img::$newy;        }        if ($tmpx < s16(Img::$newx + Img::$newl)) {            $tmpx = s16(Img::$newx + Img::$newl);        }        if ($tmpy < s16(Img::$newy + Img::$newh)) {            $tmpy = s16(Img::$newy + Img::$newh);        }        // Inclusive bounds, like the whole bloc/fen pipeline.        Img::$blocx2 = $tmpx;        Img::$blocy2 = $tmpy;        Img::$joints = 1;        return;    }    Img::$joints = 0;}function scalaire(int $scene, int &$x, int &$y, int &$z): void{    $scene = s16($scene);    if (get_scr_numelem($scene) < 0) {        $prevx = s32(get_scr_unknown0x20($scene) * $x + get_scr_unknown0x21($scene) * $y + get_scr_unknown0x22($scene) * $z);        $prevy = s32(get_scr_unknown0x23($scene) * $x + get_scr_unknown0x24($scene) * $y + get_scr_unknown0x25($scene) * $z);        $prevz = s32(get_scr_unknown0x26($scene) * $x + get_scr_unknown0x27($scene) * $y + get_scr_unknown0x28($scene) * $z);        $x = s16($prevx);        $y = s16($prevz);        $z = s16($prevy);    } else {        $prevy = $y;        $y = s16($y * get_scr_unknown0x24($scene) - $z);        $z = $prevy;    }}function depscreen(int $scene, int $elemidx): void{    $scene &= 0xffff;    if (Alis::$platform->version == 10) {        return;    }    if (Alis::$platform->version < 60) {        set_scr_depx($scene, get_scr_depx($scene) + get_scr_unknown0x2a($scene));        set_scr_depy($scene, get_scr_depy($scene) + get_scr_unknown0x2c($scene));        set_scr_depz($scene, get_scr_depz($scene) + get_scr_unknown0x2e($scene));    }    for ($sprite = sprite_var($elemidx); $sprite !== null; $sprite = sprite_var($sprite->link)) {        if (-1 < s8($sprite->chsprite) && $sprite->state == 0) {            $sprite->state = 2;        }    }    if ((Alis::$platform->uid == C::EGameTarghan0 || Alis::$platform->uid == C::EGameTarghan1) && (Alis::$platform->kind == C::EPlatformAmiga || Alis::$platform->kind == C::EPlatformAtari)) {        set_scr_state($scene, get_scr_state($scene) & 0x7f);    }}function deptopix(int $scene, int $elemidx): void{    $scene &= 0xffff;    if (Alis::$platform->version == 10) {        $sprite = sprite_var($elemidx);        $bmp = $sprite->data;        Img::$newf = s16($sprite->flaginvx);        Img::$newad = $sprite->data;        Img::$newl = s16(read16($bmp + 2));        Img::$newh = s16(read16($bmp + 4));        Img::$newzoomx = 0;        Img::$newzoomy = 0;        Img::$newx = s16($sprite->depx - (Img::$newl >> 1));        Img::$newy = s16($sprite->depy - (Img::$newh >> 1));        Img::$newd = $sprite->depz;        return;    }    if ((get_scr_numelem($scene) & 2) != 0) {        landtopix(Alis::$basemain + $scene, $elemidx); // Robinson's Requiem 3D land (rrq3d.php)    } else {        $elemsprvar = sprite_var($elemidx);        $scene = $elemsprvar->screen_id & 0xffff;        Img::$newf = s16($elemsprvar->flaginvx);        $offset = 0;        if (Alis::$platform->version >= 60) {            deptopix_v6($elemsprvar, $scene); // image_v6.php: the version >= 60 path of the C            return;        }        $tmpdepx = s16($elemsprvar->depx - get_scr_depx($scene));        $tmpdepy = s16($elemsprvar->depy - get_scr_depy($scene));        $tmpdepz = s16($elemsprvar->depz - get_scr_depz($scene));        scalaire($scene, $tmpdepx, $tmpdepy, $tmpdepz);        $cred = get_scr_creducing($scene);        if (-1 < s8($cred) && -1 < s8($elemsprvar->credon_off)) {            if ($tmpdepz == 0) {                $tmpdepz = 1;            }            // PORT: shift counts >= 32 are UB in C; masked to 5 bits like x86 (shl32 / & 31).            $tmpdepx = s16(cdiv(shl32($tmpdepx, $cred & 0x3f), $tmpdepz));            $tmpdepy = s16(cdiv(shl32($tmpdepy, $cred & 0x3f), $tmpdepz));            $offset = s16(($tmpdepz >> (($elemsprvar->credon_off & 0x3f) & 31)) + s8($elemsprvar->creducing));            if ($offset < 0) {                $offset = 0;            } else {                // NOTE: must be byte read - 16-bit read includes next field, gives wrong                // values on big-endian. May need s16 for v3.0+ games in the future.                $clink = s8(xread8(Alis::$basemain + $scene + 0x1e));                if ($clink < $offset) {                    $offset = $clink;                }                $offset = s16($offset << 2);            }        }        $tmpdepx = s16(($tmpdepx >> ((get_scr_credon_off($scene) & 0x3f) & 31)) + get_scr_unknown0x0a($scene));        $tmpdepy = s16(($tmpdepy >> ((get_scr_credon_off($scene) & 0x3f) & 31)) + get_scr_unknown0x0c($scene));        Img::$newad = s32($elemsprvar->data + $offset);        $spritedata = s32(Img::$newad + xread32(Img::$newad));        if (xread8($spritedata) == 3) {            $tmpdepx = s16($tmpdepx + ($elemsprvar->flaginvx ? -1 : 1) * read16($spritedata + 4));            $tmpdepy = s16($tmpdepy + read16($spritedata + 6));            if (xread8($spritedata + 1) != 0) {                Img::$newf ^= 1;            }            Img::$newad = s32(Img::$newad + s16(read16($spritedata + 2) << 2));            $spritedata = s32(Img::$newad + xread32(Img::$newad));        }        Img::$newl = s16(read16($spritedata + 2));        Img::$newh = s16(read16($spritedata + 4));        $anchorx = Img::$newl >> 1;        $anchory = Img::$newh >> 1;        Img::$newzoomx = 0;        Img::$newzoomy = 0;        if (Alis::$platform->kind == C::EPlatformMac) {            mac_update_pos($tmpdepx, $tmpdepy);        }        Img::$newx = s16($tmpdepx - $anchorx);        Img::$newy = s16($tmpdepy - $anchory);        Img::$newd = $tmpdepz;    }}function waitphysic(): void{    // PORT: the C busy-waits while image.fphysic != 0 (never called); non-blocking port: returns at once.}function trsfen(int $src, int $tgt): void{    $fx1 = Img::$fenx1;    $fy1 = Img::$feny1;    $fx2 = Img::$fenx2;    $fy2 = Img::$feny2;    // Clamp to screen bounds    if ($fx1 < 0) {        $fx1 = 0;    }    if ($fy1 < 0) {        $fy1 = 0;    }    if ($fx2 >= Alis::$platform->width) {        $fx2 = Alis::$platform->width - 1;    }    if ($fy2 >= Alis::$platform->height) {        $fy2 = Alis::$platform->height - 1;    }    if ($fx2 < $fx1 || $fy2 < $fy1) {        return;    }    $w = Alis::$platform->width;    $src += $fx1 + $fy1 * $w;    $tgt += $fx1 + $fy1 * $w;    $n = $fx2 - $fx1 + 1;    if ($n == $w) {        // whole rows: one copy        mem_move($tgt, $src, $n * ($fy2 - $fy1 + 1));        return;    }    for ($y = $fy1; $y <= $fy2; $y++) {        mem_move($tgt, $src, $n);        $tgt += $w;        $src += $w;    }}function phytolog(): void{    Img::$fenx1 = 0;    Img::$feny1 = 0;    Img::$fenx2 = s16(Alis::$platform->width - 1);    Img::$feny2 = s16(Alis::$platform->height - 1);    trsfen(Img::$physic, Img::$logic);}function tvtofen(): void{    trsfen(Img::$physic, Img::$logic);}function memfen(): void{    // image.ptabfen: index into Img::$tabfen    Img::$tabfen[Img::$ptabfen + 0] = Img::$fenx1;    Img::$tabfen[Img::$ptabfen + 1] = Img::$fenx2;    Img::$tabfen[Img::$ptabfen + 2] = Img::$feny1;    Img::$tabfen[Img::$ptabfen + 3] = Img::$feny2;    Img::$ptabfen += 4;    if (Img::$ptabfen < 640) {        return;    }    // error: ptabfen pointing outside of available mem! (debug log only)}function oldfen(): void{    for ($tabptr = 0; $tabptr < Img::$ptabfen; $tabptr += 4) {        Img::$fenx1 = Img::$tabfen[$tabptr + 0];        Img::$fenx2 = Img::$tabfen[$tabptr + 1];        Img::$feny1 = Img::$tabfen[$tabptr + 2];        Img::$feny2 = Img::$tabfen[$tabptr + 3];        tvtofen();    }}// v6 dirty-rectangle list (v6dirty_reset/count/set_window/add, v6clip, v6dirty_sprite, v6dirty_add3d):// fn/image_v6.php.function setphysic(): void{    if (Img::$insid == 0) {        Host::$pixelbuf->data = Img::$physic;    }    Img::$bufpack = Img::$logic;    Img::$fphysic = 1;}// when position or angle changes set screen update flagfunction folscreen(int $scene): void{    $v3 = Alis::$platform->version >= 30;    $wcy = $v3 ? 8 : 2;           // ALIS_SCR_WCY    $wcz = $v3 ? 16 : 4;          // ALIS_SCR_WCZ    $wcax = $v3 ? 0x18 : -1;      // ALIS_SCR_WCAX    $wcay = $v3 ? 0x20 : -1;      // ALIS_SCR_WCAY    $wcaz = $v3 ? 0x28 : -1;      // ALIS_SCR_WCAZ    $s = Alis::$basemain + $scene;    if (-1 < xread16($s + 0x60)) {        $addr = xread32(Alis::$atent + xread16($s + 0x60));        if ($addr != 0) {            if ((xread8($s + 0x84) & 1) != 0) {                $val = s16(xread16($s + 0x86) + xread16($addr + C::ALIS_SCR_WCX));                if ($val != xread16($s + 0x16)) {                    xwrite16($s + 0x16, $val);                    xwrite8($s, xread8($s) | 0x80);                }                $val = s16(xread16($s + 0x88) + xread16($addr + $wcy));                if ($val != xread16($s + 0x18)) {                    xwrite16($s + 0x18, $val);                    xwrite8($s, xread8($s) | 0x80);                }                $val = s16(xread16($s + 0x8a) + xread16($addr + $wcz));                if ($val != xread16($s + 0x1a)) {                    xwrite16($s + 0x1a, $val);                    xwrite8($s, xread8($s) | 0x80);                }            }            if ((xread8($s + 0x84) & 2) != 0) {                $val = s16(xread16($s + 0x8c) + xread16($addr + 0x40) + xread16($addr + $wcax));                if ($val != xread16($s + 0x34)) {                    xwrite16($s + 0x34, $val);                    xwrite8($s, xread8($s) | 0x80);                }                $val = s16(xread16($s + 0x8e) + xread16($addr + 0x44) + xread16($addr + $wcay));                if ($val != xread16($s + 0x36)) {                    xwrite16($s + 0x36, $val);                    xwrite8($s, xread8($s) | 0x80);                }                $val = s16(xread16($s + 0x90) + xread16($addr + 0x48) + xread16($addr + $wcaz));                if ($val != xread16($s + 0x38)) {                    xwrite16($s + 0x38, $val);                    xwrite8($s, xread8($s) | 0x80);                }            }        }    }}function addlink(int $elemidx): void{    $elemsprvar = sprite_var($elemidx);    if (-1 < $elemsprvar->newd) {        $tmp = $elemsprvar->newx;        if ($tmp <= Img::$blocx1) {            Img::$blocx1 = $tmp;        }        $tmp = s16($tmp + $elemsprvar->width);        if (Img::$blocx2 <= $tmp) {            Img::$blocx2 = $tmp;        }        $tmp = $elemsprvar->newy;        if ($tmp <= Img::$blocy1) {            Img::$blocy1 = $tmp;        }        $tmp = s16($tmp + $elemsprvar->height);        if (Img::$blocy2 <= $tmp) {            Img::$blocy2 = $tmp;        }    }}/** Copies image.new* into a sprite (the block repeated in inouvlink/iremplink/affiscr). */function image_store_new(Sprite $s): void{    $s->newad = Img::$newad & 0xffffff;    $s->newx = Img::$newx;    $s->newy = Img::$newy;    $s->newd = Img::$newd;    $s->newf = s8(Img::$newf);    $s->width = Img::$newl;    $s->height = Img::$newh;    $s->newzoomx = Img::$newzoomx & 0xffff;    $s->newzoomy = Img::$newzoomy & 0xffff;}function inouvlink(int $scene, int $elemidx1, int $elemidx2, int $elemidx3): int{    deptopix($scene, $elemidx1);    $elem1sprvar = sprite_var($elemidx1);    image_store_new($elem1sprvar);    $elem2sprvar = sprite_var($elemidx2);    $elem2sprvar->link = $elem1sprvar->link;    addlink($elemidx1);    return rangesprite($elemidx1, $elemidx2, $elemidx3);}function iremplink(int $scene, int $elemidx1, int $elemidx2, int $elemidx3): int{    addlink($elemidx1);    $elem1sprvar = sprite_var($elemidx1);    if (Img::$wback != 0 && Img::$backprof <= $elem1sprvar->newd) {        Img::$pback = 1;        return inouvlink($scene, $elemidx1, $elemidx2, $elemidx3);    }    deptopix($scene, $elemidx1);    image_store_new($elem1sprvar);    $elem2sprvar = sprite_var($elemidx2);    $elem2sprvar->link = $elem1sprvar->link;    addlink($elemidx1);    return rangesprite($elemidx1, $elemidx2, $elemidx3);}function iefflink(int $elemidx1, int $elemidx2): int{    addlink($elemidx1);    $elem1sprvar = sprite_var($elemidx1);    $elem2sprvar = sprite_var($elemidx2);    $elem2sprvar->link = $elem1sprvar->link;    $elem1sprvar->to_next = Img::$libsprit;    Img::$libsprit = $elemidx1 & 0xffff;    if (Img::$wback != 0 && Img::$backprof <= $elem1sprvar->newd) {        Img::$pback = 1;    }    return $elemidx2 & 0xffff;}function clrfen(): void{    $w = Alis::$platform->width;    $fx1 = Img::$fenx1 < 0 ? 0 : Img::$fenx1;    $fy1 = Img::$feny1 < 0 ? 0 : Img::$feny1;    $fx2 = Img::$fenx2 >= $w ? $w - 1 : Img::$fenx2;    $fy2 = Img::$feny2 >= Alis::$platform->height ? Alis::$platform->height - 1 : Img::$feny2;    // fen is inclusive.    $tmpx = s16(($fx2 - $fx1) + 1);    if ($tmpx <= 0 || $fy2 < $fy1) {        return;    }    if ($tmpx == $w) {        mem_set(Img::$logic + $fy1 * $w, 0, $w * ($fy2 - $fy1 + 1));        return;    }    for ($y = $fy1; $y <= $fy2; $y++) {        mem_set(Img::$logic + $fx1 + $y * $w, 0, $tmpx);    }}function clipback(): void{    if (Img::$clipy1 < Img::$backy1) {        if (Img::$clipy2 < Img::$backy1) {            return;        }    } else {        if (Img::$clipy2 <= Img::$backy2) {            Img::$cback = 1;            return;        }        if (Img::$backy2 < Img::$clipy1) {            return;        }    }    Img::$cback = -1;}function destofen(Sprite $sprite): void{    // Blit destination; re-read every call to follow buffer swaps.    Img::$wdraw = Img::$logic;    // Background cache: the backsprite copies the flattened background from the shadow    // (laid out like image.logic) to the screen as a clipped rect copy over the back rect.    if (Img::$sback != 0 && Img::$backmap != 0 && $sprite === sprite_var(Img::$backsprite)) {        $bx1 = Img::$clipx1 > Img::$backx1 ? Img::$clipx1 : Img::$backx1;        $by1 = Img::$clipy1 > Img::$backy1 ? Img::$clipy1 : Img::$backy1;        $bx2 = Img::$clipx2 < Img::$backx2 ? Img::$clipx2 : Img::$backx2;        $by2 = Img::$clipy2 < Img::$backy2 ? Img::$clipy2 : Img::$backy2;        if ($bx1 <= $bx2 && $by1 <= $by2) {            $w = Alis::$platform->width;            // Chunky: one byte per pixel.            $span = ($bx2 - $bx1) + 1;            for ($y = $by1; $y <= $by2; $y++) {                mem_move(Img::$logic + $y * $w + $bx1, Img::$backmap + $y * $w + $bx1, $span);            }        }        return;    }    // While fenetre has wlogic pointed at the cache, composite behind-sprites into the shadow.    if (Img::$backmap != 0 && Img::$wlogic == Img::$backmap) {        Img::$wdraw = Img::$backmap;    }    $addr = $sprite->newad;    if ($addr == 0 || $sprite->data == 0) {        return;    }    if (Alis::$platform->version > 10) {        $addr = s32($addr + xread32($addr));    }    $bitmap = $addr;    if (Alis::$platform->version >= 60) {        destofen_v6($sprite, $bitmap); // image_v6.php: the version >= 60 path of the C        return;    }    // ST/Amiga engines skip negative types; Falcon and DOS don't test it    if (s8(xread8($bitmap)) < 0 && Alis::$platform->version > 10        && (Alis::$platform->kind == C::EPlatformAtari || Alis::$platform->kind == C::EPlatformAmiga            || Alis::$platform->kind == C::EPlatformAmigaAGA || Alis::$platform->kind == C::EPlatformMac)) {        return;    }    $pos = image_rect(        $sprite->newx,        $sprite->newy,        $sprite->newx + s16(read16($bitmap + 2)),        $sprite->newy + s16(read16($bitmap + 4)));    $flip = s8($sprite->newf);    $width = $sprite->width + 1;    $height = $sprite->height + 1;    if (Img::$clipx2 < $pos->x1) {        return;    }    if (Img::$clipy2 < $pos->y1) {        return;    }    if ($pos->x2 < Img::$clipx1) {        return;    }    if ($pos->y2 < Img::$clipy1) {        return;    }    Img::$blocx1 = $pos->x1;    if ($pos->x1 < Img::$clipx1) {        Img::$blocx1 = Img::$clipx1;    }    Img::$blocy1 = $pos->y1;    if ($pos->y1 < Img::$clipy1) {        Img::$blocy1 = Img::$clipy1;    }    Img::$blocx2 = $pos->x2;    if (Img::$clipx2 < $pos->x2) {        Img::$blocx2 = Img::$clipx2;    }    Img::$blocy2 = $pos->y2;    if (Img::$clipy2 < $pos->y2) {        Img::$blocy2 = Img::$clipy2;    }    $at = $bitmap + 6;    $bmp = image_rect(0, 0, $width, $height);    if (Img::$blocx1 < 0) {        $bmp->x1 = s16($bmp->x1 - Img::$blocx1);        $bmp->x2 = s16($bmp->x2 + Img::$blocx1);    }    if (Img::$blocx1 > $pos->x1) {        $bmp->x1 = s16($bmp->x1 + (Img::$blocx1 - $pos->x1));        $bmp->x2 = s16($bmp->x2 - (Img::$blocx1 - $pos->x1));    }    if (Img::$blocx2 <= $pos->x2) {        $bmp->x2 = s16($bmp->x2 - ($pos->x2 - Img::$blocx2));    }    if (Img::$blocy1 > $pos->y1) {        $bmp->y1 = s16($bmp->y1 + (Img::$blocy1 - $pos->y1));        $bmp->y2 = s16($bmp->y2 - (Img::$blocy1 - $pos->y1));    }    if (Img::$blocy2 < $pos->y2) {        $bmp->y2 = s16($bmp->y2 - ($pos->y2 - Img::$blocy2));    }    if ($bmp->x2 > 0 && $bmp->y2 > 0) {        dirty_add($pos->x1 + $bmp->x1, $pos->y1 + $bmp->y1, $bmp->x2, $bmp->y2);    }    $bmp->x2 = s16($bmp->x2 + $bmp->x1);    $bmp->y2 = s16($bmp->y2 + $bmp->y1);    $type = xread8($bitmap);    // HD edition: a character of the game's font is drawn by the host with a real font (fn/hd.php)    $glyph = SysVars::$hdText && $sprite->hdChar >= 0 ? hd_glyph_before($pos, $bmp) : null;    // HD edition: the bigger version of this bitmap may replace it (App\Alis\HdSprites); the blitters change $bmp    $hdClip = HdSprites::$on && $sprite->hdChar < 0 && ($type === 0x10 || $type === 0x12 || $type === 0x14 || $type === 0x16)        && Alis::$platform->px_format != C::EPxFormatAmPlanar && !PL_CGA() && Alis::$platform->kind != C::EPlatformMac        && ($type === 0x12 || $type === 0x16 || dos_v3_text_colour($sprite) < 0)        ? [$pos->x1 + $bmp->x1, $pos->y1 + $bmp->y1, $pos->x1 + $bmp->x2, $pos->y1 + $bmp->y2] : null;    switch ($type) {        case 0x01:            if (Alis::$platform->kind == C::EPlatformMac) {                draw_mac_rect($pos, $bmp, xread8($bitmap + 1));            } elseif (PL_CGA()) {                draw_rect($pos, $bmp, xread8($bitmap + 1) % 4);            } else {                draw_rect($pos, $bmp, xread8($bitmap + 1));            }            break;        case 0x00:            if (Alis::$platform->kind == C::EPlatformMac) {                draw_mac_mono_0($at, $pos, $bmp, $width, $flip);            } elseif (PL_CGA()) {                draw_dos_cga_0($at, $pos, $bmp, $width, $flip);            } else {                draw_st_4bit_0($at, $pos, $bmp, $width, $flip);            }            break;        case 0x02:            if (Alis::$platform->kind == C::EPlatformMac) {                draw_mac_mono_0($at, $pos, $bmp, $width, $flip);            } elseif (PL_CGA()) {                draw_dos_cga_2($at, $pos, $bmp, $width, $flip);            } else {                draw_st_4bit_2($at, $pos, $bmp, $width, $flip);            }            break;        case 0x10:            if (Alis::$platform->px_format == C::EPxFormatAmPlanar) {                draw_ami_5bit_0($at, $pos, $bmp, $width, $height, $flip);            } elseif (($tint = dos_v3_text_colour($sprite)) >= 0) {                // v3 DOS 0x12a76: the colour replaces the image's palette offset                draw_4to8bit_0($at + 2, $pos, $bmp, $width, $flip, $tint);            } else {                draw_4to8bit_0($at + 2, $pos, $bmp, $width, $flip, xread8($at));            }            break;        case 0x12:            if (Alis::$platform->px_format == C::EPxFormatAmPlanar) {                draw_ami_5bit_2($at, $pos, $bmp, $width, $height, $flip);            } else {                draw_4to8bit_2($at + 2, $pos, $bmp, $width, $flip, xread8($at));            }            break;        case 0x14:            if (!$flip && ($tint = dos_v3_text_colour($sprite)) >= 0) {                // v3 DOS 0x12974: every non-zero pixel in the text colour (the flipped blitter has no such case)                draw_8bit_tinted($at, $pos, $bmp, $width, $tint);            } else {                draw_8bit_0($at, $pos, $bmp, $width, $flip);            }            break;        case 0x16:            draw_8bit_2($at, $pos, $bmp, $width, $flip);            break;        case 0x40:            draw_fli_video($bitmap);            break;        case 0x7f:            switch (Alis::$platform->uid) {                case C::EGameTransarctica:                    draw_transarctica_map($sprite, s32($sprite->newad + xread32($sprite->newad)), image_rect($bmp->x1 + $pos->x1, $bmp->y1 + $pos->y1, $bmp->x2 + $pos->x1, $bmp->y2 + $pos->y1));                    break;                case C::EGameRobinsonsRequiem0:                case C::EGameRobinsonsRequiem1:                    draw_requiem_map($sprite, s32($sprite->newad + xread32($sprite->newad)));                    break;                default:                    // MISSING DRAW MAP IMPLEMENTETATION (debug log only)                    break;            }            break;        default:            // UNKNOWN RESOURCE TYPE (debug log only)            break;    }    if ($hdClip !== null) {        HdSprites::drawn($bitmap, $type, $pos->x1, $pos->y1, $width, $height, $flip, $hdClip[0], $hdClip[1], $hdClip[2], $hdClip[3]);    }    if ($glyph !== null) {        hd_glyph_after($glyph, $sprite, $pos, $width, $height);    }}function calctop(int $scene_addr, int $grid_col, int $grid_row): int{    // Compute byte offset into 2D terrain texture map: (row + col * stride) * 2    return s32((s16($grid_row) + s16($grid_col) * xread16($scene_addr - 0x3ca)) * 2);}function fentotv(): void{    // Single buffer: nothing to copy, but the window (cleared areas included) must be presented.    if (Img::$logic == Img::$physic) {        if (Img::$fenx2 >= Img::$fenx1 && Img::$feny2 >= Img::$feny1) {            dirty_add(Img::$fenx1, Img::$feny1, Img::$fenx2 - Img::$fenx1 + 1, Img::$feny2 - Img::$feny1 + 1);        }        return;    }    trsfen(Img::$logic, Img::$physic);}/** wlogic := logic (the restore block repeated in fenetre / draw). */function image_wlogic_logic(): void{    Img::$wlogic = Img::$logic;    Img::$wlogx1 = Img::$logx1;    Img::$wlogx2 = Img::$logx2;    Img::$wlogy1 = Img::$logy1;    Img::$wlogy2 = Img::$logy2;    Img::$wloglarg = Img::$loglarg;}/** wlogic := backmap (background cache capture). */function image_wlogic_back(): void{    Img::$wlogic = Img::$backmap;    Img::$wlogx1 = Img::$backx1;    Img::$wlogx2 = Img::$backx2;    Img::$wlogy1 = Img::$backy1;    Img::$wlogy2 = Img::$backy2;    Img::$wloglarg = Img::$backlarg;}function fenetre(int $scene, int $elemidx1, int $elemidx3, int $prevspidx): void{    $scene &= 0xffff;    $tmpidx = 0;    if ((get_scr_state($scene) & 0x40) != 0) {        return;    }    Img::$scdirect = 0;    if (calcfen($elemidx1, $elemidx3)) {        if (SysVars::$hdText) {            hd_glyph_invalidate(Img::$fenx1, Img::$feny1, Img::$fenx2, Img::$feny2);        }        if ((get_scr_numelem($scene) & 2) != 0) {            Img::$fdoland = 1;        }        for ($scridx = s16(Scr::$ptscreen); $scridx != 0; $scridx = s16(get_scr_to_next($scridx))) {            if ((get_scr_state($scridx) & 0x40) == 0) {                $tmpidx = get_scr_screen_id($scridx);                if ($tmpidx != 0) {                    clipfen(sprite_var($tmpidx));                    if (Img::$fclip != 0) {                        if ((get_scr_numelem($scridx) & 2) == 0) {                            // C: "goto fenetre31" jumps into the sprite loop below: flag instead.                            $fenetre31 = false;                            Img::$cback = 0;                            if ((get_scr_numelem($scridx) & 4) != 0) {                                clipback();                            }                            if ((get_scr_numelem($scridx) & 0x40) == 0) {                                clrfen();                            }                            if (Img::$cback) {                                if (Img::$cback < 0) {                                    if ((Img::$wback != 0) && (Img::$pback != 0)) {                                        // Partial overlap: flatten the behind-sprites into the cache                                        // (clipped to the back rect's Y extent), then restore state.                                        $saveclipy1 = Img::$clipy1;                                        $saveclipy2 = Img::$clipy2;                                        image_wlogic_back();                                        if (Img::$clipy1 <= Img::$backy1) {                                            Img::$clipy1 = Img::$backy1;                                        }                                        if (Img::$backy2 <= Img::$clipy2) {                                            Img::$clipy2 = Img::$backy2;                                        }                                        $sprite = sprite_var($tmpidx);                                        while (true) {                                            $tmpidx = $sprite->link;                                            if (($tmpidx == 0) || ($tmpidx == Img::$backsprite)) {                                                break;                                            }                                            $sprite = sprite_var($tmpidx);                                            if (-1 < $sprite->state && -1 < $sprite->newf && -1 < $sprite->newd) {                                                destofen($sprite);                                            }                                        }                                        image_wlogic_logic();                                        Img::$clipy1 = $saveclipy1;                                        Img::$clipy2 = $saveclipy2;                                        $tmpidx = get_scr_screen_id($scridx);                                    }                                } else {                                    if (Img::$pback == 0) {                                        // Cache hit: draw only the backsprite then the front sprites.                                        // 16bpp has no cache: tmpidx stays the screen head.                                        $tmpidx = Img::$backsprite & 0xffff;                                        $fenetre31 = true;                                    } else {                                        image_wlogic_back();                                    }                                }                            }                            if (!$fenetre31) {                                $sprite = sprite_var($tmpidx);                            }                            while (true) {                                if (!$fenetre31) {                                    $tmpidx = $sprite->link;                                    if ($tmpidx == 0) {                                        break;                                    }                                    if (Img::$sback != 0 && $tmpidx == Img::$backsprite) {                                        image_wlogic_logic();                                    }                                }                                $fenetre31 = false;                                // fenetre31:                                $sprite = sprite_var($tmpidx);                                if (-1 < $sprite->state && -1 < $sprite->newf && -1 < $sprite->newd) {                                    destofen($sprite);                                    Img::$switchgo = 1;                                }                            }                        } else {                            landtofi($prevspidx, $scridx); // Robinson's Requiem 3D land (rrq3d.php)                        }                    }                }            }        }        // NOTE: originaly mouse cursore erase, now handled elsewhere        if ((get_scr_numelem($scene) & 0x20) == 0) {            if (Alis::$fswitch != 0) {                if (Img::$wpag == 0) {                    memfen();                }                return;            }            if (Img::$wpag == 0) {                fentotv();            }        }        // NOTE: originaly mouse cursore draw, now handled elsewhere    }}function scrolpage(): void{}function suitlin1(int $a2, int $d1w, int $d2w, int $d3w, int $d4w): int{    $d1w &= 0xffff;    $d4w &= 0xffff;    while (true) {        $d2w = $d1w;        $d1w = sprite_var($d2w)->link;        if ($d1w == 0) {            break;        }        if ($d4w == sprite_var($d1w)->clinking) {            $state = sprite_var($d1w)->state;            if ($state != 0) {                if ($state < 0) {                    $d1w = inouvlink($a2, $d1w, $d2w, $d3w);                } elseif ($state == 2) {                    $d1w = iremplink($a2, $d1w, $d2w, $d3w);                } else {                    $d1w = iefflink($d1w, $d2w);                }            }        }    }    Img::$joints = 1;    return $d1w;}/** Draws every visible sprite of the screens from scridx on (the loop repeated in affiscr). */function image_affiscr_screens(int $first): void{    for ($spriteidx = $first; $spriteidx; $spriteidx = get_scr_to_next($spriteidx)) {        if (((get_scr_state($spriteidx) & 0x40) == 0) && (($prevspidx = get_scr_screen_id($spriteidx)) != 0)) {            clipfen(sprite_var($prevspidx));            if (Img::$fclip != 0) {                while (($prevspidx = sprite_var($prevspidx)->link) != 0) {                    $s = sprite_var($prevspidx);                    if (-1 < $s->state && -1 < $s->newf && -1 < $s->newd) {                        destofen($s);                        Img::$switchgo = 1;                    }                }            }        }    }}function affiscr(int $scene, int $screenidx): void{    $scene &= 0xffff;    $screenidx &= 0xffff;    $spriteidx = $screenidx;    $prevspidx = 0;    // u16: clinking exceeds 0x7fff in Ishar 3.    $linkidx = 0;    if (Alis::$platform->version >= 30 && xread8(Alis::$basemain + $scene + 0x84) != 0) {        folscreen($scene);    }    if ((Img::$fremap != 0) || (s8(get_scr_state($scene)) < 0)) {        depscreen($scene, $screenidx);    }    $scrflags = Alis::$platform->version == 10 ? 0 : get_scr_numelem($scene);    $draw = false;    if (Alis::$platform->version == 0) {        $draw = Alis::$fswitch == 0;    } elseif (($scrflags & 2) == 0) {        $draw = true;    } else {        affiland($scene); // Robinson's Requiem 3D land (rrq3d.php)        $draw = (get_scr_state($scene) & 0x80) == 0;    }    if ($draw) {        Img::$wback = (int) (($scrflags & 4) != 0);        Img::$wpag = 0;        if ((get_scr_state($scene) & 0x20) != 0) {            Img::$wpag = 1;            Img::$spag = s8(Img::$spag - 1);            if (Img::$spag == 0) {                Img::$wpag = -1;            }        }        if (($scrflags & 0x10) == 0) {            while (true) {                $prevspidx = $spriteidx;                $spriteidx = sprite_var($spriteidx)->link;                if ($spriteidx == 0) {                    break;                }                $state = sprite_var($spriteidx)->state;                if ($state != 0) {                    Img::$joints = 0;                    Img::$pback = 0;                    if ($state == 2) {                        $linkidx = inilink($spriteidx) & 0xffff;                        if ($linkidx >= 0) { // always true: linkidx is u16 in the C                            $spriteidx = iremplink($scene, $spriteidx, $prevspidx, $screenidx);                            suitlin1($scene, $spriteidx, $prevspidx, $screenidx, $linkidx);                        } else {                            $sprite = sprite_var($spriteidx);                            // Only effect of this compare is pback (Ghidra's "isback" is CC residue).                            if (Img::$wback != 0 && Img::$backprof <= $sprite->newd) {                                Img::$pback = 1;                            }                            deptopix($scene, $spriteidx);                            tstjoints($spriteidx);                            if (Img::$joints == 0) {                                sprite_var($prevspidx)->link = $sprite->link;                                fenetre($scene, $spriteidx, $screenidx, $prevspidx);                            } else {                                sprite_var($prevspidx)->link = $sprite->link;                            }                            image_store_new($sprite);                            $prevspidx = rangesprite($spriteidx, $prevspidx, $screenidx);                        }                    } else {                        $linkidx = inilink($spriteidx) & 0xffff;                        if ($state == -1) {                            $spriteidx = inouvlink($scene, $spriteidx, $prevspidx, $screenidx);                        } else {                            $spriteidx = iefflink($spriteidx, $prevspidx);                        }                        if ($linkidx < 0) { // never true: linkidx is u16 in the C                            Img::$joints = 1;                        } else {                            suitlin1($scene, $spriteidx, $prevspidx, $screenidx, $linkidx);                        }                    }                    fenetre($scene, $spriteidx, $screenidx, $prevspidx);                    $spriteidx = $prevspidx;                }            }        } else {            Img::$fenx1 = get_scr_newx($scene);            Img::$feny1 = get_scr_newy($scene);            Img::$fenx2 = s16(Img::$fenx1 + get_scr_width($scene));            Img::$feny2 = s16(Img::$feny1 + get_scr_height($scene));            Img::$clipl = s16((Img::$fenx2 - Img::$fenx1) + 1);            Img::$cliph = s16((Img::$feny2 - Img::$feny1) + 1);            Img::$clipx1 = Img::$fenx1;            Img::$clipy1 = Img::$feny1;            Img::$clipx2 = Img::$fenx2;            Img::$clipy2 = Img::$feny2;            if ((get_scr_numelem($scene) & 0x40) == 0) {                clrfen();            }            while (true) {                $prevspidx = $spriteidx;                $spriteidx = sprite_var($spriteidx)->link;                if ($spriteidx == 0) {                    break;                }                $psprite = sprite_var($prevspidx);                $csprite = sprite_var($spriteidx);                if ($csprite->state != 0) {                    if ($csprite->state == 1) {                        $psprite->link = $csprite->link;                        $csprite->to_next = Img::$libsprit;                        Img::$libsprit = $spriteidx;                        $spriteidx = $prevspidx;                    } else {                        deptopix($scene, $spriteidx);                        $psprite->link = $csprite->link;                        image_store_new($csprite);                        $spriteidx = rangesprite($spriteidx, $prevspidx, $screenidx);                    }                }            }            image_affiscr_screens(Scr::$ptscreen & 0xffff);            if ((Alis::$fswitch == 0) && (Img::$wpag == 0)) {                fentotv();            }        }    } else {        image_affiscr_screens(get_scr_to_next($scene));        if ((Alis::$fswitch == 0) && (Img::$wpag == 0)) {            fentotv();        }    }    if (Img::$wpag < 0) {        set_scr_state($scene, get_scr_state($scene) & 0xdf);        Img::$fenx1 = get_scr_newx($scene);        Img::$feny1 = get_scr_newy($scene);        Img::$fenx2 = s16(get_scr_newx($scene) + get_scr_width($scene));        Img::$feny2 = s16(get_scr_newy($scene) + get_scr_height($scene));        scrolpage();    }    // TODO: fix this hack    // following 'if ()' is needed to draw rails under train on minimap in Transarctica    if (Alis::$platform->uid != C::EGameTransarctica) {        set_scr_state($scene, get_scr_state($scene) & 0x7f);    }}// affiscr_v6(), v6ips_measure() (v6ips_ring / v6ips_slot in ImageV6Vars; ImageVars::$v6ips_warm kept): fn/image_v6.php.function itroutine(int $interval = 0, mixed $param = null): int{    $prevtiming = Img::$vtiming;    Alis::$timeclock = s32(Alis::$timeclock + 1);    Img::$fitroutine = 1;    Img::$vtiming = (Img::$vtiming + 1) & 0xff;    if (Img::$vtiming == 0) {        Img::$vtiming = $prevtiming;    }    if (dos_pal_active()) {        dos_pal_tick();    } elseif (Img::$palc != 0 && (Img::$palt = (Img::$palt - 1) & 0xff) == 0) {        Img::$palt = Img::$palt0;        topalet();        Img::$palc = (Img::$palc - 1) & 0xff;    }    Img::$fitroutine = 0;    return Alis::$platform->is_little_endian ? 17 : 20;}function rgb_alloc(int $w, int $h): void{    // true-colour logic/physic: 3DO only; free() is a no-op.    // PORT: 3 bytes per pixel B, G, R (rows of a 24-bit BMP, stride w * 3) instead of the C u32 ARGB.    Img::$rgblogic = Img::$rgbphysic = 0;    if ($w > 0 && $h > 0 && Alis::$platform->uid == C::EGameRobinsonsRequiem3DO) {        Img::$rgblogic = host_alloc($w * $h * 3);        Img::$rgbphysic = host_alloc($w * $h * 3);    }    Host::$pixelbuf->rgb = Img::$rgbphysic;}function resize_screen(int $w, int $h): void{    $w = s16($w);    $h = s16($h);    if ($w <= 0 || $h <= 0) {        return;    }    if ($w == Alis::$platform->width && $h == Alis::$platform->height) {        return;    }    sys_lock_renderer();    // same layout as alis_init, +w+2: the v6 2x2 span banks may overrun by pitch+1 bytes    $off = Host::$pixelbuf->surface_h * $w;    Img::$buffer_alloc_size = s32($w * ($h + 2 * Host::$pixelbuf->surface_h) + $w + 2);    if (Img::$buffer_alloc_size > ImageVars::$image_buf_cap) {        // free(): no-op in the port (host_free)        ImageVars::$image_buf_cap = Img::$buffer_alloc_size;        Img::$physic_alloc = host_alloc(ImageVars::$image_buf_cap);        Img::$logic_alloc = Alis::$platform->dbl_buf ? host_alloc(ImageVars::$image_buf_cap) : Img::$physic_alloc;        if (Img::$bgcache_alloc) {            Img::$bgcache_alloc = host_alloc(ImageVars::$image_buf_cap);        }    }    mem_set(Img::$physic_alloc, 0, Img::$buffer_alloc_size);    if (Img::$logic_alloc != Img::$physic_alloc) {        mem_set(Img::$logic_alloc, 0, Img::$buffer_alloc_size);    }    Img::$physic = Img::$physic_alloc + $off;    Img::$logic = Img::$logic_alloc + $off;    if (Img::$bgcache_alloc) {        mem_set(Img::$bgcache_alloc, 0, Img::$buffer_alloc_size);        Img::$backmap = Img::$bgcache_alloc + $off;        Img::$backlarg = $w;    } elseif (Img::$backmap) {                         // regrow failed        Img::$backmap = 0;        Img::$sback = 0;    }    Alis::$platform->width = $w;    Alis::$platform->height = $h;    rgb_alloc($w, $h);    Img::$logx1 = 0;    Img::$logx2 = s16($w - 1);    Img::$logy1 = 0;    Img::$logy2 = s16($h - 1);    Img::$loglarg = $w >> 1;    Host::$pixelbuf->w = $w;    Host::$pixelbuf->h = $h;    Host::$pixelbuf->data = Img::$physic;    ImageVars::$v6xdirty = 1;    sys_unlock_renderer();}// v6x renderer, 3DO cel decoding, affiscr_v6_record, compositor_v6: fn/image_v6.php.function draw(): void{    sys_delay_frame();    // Render time excludes the frame-cap sleep.    sys_lock_renderer();    $v6def = Alis::$platform->version >= 60;    // Last flip was non-blocking: wait for the VBL latch before writing image.logic.    sys_flip_wait();    if (Trace::on()) {        Trace::event('draw start ptabfen=' . Img::$ptabfen);    }    if (!$v6def && (Alis::$fswitch != 0) && (Img::$fphytolog != 0)) {        Img::$fphytolog = 0;        phytolog();    }    Img::$vtiming = 0;    if (!$v6def && Alis::$fswitch != 0) {        // Remove image.logic's own cursor (from when it was front) before oldfen.        sys_mouse_erase();        oldfen();        if (Trace::on()) {            Trace::event('after oldfen');        }        // oldfen copied the front cursor into image.logic; remove it.        sys_mouse_uncopy();        Img::$ptabfen = 0;    }    Img::$switchgo = 0;    image_wlogic_logic();    $scnidx = s16(Scr::$ptscreen);    $oldphys = Img::$physic;    if ($v6def) {        v6x_draw(); // image_v6.php        Img::$fremap = 0;        setphysic();        sys_unlock_renderer();        return;    }    // PORT: the C's later v6def branches (affiscr_v6_record, compositor_v6, v6dirty_reset) are    // unreachable after the return above; affiscr_v6_record / compositor_v6 are in image_v6.php.    while ($scnidx != 0) {        if ((get_scr_state($scnidx) & 0x40) == 0) {            $screen_id = get_scr_screen_id($scnidx);            affiscr($scnidx, $screen_id);        }        $scnidx = s16(get_scr_to_next($scnidx));    }    Img::$fremap = 0;    if (Alis::$fswitch != 0) {        // Draw the cursor before the swap so the presented frame contains it.        sys_mouse_draw();        Img::$physic = Img::$logic;        Img::$logic = $oldphys;        setphysic();    }    if (Trace::on()) {        $wins = [];        for ($t = 0; $t < Img::$ptabfen; $t += 4) {            $wins[] = implode(',', array_slice(Img::$tabfen, $t, 4));        }        Trace::event('draw end ptabfen=' . Img::$ptabfen . ' wins=' . implode(' ', $wins));    }    sys_unlock_renderer();}// TODO: move to script.cfunction debprotf(int $target_id): int{    $target_id = s16($target_id);    $start = 0;    $end = Alis::$nbprog - 1;    do {        $mid = ($end + $start) >> 1;        $current_id = s16(read16(xread32(Alis::$atprog + $mid * 4)));   // ATPROG(mid)        if ($current_id == $target_id) {            return $mid;        }        if ($current_id < $target_id) {            $start = $mid + 1;        } else {            $end = $mid - 1;        }    } while ($start <= $end);    return -1;}