<?php/* * dmmotor — the sound effects of the WAD (DMX lumps DS<name>: 8-bit PCM) turned into WAV for JumPHP's * SoundManager, and played by distance like S_StartSound / S_AdjustSoundParams of s_sound.c (linuxdoom-1.10). * Copyright (C) 1993-1996 by id Software, Inc.; PHP port for dmmotor. GPL v2 (see LICENSE). */namespace App\Dm;use JumPHP\Audio\SoundManager;final class Sounds{ private const CLIPPING_DIST = 1200.0; private const CLOSE_DIST = 200.0; /** @var array<string,bool> loaded sound names */ private array $loaded = []; public function __construct(private Wad $wad, private SoundManager $sm) { } /** DMX sound lump => WAV bytes (volume 0..1). */ public static function toWav(string $lump, float $volume = 1.0): ?string { if (strlen($lump) < 8) { return null; } $h = unpack('vformat/vrate/Vcount', $lump); if ($h['format'] !== 3) { return null; } $count = min($h['count'], strlen($lump) - 8); $data = substr($lump, 8, $count); // DMX pads 16 samples at both ends if ($count > 32) { $data = substr($data, 16, $count - 32); } if ($volume < 1.0) { $out = ''; $n = strlen($data); for ($i = 0; $i < $n; $i++) { $out .= chr((int) (128 + (ord($data[$i]) - 128) * $volume)); } $data = $out; } $rate = $h['rate'] ?: 11025; $len = strlen($data); return 'RIFF' . pack('V', 36 + $len) . 'WAVE' . 'fmt ' . pack('VvvVVvv', 16, 1, 1, $rate, $rate, 1, 8) . 'data' . pack('V', $len) . $data; } private function ensure(string $name, int $level): ?string { $key = "dm_{$name}_{$level}"; if (isset($this->loaded[$key])) { return $this->loaded[$key] ? $key : null; } $this->loaded[$key] = false; $lump = 'DS' . strtoupper($name); if (!$this->wad->has($lump)) { return null; } $wav = self::toWav($this->wad->lump($lump), [1 => 1.0, 2 => 0.6, 3 => 0.3][$level]); if ($wav === null) { return null; } try { $this->sm->synth($key, $wav); } catch (\Throwable) { return null; } $this->loaded[$key] = true; return $key; } /** Plays a sound from (x, y) heard at (lx, ly); null position = full volume. */ public function play(int $sfx, ?float $x = null, ?float $y = null, float $lx = 0, float $ly = 0): void { $name = Info::SOUNDS[$sfx] ?? ''; if ($name === '' || $name === 'none') { return; } $level = 1; if ($x !== null) { $dx = abs($x - $lx); $dy = abs($y - $ly); $dist = $dx + $dy - min($dx, $dy) / 2; if ($dist > self::CLIPPING_DIST) { return; } $level = $dist < self::CLOSE_DIST ? 1 : ($dist < 700 ? 2 : 3); } $key = $this->ensure($name, $level); if ($key !== null) { $this->sm->playSfx($key); } } /** One sound per name and level is enough: a menu click. */ public function menu(string $name): void { $key = $this->ensure($name, 1); if ($key !== null) { $this->sm->playSfx($key); } }}