JA
games/rob-revisited / tests / RevisitedAudioTest.php · commit f9a1307
<?phpnamespace Tests;use App\Revisited\Audio\MemoryMixer;use App\Revisited\Audio\Soundscape;use App\Revisited\Land\Creature;use App\Revisited\Land\Game;use App\Revisited\Land\ZoneFactory;use JumPHP\Audio\Audio3d;use PHPUnit\Framework\TestCase;/** The sound of "Experience - Rob revisited" (src/Revisited/Audio): what plays, decided from the game state alone. */final class RevisitedAudioTest extends TestCase{    private const DT = 1 / 60;    private const SFX = __DIR__ . '/../assets/revisited/sfx/';    private Game $game;    private MemoryMixer $mixer;    private Soundscape $sound;    protected function setUp(): void    {        $this->game = Game::newGame(7);        $this->game->creatures = [];        $this->game->npcs = [];        $this->game->weather = ['kind' => 'clear', 'amount' => 0.0];        $this->at(13.0);        $this->mixer = new MemoryMixer();        $this->sound = new Soundscape(null, $this->mixer, 3);    }    public function testRunningGivesMoreFootstepsPerSecondThanWalkingAndCrouchingGivesSoftOnes(): void    {        $walk = $this->stepsPerSecond(Game::WALK, false, false);        $run = $this->stepsPerSecond(Game::RUN, true, false);        $sneak = $this->stepsPerSecond(Game::SNEAK, false, true);        self::assertEqualsWithDelta(Game::WALK / Soundscape::STRIDE_WALK, $walk, 0.3);        self::assertGreaterThan($walk + 0.2, $run);        self::assertLessThan($walk, $sneak);        self::assertGreaterThan(0, $this->mixer->count('stepsoft_'), 'crouching: soft steps');    }    public function testStandingStillMakesNoFootstep(): void    {        $this->play(5.0);        self::assertSame(0, $this->mixer->count('step'));    }    public function testTheFootstepSoundIsTheGroundUnderRob(): void    {        $cases = ['valley' => ['jungle' => 'leaves', 'grass' => 'grass', 'mud' => 'mud', 'sand' => 'sand'], 'plateau' => ['snow' => 'snow'],            'canyon' => ['redrock' => 'rock'], 'caves1' => ['cave' => 'cave']];        foreach ($cases as $zoneId => $biomes) {            $this->game->zone = ZoneFactory::make($zoneId, 7);            foreach ($biomes as $biome => $family) {                $spot = $this->find(fn (float $x, float $z): bool => $this->game->zone->biomeAt($x, $z) === $biome                    && ($this->game->zone->water <= -999 || $this->game->zone->waterDepth($x, $z) < -0.3));                self::assertNotNull($spot, "$zoneId has $biome");                [$this->game->x, $this->game->z] = $spot;                self::assertSame($family, $this->sound->groundOf($this->game), "$zoneId $biome");                $from = count($this->mixer->played);                $this->walk(Game::WALK, 3.0);                $steps = array_filter($this->mixer->names($from), fn (string $n): bool => str_starts_with($n, 'step_'));                self::assertNotEmpty($steps);                foreach ($steps as $n) {                    self::assertMatchesRegularExpression("/^step_{$family}_[1-4]$/", $n);                }            }        }        $this->game->zone = ZoneFactory::make('valley', 7);        $wade = $this->find(fn (float $x, float $z): bool => ($d = $this->game->zone->waterDepth($x, $z)) > 0.1 && $d < 0.6);        self::assertNotNull($wade, 'the valley has a shallow shore');        [$this->game->x, $this->game->z] = $wade;        self::assertSame('water', $this->sound->groundOf($this->game));    }    public function testHowlsAreHeardFarAwayOnlyAtNightAndOutdoors(): void    {        $this->play(240.0);        self::assertSame(0, $this->mixer->count('howl'), 'no howl by day');        $this->at(23.0);        $from = count($this->mixer->played);        $this->play(240.0);        $howls = array_values(array_filter(array_slice($this->mixer->played, $from), fn (array $p): bool => str_starts_with($p['name'], 'howl_far_')));        self::assertGreaterThanOrEqual(3, count($howls), 'far howls at night');        foreach ($howls as $h) {            self::assertNotNull($h['pos'], 'a howl comes from somewhere');            self::assertGreaterThan(25.0, hypot($h['pos'][0] - $this->game->x, $h['pos'][2] - $this->game->z), 'and from far');        }        $this->game->zone = ZoneFactory::make('caves1', 7);        $from = count($this->mixer->played);        $this->play(240.0);        self::assertSame(0, $this->mixer->count('howl', $from), 'no howl in the caves');    }    public function testHowlsComeMoreOftenWhenAStalkerIsNear(): void    {        $this->at(23.0);        $this->play(600.0);        $alone = $this->mixer->count('howl');        $this->game->creatures = [new Creature(1, 'stalker', $this->game->x + 60, $this->game->y, $this->game->z, state: 'wander')];        $from = count($this->mixer->played);        $this->play(600.0);        self::assertGreaterThan($alone, $this->mixer->count('howl', $from));    }    public function testAHuntingStalkerBringsTheDroneTheStingerTheHeartbeatAndTheDangerMusic(): void    {        $this->at(23.0);        $this->play(6.0);        self::assertSame(0.0, $this->mixer->loopGain('bed_drone'));        self::assertSame('music_night', $this->mixer->music);        $this->game->creatures = [new Creature(1, 'stalker', $this->game->x + 8, $this->game->y, $this->game->z, state: 'stalk')];        $from = count($this->mixer->played);        $this->play(0.2);        $this->game->creatures[0]->state = 'hunt';        $this->play(4.0);        self::assertGreaterThan(0.6, $this->sound->danger);        self::assertGreaterThan(0.3, $this->mixer->loopGain('bed_drone'));        $names = $this->mixer->names($from);        self::assertContains('stalker_snarl', $names, 'it snarls when it starts hunting');        self::assertSame(1, $this->mixer->count('stinger', $from));        self::assertGreaterThanOrEqual(3, $this->mixer->count('heartbeat', $from));        self::assertSame('music_danger', $this->mixer->music);        $snarl = array_values(array_filter($this->mixer->played, fn (array $p): bool => $p['name'] === 'stalker_snarl'))[0];        self::assertEqualsWithDelta($this->game->x + 8, $snarl['pos'][0], 0.01, 'heard where the stalker is');        // it goes away: the drone fades out        $this->game->creatures = [];        $this->play(8.0);        self::assertSame(0.0, $this->mixer->loopGain('bed_drone'));    }    public function testEachZoneAndTimeHasItsAmbience(): void    {        $this->play(4.0);        self::assertGreaterThan(0.3, $this->mixer->loopGain('bed_jungle_day'));        self::assertSame(0.0, $this->mixer->loopGain('bed_jungle_night'));        $this->at(23.0);        $this->play(4.0);        self::assertGreaterThan(0.3, $this->mixer->loopGain('bed_jungle_night'));        self::assertSame(0.0, $this->mixer->loopGain('bed_jungle_day'));        $this->game->weather = ['kind' => 'storm', 'amount' => 1.0];        $this->play(40.0);        self::assertGreaterThan(0.5, $this->mixer->loopGain('bed_rain'));        self::assertGreaterThan(0, $this->mixer->count('thunder'));        $this->game->zone = ZoneFactory::make('plateau', 7);        $this->game->weather = ['kind' => 'clear', 'amount' => 0.0];        $from = count($this->mixer->played);        $this->play(6.0);        self::assertContains('zone', $this->mixer->names($from), 'a new zone: a chime');        self::assertGreaterThan(0.4, $this->mixer->loopGain('bed_wind_plateau'));        self::assertSame(0.0, $this->mixer->loopGain('bed_jungle_night'));        $this->game->zone = ZoneFactory::make('caves1', 7);        $this->play(6.0);        self::assertGreaterThan(0.5, $this->mixer->loopGain('bed_cave'));        self::assertSame('music_cave', $this->mixer->music);    }    public function testTheStateChangesMakeTheirSounds(): void    {        $this->play(1.0);        $from = count($this->mixer->played);        $this->game->hurt = 1.0;        $this->game->inv->add('stick', 2);        $this->game->fires[] = ['x' => $this->game->x + 2, 'z' => $this->game->z, 'minutes' => 60.0];        $this->game->say('Un message de test.');        $this->play(0.5);        $names = $this->mixer->names($from);        self::assertTrue((bool) array_filter($names, fn (string $n): bool => str_starts_with($n, 'pain_')), 'hurt: pain');        self::assertContains('pickup', $names);        self::assertContains('fire_light', $names);        self::assertContains('ui_message', $names);        self::assertSame(1, $this->mixer->count('fire_loop', $from), 'the fire crackles where it is');        self::assertSame(1, $this->mixer->count('pickup', $from), 'once');        $this->sound->event('craft');        $this->sound->event('craft');        self::assertSame(1, $this->mixer->count('craft', $from), 'an event twice in a row plays once');    }    public function testAJumpAndAHeavyLandingAreHeard(): void    {        $this->play(0.5);        $ground = $this->game->y;        $this->game->vy = 7.0;        $this->game->y = $ground + 0.2;        $this->play(self::DT);        self::assertSame(1, $this->mixer->count('jump'));        $this->game->y = $ground + 4.0;        $this->game->vy = -13.0;        $this->play(self::DT);        $this->game->y = $ground;        $this->game->vy = 0.0;        $this->play(self::DT);        self::assertSame(1, $this->mixer->count('land_hard'));    }    public function testEverySoundItCanPlayIsAMonoPcmWav(): void    {        $names = ['bed_jungle_day', 'bed_jungle_night', 'bed_wind_plateau', 'bed_wind_canyon', 'bed_cave', 'bed_rain', 'bed_water', 'bed_drone',            'bed_village', 'fire_loop', 'swarm_loop', 'heartbeat', 'breath_1', 'breath_2', 'swim_1', 'swim_2', 'swim_3', 'creature_death',            'stalker_growl', 'stalker_snarl', 'grazer_1', 'grazer_2', 'grazer_alarm', 'crawler_click', 'crawler_hiss', 'burrower_rumble',            'burrower_burst', 'brute_roar', 'rodeur_shout_1', 'rodeur_shout_2', 'rodeur_attack', 'haldi_1', 'haldi_2', 'haldi_3',            'howl_1', 'howl_2', 'howl_3', 'call_day_1', 'call_day_2', 'call_night_1', 'call_night_2', 'drip_1', 'drip_2', 'drip_3',            'pebbles', 'ice_creak', 'bird_1', 'bird_2', 'bird_3', 'thunder_near', 'thunder_far'];        foreach (Soundscape::EVENTS as $files) {            array_push($names, ...$files);        }        foreach (array_unique(Soundscape::GROUNDS) as $g) {            for ($v = 1; $v <= 4; $v++) {                $names[] = "step_{$g}_$v";                $names[] = "stepsoft_{$g}_$v";            }        }        foreach (array_unique($names) as $n) {            $file = self::SFX . $n . '.wav';            self::assertFileExists($file);            $pcm = Audio3d::monoPcm((string) file_get_contents($file));            self::assertNotNull($pcm, $n);            self::assertSame(22050, $pcm[0], $n);        }        foreach (['music_day', 'music_night', 'music_cave', 'music_danger'] as $m) {            self::assertFileExists(__DIR__ . "/../assets/revisited/music/$m.ogg");        }    }    // ------------------------------------------------------------------------------------------ helpers    /** The clock at this hour of day 1. */    public function testAWaterfallRoarsWhereItFallsAndFallsSilentFarAway(): void    {        self::assertFileExists(self::SFX . 'waterfall_loop.wav');        $fall = null;        foreach ($this->game->zone->things as $t) {            if ($t->kind === 'waterfall') {                $fall = $t;            }        }        self::assertNotNull($fall);        $this->game->x = $fall->x;        $this->game->z = $fall->z + 25;        $this->play(2.0);        self::assertGreaterThan(0.0, $this->mixer->loopGain('waterfall_loop'), 'near the fall: its roar, placed at the pool');        $this->game->x = $fall->x + 200;        $this->game->z = $fall->z + 200;        $this->play(2.0);        self::assertSame(0.0, $this->mixer->loopGain('waterfall_loop'), 'far away: silent');    }    private function at(float $hour): void    {        $this->game->minutes = ($hour - Game::START_HOUR) * 60 + ($hour < Game::START_HOUR ? 1440 : 0);    }    private function play(float $seconds): void    {        for ($t = 0.0; $t < $seconds - 1e-9; $t += self::DT) {            $this->sound->update($this->game, self::DT);        }    }    /** Rob walks back and forth (5 m) at this speed. */    private function walk(float $speed, float $seconds, bool $running = false, bool $crouching = false): void    {        $g = $this->game;        [$g->running, $g->crouching, $g->moving] = [$running, $crouching, true];        $x0 = $g->x;        for ($t = 0.0; $t < $seconds; $t += self::DT) {            $phase = fmod($t * $speed, 10.0);            $g->x = $x0 + ($phase < 5 ? $phase : 10 - $phase);            $g->y = $g->zone->heightAt($g->x, $g->z);            $this->sound->update($g, self::DT);        }        $g->x = $x0;        [$g->running, $g->crouching, $g->moving] = [false, false, false];        $this->sound->update($g, self::DT);    }    private function stepsPerSecond(float $speed, bool $running, bool $crouching): float    {        $this->game->zone = ZoneFactory::make('canyon', 7);        $spot = $this->find(fn (float $x, float $z): bool => $this->game->zone->biomeAt($x, $z) === 'redrock');        [$this->game->x, $this->game->z] = $spot ?? [256.0, 256.0];        $this->play(0.2);        $from = count($this->mixer->played);        $this->walk($speed, 10.0, $running, $crouching);        return $this->mixer->count('step', $from) / 10.0;    }    /** @return array{0: float, 1: float}|null a point of the zone (not in a wall) where $test holds */    private function find(callable $test): ?array    {        $z = $this->game->zone;        for ($i = 20; $i < $z->size - 20; $i += 7) {            for ($j = 20; $j < $z->size - 20; $j += 7) {                if (!$z->solidAt($i, $j) && $test((float) $i, (float) $j)) {                    return [(float) $i, (float) $j];                }            }        }        return null;    }}