RU
games/dmmotor / src / Dm / Gfx.php · commit 9d248a4
<?php/* * dmmotor — graphics data: palettes, light maps, patches, wall textures, flats, sprites * (after r_data.c and r_things.c of linuxdoom-1.10). * Copyright (C) 1993-1996 by id Software, Inc.; PHP port for dmmotor. GPL v2 (see LICENSE). */namespace App\Dm;/** * Pictures are kept as PHP strings of palette indexes: a column of a wall texture is a string of * `height` bytes, a flat is 4096 bytes (64 x 64, row by row). */final class Gfx{    public const NUMCOLORMAPS = 32;    public const LIGHTLEVELS = 16;    public const MAXLIGHTSCALE = 48;    public const MAXLIGHTZ = 128;    /** @var list<string> 14 palettes of 768 bytes (normal, red pain, yellow pickup, green suit) */    public array $palettes = [];    /** @var list<string> 34 light maps of 256 bytes (0 = full bright, 31 = dark, 32 = invulnerability) */    public array $colormaps = [];    /** @var list<Texture> */    public array $textures = [];    /** @var array<string,int> */    public array $textureNum = [];    /** @var array<int,int> texture number => texture drawn this tic (animations, switches) */    public array $textureTranslation = [];    /** @var list<string> flat names, by flat number */    public array $flatNames = [];    /** @var array<string,int> */    public array $flatNum = [];    /** @var array<int,string> flat number => 4096 bytes */    private array $flats = [];    /** @var array<int,int> flat number => flat drawn this tic (animated liquids) */    public array $flatTranslation = [];    /** @var array<string,int> sprite lump name => lump number */    private array $spriteLumps = [];    /** @var array<int,Patch> lump number => patch */    private array $patches = [];    /**     * Sprite definitions by sprite number: frames => [rotate, lumps[8], flips[8]].     *     * @var array<int,array<int,array{0:bool,1:array<int,int>,2:array<int,bool>}>>     */    public array $sprites = [];    /** @var array<int,array<int,int>> wall light: [light level][scale index] => colormap */    public array $scaleLight = [];    /** @var array<int,array<int,int>> plane light: [light level][distance / 16] => colormap */    public array $zLight = [];    public int $skyFlat = -1;    public function __construct(public readonly Wad $wad)    {        $pal = $wad->lump('PLAYPAL');        for ($i = 0; $i + 768 <= strlen($pal); $i += 768) {            $this->palettes[] = substr($pal, $i, 768);        }        $cm = $wad->lump('COLORMAP');        for ($i = 0; $i + 256 <= strlen($cm); $i += 256) {            $this->colormaps[] = substr($cm, $i, 256);        }        $this->initTextures();        $this->initFlats();        $this->initSprites();        $this->initLightTables();        $this->skyFlat = $this->flatNum['F_SKY1'] ?? -1;    }    // ------------------------------------------------------------------ patches    public function patch(string $name): Patch    {        return $this->patchNum($this->wad->check($name));    }    public function patchNum(int $lump): Patch    {        return $this->patches[$lump] ??= Patch::decode($this->wad->lumpNum($lump));    }    // ------------------------------------------------------------------ textures    private function initTextures(): void    {        $pn = $this->wad->lump('PNAMES');        $count = unpack('V', $pn)[1];        $patchLumps = [];        for ($i = 0; $i < $count; $i++) {            $patchLumps[] = $this->wad->check(rtrim(substr($pn, 4 + $i * 8, 8), "\0"));        }        foreach (['TEXTURE1', 'TEXTURE2'] as $lumpName) {            if (!$this->wad->has($lumpName)) {                continue;            }            $data = $this->wad->lump($lumpName);            $num = unpack('V', $data)[1];            for ($i = 0; $i < $num; $i++) {                $off = unpack('V', $data, 4 + $i * 4)[1];                $t = unpack('a8name/Vmasked/vwidth/vheight/Vcoldir/vpatchcount', $data, $off);                $tex = new Texture(strtoupper(rtrim($t['name'], "\0")), $t['width'], $t['height']);                for ($p = 0; $p < $t['patchcount']; $p++) {                    $pp = unpack('soriginx/soriginy/vpatch', $data, $off + 22 + $p * 10);                    $tex->parts[] = [$pp['originx'], $pp['originy'], $patchLumps[$pp['patch']] ?? -1];                }                $this->textureNum[$tex->name] = count($this->textures);                $this->textures[] = $tex;            }        }        foreach ($this->textures as $i => $_) {            $this->textureTranslation[$i] = $i;        }    }    /** Texture number of a side's texture name, 0 = none ("-"). */    public function textureNumber(string $name): int    {        $name = strtoupper($name);        if ($name === '' || $name[0] === '-') {            return 0;        }        return $this->textureNum[$name] ?? 0;    }    /** Builds the texture's columns the first time (R_GenerateComposite). */    public function texture(int $num): Texture    {        $tex = $this->textures[$num];        if (!$tex->built) {            $this->buildTexture($tex);        }        return $tex;    }    /** The posts of a texture's columns, for see-through middle textures (built the first time). */    public function maskedTexture(int $num): Texture    {        $tex = $this->texture($num);        if ($tex->posts === []) {            $this->buildTexture($tex, true);        }        return $tex;    }    private function buildTexture(Texture $tex, bool $withPosts = false): void    {        $w = $tex->width;        $h = $tex->height;        $cols = array_fill(0, $w, str_repeat("\0", $h));        $posts = array_fill(0, $w, []);        $covered = array_fill(0, $w, 0);        foreach ($tex->parts as [$ox, $oy, $lump]) {            if ($lump < 0) {                continue;            }            $patch = $this->patchNum($lump);            $x1 = max(0, $ox);            $x2 = min($w, $ox + $patch->width);            for ($x = $x1; $x < $x2; $x++) {                $covered[$x]++;                foreach ($patch->posts[$x - $ox] as [$top, $pixels]) {                    $y = $oy + $top;                    $len = strlen($pixels);                    if ($y < 0) {                        $pixels = substr($pixels, -$y);                        $len += $y;                        $y = 0;                    }                    if ($y + $len > $h) {                        $len = $h - $y;                    }                    if ($len <= 0) {                        continue;                    }                    $cols[$x] = substr_replace($cols[$x], substr($pixels, 0, $len), $y, $len);                    if ($withPosts) {                        $posts[$x][] = [$y, substr($pixels, 0, $len)];                    }                }            }        }        $tex->columns = $cols;        if ($withPosts) {            $tex->posts = $posts;        }        $tex->built = true;    }    // ------------------------------------------------------------------ flats    private function initFlats(): void    {        foreach ($this->wad->between('F_START', 'F_END') as $name => $lump) {            if ($this->wad->size($lump) < 4096) {                continue;            }            $this->flatNum[$name] = count($this->flatNames);            $this->flatNames[] = $name;        }        foreach ($this->flatNames as $i => $_) {            $this->flatTranslation[$i] = $i;        }    }    public function flatNumber(string $name): int    {        return $this->flatNum[strtoupper($name)] ?? 0;    }    public function flat(int $num): string    {        return $this->flats[$num] ??= substr($this->wad->lump($this->flatNames[$num]), 0, 4096);    }    // ------------------------------------------------------------------ sprites    private function initSprites(): void    {        $this->spriteLumps = $this->wad->between('S_START', 'S_END');        $byPrefix = [];        foreach ($this->spriteLumps as $name => $lump) {            $byPrefix[substr($name, 0, 4)][] = $name;        }        foreach (Info::SPRITES as $num => $prefix) {            $frames = [];            foreach ($byPrefix[$prefix] ?? [] as $name) {                $lump = $this->spriteLumps[$name];                $this->installFrame($frames, $lump, ord($name[4]) - 65, ord($name[5]) - 48, false);                if (strlen($name) >= 8) {                    $this->installFrame($frames, $lump, ord($name[6]) - 65, ord($name[7]) - 48, true);                }            }            ksort($frames);            $this->sprites[$num] = $frames;        }    }    /** @param array<int,array{0:bool,1:array<int,int>,2:array<int,bool>}> $frames */    private function installFrame(array &$frames, int $lump, int $frame, int $rotation, bool $flipped): void    {        if ($frame < 0 || $frame > 28) {            return;        }        $frames[$frame] ??= [false, [], []];        if ($rotation === 0) {            $frames[$frame] = [false, array_fill(0, 8, $lump), array_fill(0, 8, $flipped)];            return;        }        $frames[$frame][0] = true;        $frames[$frame][1][$rotation - 1] = $lump;        $frames[$frame][2][$rotation - 1] = $flipped;    }    // ------------------------------------------------------------------ light (R_InitLightTables)    private function initLightTables(): void    {        for ($i = 0; $i < self::LIGHTLEVELS; $i++) {            $startmap = intdiv((self::LIGHTLEVELS - 1 - $i) * 2 * self::NUMCOLORMAPS, self::LIGHTLEVELS);            for ($j = 0; $j < self::MAXLIGHTZ; $j++) {                $scale = intdiv(160, $j + 1);                $level = $startmap - intdiv($scale, 2);                $this->zLight[$i][$j] = max(0, min(self::NUMCOLORMAPS - 1, $level));            }            for ($j = 0; $j < self::MAXLIGHTSCALE; $j++) {                $level = $startmap - intdiv($j, 2);                $this->scaleLight[$i][$j] = max(0, min(self::NUMCOLORMAPS - 1, $level));            }        }    }}