ES
games/alis / tools / hd / extract.php · commit 9c722cf
<?php// Extracts EVERY bitmap of EVERY script of a game (not only the ones seen while playing) into the HD capture folder// (App\Alis\HdSprites: <key>.png 1x + <key>.json, the same keys the game computes). A bitmap already captured while// playing keeps its picture (true palette); the others get a palette guessed from the scripts' own palettes.//   bin/jumphp php games/alis tools/hd/extract.php data/robinson var/hdcapuse App\Alis\Alis;use App\Alis\HdSprites;use App\Alis\Img;use App\Alis\ImageVars;use App\Alis\Machine;use App\Alis\UnpackVars;use function App\Alis\dpal_expand;use function App\Alis\dpal_load16;use function App\Alis\mem_read;use function App\Alis\mem_write;use function App\Alis\s32;use function App\Alis\s8;use function App\Alis\script_scratch;use function App\Alis\unpack_script;use function App\Alis\xread16;use function App\Alis\xread32;use function App\Alis\xread8;require __DIR__ . '/../../vendor/autoload.php';$base = __DIR__ . '/../../';$dir = rtrim($argv[1] ?? 'data/robinson', '/');$dir = str_starts_with($dir, '/') ? $dir : $base . $dir;$out = $argv[2] ?? 'var/hdcap';$out = rtrim(str_starts_with($out, '/') ? $out : $base . $out, '/');@mkdir($out, 0777, true);HdSprites::$capture = $out;HdSprites::$on = true;$m = new Machine();if (!$m->boot($dir)) {    fwrite(STDERR, "boot failed: {$m->error}\n");    exit(1);}/** The unpacked script at a scratch address in memory: [address, length, is main] or null (a data file). */function load_script(string $path): ?array{    $raw = file_get_contents($path);    $magic = unpack('V', $raw)[1];    $isMain = unpack('v', substr($raw, 4, 2))[1] === 0;    $pack = ($magic >> 24) & 0xff;    if ($pack & 0x80) {        $size = ($magic & 0xffffff) - UnpackVars::$kPackedHeaderSize - ($isMain ? UnpackVars::$kVMSpecsSize : 0);        Alis::$typepack = s8($pack & 0xfe);        $buf = script_scratch(1024 + $size);        $len = unpack_script($path, $buf);    } else {        $bytes = substr($raw, 6 + ($isMain ? 16 : 0));        $buf = script_scratch(1024 + strlen($bytes));        mem_write($buf, $bytes);        $len = strlen($bytes);    }    if ($len < 0x18) {        return null;    }    return [$buf, $len, $isMain];}/** The resources of the script at $org: [address, type byte] each. */function resources(int $org, int $len): array{    $res = xread32($org + 0x0e);    if ($res < 0x18 || $res + 8 > $len) {        return [];    }    $t = $org + $res;    $count = xread16($t + 4);    $list = [];    for ($i = 0; $i < $count; $i++) {        $e = $t + xread32($t) + $i * 4;        $r = s32($e + xread32($e));        if ($r <= $org || $r >= $org + $len) {            continue;        }        $list[] = $r;    }    return $list;}/** Applies a palette resource (type 0xfe) to a 256 x RGB table of 8-bit values; returns [first, n]. */function apply_palette(int $res, array &$pal): array{    $n = xread8($res + 1) + 1;    $first = xread8($res + 2);    $keep = ImageVars::$dpal_tpal;    if ($n === 1) {        ImageVars::$dpal_tpal = array_fill(0, 768, 0);        dpal_load16(\App\Alis\image_bytes($res + 2, 32), $first);        $n = 16;        $src = ImageVars::$dpal_tpal;        for ($i = $first; $i < min($first + $n, 256); $i++) {            $pal[$i] = (dpal_expand($src[$i * 3]) << 16) | (dpal_expand($src[$i * 3 + 1]) << 8) | dpal_expand($src[$i * 3 + 2]);        }    } else {        $n = min($n, 256 - $first);        for ($i = 0; $i < $n; $i++) {            $c = [];            for ($k = 0; $k < 3; $k++) {                $c[] = dpal_expand(xread8($res + 4 + $i * 3 + $k) >> 2);            }            $pal[$first + $i] = ($c[0] << 16) | ($c[1] << 8) | $c[2];        }    }    ImageVars::$dpal_tpal = $keep;    return [$first, $n];}$scripts = [];foreach (glob("$dir/*.[iI][oO]") as $path) {    $name = strtolower(basename($path, '.' . pathinfo($path, PATHINFO_EXTENSION)));    $raw = file_get_contents($path);    $isMain = unpack('v', substr($raw, 4, 2))[1] === 0;    $scripts[$name] = ['path' => $path, 'main' => $isMain];}// the main script first: its palettes are the base of the othersuasort($scripts, fn ($a, $b) => $b['main'] <=> $a['main']);$basePal = array_fill(0, 256, 0);$stats = ['scripts' => 0, 'bitmaps' => 0, 'new' => 0, 'kept' => 0, 'uncertain' => 0, 'skipped' => 0, 'types' => []];foreach ($scripts as $name => $info) {    $s = load_script($info['path']);    if ($s === null) {        continue;    }    [$org, $len] = $s;    $res = resources($org, $len);    if ($res === []) {        continue;    }    $stats['scripts']++;    $pals = [];       // [first, n, table] of each palette resource, in order    $cum = $basePal;    foreach ($res as $r) {        if (xread8($r) === 0xfe) {            $own = $basePal;            [$first, $n] = apply_palette($r, $own);            apply_palette($r, $cum);            $pals[] = [$first, $n, $own];        }    }    if ($info['main']) {        $basePal = $cum;    }    $count = 0;    foreach ($res as $r) {        $type = xread8($r);        if (!in_array($type, [0x10, 0x12, 0x14, 0x16], true)) {            continue;        }        $w = xread16($r + 2) + 1;        $h = xread16($r + 4) + 1;        $used = HdSprites::usedColours($r, $type, $w, $h);        if ($used === []) {            $stats['skipped']++;            continue;        }        $pal = null;        foreach ($pals as [$first, $n, $own]) {            $ok = true;            foreach ($used as $c) {                if ($c < $first || $c >= $first + $n) {                    $ok = false;                    break;                }            }            if ($ok) {                $pal = $own;                break;            }        }        $certain = $pal !== null;        $pal ??= $cum;        Img::$mpalet = $pal;        $stats['bitmaps']++;        $stats['types'][$type] = ($stats['types'][$type] ?? 0) + 1;        $k = HdSprites::captureBitmap($r, $type, $w, $h, false);        if ($k === null) {            $stats['skipped']++;            continue;        }        $count++;        if (!$certain) {            $stats['uncertain']++;        }    }    printf("%-12s %4d bitmaps, %d palettes\n", $name, $count, count($pals));}$files = count(glob("$out/*.png") ?: []);printf("%d scripts, %d bitmaps (%s), %d skipped, %d with an uncertain palette; %d pictures in %s\n", $stats['scripts'],    $stats['bitmaps'], implode(', ', array_map(fn ($t, $n) => sprintf('0x%02x: %d', $t, $n), array_keys($stats['types']), $stats['types'])),    $stats['skipped'], $stats['uncertain'], $files, $out);