EN
games/rob-revisited / tests / RevisitedCollisionTest.php · commit f9a1307
<?phpnamespace Tests;use App\Revisited\Land\Creature;use App\Revisited\Land\Game;use App\Revisited\Land\Intent;use App\Revisited\Land\Solids;use App\Revisited\Land\Thing;use App\Revisited\Land\Wildlife;use App\Revisited\Land\Zone;use App\Revisited\Land\ZoneFactory;use App\Revisited\Sim\Body;use App\Revisited\Sim\Crafting;use PHPUnit\Framework\TestCase;/** * "Experience - Rob revisited": nothing walks through the solid things (Land\Solids: rocks, trunks, huts, the shuttle, * wrecks...) nor the walls, Rob included; climbing with stakes; putting things down and choosing what the action is about. */final class RevisitedCollisionTest extends TestCase{    private const SEED = 7;    private static function inZone(string $zone): Game    {        if ($zone === 'valley') {            return Game::newGame(self::SEED);        }        $g = Game::fromArray(['seed' => self::SEED, 'zone' => $zone, 'inv' => Game::newGame(self::SEED)->inv->toArray()]);        $g->x = $g->zone->exits[0]['x'] + 6;        $g->z = $g->zone->exits[0]['z'];        $g->y = $g->zone->heightAt($g->x, $g->z);        return $g;    }    /** Open ground with a big boulder put in the middle of it (Rob 8 m south of it). @return array{0: Game, 1: Thing} */    private static function withBoulder(): array    {        $g = self::openGround(12.0);        $g->npcs = [];        $b = $g->addThing('boulder', $g->x, $g->z, [], 0.0, 1.2);        $g->z -= 8;        $g->y = $g->zone->heightAt($g->x, $g->z);        return [$g, $b];    }    /** How deep a body of radius $r is inside a solid thing (0: outside). */    private static function depth(Zone $z, float $x, float $zz, float $r): float    {        $worst = 0.0;        foreach ($z->thingsNear($x, $zz, 20) as $t) {            foreach (Solids::circles($t) as [$cx, $cz, $cr]) {                $worst = max($worst, $cr + $r - hypot($x - $cx, $zz - $cz));            }        }        return $worst;    }    public function testEveryBigSolidKindHasAShapeSizedByItsScale(): void    {        $t = new Thing(1, 'boulder', 10.0, 0.0, 10.0, 0.0, 1.4);        self::assertEqualsWithDelta(1.75 * 1.4, Solids::circles($t)[0][2], 0.001);        $s = new Thing(2, 'shuttle', 100.0, 0.0, 100.0, M_PI / 2, 1.0);        $xs = array_map(static fn (array $c): float => $c[0], Solids::circles($s));        self::assertGreaterThan(20.0, max($xs) - min($xs), 'the shuttle lies along its yaw: a row of circles 25 m long');        self::assertSame([], Solids::circles(new Thing(3, 'bush_berry', 0, 0, 0)), 'bushes are walked through');        foreach (['rock', 'boulder', 'basalt', 'tree_broad', 'giant_tree', 'hut', 'stilt_hut', 'shuttle', 'wreck_colony', 'wreck_pod', 'crate', 'boat_wreck', 'mangrove'] as $kind) {            self::assertTrue(Solids::solid($kind), $kind);        }    }    public function testAnAnimalWalkingIntoABoulderSlidesAlongItAndGoesAround(): void    {        [$g, $b] = self::withBoulder();        $r = Solids::circles($b)[0][2];        $c = Wildlife::make($g, 'grazer', $b->x - $r - 4, $b->z + 0.2);        $g->creatures = [$c];        $tx = $b->x + $r + 4;        $tz = $b->z;        $deepest = 0.0;        for ($k = 0; $k < 600 && hypot($c->x - $tx, $c->z - $tz) > 0.5; $k++) {            Wildlife::moveTo($g, $c, $tx, $tz, 1.6, 1 / 30);            $deepest = max($deepest, self::depth($g->zone, $c->x, $c->z, Solids::body('grazer')));        }        self::assertLessThan(0.02, $deepest, 'never inside the boulder');        self::assertLessThan(0.6, hypot($c->x - $tx, $c->z - $tz), "round the boulder to the other side ($k frames)");    }    public function testAHunterStillReachesRobBehindABoulder(): void    {        [$g, $b] = self::withBoulder();        $g->creatures = [];        $r = Solids::circles($b)[0][2];        $g->x = $b->x + $r + 1.0;        $g->z = $b->z;        $g->y = $g->zone->heightAt($g->x, $g->z);        $g->minutes = 16 * 60;      // 23:00, night: the stalkers hunt        $c = Wildlife::make($g, 'stalker', $b->x - $r - 3, $b->z);        $c->state = 'hunt';        $g->creatures = [$c];        $body = $g->body->toArray();        $closest = 99.0;        for ($k = 0; $k < 30 * 20; $k++) {            $g->update(1 / 30, new Intent());            $g->body = Body::fromArray($body);            $closest = min($closest, hypot($c->x - $g->x, $c->z - $g->z));            self::assertLessThan(0.02, self::depth($g->zone, $c->x, $c->z, Solids::body('stalker')), "frame $k: inside the boulder");        }        self::assertLessThan(2.0, $closest, 'the hunter went round the boulder to Rob');    }    public function testRobStopsAtABoulderAndSlidesAlongIt(): void    {        [$g, $b] = self::withBoulder();        $r = Solids::circles($b)[0][2];        $g->x = $b->x - $r - 3;        $g->z = $b->z + 0.4;        $g->y = $g->zone->heightAt($g->x, $g->z);        $g->yaw = M_PI / 2;      // facing +x: the boulder        $in = new Intent();        $in->forward = 1.0;        $deepest = 0.0;        for ($k = 0; $k < 120; $k++) {            $g->update(1 / 30, $in);            $deepest = max($deepest, self::depth($g->zone, $g->x, $g->z, Solids::ROB));        }        self::assertLessThan(0.02, $deepest, 'Rob never walks into the boulder');        self::assertGreaterThan($b->z + 0.4, $g->z, 'he slid along its side (the step\'s other axis)');        // a solid thing put on him (an old save, a test placing him): he is pushed out at once        $g->x = $b->x + 0.3;        $g->z = $b->z;        $g->update(1 / 30, new Intent());        self::assertLessThan(0.02, self::depth($g->zone, $g->x, $g->z, Solids::ROB));    }    /** @return iterable<string, array{0: string}> */    public static function zones(): iterable    {        foreach (ZoneFactory::IDS as $id) {            yield $id => [$id];        }    }    /**     * Minutes of the zone's life (animals spawned, wandering, hunting; people going about), Rob walking around: nobody     * ends inside a rock, a trunk, a hut or a wall. Also measures the cost of the AI.     * @dataProvider zones     */    #[\PHPUnit\Framework\Attributes\DataProvider('zones')]    public function testNothingEndsInsideASolidThingAfterMinutesOfLife(string $zone): void    {        $g = self::inZone($zone);        $body = $g->body->toArray();        $in = new Intent();        $in->forward = 1.0;        $seen = 0;        $time = 0.0;        $frames = 0;        for ($s = 0; $s < 150; $s++) {            $in->turn = sin($s * 0.7) * 0.6;            for ($f = 0; $f < 20; $f++) {                $t0 = hrtime(true);                $g->update(1 / 20, $in);                $time += (hrtime(true) - $t0) / 1e6;                $frames++;            }            $g->body = Body::fromArray($body);       // Rob lives on (the animals keep hunting)            foreach ($g->creatures as $c) {                if (in_array($c->species, ['bird', 'swarm'], true) || $c->state === 'buried') {                    continue;                }                $seen++;                self::assertLessThan(0.05, self::depth($g->zone, $c->x, $c->z, Solids::body($c->species)), "$zone, {$s}s: a {$c->species} inside a solid thing");                self::assertFalse($g->zone->solidAt($c->x, $c->z), "$zone, {$s}s: a {$c->species} in a wall");            }            foreach ($g->npcs as $n) {                self::assertLessThan(0.05, self::depth($g->zone, $n->x, $n->z, Solids::PERSON), "$zone, {$s}s: {$n->name} inside a solid thing");            }            self::assertLessThan(0.05, self::depth($g->zone, $g->x, $g->z, Solids::ROB), "$zone, {$s}s: Rob inside a solid thing");        }        self::assertGreaterThan(0, $seen + count($g->npcs), "$zone has life");        fwrite(STDERR, sprintf("%-8s update %.2f ms/frame (%d creatures, %d people)\n", $zone, $time / $frames, count($g->creatures), count($g->npcs)));        self::assertLessThan(8.0, $time / $frames, 'the whole update stays cheap');    }    // ------------------------------------------------------------------------------------------ climbing    /** Rob at the foot of the mesa of the lookout's cache, looking at it. @return array{0: Game, 1: Thing} */    private static function atTheMesa(): array    {        $g = self::inZone('canyon');        $g->creatures = [];        $g->npcs = [];        $cache = null;        foreach ($g->zone->things as $t) {            if (!empty($t->data['climb'])) {                $cache = $t;            }        }        self::assertNotNull($cache, 'the lookout\'s cache is on the mesa');        foreach (range(0, 31) as $k) {            $a = $k * M_PI / 16;            for ($d = 9.0; $d < 30; $d += 0.5) {                $x = $cache->x + sin($a) * $d;                $z = $cache->z + cos($a) * $d;                if (!$g->zone->solidAt($x, $z) && Solids::free($g->zone, $x, $z, 0.5) && $g->zone->waterDepth($x, $z) < 0.1                    && $cache->y - $g->zone->heightAt($x, $z) > 8) {                    $g->x = $x;                    $g->z = $z;                    $g->y = $g->zone->heightAt($x, $z);                    $g->yaw = atan2($cache->x - $x, $cache->z - $z);                    return [$g, $cache];                }            }        }        self::fail('no foot of the mesa');    }    private static function walkTo(Game $g, Thing $t, float $seconds): void    {        $body = $g->body->toArray();        $in = new Intent();        $in->forward = 1.0;        for ($k = 0; $k < $seconds * 30; $k++) {            $g->yaw = atan2($t->x - $g->x, $t->z - $g->z);            $g->update(1 / 30, $in);            if ($k % 30 === 0) {                $keep = $g->body->toArray();                $g->body = Body::fromArray(['fatigue' => max(30.0, (float) ($keep['fatigue'] ?? 90))] + $body);            }            if (hypot($t->x - $g->x, $t->z - $g->z) < 2.0) {                return;            }        }    }    public function testClimbingStakesAreCraftedFromSticksWithTheKnife(): void    {        $ids = array_column(Crafting::recipes(), 'id');        self::assertContains('climbing_stakes', $ids);        self::assertContains('ice_pick', $ids);        $g = Game::newGame(self::SEED);        $g->inv->add('knife_flint');        $g->inv->add('stick', 3);        $g->inv->add('fiber', 2);        $g->craft('climbing_stakes');        self::assertTrue($g->inv->has('climbing_stakes'));        self::assertSame('climbing_stakes', $g->climbTool());    }    public function testWithoutStakesTheMesaWallStopsRobAndWithThemHeClimbsItAndTheyWear(): void    {        [$g, $cache] = self::atTheMesa();        $g->inv->remove('climbing_stakes', $g->inv->count('climbing_stakes'));        $foot = $g->y;        self::walkTo($g, $cache, 20);        self::assertGreaterThan(4.0, $cache->y - $g->y, 'without stakes Rob stays at the foot of the wall');        self::assertFalse($g->climbing);        [$g, $cache] = self::atTheMesa();        $g->inv->add('climbing_stakes');        self::walkTo($g, $cache, 90);        self::assertLessThan(2.5, hypot($cache->x - $g->x, $cache->z - $g->z), 'with stakes Rob climbs to the cache');        self::assertGreaterThan($foot + 8, $g->y, 'up on the mesa');        self::assertLessThan(100.0, $g->inv->condition('climbing_stakes'), 'the stakes wear');        self::assertTrue((bool) ($g->flags['climb_told'] ?? false), 'the first climb says how it works');        $names = array_column($g->takeEvents(), 0);        self::assertContains('climb', $names, 'it sounds');        self::assertSame('search', $g->actions()[0]['id'] ?? null, 'the cache can be searched up there');    }    public function testWornOutStakesBreak(): void    {        [$g, $cache] = self::atTheMesa();        $g->inv->add('climbing_stakes');        $g->inv->cond['climbing_stakes'] = 4.0;        self::walkTo($g, $cache, 40);        self::assertFalse($g->inv->has('climbing_stakes'), 'they break after a couple of metres');    }    public function testACaveWallIsNeverClimbed(): void    {        $g = self::inZone('caves1');        $g->inv->add('ice_pick');        foreach ([[0, 0], [20, 30], [100, 100]] as [$dx, $dz]) {            self::assertFalse($g->climbableAt($g->x + $dx, $g->z + $dz));        }    }    // ------------------------------------------------------------------------------------------ putting things down    /** Rob on open grass, nothing within reach. */    private static function openGround(float $empty = 9.0): Game    {        $g = Game::newGame(self::SEED);        $g->creatures = [];        $z = $g->zone;        for ($k = 0; $k < 4000; $k++) {            $x = 40 + ($k * 37) % 420;            $zz = 40 + intdiv($k * 37, 420) * 9 % 420;            if ($z->biomeAt($x, $zz) === 'grass' && $z->thingsNear($x, $zz, $empty) === []                && abs($z->heightAt($x + $empty, $zz) - $z->heightAt($x - $empty, $zz)) < 1.5 && abs($z->heightAt($x, $zz + $empty) - $z->heightAt($x, $zz - $empty)) < 1.5 && !$z->solidAt($x, $zz) && $z->waterDepth($x, $zz) < -0.5) {                $g->x = $x;                $g->z = $zz;                $g->y = $z->heightAt($x, $zz);                $g->pitch = 0.0;                return $g;            }        }        self::fail('no open grass');    }    public function testPuttingSomethingDownTakesItOutOfTheBagAndLaysItAheadOfRob(): void    {        $g = self::openGround();        $g->inv->add('spear');        $g->inv->hand = 'spear';        $g->inv->add('stick', 4);        self::assertSame(1, $g->dropBag('spear'));        self::assertFalse($g->inv->has('spear'), 'gone from the bag');        self::assertNull($g->inv->hand, 'out of the hand');        self::assertSame(2, $g->dropBag('stick', 2));        self::assertSame(2, $g->inv->count('stick'));        $bundles = array_values(array_filter($g->zone->thingsNear($g->x, $g->z, 4), static fn (Thing $t): bool => !empty($t->data['bundle'])));        self::assertCount(1, $bundles, 'one bundle');        self::assertSame(['spear' => 1, 'stick' => 2], $bundles[0]->data['loot']);        $d = hypot($bundles[0]->x - $g->x, $bundles[0]->z - $g->z);        self::assertEqualsWithDelta(Game::DROP_AHEAD, $d, 0.2, 'a step in front of Rob, not under his feet');        $ahead = ($bundles[0]->x - $g->x) * sin($g->yaw) + ($bundles[0]->z - $g->z) * cos($g->yaw);        self::assertGreaterThan(1.0, $ahead);        self::assertSame(0, $g->dropBag('spear'), 'nothing left to put down');    }    public function testABundleIsNeverPutInsideARock(): void    {        [$g, $b] = self::withBoulder();        $r = Solids::circles($b)[0][2];        $g->x = $b->x - $r - 0.4;        $g->z = $b->z;        $g->yaw = M_PI / 2;      // the boulder right ahead        $g->inv->add('stick', 2);        $g->dropBag('stick');        foreach ($g->zone->thingsNear($g->x, $g->z, 8) as $t) {            if (!empty($t->data['bundle'])) {                self::assertGreaterThan($r, hypot($t->x - $b->x, $t->z - $b->z), 'beside the boulder, not in it');                return;            }        }        self::fail('no bundle');    }    public function testTheActionPrefersWhatWasOnTheSpotToWhatRobJustPutDown(): void    {        $g = self::openGround();        $g->inv->add('stick', 3);        $before = $g->actions()[0]['id'];        $g->dropBag('stick');        self::assertNotSame('search', $g->actions()[0]['id'], 'not "pick it up again" at once');        self::assertSame($before, $g->actions()[0]['id'], 'what the spot offered before');        self::assertContains('search', array_column($g->actions(), 'id'), 'still in the list');        // looking down at it: now it is the one        $bundle = $g->thingAhead();        self::assertNotNull($bundle);        $flat = hypot($bundle->x - $g->x, $bundle->z - $g->z);        $g->pitch = -atan2($g->eyeY() - $bundle->y - 0.2, $flat);        self::assertTrue($g->lookingAt($bundle));        self::assertSame('search', $g->actions()[0]['id']);        $g->act('search');        self::assertSame(3, $g->inv->count('stick'), 'picked up again');    }    public function testSeveralThingsWithinReachTheOneInTheCrosshairFirstAndGCyclesThem(): void    {        $g = self::openGround();        $a = $g->addThing('stick', $g->x + 0.6, $g->z + 1.0);        $b = $g->addThing('flint', $g->x - 0.6, $g->z + 1.0);        $g->yaw = atan2($a->x - $g->x, $a->z - $g->z);        $g->pitch = -0.6;        self::assertSame($a, $g->thingAhead(), 'the one under the crosshair');        $g->yaw = atan2($b->x - $g->x, $b->z - $g->z);        self::assertSame($b, $g->thingAhead());        $g->yaw = 0.0;      // between them        self::assertCount(2, $g->thingsAhead());        $first = $g->thingAhead();        $second = $g->cycleFocus();        self::assertNotSame($first, $second, 'G: the other one');        self::assertSame($first, $g->cycleFocus(), 'and back');    }}