TR
games/dmmotor / src / Dm / Play / World.php · commit 9d248a4
<?php/* * dmmotor — the running level: thinkers, map objects, movement and collisions, line of sight, attacks * (after p_tick.c, p_mobj.c, p_maputl.c, p_map.c, p_sight.c and p_setup.c of linuxdoom-1.10). * Copyright (C) 1993-1996 by id Software, Inc.; PHP port for dmmotor. GPL v2 (see LICENSE). * * The original keeps this state in globals; here it is one object. The monster and weapon actions, * the pickups and damage, the player's moves and the map specials are in the traits it uses. * Floats replace fixed point: 1.0 = one map unit (FRACUNIT), angles are radians. */namespace App\Dm\Play;use App\Dm\Gfx;use App\Dm\Info;use App\Dm\Line;use App\Dm\MapData;use App\Dm\MapThing;use App\Dm\Node;use App\Dm\Sector;use App\Dm\Wad;final class World{    use Enemy;    use Weapons;    use Interaction;    use PlayerMove;    use Specials;    public const MAXRADIUS = 32.0;    public const GRAVITY = 1.0;    public const MAXMOVE = 30.0;    public const STOPSPEED = 0.0625;    public const FRICTION = 0.90625;    public const VIEWHEIGHT = 41.0;    public const USERANGE = 64.0;    public const MELEERANGE = 64.0;    public const MISSILERANGE = 2048.0;    public const FLOATSPEED = 4.0;    public const MAXHEALTH = 100;    public const ONFLOORZ = -1.0e9;    public const ONCEILINGZ = 1.0e9;    public const MAPBLOCKSIZE = 128.0;    /** 2^26 of the 2^32 angle units: 5.625 degrees */    public const ANG_SPREAD = M_PI / 32;    public const SK_BABY = 0;    public const SK_EASY = 1;    public const SK_MEDIUM = 2;    public const SK_HARD = 3;    public const SK_NIGHTMARE = 4;    public MapData $map;    public Player $player;    public int $skill = self::SK_MEDIUM;    public int $episode = 1;    /** Phase 2 (the commercial format): maps MAP01..MAP32, its monsters and super shotgun */    public bool $commercial = false;    public int $mapNum = 1;    /** @var list<Thinker|Mobj> */    public array $thinkers = [];    public int $levelTime = 0;    public int $totalKills = 0;    public int $totalItems = 0;    public int $totalSecret = 0;    public int $validCount = 1;    /** set by an exit line: 'normal' or 'secret' */    public ?string $exit = null;    /** @var list<array{0:int,1:?float,2:?float}> sounds this tic: [sfx, x, y] (null = everywhere) */    public array $soundQueue = [];    // ---- P_CheckPosition / P_TryMove results (globals of p_map.c)    private Mobj $tmThing;    private int $tmFlags = 0;    private float $tmX = 0;    private float $tmY = 0;    /** @var array{0:float,1:float,2:float,3:float} */    private array $tmBox = [0, 0, 0, 0];    public float $tmFloorZ = 0;    public float $tmCeilingZ = 0;    public float $tmDropoffZ = 0;    public bool $floatOk = false;    public ?Line $ceilingLine = null;    /** @var list<Line> */    private array $specHit = [];    // line opening (P_LineOpening)    public float $openTop = 0;    public float $openBottom = 0;    public float $openRange = 0;    public float $lowFloor = 0;    // traces (P_PathTraverse)    /** @var array{0:float,1:float,2:float,3:float} x, y, dx, dy */    private array $trace = [0, 0, 0, 0];    private bool $earlyOut = false;    /** @var list<array{0:float,1:?Line,2:?Mobj}> */    private array $intercepts = [];    // attacks    public ?Mobj $lineTarget = null;    private Mobj $shootThing;    private float $shootZ = 0;    private int $laDamage = 0;    private float $attackRange = 0;    private float $aimSlope = 0;    private float $topSlope = 0;    private float $bottomSlope = 0;    // sliding    private Mobj $slideMo;    private float $bestSlideFrac = 0;    private ?Line $bestSlideLine = null;    private float $tmXMove = 0;    private float $tmYMove = 0;    // sight    private float $sightZStart = 0;    /** @var array{0:float,1:float,2:float,3:float} */    private array $sTrace = [0, 0, 0, 0];    private float $t2x = 0;    private float $t2y = 0;    // radius attack / change sector    private Mobj $bombSpot;    private ?Mobj $bombSource = null;    private int $bombDamage = 0;    private bool $noFit = false;    private bool $crushChange = false;    /** The thing the last aimLineAttack() found (set by the trace callbacks). */    public function aimed(): ?Mobj    {        return $this->lineTarget;    }    /** @return list<array{0:float,1:?Line,2:?Mobj}> the intercepts the trace callbacks collected */    private function collected(): array    {        return $this->intercepts;    }    private function slideFrac(): float    {        return $this->bestSlideFrac;    }    private function slideLine(): ?Line    {        return $this->bestSlideLine;    }    public function __construct(public Wad $wad, public Gfx $gfx)    {        $this->player = new Player();    }    /** Save games: everything but the WAD and the graphics (given back by attach()). */    public function __serialize(): array    {        $vars = get_object_vars($this);        unset($vars['wad'], $vars['gfx']);        return $vars;    }    /** @param array<string,mixed> $data */    public function __unserialize(array $data): void    {        foreach ($data as $k => $v) {            $this->$k = $v;        }    }    /** After unserialize(): the WAD and graphics of the running game. */    public function attach(Wad $wad, Gfx $gfx): void    {        $this->wad = $wad;        $this->gfx = $gfx;        foreach ($gfx->textures as $i => $_) {            $gfx->textureTranslation[$i] = $i;        }        foreach ($gfx->flatNames as $i => $_) {            $gfx->flatTranslation[$i] = $i;        }    }    // =================================================================== level (p_setup.c, g_game.c)    public function mapName(int $episode, int $map): string    {        return $this->commercial ? sprintf('MAP%02d', $map) : "E{$episode}M{$map}";    }    /** P_SetupLevel: loads the map, spawns its things and starts its specials. */    public function setupLevel(int $episode, int $map, int $skill): void    {        $this->episode = $episode;        $this->mapNum = $map;        $this->skill = $skill;        $this->thinkers = [];        $this->levelTime = 0;        $this->totalKills = $this->totalItems = $this->totalSecret = 0;        $this->exit = null;        $this->soundQueue = [];        $this->player->killCount = $this->player->itemCount = $this->player->secretCount = 0;        if ($this->player->playerState === Player::DEAD) {            $this->player->playerState = Player::REBORN;        }        Random::clear();        $this->map = MapData::load($this->wad, $this->gfx, $this->mapName($episode, $map));        foreach ($this->gfx->textures as $i => $_) {            $this->gfx->textureTranslation[$i] = $i;        }        foreach ($this->gfx->flatNames as $i => $_) {            $this->gfx->flatTranslation[$i] = $i;        }        foreach ($this->map->things as $mt) {            $this->spawnMapThing($mt);        }        $this->spawnSpecials();    }    /** P_Ticker: one tic of the level. */    public function tick(): void    {        $this->playerThink($this->player);        foreach ($this->thinkers as $t) {            if ($t instanceof Mobj) {                if (!$t->removed) {                    $this->mobjThinker($t);                }            } elseif (!$t->isRemoved()) {                $t->think($this);            }        }        if (($this->levelTime & 63) === 0) {            $this->thinkers = array_values(array_filter(                $this->thinkers,                fn ($t) => $t instanceof Mobj ? !$t->removed : !$t->isRemoved(),            ));        }        $this->updateSpecials();        $this->levelTime++;    }    public function addThinker(Thinker|Mobj $t): void    {        $this->thinkers[] = $t;    }    /** S_StartSound: queued, the scene plays it (louder when near the player). */    public function startSound(?Mobj $origin, int $sfx): void    {        if ($sfx <= 0) {            return;        }        if ($origin === null || $origin === $this->player->mo) {            $this->soundQueue[] = [$sfx, null, null];            return;        }        $this->soundQueue[] = [$sfx, $origin->x, $origin->y];    }    public function startSoundAt(float $x, float $y, int $sfx): void    {        $this->soundQueue[] = [$sfx, $x, $y];    }    // =================================================================== map objects (p_mobj.c)    /** P_SetMobjState: false when the object was removed. */    public function setMobjState(Mobj $mo, int $state): bool    {        do {            if ($state === Info::S_NULL) {                $mo->state = Info::S_NULL;                $this->removeMobj($mo);                return false;            }            [$sprite, $frame, $tics, $action, $next] = Info::STATES[$state];            $mo->state = $state;            $mo->tics = $tics;            $mo->sprite = $sprite;            $mo->frame = $frame;            if ($action !== null) {                $this->callAction($action, $mo);                if ($mo->removed) {                    return false;                }            }            $state = $next;        } while ($mo->tics === 0);        return true;    }    /** The A_* function of a state, for a map object. */    private function callAction(string $action, Mobj $mo): void    {        if (method_exists($this, $action)) {            $this->$action($mo);        }    }    public function explodeMissile(Mobj $mo): void    {        $mo->momX = $mo->momY = $mo->momZ = 0;        $this->setMobjState($mo, $mo->info['deathstate']);        $mo->tics -= Random::p() & 3;        if ($mo->tics < 1) {            $mo->tics = 1;        }        $mo->flags &= ~Info::MF_MISSILE;        $this->startSound($mo, $mo->info['deathsound']);    }    private function xyMovement(Mobj $mo): void    {        if ($mo->momX == 0 && $mo->momY == 0) {            if ($mo->flags & Info::MF_SKULLFLY) {                // the skull slammed into something                $mo->flags &= ~Info::MF_SKULLFLY;                $mo->momX = $mo->momY = $mo->momZ = 0;                $this->setMobjState($mo, $mo->info['spawnstate']);            }            return;        }        $player = $mo->player;        $mo->momX = max(-self::MAXMOVE, min(self::MAXMOVE, $mo->momX));        $mo->momY = max(-self::MAXMOVE, min(self::MAXMOVE, $mo->momY));        $xmove = $mo->momX;        $ymove = $mo->momY;        do {            if (abs($xmove) > self::MAXMOVE / 2 || abs($ymove) > self::MAXMOVE / 2) {                $ptryx = $mo->x + $xmove / 2;                $ptryy = $mo->y + $ymove / 2;                $xmove /= 2;                $ymove /= 2;            } else {                $ptryx = $mo->x + $xmove;                $ptryy = $mo->y + $ymove;                $xmove = $ymove = 0;            }            if (!$this->tryMove($mo, $ptryx, $ptryy)) {                if ($player !== null) {                    $this->slideMove($mo);                } elseif ($mo->flags & Info::MF_MISSILE) {                    // a missile hitting the sky vanishes                    if ($this->ceilingLine !== null && $this->ceilingLine->backSector !== null                        && $this->ceilingLine->backSector->ceilingPic === $this->gfx->skyFlat) {                        $this->removeMobj($mo);                        return;                    }                    $this->explodeMissile($mo);                } else {                    $mo->momX = $mo->momY = 0;                }            }        } while ($xmove != 0 || $ymove != 0);        if ($mo->flags & (Info::MF_MISSILE | Info::MF_SKULLFLY)) {            return;        }        if ($mo->z > $mo->floorZ) {            return;   // no friction in the air        }        if ($mo->flags & Info::MF_CORPSE) {            // bodies slide down stairs            if (($mo->momX > 0.25 || $mo->momX < -0.25 || $mo->momY > 0.25 || $mo->momY < -0.25)                && $mo->floorZ != $mo->subsector->sector->floorHeight) {                return;            }        }        if ($mo->momX > -self::STOPSPEED && $mo->momX < self::STOPSPEED            && $mo->momY > -self::STOPSPEED && $mo->momY < self::STOPSPEED            && ($player === null || ($player->cmd->forwardMove === 0 && $player->cmd->sideMove === 0))) {            if ($player !== null && $player->mo->state >= Info::S_PLAY_RUN1 && $player->mo->state < Info::S_PLAY_RUN1 + 4) {                $this->setMobjState($player->mo, Info::S_PLAY);            }            $mo->momX = $mo->momY = 0;        } else {            $mo->momX *= self::FRICTION;            $mo->momY *= self::FRICTION;        }    }    private function zMovement(Mobj $mo): void    {        if ($mo->player !== null && $mo->z < $mo->floorZ) {            // smooth the step up            $mo->player->viewHeight -= $mo->floorZ - $mo->z;            $mo->player->deltaViewHeight = (self::VIEWHEIGHT - $mo->player->viewHeight) / 8;        }        $mo->z += $mo->momZ;        if (($mo->flags & Info::MF_FLOAT) && $mo->target !== null) {            if (!($mo->flags & Info::MF_SKULLFLY) && !($mo->flags & Info::MF_INFLOAT)) {                $dist = self::approxDistance($mo->x - $mo->target->x, $mo->y - $mo->target->y);                $delta = $mo->target->z + $mo->height / 2 - $mo->z;                if ($delta < 0 && $dist < -($delta * 3)) {                    $mo->z -= self::FLOATSPEED;                } elseif ($delta > 0 && $dist < $delta * 3) {                    $mo->z += self::FLOATSPEED;                }            }        }        if ($mo->z <= $mo->floorZ) {            if ($mo->flags & Info::MF_SKULLFLY) {                $mo->momZ = -$mo->momZ;            }            if ($mo->momZ < 0) {                if ($mo->player !== null && $mo->momZ < -self::GRAVITY * 8) {                    // a hard landing squats the view                    $mo->player->deltaViewHeight = $mo->momZ / 8;                    $this->startSound($mo, $this->sfx('oof'));                }                $mo->momZ = 0;            }            $mo->z = $mo->floorZ;            if (($mo->flags & Info::MF_MISSILE) && !($mo->flags & Info::MF_NOCLIP)) {                $this->explodeMissile($mo);                return;            }        } elseif (!($mo->flags & Info::MF_NOGRAVITY)) {            $mo->momZ = $mo->momZ == 0 ? -self::GRAVITY * 2 : $mo->momZ - self::GRAVITY;        }        if ($mo->z + $mo->height > $mo->ceilingZ) {            if ($mo->momZ > 0) {                $mo->momZ = 0;            }            $mo->z = $mo->ceilingZ - $mo->height;            if ($mo->flags & Info::MF_SKULLFLY) {                $mo->momZ = -$mo->momZ;            }            if (($mo->flags & Info::MF_MISSILE) && !($mo->flags & Info::MF_NOCLIP)) {                $this->explodeMissile($mo);            }        }    }    public function mobjThinker(Mobj $mo): void    {        if ($mo->momX != 0 || $mo->momY != 0 || ($mo->flags & Info::MF_SKULLFLY)) {            $this->xyMovement($mo);            if ($mo->removed) {                return;            }        }        if ($mo->z != $mo->floorZ || $mo->momZ != 0) {            $this->zMovement($mo);            if ($mo->removed) {                return;            }        }        if ($mo->tics !== -1) {            $mo->tics--;            if ($mo->tics <= 0) {                $this->setMobjState($mo, Info::STATES[$mo->state][4]);            }        }    }    public function spawnMobj(float $x, float $y, float $z, int $type): Mobj    {        $info = Info::MOBJINFO[$type];        $mo = new Mobj();        $mo->type = $type;        $mo->info = $info;        $mo->x = $x;        $mo->y = $y;        $mo->radius = (float) $info['radius'];        $mo->height = (float) $info['height'];        $mo->flags = $info['flags'];        $mo->health = $info['spawnhealth'];        if ($this->skill !== self::SK_NIGHTMARE) {            $mo->reactionTime = $info['reactiontime'];        }        $mo->lastLook = Random::p() % 4;        [$sprite, $frame, $tics] = Info::STATES[$info['spawnstate']];        $mo->state = $info['spawnstate'];        $mo->tics = $tics;        $mo->sprite = $sprite;        $mo->frame = $frame;        $this->setThingPosition($mo);        $mo->floorZ = $mo->subsector->sector->floorHeight;        $mo->ceilingZ = $mo->subsector->sector->ceilingHeight;        if ($z === self::ONFLOORZ) {            $mo->z = $mo->floorZ;        } elseif ($z === self::ONCEILINGZ) {            $mo->z = $mo->ceilingZ - $mo->height;        } else {            $mo->z = $z;        }        $this->addThinker($mo);        return $mo;    }    public function removeMobj(Mobj $mo): void    {        if ($mo->removed) {            return;        }        $this->unsetThingPosition($mo);        $mo->removed = true;    }    private function spawnPlayer(MapThing $mt): void    {        $p = $this->player;        if ($p->playerState === Player::REBORN) {            $p->reborn();        }        $mo = $this->spawnMobj($mt->x, $mt->y, self::ONFLOORZ, Info::MT_PLAYER);        $mo->angle = deg2rad(45 * intdiv($mt->angle, 45));        $mo->player = $p;        $mo->health = $p->health;        $p->mo = $mo;        $p->playerState = Player::LIVE;        $p->refire = 0;        $p->message = null;        $p->damageCount = 0;        $p->bonusCount = 0;        $p->extraLight = 0;        $p->fixedColormap = 0;        $p->viewHeight = self::VIEWHEIGHT;        $p->deltaViewHeight = 0;        $this->setupPsprites($p);    }    /** P_SpawnMapThing */    private function spawnMapThing(MapThing $mt): void    {        if ($mt->type === 11 || ($mt->type >= 2 && $mt->type <= 4)) {            return;   // deathmatch and other players' starts        }        if ($mt->type === 1) {            $this->spawnPlayer($mt);            return;        }        if ($mt->options & 16) {            return;   // multiplayer only        }        $bit = match (true) {            $this->skill <= self::SK_EASY => 1,            $this->skill === self::SK_MEDIUM => 2,            default => 4,        };        if (!($mt->options & $bit)) {            return;        }        $type = -1;        foreach (Info::MOBJINFO as $i => $info) {            if ($info['doomednum'] === $mt->type) {                $type = $i;                break;            }        }        if ($type < 0) {            return;        }        $info = Info::MOBJINFO[$type];        $z = ($info['flags'] & Info::MF_SPAWNCEILING) ? self::ONCEILINGZ : self::ONFLOORZ;        $mo = $this->spawnMobj($mt->x, $mt->y, $z, $type);        $mo->spawnPoint = $mt;        if ($mo->tics > 0) {            $mo->tics = 1 + (Random::p() % $mo->tics);        }        if ($mo->flags & Info::MF_COUNTKILL) {            $this->totalKills++;        }        if ($mo->flags & Info::MF_COUNTITEM) {            $this->totalItems++;        }        $mo->angle = deg2rad(45 * intdiv($mt->angle, 45));        if ($mt->options & 8) {            $mo->flags |= Info::MF_AMBUSH;        }    }    public function spawnPuff(float $x, float $y, float $z): void    {        $z += (Random::p() - Random::p()) / 64;        $th = $this->spawnMobj($x, $y, $z, Info::MT_PUFF);        $th->momZ = 1;        $th->tics -= Random::p() & 3;        if ($th->tics < 1) {            $th->tics = 1;        }        if ($this->attackRange == self::MELEERANGE) {            $this->setMobjState($th, Info::S_PUFF3);   // no sparks against a wall with the fist        }    }    public function spawnBlood(float $x, float $y, float $z, int $damage): void    {        $z += (Random::p() - Random::p()) / 64;        $th = $this->spawnMobj($x, $y, $z, Info::MT_BLOOD);        $th->momZ = 2;        $th->tics -= Random::p() & 3;        if ($th->tics < 1) {            $th->tics = 1;        }        if ($damage <= 12 && $damage >= 9) {            $this->setMobjState($th, Info::S_BLOOD2);        } elseif ($damage < 9) {            $this->setMobjState($th, Info::S_BLOOD3);        }    }    private function checkMissileSpawn(Mobj $th): void    {        $th->tics -= Random::p() & 3;        if ($th->tics < 1) {            $th->tics = 1;        }        // move a little forward so an angle can be computed if it immediately explodes        $th->x += $th->momX / 2;        $th->y += $th->momY / 2;        $th->z += $th->momZ / 2;        if (!$this->tryMove($th, $th->x, $th->y)) {            $this->explodeMissile($th);        }    }    public function spawnMissile(Mobj $source, Mobj $dest, int $type): Mobj    {        $th = $this->spawnMobj($source->x, $source->y, $source->z + 32, $type);        $this->startSound($th, $th->info['seesound']);        $th->target = $source;        $an = self::pointToAngle($source->x, $source->y, $dest->x, $dest->y);        if ($dest->flags & Info::MF_SHADOW) {            $an += (Random::p() - Random::p()) * (M_PI / 2048);   // << 20 angle units        }        $th->angle = $an;        $speed = (float) $th->info['speed'];        $th->momX = $speed * cos($an);        $th->momY = $speed * sin($an);        $dist = (int) (self::approxDistance($dest->x - $source->x, $dest->y - $source->y) / $speed);        if ($dist < 1) {            $dist = 1;        }        $th->momZ = ($dest->z - $source->z) / $dist;        $this->checkMissileSpawn($th);        return $th;    }    public function spawnPlayerMissile(Mobj $source, int $type): void    {        $an = $source->angle;        $slope = $this->aimLineAttack($source, $an, 16 * 64);        if ($this->aimed() === null) {            $an += self::ANG_SPREAD;            $slope = $this->aimLineAttack($source, $an, 16 * 64);            if ($this->aimed() === null) {                $an -= 2 * self::ANG_SPREAD;                $slope = $this->aimLineAttack($source, $an, 16 * 64);            }            if ($this->aimed() === null) {                $an = $source->angle;                $slope = 0;            }        }        $th = $this->spawnMobj($source->x, $source->y, $source->z + 32, $type);        $this->startSound($th, $th->info['seesound']);        $th->target = $source;        $th->angle = $an;        $speed = (float) $th->info['speed'];        $th->momX = $speed * cos($an);        $th->momY = $speed * sin($an);        $th->momZ = $speed * $slope;        $this->checkMissileSpawn($th);    }    /** sfx number of a sound name ("pistol", "oof"...). */    public function sfx(string $name): int    {        static $index = null;        $index ??= array_flip(Info::SOUNDS);        return $index[$name] ?? 0;    }    // =================================================================== map utilities (p_maputl.c)    public static function approxDistance(float $dx, float $dy): float    {        $dx = abs($dx);        $dy = abs($dy);        return $dx < $dy ? $dx + $dy - $dx / 2 : $dx + $dy - $dy / 2;    }    public static function pointToAngle(float $x1, float $y1, float $x2, float $y2): float    {        return atan2($y2 - $y1, $x2 - $x1);    }    /** an angle in 0 .. 2 pi */    public static function normAngle(float $a): float    {        $a = fmod($a, 2 * M_PI);        return $a < 0 ? $a + 2 * M_PI : $a;    }    public static function pointOnLineSide(float $x, float $y, Line $line): int    {        $lx = $line->v1->x;        $ly = $line->v1->y;        if ($line->dx == 0) {            return $x <= $lx ? ($line->dy > 0 ? 1 : 0) : ($line->dy < 0 ? 1 : 0);        }        if ($line->dy == 0) {            return $y <= $ly ? ($line->dx < 0 ? 1 : 0) : ($line->dx > 0 ? 1 : 0);        }        $left = $line->dy * ($x - $lx);        $right = ($y - $ly) * $line->dx;        return $right < $left ? 0 : 1;    }    /** P_BoxOnLineSide: 0 or 1 when the box is on one side, -1 when it crosses. @param array<int,float> $box */    public static function boxOnLineSide(array $box, Line $ld): int    {        switch ($ld->slopeType) {            case Line::ST_HORIZONTAL:                $p1 = $box[0] > $ld->v1->y ? 1 : 0;                $p2 = $box[1] > $ld->v1->y ? 1 : 0;                if ($ld->dx < 0) {                    $p1 ^= 1;                    $p2 ^= 1;                }                break;            case Line::ST_VERTICAL:                $p1 = $box[3] < $ld->v1->x ? 1 : 0;                $p2 = $box[2] < $ld->v1->x ? 1 : 0;                if ($ld->dy < 0) {                    $p1 ^= 1;                    $p2 ^= 1;                }                break;            case Line::ST_POSITIVE:                $p1 = self::pointOnLineSide($box[2], $box[0], $ld);                $p2 = self::pointOnLineSide($box[3], $box[1], $ld);                break;            default:                $p1 = self::pointOnLineSide($box[3], $box[0], $ld);                $p2 = self::pointOnLineSide($box[2], $box[1], $ld);                break;        }        return $p1 === $p2 ? $p1 : -1;    }    /** @param array{0:float,1:float,2:float,3:float} $dl x, y, dx, dy */    private static function pointOnDivlineSide(float $x, float $y, array $dl): int    {        if ($dl[2] == 0) {            return $x <= $dl[0] ? ($dl[3] > 0 ? 1 : 0) : ($dl[3] < 0 ? 1 : 0);        }        if ($dl[3] == 0) {            return $y <= $dl[1] ? ($dl[2] < 0 ? 1 : 0) : ($dl[2] > 0 ? 1 : 0);        }        $left = $dl[3] * ($x - $dl[0]);        $right = ($y - $dl[1]) * $dl[2];        return $right < $left ? 0 : 1;    }    /**     * P_InterceptVector: where $v1 crosses $v2, as a fraction of $v2.     *     * @param array{0:float,1:float,2:float,3:float} $v2     * @param array{0:float,1:float,2:float,3:float} $v1     */    private static function interceptVector(array $v2, array $v1): float    {        $den = $v1[3] * $v2[2] - $v1[2] * $v2[3];        if ($den == 0) {            return 0;        }        $num = ($v1[0] - $v2[0]) * $v1[3] + ($v2[1] - $v1[1]) * $v1[2];        return $num / $den;    }    /** P_LineOpening: the gap of a two-sided line (openTop, openBottom, openRange, lowFloor). */    public function lineOpening(Line $line): void    {        if ($line->sidenum[1] === -1 || $line->backSector === null) {            $this->openRange = 0;            return;        }        $front = $line->frontSector;        $back = $line->backSector;        $this->openTop = min($front->ceilingHeight, $back->ceilingHeight);        if ($front->floorHeight > $back->floorHeight) {            $this->openBottom = $front->floorHeight;            $this->lowFloor = $back->floorHeight;        } else {            $this->openBottom = $back->floorHeight;            $this->lowFloor = $front->floorHeight;        }        $this->openRange = $this->openTop - $this->openBottom;    }    public function unsetThingPosition(Mobj $thing): void    {        if (!($thing->flags & Info::MF_NOSECTOR)) {            if ($thing->snext !== null) {                $thing->snext->sprev = $thing->sprev;            }            if ($thing->sprev !== null) {                $thing->sprev->snext = $thing->snext;            } elseif ($thing->subsector !== null && $thing->subsector->sector->thingList === $thing) {                $thing->subsector->sector->thingList = $thing->snext;            }            $thing->snext = $thing->sprev = null;        }        if (!($thing->flags & Info::MF_NOBLOCKMAP)) {            if ($thing->bnext !== null) {                $thing->bnext->bprev = $thing->bprev;            }            if ($thing->bprev !== null) {                $thing->bprev->bnext = $thing->bnext;            } elseif ($thing->blockIndex >= 0 && $this->map->blockLinks[$thing->blockIndex] === $thing) {                $this->map->blockLinks[$thing->blockIndex] = $thing->bnext;            }            $thing->bnext = $thing->bprev = null;            $thing->blockIndex = -1;        }    }    public function setThingPosition(Mobj $thing): void    {        $ss = $this->map->pointInSubsector($thing->x, $thing->y);        $thing->subsector = $ss;        if (!($thing->flags & Info::MF_NOSECTOR)) {            $sec = $ss->sector;            $thing->sprev = null;            $thing->snext = $sec->thingList;            if ($sec->thingList !== null) {                $sec->thingList->sprev = $thing;            }            $sec->thingList = $thing;        }        if (!($thing->flags & Info::MF_NOBLOCKMAP)) {            $bx = (int) floor(($thing->x - $this->map->bmapOrgX) / self::MAPBLOCKSIZE);            $by = (int) floor(($thing->y - $this->map->bmapOrgY) / self::MAPBLOCKSIZE);            if ($bx >= 0 && $by >= 0 && $bx < $this->map->bmapWidth && $by < $this->map->bmapHeight) {                $i = $by * $this->map->bmapWidth + $bx;                $thing->bprev = null;                $thing->bnext = $this->map->blockLinks[$i];                if ($thing->bnext !== null) {                    $thing->bnext->bprev = $thing;                }                $this->map->blockLinks[$i] = $thing;                $thing->blockIndex = $i;            } else {                $thing->bnext = $thing->bprev = null;                $thing->blockIndex = -1;            }        }    }    /** P_BlockLinesIterator: false when $func stopped it. @param callable(Line):bool $func */    public function blockLinesIterator(int $x, int $y, callable $func): bool    {        $map = $this->map;        if ($x < 0 || $y < 0 || $x >= $map->bmapWidth || $y >= $map->bmapHeight) {            return true;        }        foreach ($map->blockLines[$y * $map->bmapWidth + $x] as $num) {            $ld = $map->lines[$num] ?? null;            if ($ld === null || $ld->validCount === $this->validCount) {                continue;            }            $ld->validCount = $this->validCount;            if (!$func($ld)) {                return false;            }        }        return true;    }    /** P_BlockThingsIterator. @param callable(Mobj):bool $func */    public function blockThingsIterator(int $x, int $y, callable $func): bool    {        $map = $this->map;        if ($x < 0 || $y < 0 || $x >= $map->bmapWidth || $y >= $map->bmapHeight) {            return true;        }        $mo = $map->blockLinks[$y * $map->bmapWidth + $x];        while ($mo !== null) {            $next = $mo->bnext;            if (!$func($mo)) {                return false;            }            $mo = $next;        }        return true;    }    /** Block coordinates of a map position. @return array{0:int,1:int} */    public function blockOf(float $x, float $y): array    {        return [            (int) floor(($x - $this->map->bmapOrgX) / self::MAPBLOCKSIZE),            (int) floor(($y - $this->map->bmapOrgY) / self::MAPBLOCKSIZE),        ];    }    public const PT_ADDLINES = 1;    public const PT_ADDTHINGS = 2;    public const PT_EARLYOUT = 4;    /**     * P_PathTraverse: calls $trav for every line / thing crossed from (x1, y1) to (x2, y2), nearest first,     * until it returns false. @param callable(array{0:float,1:?Line,2:?Mobj}):bool $trav     */    public function pathTraverse(float $x1, float $y1, float $x2, float $y2, int $flags, callable $trav): bool    {        $map = $this->map;        $this->earlyOut = (bool) ($flags & self::PT_EARLYOUT);        $this->validCount++;        $this->intercepts = [];        if (fmod($x1 - $map->bmapOrgX, self::MAPBLOCKSIZE) == 0) {            $x1 += 1;   // do not side exactly on a line        }        if (fmod($y1 - $map->bmapOrgY, self::MAPBLOCKSIZE) == 0) {            $y1 += 1;        }        $this->trace = [$x1, $y1, $x2 - $x1, $y2 - $y1];        $fx1 = ($x1 - $map->bmapOrgX) / self::MAPBLOCKSIZE;        $fy1 = ($y1 - $map->bmapOrgY) / self::MAPBLOCKSIZE;        $fx2 = ($x2 - $map->bmapOrgX) / self::MAPBLOCKSIZE;        $fy2 = ($y2 - $map->bmapOrgY) / self::MAPBLOCKSIZE;        $xt1 = (int) floor($fx1);        $yt1 = (int) floor($fy1);        $xt2 = (int) floor($fx2);        $yt2 = (int) floor($fy2);        if ($xt2 > $xt1) {            $mapXStep = 1;            $partial = 1 - ($fx1 - floor($fx1));            $yStep = ($fy2 - $fy1) / abs($fx2 - $fx1);        } elseif ($xt2 < $xt1) {            $mapXStep = -1;            $partial = $fx1 - floor($fx1);            $yStep = ($fy2 - $fy1) / abs($fx2 - $fx1);        } else {            $mapXStep = 0;            $partial = 1;            $yStep = 256;        }        $yIntercept = $fy1 + $partial * $yStep;        if ($yt2 > $yt1) {            $mapYStep = 1;            $partial = 1 - ($fy1 - floor($fy1));            $xStep = ($fx2 - $fx1) / abs($fy2 - $fy1);        } elseif ($yt2 < $yt1) {            $mapYStep = -1;            $partial = $fy1 - floor($fy1);            $xStep = ($fx2 - $fx1) / abs($fy2 - $fy1);        } else {            $mapYStep = 0;            $partial = 1;            $xStep = 256;        }        $xIntercept = $fx1 + $partial * $xStep;        $mapX = $xt1;        $mapY = $yt1;        for ($count = 0; $count < 64; $count++) {            if ($flags & self::PT_ADDLINES) {                if (!$this->blockLinesIterator($mapX, $mapY, fn (Line $ld) => $this->addLineIntercepts($ld))) {                    return false;                }            }            if ($flags & self::PT_ADDTHINGS) {                if (!$this->blockThingsIterator($mapX, $mapY, fn (Mobj $th) => $this->addThingIntercepts($th))) {                    return false;                }            }            if ($mapX === $xt2 && $mapY === $yt2) {                break;            }            if ((int) floor($yIntercept) === $mapY) {                $yIntercept += $yStep;                $mapX += $mapXStep;            } elseif ((int) floor($xIntercept) === $mapX) {                $xIntercept += $xStep;                $mapY += $mapYStep;            } else {                break;            }        }        // P_TraverseIntercepts: nearest first        $intercepts = $this->collected();        usort($intercepts, fn ($a, $b) => $a[0] <=> $b[0]);        foreach ($intercepts as $in) {            if ($in[0] > 1) {                return true;            }            if (!$trav($in)) {                return false;            }        }        return true;    }    private function addLineIntercepts(Line $ld): bool    {        $s1 = self::pointOnDivlineSide($ld->v1->x, $ld->v1->y, $this->trace);        $s2 = self::pointOnDivlineSide($ld->v2->x, $ld->v2->y, $this->trace);        if ($s1 === $s2) {            return true;   // not crossed        }        $frac = self::interceptVector($this->trace, [$ld->v1->x, $ld->v1->y, $ld->dx, $ld->dy]);        if ($frac < 0) {            return true;   // behind the source        }        if ($this->earlyOut && $frac < 1 && $ld->backSector === null) {            return false;   // stop        }        $this->intercepts[] = [$frac, $ld, null];        return true;    }    private function addThingIntercepts(Mobj $thing): bool    {        $positive = ($this->trace[2] > 0) === ($this->trace[3] > 0);        $r = $thing->radius;        if ($positive) {            $x1 = $thing->x - $r;            $y1 = $thing->y + $r;            $x2 = $thing->x + $r;            $y2 = $thing->y - $r;        } else {            $x1 = $thing->x - $r;            $y1 = $thing->y - $r;            $x2 = $thing->x + $r;            $y2 = $thing->y + $r;        }        $s1 = self::pointOnDivlineSide($x1, $y1, $this->trace);        $s2 = self::pointOnDivlineSide($x2, $y2, $this->trace);        if ($s1 === $s2) {            return true;        }        $frac = self::interceptVector($this->trace, [$x1, $y1, $x2 - $x1, $y2 - $y1]);        if ($frac < 0) {            return true;        }        $this->intercepts[] = [$frac, null, $thing];        return true;    }    // =================================================================== movement and collisions (p_map.c)    /** P_TeleportMove: kills anything in the way (players only). */    public function teleportMove(Mobj $thing, float $x, float $y): bool    {        $this->tmThing = $thing;        $this->tmFlags = $thing->flags;        $this->tmX = $x;        $this->tmY = $y;        $r = $thing->radius;        $this->tmBox = [$y + $r, $y - $r, $x - $r, $x + $r];        $ss = $this->map->pointInSubsector($x, $y);        $this->ceilingLine = null;        $this->tmFloorZ = $this->tmDropoffZ = $ss->sector->floorHeight;        $this->tmCeilingZ = $ss->sector->ceilingHeight;        $this->validCount++;        $this->specHit = [];        [$xl, $yl] = $this->blockOf($this->tmBox[2] - self::MAXRADIUS, $this->tmBox[1] - self::MAXRADIUS);        [$xh, $yh] = $this->blockOf($this->tmBox[3] + self::MAXRADIUS, $this->tmBox[0] + self::MAXRADIUS);        for ($bx = $xl; $bx <= $xh; $bx++) {            for ($by = $yl; $by <= $yh; $by++) {                if (!$this->blockThingsIterator($bx, $by, fn (Mobj $th) => $this->stompThing($th))) {                    return false;                }            }        }        $this->unsetThingPosition($thing);        $thing->floorZ = $this->tmFloorZ;        $thing->ceilingZ = $this->tmCeilingZ;        $thing->x = $x;        $thing->y = $y;        $this->setThingPosition($thing);        return true;    }    private function stompThing(Mobj $thing): bool    {        if (!($thing->flags & Info::MF_SHOOTABLE)) {            return true;        }        $blockDist = $thing->radius + $this->tmThing->radius;        if (abs($thing->x - $this->tmX) >= $blockDist || abs($thing->y - $this->tmY) >= $blockDist) {            return true;        }        if ($thing === $this->tmThing) {            return true;        }        if ($this->tmThing->player === null) {            return false;   // monsters do not telefrag        }        $this->damageMobj($thing, $this->tmThing, $this->tmThing, 10000);        return true;    }    private function checkLine(Line $ld): bool    {        $box = $this->tmBox;        if ($box[3] <= $ld->bbox[2] || $box[2] >= $ld->bbox[3] || $box[0] <= $ld->bbox[1] || $box[1] >= $ld->bbox[0]) {            return true;        }        if (self::boxOnLineSide($box, $ld) !== -1) {            return true;        }        if ($ld->backSector === null) {            return false;   // one-sided: a wall        }        if (!($this->tmThing->flags & Info::MF_MISSILE)) {            if ($ld->flags & Line::ML_BLOCKING) {                return false;            }            if ($this->tmThing->player === null && ($ld->flags & Line::ML_BLOCKMONSTERS)) {                return false;            }        }        $this->lineOpening($ld);        if ($this->openTop < $this->tmCeilingZ) {            $this->tmCeilingZ = $this->openTop;            $this->ceilingLine = $ld;        }        if ($this->openBottom > $this->tmFloorZ) {            $this->tmFloorZ = $this->openBottom;        }        if ($this->lowFloor < $this->tmDropoffZ) {            $this->tmDropoffZ = $this->lowFloor;        }        if ($ld->special) {            $this->specHit[] = $ld;        }        return true;    }    private function checkThing(Mobj $thing): bool    {        if (!($thing->flags & (Info::MF_SOLID | Info::MF_SPECIAL | Info::MF_SHOOTABLE))) {            return true;        }        $tm = $this->tmThing;        $blockDist = $thing->radius + $tm->radius;        if (abs($thing->x - $this->tmX) >= $blockDist || abs($thing->y - $this->tmY) >= $blockDist) {            return true;        }        if ($thing === $tm) {            return true;        }        if ($tm->flags & Info::MF_SKULLFLY) {            $damage = ((Random::p() % 8) + 1) * $tm->info['damage'];            $this->damageMobj($thing, $tm, $tm, $damage);            $tm->flags &= ~Info::MF_SKULLFLY;            $tm->momX = $tm->momY = $tm->momZ = 0;            $this->setMobjState($tm, $tm->info['spawnstate']);            return false;        }        if ($tm->flags & Info::MF_MISSILE) {            if ($tm->z > $thing->z + $thing->height) {                return true;   // over it            }            if ($tm->z + $tm->height < $thing->z) {                return true;   // under it            }            $t = $tm->target;            if ($t !== null && ($t->type === $thing->type                || ($t->type === Info::MT_KNIGHT && $thing->type === Info::MT_BRUISER)                || ($t->type === Info::MT_BRUISER && $thing->type === Info::MT_KNIGHT))) {                if ($thing === $t) {                    return true;                }                if ($thing->type !== Info::MT_PLAYER) {                    return false;   // the same species: explode, no damage                }            }            if (!($thing->flags & Info::MF_SHOOTABLE)) {                return !($thing->flags & Info::MF_SOLID);            }            $damage = ((Random::p() % 8) + 1) * $tm->info['damage'];            $this->damageMobj($thing, $tm, $tm->target, $damage);            return false;        }        if ($thing->flags & Info::MF_SPECIAL) {            $solid = (bool) ($thing->flags & Info::MF_SOLID);            if ($this->tmFlags & Info::MF_PICKUP) {                $this->touchSpecialThing($thing, $tm);            }            return !$solid;        }        return !($thing->flags & Info::MF_SOLID);    }    /** P_CheckPosition: can the thing stand there? Fills tmFloorZ, tmCeilingZ, tmDropoffZ and the lines touched. */    public function checkPosition(Mobj $thing, float $x, float $y): bool    {        $this->tmThing = $thing;        $this->tmFlags = $thing->flags;        $this->tmX = $x;        $this->tmY = $y;        $r = $thing->radius;        $this->tmBox = [$y + $r, $y - $r, $x - $r, $x + $r];        $ss = $this->map->pointInSubsector($x, $y);        $this->ceilingLine = null;        $this->tmFloorZ = $this->tmDropoffZ = $ss->sector->floorHeight;        $this->tmCeilingZ = $ss->sector->ceilingHeight;        $this->validCount++;        $this->specHit = [];        if ($this->tmFlags & Info::MF_NOCLIP) {            return true;        }        [$xl, $yl] = $this->blockOf($this->tmBox[2] - self::MAXRADIUS, $this->tmBox[1] - self::MAXRADIUS);        [$xh, $yh] = $this->blockOf($this->tmBox[3] + self::MAXRADIUS, $this->tmBox[0] + self::MAXRADIUS);        $checkThing = fn (Mobj $th) => $this->checkThing($th);        for ($bx = $xl; $bx <= $xh; $bx++) {            for ($by = $yl; $by <= $yh; $by++) {                if (!$this->blockThingsIterator($bx, $by, $checkThing)) {                    return false;                }            }        }        [$xl, $yl] = $this->blockOf($this->tmBox[2], $this->tmBox[1]);        [$xh, $yh] = $this->blockOf($this->tmBox[3], $this->tmBox[0]);        $checkLine = fn (Line $ld) => $this->checkLine($ld);        for ($bx = $xl; $bx <= $xh; $bx++) {            for ($by = $yl; $by <= $yh; $by++) {                if (!$this->blockLinesIterator($bx, $by, $checkLine)) {                    return false;                }            }        }        return true;    }    /** P_TryMove: moves the thing if it fits, and crosses the special lines it passed. */    public function tryMove(Mobj $thing, float $x, float $y): bool    {        $this->floatOk = false;        if (!$this->checkPosition($thing, $x, $y)) {            return false;        }        if (!($thing->flags & Info::MF_NOCLIP)) {            if ($this->tmCeilingZ - $this->tmFloorZ < $thing->height) {                return false;   // does not fit            }            $this->floatOk = true;            if (!($thing->flags & Info::MF_TELEPORT) && $this->tmCeilingZ - $thing->z < $thing->height) {                return false;   // must lower itself to fit            }            if (!($thing->flags & Info::MF_TELEPORT) && $this->tmFloorZ - $thing->z > 24) {                return false;   // too big a step up            }            if (!($thing->flags & (Info::MF_DROPOFF | Info::MF_FLOAT)) && $this->tmFloorZ - $this->tmDropoffZ > 24) {                return false;   // do not stand over a drop off            }        }        $this->unsetThingPosition($thing);        $oldX = $thing->x;        $oldY = $thing->y;        $thing->floorZ = $this->tmFloorZ;        $thing->ceilingZ = $this->tmCeilingZ;        $thing->x = $x;        $thing->y = $y;        $this->setThingPosition($thing);        if (!($thing->flags & (Info::MF_TELEPORT | Info::MF_NOCLIP))) {            $hits = $this->specHit;            for ($i = count($hits) - 1; $i >= 0; $i--) {                $ld = $hits[$i];                $side = self::pointOnLineSide($thing->x, $thing->y, $ld);                $oldSide = self::pointOnLineSide($oldX, $oldY, $ld);                if ($side !== $oldSide && $ld->special) {                    $this->crossSpecialLine($ld, $oldSide, $thing);                }            }        }        return true;    }    /** P_ThingHeightClip: false when it does not fit any more (crushed). */    private function thingHeightClip(Mobj $thing): bool    {        $onFloor = $thing->z == $thing->floorZ;        $this->checkPosition($thing, $thing->x, $thing->y);        $thing->floorZ = $this->tmFloorZ;        $thing->ceilingZ = $this->tmCeilingZ;        if ($onFloor) {            $thing->z = $thing->floorZ;        } elseif ($thing->z + $thing->height > $thing->ceilingZ) {            $thing->z = $thing->ceilingZ - $thing->height;        }        return $thing->ceilingZ - $thing->floorZ >= $thing->height;    }    /** P_SlideMove: the player slides along the wall he hit. */    private function slideMove(Mobj $mo): void    {        $this->slideMo = $mo;        for ($hitCount = 1; $hitCount < 3; $hitCount++) {            if ($mo->momX > 0) {                $leadX = $mo->x + $mo->radius;                $trailX = $mo->x - $mo->radius;            } else {                $leadX = $mo->x - $mo->radius;                $trailX = $mo->x + $mo->radius;            }            if ($mo->momY > 0) {                $leadY = $mo->y + $mo->radius;                $trailY = $mo->y - $mo->radius;            } else {                $leadY = $mo->y - $mo->radius;                $trailY = $mo->y + $mo->radius;            }            $this->bestSlideFrac = 1.0001;            $this->bestSlideLine = null;            $trav = fn (array $in) => $this->slideTraverse($in);            $this->pathTraverse($leadX, $leadY, $leadX + $mo->momX, $leadY + $mo->momY, self::PT_ADDLINES, $trav);            $this->pathTraverse($trailX, $leadY, $trailX + $mo->momX, $leadY + $mo->momY, self::PT_ADDLINES, $trav);            $this->pathTraverse($leadX, $trailY, $leadX + $mo->momX, $trailY + $mo->momY, self::PT_ADDLINES, $trav);            $line = $this->slideLine();            $best = $this->slideFrac();            if ($best > 1 || $line === null) {                break;   // the move must have hit the middle: stairstep            }            $best -= 1 / 32;            if ($best > 0) {                if (!$this->tryMove($mo, $mo->x + $mo->momX * $best, $mo->y + $mo->momY * $best)) {                    break;                }            }            // the rest of the move, along the wall            $frac = min(1.0, 1 - ($best + 1 / 32));            if ($frac <= 0) {                return;            }            $this->tmXMove = $mo->momX * $frac;            $this->tmYMove = $mo->momY * $frac;            $this->hitSlideLine($line);            $mo->momX = $this->tmXMove;            $mo->momY = $this->tmYMove;            if ($this->tryMove($mo, $mo->x + $this->tmXMove, $mo->y + $this->tmYMove)) {                return;            }        }        if (!$this->tryMove($mo, $mo->x, $mo->y + $mo->momY)) {            $this->tryMove($mo, $mo->x + $mo->momX, $mo->y);        }    }    /** @param array{0:float,1:?Line,2:?Mobj} $in */    private function slideTraverse(array $in): bool    {        $li = $in[1];        $mo = $this->slideMo;        $blocking = false;        if (!($li->flags & Line::ML_TWOSIDED)) {            if (self::pointOnLineSide($mo->x, $mo->y, $li)) {                return true;   // do not hit the back side            }            $blocking = true;        } else {            $this->lineOpening($li);            if ($this->openRange < $mo->height || $this->openTop - $mo->z < $mo->height || $this->openBottom - $mo->z > 24) {                $blocking = true;            }        }        if (!$blocking) {            return true;        }        if ($in[0] < $this->bestSlideFrac) {            $this->bestSlideFrac = $in[0];            $this->bestSlideLine = $li;        }        return false;    }    /** P_HitSlideLine: keeps the part of the move along the line. */    private function hitSlideLine(Line $ld): void    {        if ($ld->slopeType === Line::ST_HORIZONTAL) {            $this->tmYMove = 0;            return;        }        if ($ld->slopeType === Line::ST_VERTICAL) {            $this->tmXMove = 0;            return;        }        $side = self::pointOnLineSide($this->slideMo->x, $this->slideMo->y, $ld);        $lineAngle = atan2($ld->dy, $ld->dx);        if ($side === 1) {            $lineAngle += M_PI;        }        $moveAngle = atan2($this->tmYMove, $this->tmXMove);        $delta = self::normAngle($moveAngle - $lineAngle);        if ($delta > M_PI) {            $delta += M_PI;        }        $moveLen = self::approxDistance($this->tmXMove, $this->tmYMove);        $newLen = $moveLen * cos($delta);        $this->tmXMove = $newLen * cos($lineAngle);        $this->tmYMove = $newLen * sin($lineAngle);    }    /** P_AimLineAttack: the slope to hit the first shootable thing in that direction (lineTarget), or 0. */    public function aimLineAttack(Mobj $t1, float $angle, float $distance): float    {        $x2 = $t1->x + $distance * cos($angle);        $y2 = $t1->y + $distance * sin($angle);        $this->shootThing = $t1;        $this->shootZ = $t1->z + $t1->height / 2 + 8;        $this->topSlope = 100 / 160;        $this->bottomSlope = -100 / 160;        $this->attackRange = $distance;        $this->lineTarget = null;        $this->pathTraverse($t1->x, $t1->y, $x2, $y2, self::PT_ADDLINES | self::PT_ADDTHINGS, fn (array $in) => $this->aimTraverse($in));        return $this->aimed() !== null ? $this->aimSlope : 0.0;    }    /** @param array{0:float,1:?Line,2:?Mobj} $in */    private function aimTraverse(array $in): bool    {        [$frac, $li, $th] = $in;        if ($li !== null) {            if (!($li->flags & Line::ML_TWOSIDED)) {                return false;            }            $this->lineOpening($li);            if ($this->openBottom >= $this->openTop) {                return false;            }            $dist = $this->attackRange * $frac;            if ($dist <= 0) {                return true;            }            if ($li->frontSector->floorHeight != $li->backSector->floorHeight) {                $slope = ($this->openBottom - $this->shootZ) / $dist;                if ($slope > $this->bottomSlope) {                    $this->bottomSlope = $slope;                }            }            if ($li->frontSector->ceilingHeight != $li->backSector->ceilingHeight) {                $slope = ($this->openTop - $this->shootZ) / $dist;                if ($slope < $this->topSlope) {                    $this->topSlope = $slope;                }            }            return $this->topSlope > $this->bottomSlope;        }        if ($th === $this->shootThing || !($th->flags & Info::MF_SHOOTABLE)) {            return true;        }        $dist = $this->attackRange * $frac;        if ($dist <= 0) {            return true;        }        $thingTop = ($th->z + $th->height - $this->shootZ) / $dist;        if ($thingTop < $this->bottomSlope) {            return true;   // shot over the thing        }        $thingBottom = ($th->z - $this->shootZ) / $dist;        if ($thingBottom > $this->topSlope) {            return true;   // shot under the thing        }        $thingTop = min($thingTop, $this->topSlope);        $thingBottom = max($thingBottom, $this->bottomSlope);        $this->aimSlope = ($thingTop + $thingBottom) / 2;        $this->lineTarget = $th;        return false;    }    /** P_LineAttack: a bullet (or a fist) along that line; puffs on walls, blood on things. */    public function lineAttack(Mobj $t1, float $angle, float $distance, float $slope, int $damage): void    {        $x2 = $t1->x + $distance * cos($angle);        $y2 = $t1->y + $distance * sin($angle);        $this->shootThing = $t1;        $this->laDamage = $damage;        $this->shootZ = $t1->z + $t1->height / 2 + 8;        $this->attackRange = $distance;        $this->aimSlope = $slope;        $this->pathTraverse($t1->x, $t1->y, $x2, $y2, self::PT_ADDLINES | self::PT_ADDTHINGS, fn (array $in) => $this->shootTraverse($in));    }    /** @param array{0:float,1:?Line,2:?Mobj} $in */    private function shootTraverse(array $in): bool    {        [$frac, $li, $th] = $in;        if ($li !== null) {            if ($li->special) {                $this->shootSpecialLine($this->shootThing, $li);            }            $hit = !($li->flags & Line::ML_TWOSIDED);            if (!$hit) {                $this->lineOpening($li);                $dist = $this->attackRange * $frac;                if ($dist > 0 && $li->frontSector->floorHeight != $li->backSector->floorHeight                    && ($this->openBottom - $this->shootZ) / $dist > $this->aimSlope) {                    $hit = true;                }                if (!$hit && $dist > 0 && $li->frontSector->ceilingHeight != $li->backSector->ceilingHeight                    && ($this->openTop - $this->shootZ) / $dist < $this->aimSlope) {                    $hit = true;                }                if (!$hit) {                    return true;   // the shot continues                }            }            // a puff a little before the wall            $frac -= 4 / $this->attackRange;            $x = $this->trace[0] + $this->trace[2] * $frac;            $y = $this->trace[1] + $this->trace[3] * $frac;            $z = $this->shootZ + $this->aimSlope * ($frac * $this->attackRange);            if ($li->frontSector->ceilingPic === $this->gfx->skyFlat) {                if ($z > $li->frontSector->ceilingHeight) {                    return false;   // into the sky                }                if ($li->backSector !== null && $li->backSector->ceilingPic === $this->gfx->skyFlat) {                    return false;                }            }            $this->spawnPuff($x, $y, $z);            return false;        }        if ($th === $this->shootThing || !($th->flags & Info::MF_SHOOTABLE)) {            return true;        }        $dist = $this->attackRange * $frac;        if ($dist <= 0) {            return true;        }        if (($th->z + $th->height - $this->shootZ) / $dist < $this->aimSlope) {            return true;        }        if (($th->z - $this->shootZ) / $dist > $this->aimSlope) {            return true;        }        $frac -= 10 / $this->attackRange;        $x = $this->trace[0] + $this->trace[2] * $frac;        $y = $this->trace[1] + $this->trace[3] * $frac;        $z = $this->shootZ + $this->aimSlope * ($frac * $this->attackRange);        if ($th->flags & Info::MF_NOBLOOD) {            $this->spawnPuff($x, $y, $z);        } else {            $this->spawnBlood($x, $y, $z, $this->laDamage);        }        if ($this->laDamage) {            $this->damageMobj($th, $this->shootThing, $this->shootThing, $this->laDamage);        }        return false;    }    /** P_UseLines: the use key, on the first line in front of the player. */    public function useLines(Player $player): void    {        $mo = $player->mo;        $x2 = $mo->x + self::USERANGE * cos($mo->angle);        $y2 = $mo->y + self::USERANGE * sin($mo->angle);        $this->pathTraverse($mo->x, $mo->y, $x2, $y2, self::PT_ADDLINES, function (array $in) use ($mo): bool {            $line = $in[1];            if (!$line->special) {                $this->lineOpening($line);                if ($this->openRange <= 0) {                    $this->startSound($mo, $this->sfx('noway'));                    return false;   // cannot use through a wall                }                return true;   // not a special line, but keep checking            }            $side = self::pointOnLineSide($mo->x, $mo->y, $line) === 1 ? 1 : 0;            $this->useSpecialLine($mo, $line, $side);            return false;   // only one line        });    }    /** P_RadiusAttack: an explosion hurts what it sees around it. */    public function radiusAttack(Mobj $spot, ?Mobj $source, int $damage): void    {        $dist = $damage + self::MAXRADIUS;        [$xl, $yl] = $this->blockOf($spot->x - $dist, $spot->y - $dist);        [$xh, $yh] = $this->blockOf($spot->x + $dist, $spot->y + $dist);        $this->bombSpot = $spot;        $this->bombSource = $source;        $this->bombDamage = $damage;        for ($y = $yl; $y <= $yh; $y++) {            for ($x = $xl; $x <= $xh; $x++) {                $this->blockThingsIterator($x, $y, fn (Mobj $th) => $this->radiusAttackThing($th));            }        }    }    private function radiusAttackThing(Mobj $thing): bool    {        if (!($thing->flags & Info::MF_SHOOTABLE)) {            return true;        }        if ($thing->type === Info::MT_CYBORG || $thing->type === Info::MT_SPIDER) {            return true;   // the bosses do not mind        }        $dx = abs($thing->x - $this->bombSpot->x);        $dy = abs($thing->y - $this->bombSpot->y);        $dist = (int) (max($dx, $dy) - $thing->radius);        if ($dist < 0) {            $dist = 0;        }        if ($dist >= $this->bombDamage) {            return true;        }        if ($this->checkSight($thing, $this->bombSpot)) {            $this->damageMobj($thing, $this->bombSpot, $this->bombSource, $this->bombDamage - $dist);        }        return true;    }    /** P_ChangeSector: after a floor or ceiling moved; true when something does not fit (crushed). */    public function changeSector(Sector $sector, bool $crunch): bool    {        $this->noFit = false;        $this->crushChange = $crunch;        [$xl, $yl] = $this->blockOf($sector->bbox[2] - self::MAXRADIUS, $sector->bbox[1] - self::MAXRADIUS);        [$xh, $yh] = $this->blockOf($sector->bbox[3] + self::MAXRADIUS, $sector->bbox[0] + self::MAXRADIUS);        for ($x = $xl; $x <= $xh; $x++) {            for ($y = $yl; $y <= $yh; $y++) {                $this->blockThingsIterator($x, $y, fn (Mobj $th) => $this->changeSectorThing($th));            }        }        return $this->noFit;    }    private function changeSectorThing(Mobj $thing): bool    {        if ($this->thingHeightClip($thing)) {            return true;        }        if ($thing->health <= 0) {            // crush the bodies into gibs            $this->setMobjState($thing, Info::S_GIBS);            $thing->flags &= ~Info::MF_SOLID;            $thing->height = 0;            $thing->radius = 0;            return true;        }        if ($thing->flags & Info::MF_DROPPED) {            $this->removeMobj($thing);            return true;        }        if (!($thing->flags & Info::MF_SHOOTABLE)) {            return true;        }        $this->noFit = true;        if ($this->crushChange && !($this->levelTime & 3)) {            $this->damageMobj($thing, null, null, 10);            $mo = $this->spawnMobj($thing->x, $thing->y, $thing->z + $thing->height / 2, Info::MT_BLOOD);            $mo->momX = (Random::p() - Random::p()) / 16;            $mo->momY = (Random::p() - Random::p()) / 16;        }        return true;    }    // =================================================================== line of sight (p_sight.c)    /** P_CheckSight: can t1 see t2? */    public function checkSight(Mobj $t1, Mobj $t2): bool    {        $map = $this->map;        $s1 = $t1->subsector->sector->id;        $s2 = $t2->subsector->sector->id;        $pnum = $s1 * count($map->sectors) + $s2;        $byte = $pnum >> 3;        if ($byte < strlen($map->reject) && (ord($map->reject[$byte]) & (1 << ($pnum & 7)))) {            return false;   // the REJECT table says no        }        $this->validCount++;        $this->sightZStart = $t1->z + $t1->height - $t1->height / 4;        $this->topSlope = $t2->z + $t2->height - $this->sightZStart;        $this->bottomSlope = $t2->z - $this->sightZStart;        $this->sTrace = [$t1->x, $t1->y, $t2->x - $t1->x, $t2->y - $t1->y];        $this->t2x = $t2->x;        $this->t2y = $t2->y;        if ($map->nodes === []) {            return $this->crossSubsector(0);        }        return $this->crossBspNode(count($map->nodes) - 1);    }    /** P_DivlineSide: 0 front, 1 back, 2 on the line. @param array{0:float,1:float,2:float,3:float} $n */    private static function divlineSide(float $x, float $y, array $n): int    {        if ($n[2] == 0) {            if ($x == $n[0]) {                return 2;            }            return $x <= $n[0] ? ($n[3] > 0 ? 1 : 0) : ($n[3] < 0 ? 1 : 0);        }        if ($n[3] == 0) {            if ($y == $n[1]) {                return 2;            }            return $y <= $n[1] ? ($n[2] < 0 ? 1 : 0) : ($n[2] > 0 ? 1 : 0);        }        $left = $n[3] * ($x - $n[0]);        $right = ($y - $n[1]) * $n[2];        if ($right < $left) {            return 0;        }        return $left == $right ? 2 : 1;    }    private function crossBspNode(int $num): bool    {        if ($num & 0x8000) {            return $this->crossSubsector($num === -1 ? 0 : $num & 0x7FFF);        }        $node = $this->map->nodes[$num];        $dl = [$node->x, $node->y, $node->dx, $node->dy];        $side = self::divlineSide($this->sTrace[0], $this->sTrace[1], $dl);        if ($side === 2) {            $side = 0;        }        if (!$this->crossBspNode($node->children[$side])) {            return false;        }        if ($side === self::divlineSide($this->t2x, $this->t2y, $dl)) {            return true;   // the line does not touch the other side        }        return $this->crossBspNode($node->children[$side ^ 1]);    }    private function crossSubsector(int $num): bool    {        $map = $this->map;        $sub = $map->subsectors[$num];        $end = $sub->firstLine + $sub->numLines;        for ($i = $sub->firstLine; $i < $end; $i++) {            $seg = $map->segs[$i];            $line = $seg->line;            if ($line->validCount === $this->validCount) {                continue;            }            $line->validCount = $this->validCount;            $v1 = $line->v1;            $v2 = $line->v2;            $s1 = self::divlineSide($v1->x, $v1->y, $this->sTrace);            $s2 = self::divlineSide($v2->x, $v2->y, $this->sTrace);            if ($s1 === $s2) {                continue;   // not crossed            }            $divl = [$v1->x, $v1->y, $v2->x - $v1->x, $v2->y - $v1->y];            $s1 = self::divlineSide($this->sTrace[0], $this->sTrace[1], $divl);            $s2 = self::divlineSide($this->t2x, $this->t2y, $divl);            if ($s1 === $s2) {                continue;            }            if (!($line->flags & Line::ML_TWOSIDED) || $seg->backSector === null) {                return false;   // a wall            }            $front = $seg->frontSector;            $back = $seg->backSector;            if ($front->floorHeight == $back->floorHeight && $front->ceilingHeight == $back->ceilingHeight) {                continue;   // no wall to block the view            }            $openTop = min($front->ceilingHeight, $back->ceilingHeight);            $openBottom = max($front->floorHeight, $back->floorHeight);            if ($openBottom >= $openTop) {                return false;   // a closed door            }            $frac = self::interceptVector($this->sTrace, $divl);            if ($frac <= 0) {                continue;            }            if ($front->floorHeight != $back->floorHeight) {                $slope = ($openBottom - $this->sightZStart) / $frac;                if ($slope > $this->bottomSlope) {                    $this->bottomSlope = $slope;                }            }            if ($front->ceilingHeight != $back->ceilingHeight) {                $slope = ($openTop - $this->sightZStart) / $frac;                if ($slope < $this->topSlope) {                    $this->topSlope = $slope;                }            }            if ($this->topSlope <= $this->bottomSlope) {                return false;            }        }        return true;    }}