RU
games/dmmotor / src / Dm / Render / View.php · commit 9d248a4
<?php/* * dmmotor — the 3D view: BSP walk, walls, floors and ceilings, sprites, weapon * (after r_main.c, r_bsp.c, r_segs.c, r_plane.c, r_things.c and r_draw.c of linuxdoom-1.10). * Copyright (C) 1993-1996 by id Software, Inc.; PHP port for dmmotor. GPL v2 (see LICENSE). * * Differences with the original: floats instead of fixed point, and walls are projected by * clipping each seg in view space and interpolating 1/z across the screen (the original uses * angle tables); the result is the same picture. */namespace App\Dm\Render;use App\Dm\Gfx;use App\Dm\Info;use App\Dm\MapData;use App\Dm\Node;use App\Dm\Line;use App\Dm\Seg;use App\Dm\Sector;use App\Dm\Play\Mobj;final class View{    private const SIL_BOTTOM = 1;    private const SIL_TOP = 2;    private const BIG = 1.0e9;    private const MINZ = 4.0;    private const FF_FULLBRIGHT = 0x8000;    private const FF_FRAMEMASK = 0x7FFF;    public int $width = 320;    public int $height = 168;    private float $centerX = 160;    private float $centerY = 84;    private float $projection = 160;    // the viewer    private float $viewX = 0;    private float $viewY = 0;    private float $viewZ = 0;    private float $viewAngle = 0;    private float $viewCos = 1;    private float $viewSin = 0;    /** added to every light level (gun flash) */    public int $extraLight = 0;    /** a fixed light map for everything (-1 = none; 0 = light amplification; 32 = invulnerability) */    public int $fixedColormap = -1;    private MapData $map;    private int $validCount = 0;    /** @var list<array{0:int,1:int}> solid wall ranges [first, last] */    private array $solidSegs = [];    /** @var array<int,int> */    private array $ceilingClip = [];    /** @var array<int,int> */    private array $floorClip = [];    /** @var array<int,int> */    private array $screenHeightArray = [];    /** @var array<int,int> */    private array $negOneArray = [];    /** @var list<Visplane> */    private array $planes = [];    private ?Visplane $floorPlane = null;    private ?Visplane $ceilingPlane = null;    /** @var list<DrawSeg> */    private array $drawSegs = [];    /** @var list<VisSprite> */    private array $visSprites = [];    /** @var array<int,float> y => projection / |y - centery + 0.5| (r_plane yslope) */    private array $ySlope = [];    /** @var array<int,float> x => angle offset of the column (radians, positive = left) */    private array $xToAngle = [];    private int $skyTexture = 0;    // the seg being drawn (R_StoreWallRange)    private Seg $curLine;    private float $segSx1 = 0;    private float $segSx2 = 0;    private float $segIz1 = 0;    private float $segIz2 = 0;    private float $segUz1 = 0;    private float $segUz2 = 0;    private int $wallLightNum = 0;    // fuzz (spectre) offsets    private const FUZZ = [1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, 1];    private int $fuzzPos = 0;    public function __construct(private Gfx $gfx, private Framebuffer $fb)    {        $this->setSize(320, 168);    }    public function setSize(int $width, int $height): void    {        $this->width = $width;        $this->height = $height;        $this->centerX = $width / 2;        $this->centerY = intdiv($height, 2);        $this->projection = $width / 2;        $this->screenHeightArray = array_fill(0, $width, $height);        $this->negOneArray = array_fill(0, $width, -1);        $this->ySlope = [];        for ($y = 0; $y < $height; $y++) {            $this->ySlope[$y] = $this->projection / abs($y - $this->centerY + 0.5);        }        $this->xToAngle = [];        for ($x = 0; $x <= $width; $x++) {            $this->xToAngle[$x] = atan(($this->centerX - $x - 0.5) / $this->projection);        }    }    public function setMap(MapData $map, string $skyName): void    {        $this->map = $map;        $this->skyTexture = $this->gfx->textureNumber($skyName);    }    /**     * Draws the player's view into the frame buffer (R_RenderPlayerView).     *     * @param list<array{0:int,1:float,2:float,3:bool}> $psprites weapon sprites: [state, sx, sy, full bright]     */    public function render(float $x, float $y, float $z, float $angle, array $psprites = [], bool $shadowWeapon = false): void    {        $this->viewX = $x;        $this->viewY = $y;        $this->viewZ = $z;        $this->viewAngle = $angle;        $this->viewCos = cos($angle);        $this->viewSin = sin($angle);        $this->validCount++;        $this->solidSegs = [[-0x7FFFFFFF, -1], [$this->width, 0x7FFFFFFF]];        $this->ceilingClip = $this->negOneArray;        $this->floorClip = $this->screenHeightArray;        $this->planes = [];        $this->drawSegs = [];        $this->visSprites = [];        if ($this->map->nodes === []) {            $this->subsector(0);        } else {            $this->renderBspNode(count($this->map->nodes) - 1);        }        $this->drawPlanes();        $this->drawMasked($psprites, $shadowWeapon);    }    // =================================================================== BSP (r_bsp.c)    private function renderBspNode(int $num): void    {        // iterative on the near side, recursive on the far side, like the original        while (!($num & 0x8000)) {            $node = $this->map->nodes[$num];            $side = MapData::pointOnSide($this->viewX, $this->viewY, $node);            $this->renderBspNode($node->children[$side]);            if (!$this->checkBBox($node->bbox[$side ^ 1])) {                return;            }            $num = $node->children[$side ^ 1];        }        $this->subsector($num === -1 ? 0 : $num & 0x7FFF);    }    /** @param list<float> $box top, bottom, left, right */    private function checkBBox(array $box): bool    {        static $check = [            [3, 0, 2, 1], [3, 0, 2, 0], [3, 1, 2, 0], [0, 0, 0, 0],            [2, 0, 2, 1], [0, 0, 0, 0], [3, 1, 3, 0], [0, 0, 0, 0],            [2, 0, 3, 1], [2, 1, 3, 1], [2, 1, 3, 0],        ];        $bx = $this->viewX <= $box[2] ? 0 : ($this->viewX < $box[3] ? 1 : 2);        $by = $this->viewY >= $box[0] ? 0 : ($this->viewY > $box[1] ? 1 : 2);        $pos = ($by << 2) + $bx;        if ($pos === 5) {            return true;        }        $c = $check[$pos];        $p = $this->project($box[$c[0]], $box[$c[1]], $box[$c[2]], $box[$c[3]], true);        if ($p === null) {            return false;        }        [$x1, $x2] = $p;        if ($x1 > $x2) {            return true;   // a sliver: let the walls decide        }        $start = 0;        while ($this->solidSegs[$start][1] < $x2) {            $start++;        }        return !($x1 >= $this->solidSegs[$start][0] && $x2 <= $this->solidSegs[$start][1]);    }    /**     * Clips a line (map coordinates) to the view and returns its columns [x1, x2, sx1, sx2, iz1, iz2, s1, s2]     * (sx: screen x, iz: 1 / depth, s: 0..1 along the line), or null when it is not in front.     * $any: also accept a back-facing line (bounding boxes).     *     * @return array{0:int,1:int,2:float,3:float,4:float,5:float,6:float,7:float}|null     */    private function project(float $ax, float $ay, float $bx, float $by, bool $any = false): ?array    {        $cos = $this->viewCos;        $sin = $this->viewSin;        $dx = $ax - $this->viewX;        $dy = $ay - $this->viewY;        $az = $dx * $cos + $dy * $sin;        $at = $dx * $sin - $dy * $cos;        $dx = $bx - $this->viewX;        $dy = $by - $this->viewY;        $bz = $dx * $cos + $dy * $sin;        $bt = $dx * $sin - $dy * $cos;        $s1 = 0.0;        $s2 = 1.0;        // left plane: z + t >= 0        $d1 = $az + $at;        $d2 = $bz + $bt;        if ($d1 < 0 && $d2 < 0) {            return null;        }        if ($d1 < 0 || $d2 < 0) {            $f = $d1 / ($d1 - $d2);            $nz = $az + ($bz - $az) * $f;            $nt = $at + ($bt - $at) * $f;            $ns = $s1 + ($s2 - $s1) * $f;            if ($d1 < 0) {                [$az, $at, $s1] = [$nz, $nt, $ns];            } else {                [$bz, $bt, $s2] = [$nz, $nt, $ns];            }        }        // right plane: z - t >= 0        $d1 = $az - $at;        $d2 = $bz - $bt;        if ($d1 < 0 && $d2 < 0) {            return null;        }        if ($d1 < 0 || $d2 < 0) {            $f = $d1 / ($d1 - $d2);            $nz = $az + ($bz - $az) * $f;            $nt = $at + ($bt - $at) * $f;            $ns = $s1 + ($s2 - $s1) * $f;            if ($d1 < 0) {                [$az, $at, $s1] = [$nz, $nt, $ns];            } else {                [$bz, $bt, $s2] = [$nz, $nt, $ns];            }        }        if ($az < 0.01 && $bz < 0.01) {            if ($any) {                return [0, $this->width - 1, 0.0, (float) $this->width, 0.0, 0.0, 0.0, 1.0];            }            return null;        }        $az = max($az, 0.01);        $bz = max($bz, 0.01);        $sx1 = $this->centerX + $this->projection * $at / $az;        $sx2 = $this->centerX + $this->projection * $bt / $bz;        if ($sx1 > $sx2) {            if (!$any) {                return null;   // back side            }            [$sx1, $sx2] = [$sx2, $sx1];            [$az, $bz] = [$bz, $az];            [$s1, $s2] = [$s2, $s1];        }        $x1 = (int) ceil($sx1 - 0.5);        $x2 = (int) ceil($sx2 - 0.5) - 1;        if ($x1 < 0) {            $x1 = 0;        }        if ($x2 >= $this->width) {            $x2 = $this->width - 1;        }        return [$x1, $x2, $sx1, $sx2, 1 / $az, 1 / $bz, $s1, $s2];    }    private function subsector(int $num): void    {        $sub = $this->map->subsectors[$num];        $sec = $sub->sector;        $sky = $this->gfx->skyFlat;        $floorPic = $this->gfx->flatTranslation[$sec->floorPic] ?? $sec->floorPic;        $ceilPic = $this->gfx->flatTranslation[$sec->ceilingPic] ?? $sec->ceilingPic;        $this->floorPlane = $sec->floorHeight < $this->viewZ            ? $this->findPlane($sec->floorHeight, $floorPic, $sec->lightLevel) : null;        $this->ceilingPlane = ($sec->ceilingHeight > $this->viewZ || $sec->ceilingPic === $sky)            ? $this->findPlane($sec->ceilingHeight, $ceilPic, $sec->lightLevel) : null;        $this->addSprites($sec);        $end = $sub->firstLine + $sub->numLines;        for ($i = $sub->firstLine; $i < $end; $i++) {            $this->addLine($this->map->segs[$i]);        }    }    private function addLine(Seg $seg): void    {        $p = $this->project($seg->v1->x, $seg->v1->y, $seg->v2->x, $seg->v2->y);        if ($p === null) {            return;        }        [$x1, $x2, $sx1, $sx2, $iz1, $iz2, $s1, $s2] = $p;        if ($x1 > $x2) {            return;        }        $this->curLine = $seg;        // texture u at both ends, divided by depth (perspective-correct interpolation)        $len = hypot($seg->v2->x - $seg->v1->x, $seg->v2->y - $seg->v1->y);        $u0 = $seg->offset + $seg->side->textureOffset;        $this->segSx1 = $sx1;        $this->segSx2 = $sx2;        $this->segIz1 = $iz1;        $this->segIz2 = $iz2;        $this->segUz1 = ($u0 + $s1 * $len) * $iz1;        $this->segUz2 = ($u0 + $s2 * $len) * $iz2;        $front = $seg->frontSector;        $back = $seg->backSector;        if ($back === null            || $back->ceilingHeight <= $front->floorHeight            || $back->floorHeight >= $front->ceilingHeight) {            $this->clipSolidWallSegment($x1, $x2);            return;        }        if ($back->ceilingHeight != $front->ceilingHeight || $back->floorHeight != $front->floorHeight) {            $this->clipPassWallSegment($x1, $x2);            return;        }        // identical sectors on both sides: an invisible line, unless it has a middle texture        if ($back->ceilingPic === $front->ceilingPic && $back->floorPic === $front->floorPic            && $back->lightLevel === $front->lightLevel && $seg->side->midTexture === 0) {            return;        }        $this->clipPassWallSegment($x1, $x2);    }    private function clipSolidWallSegment(int $first, int $last): void    {        $segs = &$this->solidSegs;        $start = 0;        while ($segs[$start][1] < $first - 1) {            $start++;        }        if ($first < $segs[$start][0]) {            if ($last < $segs[$start][0] - 1) {                $this->storeWallRange($first, $last);                array_splice($segs, $start, 0, [[$first, $last]]);                return;            }            $this->storeWallRange($first, $segs[$start][0] - 1);            $segs[$start][0] = $first;        }        if ($last <= $segs[$start][1]) {            return;        }        $next = $start;        while ($last >= $segs[$next + 1][0] - 1) {            $this->storeWallRange($segs[$next][1] + 1, $segs[$next + 1][0] - 1);            $next++;            if ($last <= $segs[$next][1]) {                $segs[$start][1] = $segs[$next][1];                if ($next !== $start) {                    array_splice($segs, $start + 1, $next - $start);                }                return;            }        }        $this->storeWallRange($segs[$next][1] + 1, $last);        $segs[$start][1] = $last;        if ($next !== $start) {            array_splice($segs, $start + 1, $next - $start);        }    }    private function clipPassWallSegment(int $first, int $last): void    {        $segs = $this->solidSegs;        $start = 0;        while ($segs[$start][1] < $first - 1) {            $start++;        }        if ($first < $segs[$start][0]) {            if ($last < $segs[$start][0] - 1) {                $this->storeWallRange($first, $last);                return;            }            $this->storeWallRange($first, $segs[$start][0] - 1);        }        if ($last <= $segs[$start][1]) {            return;        }        while ($last >= $segs[$start + 1][0] - 1) {            $this->storeWallRange($segs[$start][1] + 1, $segs[$start + 1][0] - 1);            $start++;            if ($last <= $segs[$start][1]) {                return;            }        }        $this->storeWallRange($segs[$start][1] + 1, $last);    }    // =================================================================== walls (r_segs.c)    /** 1/z and u/z of the current seg at column x. @return array{0:float,1:float} */    private function wallColumnAt(int $x): array    {        $span = $this->segSx2 - $this->segSx1;        $t = $span > 0 ? ($x + 0.5 - $this->segSx1) / $span : 0.0;        if ($t < 0) {            $t = 0.0;        } elseif ($t > 1) {            $t = 1.0;        }        return [$this->segIz1 + ($this->segIz2 - $this->segIz1) * $t, $this->segUz1 + ($this->segUz2 - $this->segUz1) * $t];    }    private function storeWallRange(int $start, int $stop): void    {        if ($start > $stop) {            return;        }        $seg = $this->curLine;        $side = $seg->side;        $line = $seg->line;        $line->flags |= Line::ML_MAPPED;        $front = $seg->frontSector;        $back = $seg->backSector;        $gfx = $this->gfx;        $viewZ = $this->viewZ;        $ds = new DrawSeg();        $ds->curLine = $seg;        $ds->x1 = $start;        $ds->x2 = $stop;        [$iz1] = $this->wallColumnAt($start);        [$iz2] = $this->wallColumnAt($stop);        $ds->scale1 = $this->projection * $iz1;        $ds->scale2 = $this->projection * $iz2;        $ds->scaleStep = $stop > $start ? ($ds->scale2 - $ds->scale1) / ($stop - $start) : 0.0;        $worldTop = $front->ceilingHeight - $viewZ;        $worldBottom = $front->floorHeight - $viewZ;        $worldHigh = $worldLow = 0.0;        $midTex = $topTex = $bottomTex = 0;        $masked = false;        $midMid = $topMid = $bottomMid = 0.0;        $markFloor = $markCeiling = false;        if ($back === null) {            $midTex = $gfx->textureTranslation[$side->midTexture] ?? 0;            $markFloor = $markCeiling = true;            if ($line->flags & Line::ML_DONTPEGBOTTOM) {                $h = $midTex ? $gfx->textures[$midTex]->height : 0;                $midMid = $front->floorHeight + $h - $viewZ;            } else {                $midMid = $worldTop;            }            $midMid += $side->rowOffset;            $ds->silhouette = self::SIL_BOTH;            $ds->sprTopClip = $this->screenHeightArray;            $ds->sprBottomClip = $this->negOneArray;            $ds->bsilHeight = self::BIG;            $ds->tsilHeight = -self::BIG;        } else {            if ($front->floorHeight > $back->floorHeight) {                $ds->silhouette = self::SIL_BOTTOM;                $ds->bsilHeight = $front->floorHeight;            } elseif ($back->floorHeight > $viewZ) {                $ds->silhouette = self::SIL_BOTTOM;                $ds->bsilHeight = self::BIG;            }            if ($front->ceilingHeight < $back->ceilingHeight) {                $ds->silhouette |= self::SIL_TOP;                $ds->tsilHeight = $front->ceilingHeight;            } elseif ($back->ceilingHeight < $viewZ) {                $ds->silhouette |= self::SIL_TOP;                $ds->tsilHeight = -self::BIG;            }            if ($back->ceilingHeight <= $front->floorHeight) {                $ds->sprBottomClip = $this->negOneArray;                $ds->bsilHeight = self::BIG;                $ds->silhouette |= self::SIL_BOTTOM;            }            if ($back->floorHeight >= $front->ceilingHeight) {                $ds->sprTopClip = $this->screenHeightArray;                $ds->tsilHeight = -self::BIG;                $ds->silhouette |= self::SIL_TOP;            }            $worldHigh = $back->ceilingHeight - $viewZ;            $worldLow = $back->floorHeight - $viewZ;            if ($front->ceilingPic === $gfx->skyFlat && $back->ceilingPic === $gfx->skyFlat) {                $worldTop = $worldHigh;   // hack: the sky goes over both            }            $markFloor = $worldLow != $worldBottom || $back->floorPic !== $front->floorPic                || $back->lightLevel !== $front->lightLevel;            $markCeiling = $worldHigh != $worldTop || $back->ceilingPic !== $front->ceilingPic                || $back->lightLevel !== $front->lightLevel;            if ($back->ceilingHeight <= $front->floorHeight || $back->floorHeight >= $front->ceilingHeight) {                $markCeiling = $markFloor = true;   // a closed door            }            if ($worldHigh < $worldTop) {                $topTex = $gfx->textureTranslation[$side->topTexture] ?? 0;                if ($line->flags & Line::ML_DONTPEGTOP) {                    $topMid = $worldTop;                } else {                    $h = $topTex ? $gfx->textures[$topTex]->height : 0;                    $topMid = $back->ceilingHeight + $h - $viewZ;                }            }            if ($worldLow > $worldBottom) {                $bottomTex = $gfx->textureTranslation[$side->bottomTexture] ?? 0;                $bottomMid = ($line->flags & Line::ML_DONTPEGBOTTOM) ? $worldTop : $worldLow;            }            $topMid += $side->rowOffset;            $bottomMid += $side->rowOffset;            if ($side->midTexture) {                $masked = true;                $ds->maskedTextureCol = [];            }        }        $segTextured = $midTex || $topTex || $bottomTex || $masked;        if ($segTextured) {            $light = ($front->lightLevel >> 4) + $this->extraLight;            if ($seg->v1->y == $seg->v2->y) {                $light--;            } elseif ($seg->v1->x == $seg->v2->x) {                $light++;            }            $this->wallLightNum = max(0, min(Gfx::LIGHTLEVELS - 1, $light));        }        if ($front->floorHeight >= $viewZ) {            $markFloor = false;        }        if ($front->ceilingHeight <= $viewZ && $front->ceilingPic !== $gfx->skyFlat) {            $markCeiling = false;        }        if ($markCeiling && $this->ceilingPlane !== null) {            $this->ceilingPlane = $this->checkPlane($this->ceilingPlane, $start, $stop);        } else {            $markCeiling = false;        }        if ($markFloor && $this->floorPlane !== null) {            $this->floorPlane = $this->checkPlane($this->floorPlane, $start, $stop);        } else {            $markFloor = false;        }        // ---- R_RenderSegLoop        $cy = $this->centerY;        $proj = $this->projection;        $lights = $gfx->scaleLight[$this->wallLightNum];        $fixed = $this->fixedColormap;        $ceilingPlane = $this->ceilingPlane;        $floorPlane = $this->floorPlane;        $viewHeight = $this->height;        $midTexture = $midTex ? $gfx->texture($midTex) : null;        $topTexture = $topTex ? $gfx->texture($topTex) : null;        $bottomTexture = $bottomTex ? $gfx->texture($bottomTex) : null;        $maskedCols = [];        for ($x = $start; $x <= $stop; $x++) {            [$iz, $uz] = $this->wallColumnAt($x);            $scale = $proj * $iz;            $topFrac = $cy - $worldTop * $scale;            $bottomFrac = $cy - $worldBottom * $scale;            $yl = (int) ceil($topFrac);            if ($yl < $this->ceilingClip[$x] + 1) {                $yl = $this->ceilingClip[$x] + 1;            }            if ($markCeiling) {                $top = $this->ceilingClip[$x] + 1;                $bottom = $yl - 1;                if ($bottom >= $this->floorClip[$x]) {                    $bottom = $this->floorClip[$x] - 1;                }                if ($top <= $bottom) {                    $ceilingPlane->top[$x] = $top;                    $ceilingPlane->bottom[$x] = $bottom;                }            }            $yh = (int) floor($bottomFrac);            if ($yh >= $this->floorClip[$x]) {                $yh = $this->floorClip[$x] - 1;            }            if ($markFloor) {                $top = $yh + 1;                $bottom = $this->floorClip[$x] - 1;                if ($top <= $this->ceilingClip[$x]) {                    $top = $this->ceilingClip[$x] + 1;                }                if ($top <= $bottom) {                    $floorPlane->top[$x] = $top;                    $floorPlane->bottom[$x] = $bottom;                }            }            $texCol = 0;            $cmap = 0;            $iscale = 1.0;            if ($segTextured) {                $texCol = (int) floor($uz / $iz);                $idx = (int) ($scale * 16);                $cmap = $fixed >= 0 ? $fixed : $lights[$idx > 47 ? 47 : $idx];                $iscale = 1 / $scale;            }            if ($midTexture !== null) {                if ($yl <= $yh) {                    $this->drawWallColumn($x, $yl, $yh, $midTexture, $texCol, $midMid, $iscale, $cmap);                }                $this->ceilingClip[$x] = $viewHeight;                $this->floorClip[$x] = -1;                continue;            }            if ($topTexture !== null) {                $mid = (int) floor($cy - $worldHigh * $scale);                if ($mid >= $this->floorClip[$x]) {                    $mid = $this->floorClip[$x] - 1;                }                if ($mid >= $yl) {                    $this->drawWallColumn($x, $yl, $mid, $topTexture, $texCol, $topMid, $iscale, $cmap);                    $this->ceilingClip[$x] = $mid;                } else {                    $this->ceilingClip[$x] = $yl - 1;                }            } elseif ($markCeiling) {                $this->ceilingClip[$x] = $yl - 1;            }            if ($bottomTexture !== null) {                $mid = (int) ceil($cy - $worldLow * $scale);                if ($mid <= $this->ceilingClip[$x]) {                    $mid = $this->ceilingClip[$x] + 1;                }                if ($mid <= $yh) {                    $this->drawWallColumn($x, $mid, $yh, $bottomTexture, $texCol, $bottomMid, $iscale, $cmap);                    $this->floorClip[$x] = $mid;                } else {                    $this->floorClip[$x] = $yh + 1;                }            } elseif ($markFloor) {                $this->floorClip[$x] = $yh + 1;            }            if ($masked) {                $maskedCols[$x] = $texCol;            }        }        if ($masked) {            $ds->maskedTextureCol = $maskedCols;        }        // sprite clipping information        if ((($ds->silhouette & self::SIL_TOP) || $masked) && $ds->sprTopClip === null) {            $ds->sprTopClip = $this->ceilingClip;        }        if ((($ds->silhouette & self::SIL_BOTTOM) || $masked) && $ds->sprBottomClip === null) {            $ds->sprBottomClip = $this->floorClip;        }        if ($masked && !($ds->silhouette & self::SIL_TOP)) {            $ds->silhouette |= self::SIL_TOP;            $ds->tsilHeight = -self::BIG;        }        if ($masked && !($ds->silhouette & self::SIL_BOTTOM)) {            $ds->silhouette |= self::SIL_BOTTOM;            $ds->bsilHeight = self::BIG;        }        $this->drawSegs[] = $ds;    }    private const SIL_BOTH = 3;    /** R_DrawColumn for a wall: one column of a texture, from screen row yl to yh. */    private function drawWallColumn(int $x, int $yl, int $yh, \App\Dm\Texture $tex, int $texCol, float $textureMid, float $iscale, int $cmapNum): void    {        $w = $tex->width;        $col = $tex->columns[(($texCol % $w) + $w) % $w];        $h = $tex->height;        $cmap = $this->gfx->colormaps[$cmapNum];        $frac = $textureMid + ($yl - $this->centerY) * $iscale;        $fb = &$this->fb->pixels;        $off = $yl * $this->fb->width + $x;        $pitch = $this->fb->width;        if (($h & ($h - 1)) === 0) {            $mask = $h - 1;            $frac += $h * 1024;   // keep it positive: (int) truncates toward zero            for ($y = $yl; $y <= $yh; $y++) {                $fb[$off] = $cmap[ord($col[((int) $frac) & $mask])];                $frac += $iscale;                $off += $pitch;            }            return;        }        $frac = fmod($frac, $h);        if ($frac < 0) {            $frac += $h;        }        for ($y = $yl; $y <= $yh; $y++) {            $fb[$off] = $cmap[ord($col[(int) $frac])];            $frac += $iscale;            if ($frac >= $h) {                $frac -= $h;            }            $off += $pitch;        }    }    // =================================================================== planes (r_plane.c)    private function findPlane(float $height, int $pic, int $light): Visplane    {        if ($pic === $this->gfx->skyFlat) {            $height = 0;            $light = 0;        }        foreach ($this->planes as $pl) {            if ($pl->height == $height && $pl->picNum === $pic && $pl->lightLevel === $light) {                return $pl;            }        }        $pl = new Visplane($height, $pic, $light, $this->width);        $this->planes[] = $pl;        return $pl;    }    private function checkPlane(Visplane $pl, int $start, int $stop): Visplane    {        if ($start < $pl->minX) {            $intrl = $pl->minX;            $unionl = $start;        } else {            $unionl = $pl->minX;            $intrl = $start;        }        if ($stop > $pl->maxX) {            $intrh = $pl->maxX;            $unionh = $stop;        } else {            $unionh = $pl->maxX;            $intrh = $stop;        }        for ($x = $intrl; $x <= $intrh; $x++) {            if ($pl->top[$x] !== Visplane::EMPTY) {                break;            }        }        if ($x > $intrh) {            $pl->minX = $unionl;            $pl->maxX = $unionh;            return $pl;        }        $new = new Visplane($pl->height, $pl->picNum, $pl->lightLevel, $this->width);        $new->minX = $start;        $new->maxX = $stop;        $this->planes[] = $new;        return $new;    }    private function drawPlanes(): void    {        $gfx = $this->gfx;        foreach ($this->planes as $pl) {            if ($pl->minX > $pl->maxX) {                continue;            }            if ($pl->picNum === $gfx->skyFlat) {                $this->drawSky($pl);                continue;            }            $flat = $gfx->flat($pl->picNum);            $planeHeight = abs($pl->height - $this->viewZ);            $light = max(0, min(Gfx::LIGHTLEVELS - 1, ($pl->lightLevel >> 4) + $this->extraLight));            $zlight = $gfx->zLight[$light];            $top = $pl->top;            $bottom = $pl->bottom;            $top[$pl->maxX + 1] = Visplane::EMPTY;            $top[$pl->minX - 1] = Visplane::EMPTY;            $bottom[$pl->maxX + 1] = 0;            $bottom[$pl->minX - 1] = 0;            $spanStart = [];            $stop = $pl->maxX + 1;            for ($x = $pl->minX; $x <= $stop; $x++) {                $t1 = $top[$x - 1];                $b1 = $bottom[$x - 1];                $t2 = $top[$x];                $b2 = $bottom[$x];                while ($t1 < $t2 && $t1 <= $b1) {                    $this->mapPlane($t1, $spanStart[$t1], $x - 1, $flat, $planeHeight, $zlight);                    $t1++;                }                while ($b1 > $b2 && $b1 >= $t1) {                    $this->mapPlane($b1, $spanStart[$b1], $x - 1, $flat, $planeHeight, $zlight);                    $b1--;                }                while ($t2 < $t1 && $t2 <= $b2) {                    $spanStart[$t2] = $x;                    $t2++;                }                while ($b2 > $b1 && $b2 >= $t2) {                    $spanStart[$b2] = $x;                    $b2--;                }            }        }    }    /** R_MapPlane + R_DrawSpan: one row of a floor or ceiling, from x1 to x2. @param array<int,int> $zlight */    private function mapPlane(int $y, int $x1, int $x2, string $flat, float $planeHeight, array $zlight): void    {        $dist = $planeHeight * $this->ySlope[$y];        $cos = $this->viewCos;        $sin = $this->viewSin;        $lateral = ($x1 + 0.5 - $this->centerX) / $this->projection * $dist;        // flat coordinates: x east, y = -north; +65536 keeps them positive for the & 63        $u = $this->viewX + $cos * $dist + $sin * $lateral + 65536.0;        $v = -($this->viewY + $sin * $dist - $cos * $lateral) + 65536.0;        $step = $dist / $this->projection;        $du = $sin * $step;        $dv = $cos * $step;        if ($this->fixedColormap >= 0) {            $cmap = $this->gfx->colormaps[$this->fixedColormap];        } else {            $idx = (int) ($dist / 16);            $cmap = $this->gfx->colormaps[$zlight[$idx > 127 ? 127 : $idx]];        }        $fb = &$this->fb->pixels;        $off = $y * $this->fb->width + $x1;        for ($x = $x1; $x <= $x2; $x++) {            $fb[$off++] = $cmap[ord($flat[((((int) $v) & 63) << 6) | (((int) $u) & 63)])];            $u += $du;            $v += $dv;        }    }    private function drawSky(Visplane $pl): void    {        if ($this->skyTexture === 0) {            return;        }        $tex = $this->gfx->texture($this->gfx->textureTranslation[$this->skyTexture] ?? $this->skyTexture);        // the sky is drawn at the original 320 x 200 scale, 1024 columns around (ANGLETOSKYSHIFT)        $cmapNum = $this->fixedColormap >= 0 ? $this->fixedColormap : 0;        $iscale = 200 / $this->height * ($this->height / 200);        for ($x = $pl->minX; $x <= $pl->maxX; $x++) {            $yl = $pl->top[$x];            $yh = $pl->bottom[$x];            if ($yl === Visplane::EMPTY || $yl > $yh) {                continue;            }            $angle = $this->viewAngle + $this->xToAngle[$x];            $col = (int) floor($angle / (2 * M_PI) * 1024);            $this->drawWallColumn($x, $yl, $yh, $tex, $col, 100.0, $iscale, $cmapNum);        }    }    // =================================================================== things (r_things.c)    private function addSprites(Sector $sec): void    {        if ($sec->validCount === $this->validCount) {            return;        }        $sec->validCount = $this->validCount;        $light = max(0, min(Gfx::LIGHTLEVELS - 1, ($sec->lightLevel >> 4) + $this->extraLight));        for ($thing = $sec->thingList; $thing !== null; $thing = $thing->snext) {            $this->projectSprite($thing, $light);        }    }    private function projectSprite(Mobj $thing, int $lightNum): void    {        if ($thing->player !== null && $thing->player->isViewer) {            return;   // the player looking does not see himself        }        $trX = $thing->x - $this->viewX;        $trY = $thing->y - $this->viewY;        $tz = $trX * $this->viewCos + $trY * $this->viewSin;        if ($tz < self::MINZ) {            return;        }        $xscale = $this->projection / $tz;        $tx = $trX * $this->viewSin - $trY * $this->viewCos;        if (abs($tx) > $tz * 4) {            return;        }        $frames = $this->gfx->sprites[$thing->sprite] ?? [];        $frameNum = $thing->frame & self::FF_FRAMEMASK;        if (!isset($frames[$frameNum])) {            return;        }        [$rotate, $lumps, $flips] = $frames[$frameNum];        if ($rotate) {            $ang = atan2($trY, $trX);            $rel = $ang - $thing->angle + M_PI + M_PI / 8;            $rot = ((int) floor($rel / (M_PI / 4))) & 7;            $lump = $lumps[$rot] ?? $lumps[0] ?? -1;            $flip = $flips[$rot] ?? false;        } else {            $lump = $lumps[0] ?? -1;            $flip = $flips[0] ?? false;        }        if ($lump < 0) {            return;        }        $patch = $this->gfx->patchNum($lump);        $tx -= $patch->leftOffset;        $x1 = (int) floor($this->centerX + $tx * $xscale);        if ($x1 > $this->width) {            return;        }        $tx += $patch->width;        $x2 = (int) floor($this->centerX + $tx * $xscale) - 1;        if ($x2 < 0) {            return;        }        $vis = new VisSprite();        $vis->mobjFlags = $thing->flags;        $vis->scale = $xscale;        $vis->gx = $thing->x;        $vis->gy = $thing->y;        $vis->gz = $thing->z;        $vis->gzt = $thing->z + $patch->topOffset;        $vis->textureMid = $vis->gzt - $this->viewZ;        $vis->x1 = max(0, $x1);        $vis->x2 = min($this->width - 1, $x2);        $iscale = 1 / $xscale;        if ($flip) {            $vis->startFrac = $patch->width - 0.0001;            $vis->xiScale = -$iscale;        } else {            $vis->startFrac = 0;            $vis->xiScale = $iscale;        }        if ($vis->x1 > $x1) {            $vis->startFrac += $vis->xiScale * ($vis->x1 - $x1);        }        $vis->patch = $patch;        if ($thing->flags & Info::MF_SHADOW) {            $vis->colormap = -1;        } elseif ($this->fixedColormap >= 0) {            $vis->colormap = $this->fixedColormap;        } elseif ($thing->frame & self::FF_FULLBRIGHT) {            $vis->colormap = 0;        } else {            $idx = (int) ($xscale * 16);            $vis->colormap = $this->gfx->scaleLight[$lightNum][$idx > 47 ? 47 : $idx];        }        $this->visSprites[] = $vis;    }    /** @param list<array{0:int,1:float,2:float,3:bool}> $psprites */    private function drawMasked(array $psprites, bool $shadowWeapon): void    {        if ($this->visSprites !== []) {            usort($this->visSprites, fn (VisSprite $a, VisSprite $b) => $a->scale <=> $b->scale);            foreach ($this->visSprites as $spr) {                $this->drawSprite($spr);            }        }        for ($i = count($this->drawSegs) - 1; $i >= 0; $i--) {            $ds = $this->drawSegs[$i];            if ($ds->maskedTextureCol !== null) {                $this->renderMaskedSegRange($ds, $ds->x1, $ds->x2);            }        }        $this->drawPlayerSprites($psprites, $shadowWeapon);    }    private function drawSprite(VisSprite $spr): void    {        $clipBot = [];        $clipTop = [];        for ($x = $spr->x1; $x <= $spr->x2; $x++) {            $clipBot[$x] = -2;            $clipTop[$x] = -2;        }        for ($i = count($this->drawSegs) - 1; $i >= 0; $i--) {            $ds = $this->drawSegs[$i];            if ($ds->x1 > $spr->x2 || $ds->x2 < $spr->x1 || (!$ds->silhouette && $ds->maskedTextureCol === null)) {                continue;            }            $r1 = max($ds->x1, $spr->x1);            $r2 = min($ds->x2, $spr->x2);            if ($ds->scale1 > $ds->scale2) {                $lowScale = $ds->scale2;                $scale = $ds->scale1;            } else {                $lowScale = $ds->scale1;                $scale = $ds->scale2;            }            if ($scale < $spr->scale || ($lowScale < $spr->scale && !$this->pointOnSegSide($spr->gx, $spr->gy, $ds->curLine))) {                if ($ds->maskedTextureCol !== null) {                    $this->renderMaskedSegRange($ds, $r1, $r2);                }                continue;   // the seg is behind the sprite            }            $sil = $ds->silhouette;            if ($spr->gz >= $ds->bsilHeight) {                $sil &= ~self::SIL_BOTTOM;            }            if ($spr->gzt <= $ds->tsilHeight) {                $sil &= ~self::SIL_TOP;            }            if ($sil & self::SIL_BOTTOM) {                for ($x = $r1; $x <= $r2; $x++) {                    if ($clipBot[$x] === -2) {                        $clipBot[$x] = $ds->sprBottomClip[$x];                    }                }            }            if ($sil & self::SIL_TOP) {                for ($x = $r1; $x <= $r2; $x++) {                    if ($clipTop[$x] === -2) {                        $clipTop[$x] = $ds->sprTopClip[$x];                    }                }            }        }        for ($x = $spr->x1; $x <= $spr->x2; $x++) {            if ($clipBot[$x] === -2) {                $clipBot[$x] = $this->height;            }            if ($clipTop[$x] === -2) {                $clipTop[$x] = -1;            }        }        $this->drawVisSprite($spr, $clipTop, $clipBot);    }    /** R_PointOnSegSide: 0 = front. */    private function pointOnSegSide(float $x, float $y, Seg $seg): int    {        $lx = $seg->v1->x;        $ly = $seg->v1->y;        $ldx = $seg->v2->x - $lx;        $ldy = $seg->v2->y - $ly;        if ($ldx == 0) {            return $x <= $lx ? ($ldy > 0 ? 1 : 0) : ($ldy < 0 ? 1 : 0);        }        if ($ldy == 0) {            return $y <= $ly ? ($ldx < 0 ? 1 : 0) : ($ldx > 0 ? 1 : 0);        }        $left = $ldy * ($x - $lx);        $right = ($y - $ly) * $ldx;        return $right < $left ? 0 : 1;    }    /** @param array<int,int> $clipTop @param array<int,int> $clipBot */    private function drawVisSprite(VisSprite $spr, array $clipTop, array $clipBot): void    {        $patch = $spr->patch;        $frac = $spr->startFrac;        $scale = $spr->scale;        $iscale = 1 / $scale;        $topScreen = $this->centerY - $spr->textureMid * $scale;        for ($x = $spr->x1; $x <= $spr->x2; $x++) {            $col = (int) $frac;            if ($col >= 0 && $col < $patch->width) {                $this->drawMaskedColumn($x, $patch->posts[$col], $topScreen, $scale, $iscale, $spr->textureMid, $clipTop[$x], $clipBot[$x], $spr->colormap);            }            $frac += $spr->xiScale;        }    }    /**     * R_DrawMaskedColumn: the posts of a column between the clips.     *     * @param list<array{0:int,1:string}> $posts     * @param int $colormap -1 = fuzz (spectre)     */    private function drawMaskedColumn(int $x, array $posts, float $topScreen, float $scale, float $iscale, float $textureMid, int $ceilClip, int $floorClip, int $colormap): void    {        $fbw = $this->fb->width;        $fb = &$this->fb->pixels;        $cmap = $colormap >= 0 ? $this->gfx->colormaps[$colormap] : $this->gfx->colormaps[6];        foreach ($posts as [$delta, $pixels]) {            $len = strlen($pixels);            $top = $topScreen + $scale * $delta;            $bottom = $top + $scale * $len;            $yl = (int) ceil($top);            $yh = (int) ceil($bottom) - 1;            if ($yh >= $floorClip) {                $yh = $floorClip - 1;            }            if ($yl <= $ceilClip) {                $yl = $ceilClip + 1;            }            if ($yl > $yh) {                continue;            }            $off = $yl * $fbw + $x;            if ($colormap < 0) {                // fuzz: darken the pixel next to it                if ($yl === 0) {                    $yl = 1;                    $off += $fbw;                }                if ($yh >= $this->height - 1) {                    $yh = $this->height - 2;                }                for ($y = $yl; $y <= $yh; $y++) {                    $fb[$off] = $cmap[ord($fb[$off + self::FUZZ[$this->fuzzPos] * $fbw])];                    $this->fuzzPos = ($this->fuzzPos + 1) % 50;                    $off += $fbw;                }                continue;            }            $frac = ($textureMid - $delta) + ($yl - $this->centerY) * $iscale;            $last = $len - 1;            for ($y = $yl; $y <= $yh; $y++) {                $i = (int) $frac;                $fb[$off] = $cmap[ord($pixels[$i < 0 ? 0 : ($i > $last ? $last : $i)])];                $frac += $iscale;                $off += $fbw;            }        }    }    private function renderMaskedSegRange(DrawSeg $ds, int $x1, int $x2): void    {        $seg = $ds->curLine;        $front = $seg->frontSector;        $back = $seg->backSector;        if ($back === null) {            return;        }        $texNum = $this->gfx->textureTranslation[$seg->side->midTexture] ?? 0;        if ($texNum === 0) {            return;        }        $tex = $this->gfx->maskedTexture($texNum);        $light = ($front->lightLevel >> 4) + $this->extraLight;        if ($seg->v1->y == $seg->v2->y) {            $light--;        } elseif ($seg->v1->x == $seg->v2->x) {            $light++;        }        $lights = $this->gfx->scaleLight[max(0, min(Gfx::LIGHTLEVELS - 1, $light))];        if ($seg->line->flags & Line::ML_DONTPEGBOTTOM) {            $textureMid = max($front->floorHeight, $back->floorHeight) + $tex->height - $this->viewZ;        } else {            $textureMid = min($front->ceilingHeight, $back->ceilingHeight) - $this->viewZ;        }        $textureMid += $seg->side->rowOffset;        $cols = &$ds->maskedTextureCol;        $w = $tex->width;        for ($x = $x1; $x <= $x2; $x++) {            if (!isset($cols[$x])) {                continue;            }            $scale = $ds->scale1 + ($x - $ds->x1) * $ds->scaleStep;            $idx = (int) ($scale * 16);            $cmap = $this->fixedColormap >= 0 ? $this->fixedColormap : $lights[$idx > 47 ? 47 : $idx];            $topScreen = $this->centerY - $textureMid * $scale;            $col = (($cols[$x] % $w) + $w) % $w;            $this->drawMaskedColumn($x, $tex->posts[$col], $topScreen, $scale, 1 / $scale, $textureMid, $ds->sprTopClip[$x] ?? -1, $ds->sprBottomClip[$x] ?? $this->height, $cmap);            unset($cols[$x]);        }    }    /** @param list<array{0:int,1:float,2:float,3:bool}> $psprites [state, sx, sy, full bright] */    private function drawPlayerSprites(array $psprites, bool $shadow): void    {        $lightLevel = 0;        foreach ($psprites as [$state, $sx, $sy, $_]) {            [$sprite, $frame] = Info::STATES[$state];            $frames = $this->gfx->sprites[$sprite] ?? [];            $f = $frames[$frame & self::FF_FRAMEMASK] ?? null;            if ($f === null) {                continue;            }            $patch = $this->gfx->patchNum($f[1][0]);            $flip = $f[2][0];            $scale = $this->width / 320;            $tx = $sx - 160 - $patch->leftOffset;            $x1 = (int) floor($this->centerX + $tx * $scale);            if ($x1 > $this->width) {                continue;            }            $tx += $patch->width;            $x2 = (int) floor($this->centerX + $tx * $scale) - 1;            if ($x2 < 0) {                continue;            }            $vis = new VisSprite();            $vis->textureMid = 100.5 - ($sy - $patch->topOffset);            $vis->x1 = max(0, $x1);            $vis->x2 = min($this->width - 1, $x2);            $vis->scale = $scale;            if ($flip) {                $vis->xiScale = -1 / $scale;                $vis->startFrac = $patch->width - 0.0001;            } else {                $vis->xiScale = 1 / $scale;                $vis->startFrac = 0;            }            if ($vis->x1 > $x1) {                $vis->startFrac += $vis->xiScale * ($vis->x1 - $x1);            }            $vis->patch = $patch;            if ($shadow) {                $vis->colormap = -1;            } elseif ($this->fixedColormap >= 0) {                $vis->colormap = $this->fixedColormap;            } elseif ($frame & self::FF_FULLBRIGHT) {                $vis->colormap = 0;            } else {                $vis->colormap = $this->gfx->scaleLight[$this->psprLight][Gfx::MAXLIGHTSCALE - 1];            }            $this->drawVisSprite($vis, $this->negOneArray, $this->screenHeightArray);        }    }    /** light level index of the player's sector (weapon sprites) */    public int $psprLight = 15;}