diff --git a/README.md b/README.md index 7d6e95b..d500bb8 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,11 @@ royale, aliens, language design). This repo holds no lore. `mech_paint.gdshader`, `PomDecalPool` combat scars, tactical radar, clickable Aetheria Hardpoint & Heat schematic, and Imperial Broadcast chyron. - Sion terrain and building data attribution: `"Federal Office of Topography swisstopo"`. + - Hybrid 3D combat audio (`ArenaAudioSystem` + `ProceduralAudioBank` + `WalkerFootstepTracker`): + curated weapon/mechanical WAVs by **Haven Kendrick** (`assets/audio/haven/`, + see [`assets/audio/ATTRIBUTION.md`](assets/audio/ATTRIBUTION.md)) paired with + deterministic `PcmSynth` GRF-synced footsteps, vehicle/servo loops, impacts, + and 2D UI cues behind a separable `WetMixMode` room stage. ## Build, test, and run @@ -59,7 +64,3 @@ godot --path client # Run the headless Godot smoke test godot --headless --path client res://tests/Smoke.tscn ``` - -## Planned, not live yet - -- Multiplayer networking and audio synthesis. diff --git a/assets/audio/ATTRIBUTION.md b/assets/audio/ATTRIBUTION.md new file mode 100644 index 0000000..743690b --- /dev/null +++ b/assets/audio/ATTRIBUTION.md @@ -0,0 +1,47 @@ +# Audio Attribution & Migration Notes + +## Curated Weapon & Mechanical Sound Effects (`assets/audio/haven/`) + +- **Author / Source:** **Haven Kendrick** (Cult member) — *MWO Soundpack* (original weapon and mechanical sound effects, used with explicit permission). +- **Modifications applied by `tools/audio/curate_haven_audio.py`:** + - Converted to mono `44,100 Hz` `16-bit` signed PCM WAV (`RIFF/WAVE`). + - Trimmed leading silence / sliced sustained loops into crisp single-shot and burst windows with smooth cosine fade-outs (`30-50 ms`). + - Peak-normalized to `0.89` (`-1.0 dBFS`). +- **Explicitly excluded:** All third-party/stock-named files in the source folder (`SW01_*`, `MW4 - *`, `Utilities-*`, `desktop.ini`) were excluded and never copied. + +### Curated Clip Manifest (25 files) + +| Destination (`assets/audio/haven/`) | Source File | Role | +|---|---|---| +| `mg_shot_01.wav` | `ClanMG3_fixed.wav` | 7.62 MG shot variant A (`0.24 s`) | +| `mg_shot_02.wav` | `New_MG 2.wav` | 7.62 MG shot variant B (`0.24 s`) | +| `mg_tail.wav` | `mgtail.wav` | MG mechanical receiver tail (`0.66 s`) | +| `ac_light_01.wav` | `AC5.wav` | Light autocannon variant A (`0.85 s`) | +| `ac_light_02.wav` | `AC5_2.wav` | Light autocannon variant B (`0.80 s`) | +| `ac_med_01.wav` | `AC10.wav` | Medium autocannon (`0.95 s`) | +| `ac_rotary.wav` | `RAC5.wav` | Rotary autocannon (`1.01 s`) | +| `flak_blast_01.wav` | `ClanLBX7_2019.wav` | Flak scattergun variant A (`1.15 s`) | +| `flak_blast_02.wav` | `IS_LBX20_2.wav` | Flak scattergun variant B (`1.35 s`) | +| `cannon_heavy_01.wav` | `BigCannon1.wav` | 105mm Recoilless / heavy cannon A (`1.80 s`) | +| `cannon_heavy_02.wav` | `AC20.wav` | 105mm Recoilless / heavy cannon B (`1.50 s`) | +| `pd_bark_01.wav` | `AMS3.wav` | Point-defense flak bark A (`0.28 s`) | +| `pd_bark_02.wav` | `amsTP.wav` | Point-defense flak bark B (`0.28 s`) | +| `pd_laser.wav` | `laserams.wav` | Imperial Aegis PD pulse (`0.32 s`) | +| `rocket_salvo_01.wav` | `MRM1.wav` | Rocket/missile salvo A (`1.20 s`) | +| `rocket_salvo_02.wav` | `NEWSRM1.wav` | Rocket/missile salvo B (`1.35 s`) | +| `plasma_ppc_01.wav` | `Snub_PPC2.wav` | Touring Plasma Repeater A (`1.25 s`) | +| `plasma_ppc_02.wav` | `PPcSWEET.wav` | Touring Plasma Repeater B (`0.78 s`) | +| `lance_beam_01.wav` | `CPPC_DEC2018_2.wav` | Gilded Thermal Lance (`1.55 s`) | +| `laser_heavy_01.wav` | `CLL3.wav` | Heavy laser (reserved for Cut 7) (`1.20 s`) | +| `gauss_rail_01.wav` | `Gauss Sweet 1.wav` | Gauss rifle (reserved for Cut 7) (`1.15 s`) | +| `mech_reload_bolt.wav` | `CannonReload2.wav` | Heavy chassis swap bolt-clank (`1.25 s`) | +| `mech_quick_bolt.wav` | `reload.wav` | Module equip latch (`0.94 s`) | +| `mech_eject.wav` | `eject.wav` | Ruin / casing ejection clatter (`0.74 s`) | +| `mech_turret_servo.wav` | `turret9.wav` | Turret traverse mechanical accent (`1.10 s`) | + +## Procedural Synth & `WetMixMode` Dry-Mode Migration Plan + +`RustToDust.Core.Audio.PcmSynth` synthesizes all non-weapon audio cues (GRF-synced mech footsteps, engine/rotor/servo loops, metallic ricochets, armor/core impacts, explosions, and 2D UI feedback) as **pure dry mono 44.1 kHz PCM buffers first**, then passes them through a cleanly separable `WetMixMode` post-stage: + +- **`WetMixMode = true` (current default):** Applies early reflections (`11-43 ms` taps), a short diffused room tail, and gentle `tanh` soft-clipping so procedural footsteps, impacts, and loops sit cohesively alongside Haven's pre-reverbed weapon recordings. +- **`WetMixMode = false` (future acoustic raycast DSP):** Bypasses the baked room stage and returns the dry PCM buffers untouched so an audio raytracer / convolution reverb bus can compute per-ray canyon and city-corridor reflections dynamically without double-reverberating procedural sources. diff --git a/assets/audio/haven/ac_light_01.wav b/assets/audio/haven/ac_light_01.wav new file mode 100644 index 0000000..624741d Binary files /dev/null and b/assets/audio/haven/ac_light_01.wav differ diff --git a/assets/audio/haven/ac_light_02.wav b/assets/audio/haven/ac_light_02.wav new file mode 100644 index 0000000..cd97a3d Binary files /dev/null and b/assets/audio/haven/ac_light_02.wav differ diff --git a/assets/audio/haven/ac_med_01.wav b/assets/audio/haven/ac_med_01.wav new file mode 100644 index 0000000..acad76f Binary files /dev/null and b/assets/audio/haven/ac_med_01.wav differ diff --git a/assets/audio/haven/ac_rotary.wav b/assets/audio/haven/ac_rotary.wav new file mode 100644 index 0000000..2aa4e24 Binary files /dev/null and b/assets/audio/haven/ac_rotary.wav differ diff --git a/assets/audio/haven/cannon_heavy_01.wav b/assets/audio/haven/cannon_heavy_01.wav new file mode 100644 index 0000000..cfed3ab Binary files /dev/null and b/assets/audio/haven/cannon_heavy_01.wav differ diff --git a/assets/audio/haven/cannon_heavy_02.wav b/assets/audio/haven/cannon_heavy_02.wav new file mode 100644 index 0000000..6c6c037 Binary files /dev/null and b/assets/audio/haven/cannon_heavy_02.wav differ diff --git a/assets/audio/haven/flak_blast_01.wav b/assets/audio/haven/flak_blast_01.wav new file mode 100644 index 0000000..73e2d3c Binary files /dev/null and b/assets/audio/haven/flak_blast_01.wav differ diff --git a/assets/audio/haven/flak_blast_02.wav b/assets/audio/haven/flak_blast_02.wav new file mode 100644 index 0000000..d13fefa Binary files /dev/null and b/assets/audio/haven/flak_blast_02.wav differ diff --git a/assets/audio/haven/gauss_rail_01.wav b/assets/audio/haven/gauss_rail_01.wav new file mode 100644 index 0000000..8d96ebb Binary files /dev/null and b/assets/audio/haven/gauss_rail_01.wav differ diff --git a/assets/audio/haven/lance_beam_01.wav b/assets/audio/haven/lance_beam_01.wav new file mode 100644 index 0000000..8f0c1cf Binary files /dev/null and b/assets/audio/haven/lance_beam_01.wav differ diff --git a/assets/audio/haven/laser_heavy_01.wav b/assets/audio/haven/laser_heavy_01.wav new file mode 100644 index 0000000..a9f5b0b Binary files /dev/null and b/assets/audio/haven/laser_heavy_01.wav differ diff --git a/assets/audio/haven/mech_eject.wav b/assets/audio/haven/mech_eject.wav new file mode 100644 index 0000000..95dd814 Binary files /dev/null and b/assets/audio/haven/mech_eject.wav differ diff --git a/assets/audio/haven/mech_quick_bolt.wav b/assets/audio/haven/mech_quick_bolt.wav new file mode 100644 index 0000000..a378c62 Binary files /dev/null and b/assets/audio/haven/mech_quick_bolt.wav differ diff --git a/assets/audio/haven/mech_reload_bolt.wav b/assets/audio/haven/mech_reload_bolt.wav new file mode 100644 index 0000000..3a7f1a0 Binary files /dev/null and b/assets/audio/haven/mech_reload_bolt.wav differ diff --git a/assets/audio/haven/mech_turret_servo.wav b/assets/audio/haven/mech_turret_servo.wav new file mode 100644 index 0000000..41e8598 Binary files /dev/null and b/assets/audio/haven/mech_turret_servo.wav differ diff --git a/assets/audio/haven/mg_shot_01.wav b/assets/audio/haven/mg_shot_01.wav new file mode 100644 index 0000000..433fe7b Binary files /dev/null and b/assets/audio/haven/mg_shot_01.wav differ diff --git a/assets/audio/haven/mg_shot_02.wav b/assets/audio/haven/mg_shot_02.wav new file mode 100644 index 0000000..73f02f3 Binary files /dev/null and b/assets/audio/haven/mg_shot_02.wav differ diff --git a/assets/audio/haven/mg_tail.wav b/assets/audio/haven/mg_tail.wav new file mode 100644 index 0000000..466e743 Binary files /dev/null and b/assets/audio/haven/mg_tail.wav differ diff --git a/assets/audio/haven/pd_bark_01.wav b/assets/audio/haven/pd_bark_01.wav new file mode 100644 index 0000000..2ab8bff Binary files /dev/null and b/assets/audio/haven/pd_bark_01.wav differ diff --git a/assets/audio/haven/pd_bark_02.wav b/assets/audio/haven/pd_bark_02.wav new file mode 100644 index 0000000..6f3b7ff Binary files /dev/null and b/assets/audio/haven/pd_bark_02.wav differ diff --git a/assets/audio/haven/pd_laser.wav b/assets/audio/haven/pd_laser.wav new file mode 100644 index 0000000..cabd5d0 Binary files /dev/null and b/assets/audio/haven/pd_laser.wav differ diff --git a/assets/audio/haven/plasma_ppc_01.wav b/assets/audio/haven/plasma_ppc_01.wav new file mode 100644 index 0000000..6cafe19 Binary files /dev/null and b/assets/audio/haven/plasma_ppc_01.wav differ diff --git a/assets/audio/haven/plasma_ppc_02.wav b/assets/audio/haven/plasma_ppc_02.wav new file mode 100644 index 0000000..61e366e Binary files /dev/null and b/assets/audio/haven/plasma_ppc_02.wav differ diff --git a/assets/audio/haven/rocket_salvo_01.wav b/assets/audio/haven/rocket_salvo_01.wav new file mode 100644 index 0000000..c31620c Binary files /dev/null and b/assets/audio/haven/rocket_salvo_01.wav differ diff --git a/assets/audio/haven/rocket_salvo_02.wav b/assets/audio/haven/rocket_salvo_02.wav new file mode 100644 index 0000000..35265b0 Binary files /dev/null and b/assets/audio/haven/rocket_salvo_02.wav differ diff --git a/client/ArenaAudioSystem.cs b/client/ArenaAudioSystem.cs new file mode 100644 index 0000000..b009b36 --- /dev/null +++ b/client/ArenaAudioSystem.cs @@ -0,0 +1,1081 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Owns the fixed 24 pool (5 continuous vehicle/servo +/// loops + 19 priority-stealing one-shots) and 4 2D UI +/// voices on a dynamically registered SFX bus with . +/// 100% crash-free under --headless / Dummy audio driver. +/// +public partial class ArenaAudioSystem : Node3D +{ + public const int LoopVoiceCount = 5; + public const int OneShotVoiceCount = 19; + public const int Total3DVoiceCount = LoopVoiceCount + OneShotVoiceCount; // 24 + public const int UiVoiceCount = 4; + + public const float MaxAudioDistance = 260f; + public const float MaxLoopDistance = 160f; + public const float LoopHysteresisMeters = 12f; + public const float ShotDedupeWindowSec = 0.035f; + public const float ImpactDedupeWindowSec = 0.045f; + public const float OverheatAlarmPeriodSec = 0.90f; + + public const int PriorityLocalAction = 10; + public const int PriorityLocalImpactOrKill = 8; + public const int PriorityNearCombat = 5; + public const int PriorityDistantCombat = 1; + + private struct LoopSlot + { + public AudioStreamPlayer3D Player; + public bool Active; + public bool IsContender; + public int EntityId; + public string ClipKey; + public float DistSq; + public float VolumeDb; + public float PitchScale; + } + + private struct OneShotSlot + { + public AudioStreamPlayer3D Player; + public bool Active; + public int Priority; + public long AssignedSeq; + public float RemainingSec; + public float DurationSec; + public string ClipKey; + public bool IsLocalSource; + public int SourceEntityId; + public float LastPitch; + public float LastVolumeDb; + } + + private struct UiSlot + { + public AudioStreamPlayer Player; + public bool Active; + public float RemainingSec; + public long AssignedSeq; + public string ClipKey; + } + + private readonly struct LoopCandidate + { + public readonly bool IsContender; + public readonly int EntityId; + public readonly string ClipKey; + public readonly Vector3 Position; + public readonly float DistSq; + public readonly float VolumeDb; + public readonly float PitchScale; + + public LoopCandidate( + bool isContender, + int entityId, + string clipKey, + Vector3 position, + float distSq, + float volumeDb, + float pitchScale) + { + IsContender = isContender; + EntityId = entityId; + ClipKey = clipKey; + Position = position; + DistSq = distSq; + VolumeDb = volumeDb; + PitchScale = pitchScale; + } + } + + private ProceduralAudioBank _bank = null!; + private readonly LoopSlot[] _loopSlots = new LoopSlot[LoopVoiceCount]; + private readonly OneShotSlot[] _oneShotSlots = new OneShotSlot[OneShotVoiceCount]; + private readonly UiSlot[] _uiSlots = new UiSlot[UiVoiceCount]; + + private readonly Dictionary<(bool IsSpectator, int ShooterId, string WeaponId), float> _shotDedupeExpiry = new(); + private readonly Dictionary<(byte TargetKind, int TargetId), float> _impactDedupeExpiry = new(); + private readonly Dictionary _lastContenderChassis = new(); + private readonly Dictionary _lastContenderLoadoutVer = new(); + private readonly List<(float X, float Z, float Expiry)> _recentExplosionPoints = new(16); + private readonly List _loopCandidates = new(32); + + private bool _initialized; + private bool _isDummyAudio; + private float _audioTime; + private float _overheatAlarmCooldown; + private long _voiceSeq = 1; + private uint _variantCounter; + private uint _rng = 0x9E3779B9u; + + public ProceduralAudioBank Bank => _bank; + public bool IsDummyAudio => _isDummyAudio; + public bool WetMixMode => _bank?.WetMixMode ?? true; + + public int Total3DPlaysRequested { get; private set; } + public int RejectedDistanceCount { get; private set; } + public int DedupedCount { get; private set; } + public int StolenVoiceCount { get; private set; } + public string LastAllocatedClipKey { get; private set; } = string.Empty; + public float LastAllocatedPitch { get; private set; } = 1f; + + public int ActiveLoopVoiceCount + { + get + { + int count = 0; + for (int i = 0; i < _loopSlots.Length; i++) + { + if (_loopSlots[i].Active) count++; + } + return count; + } + } + + public int ActiveOneShotVoiceCount + { + get + { + int count = 0; + for (int i = 0; i < _oneShotSlots.Length; i++) + { + if (_oneShotSlots[i].Active) count++; + } + return count; + } + } + + public int Active3DVoiceCount => ActiveLoopVoiceCount + ActiveOneShotVoiceCount; + + public int ActiveUiVoiceCount + { + get + { + int count = 0; + for (int i = 0; i < _uiSlots.Length; i++) + { + if (_uiSlots[i].Active) count++; + } + return count; + } + } + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + _isDummyAudio = DisplayServer.GetName().Equals("headless", StringComparison.OrdinalIgnoreCase) + || AudioServer.GetDriverName().Equals("Dummy", StringComparison.OrdinalIgnoreCase); + + EnsureSfxBusAndLimiter(); + _bank = new ProceduralAudioBank(wetMixMode: true); + + for (int i = 0; i < LoopVoiceCount; i++) + { + var p = Create3DPlayer($"AudioLoop3D_{i}"); + AddChild(p); + _loopSlots[i] = new LoopSlot { Player = p, ClipKey = string.Empty }; + } + + for (int i = 0; i < OneShotVoiceCount; i++) + { + var p = Create3DPlayer($"AudioOneShot3D_{i}"); + AddChild(p); + _oneShotSlots[i] = new OneShotSlot { Player = p, ClipKey = string.Empty }; + } + + for (int i = 0; i < UiVoiceCount; i++) + { + var p = new AudioStreamPlayer + { + Name = $"AudioUi2D_{i}", + Bus = "SFX" + }; + AddChild(p); + _uiSlots[i] = new UiSlot { Player = p, ClipKey = string.Empty }; + } + } + + private static AudioStreamPlayer3D Create3DPlayer(string name) => new() + { + Name = name, + Bus = "SFX", + UnitSize = 24f, + MaxDistance = MaxAudioDistance, + AttenuationModel = AudioStreamPlayer3D.AttenuationModelEnum.InverseDistance, + MaxDb = 3f + }; + + private static void EnsureSfxBusAndLimiter() + { + int busIdx = AudioServer.GetBusIndex("SFX"); + if (busIdx < 0) + { + busIdx = AudioServer.BusCount; + AudioServer.AddBus(busIdx); + AudioServer.SetBusName(busIdx, "SFX"); + AudioServer.SetBusSend(busIdx, "Master"); + } + + bool hasLimiter = false; + int effectCount = AudioServer.GetBusEffectCount(busIdx); + for (int i = 0; i < effectCount; i++) + { + if (AudioServer.GetBusEffect(busIdx, i) is AudioEffectHardLimiter) + { + hasLimiter = true; + break; + } + } + if (!hasLimiter) + { + AudioServer.AddBusEffect(busIdx, new AudioEffectHardLimiter + { + CeilingDb = -1.0f + }); + } + } + + public void ClearAll() + { + EnsureInitialized(); + for (int i = 0; i < _loopSlots.Length; i++) + { + if (!_isDummyAudio && _loopSlots[i].Player.Playing) + { + _loopSlots[i].Player.Stop(); + } + _loopSlots[i].Active = false; + _loopSlots[i].EntityId = -1; + _loopSlots[i].ClipKey = string.Empty; + } + for (int i = 0; i < _oneShotSlots.Length; i++) + { + if (!_isDummyAudio && _oneShotSlots[i].Player.Playing) + { + _oneShotSlots[i].Player.Stop(); + } + _oneShotSlots[i].Active = false; + _oneShotSlots[i].Priority = 0; + _oneShotSlots[i].RemainingSec = 0f; + _oneShotSlots[i].ClipKey = string.Empty; + _oneShotSlots[i].IsLocalSource = false; + _oneShotSlots[i].SourceEntityId = -1; + } + for (int i = 0; i < _uiSlots.Length; i++) + { + if (!_isDummyAudio && _uiSlots[i].Player.Playing) + { + _uiSlots[i].Player.Stop(); + } + _uiSlots[i].Active = false; + _uiSlots[i].RemainingSec = 0f; + _uiSlots[i].ClipKey = string.Empty; + } + + _shotDedupeExpiry.Clear(); + _impactDedupeExpiry.Clear(); + _lastContenderChassis.Clear(); + _lastContenderLoadoutVer.Clear(); + _recentExplosionPoints.Clear(); + _overheatAlarmCooldown = 0f; + } + + public void ResetStatsForTest() + { + Total3DPlaysRequested = 0; + RejectedDistanceCount = 0; + DedupedCount = 0; + StolenVoiceCount = 0; + LastAllocatedClipKey = string.Empty; + LastAllocatedPitch = 1f; + } + + public bool HasActiveVoiceForSource(bool isLocalSource, int sourceEntityId) + { + for (int i = 0; i < _oneShotSlots.Length; i++) + { + ref readonly var slot = ref _oneShotSlots[i]; + if (slot.Active && slot.IsLocalSource == isLocalSource && slot.SourceEntityId == sourceEntityId) + { + return true; + } + } + return false; + } + + public float? GetLastPitchForClipPrefix(string prefix) + { + for (int i = _oneShotSlots.Length - 1; i >= 0; i--) + { + if (_oneShotSlots[i].Active && _oneShotSlots[i].ClipKey.StartsWith(prefix, StringComparison.Ordinal)) + { + return _oneShotSlots[i].LastPitch; + } + } + return null; + } + + public void UpdateFrame( + IClientArenaSession session, + IReadOnlyList events, + IReadOnlyList footsteps, + Vector3 listenerPos, + float dt, + float alpha) + { + EnsureInitialized(); + + float stepDt = MathF.Max(0f, dt); + _audioTime += stepDt; + AdvanceVoices(stepDt); + + if (_overheatAlarmCooldown > 0f) + { + _overheatAlarmCooldown = MathF.Max(0f, _overheatAlarmCooldown - stepDt); + } + + var local = session.LocalContender; + int localId = session.LocalContenderId; + UpdateLoopSlots(session, listenerPos, alpha); + ConsumeSimEvents(session, events, listenerPos); + ConsumeFootsteps(footsteps, localId, listenerPos); + + if (local.Alive && local.MaxThermalRatio >= 0.85f && _overheatAlarmCooldown <= 0f) + { + PlayUi("ui_overheat_alarm", volumeDb: -4.5f, pitchScale: 1f); + _overheatAlarmCooldown = OverheatAlarmPeriodSec; + } + } + + public void ConsumeSimEvents( + IClientArenaSession session, + IReadOnlyList events, + Vector3 listenerPos) + { + EnsureInitialized(); + int localId = session.LocalContenderId; + var state = session.ViewState; + + for (int i = 0; i < events.Count; i++) + { + switch (events[i]) + { + case MatchResetEvent: + ClearAll(); + break; + + case ShotFiredEvent shot: + HandleShotFired(shot, localId, listenerPos); + break; + + case HitImpactEvent hit: + HandleHitImpact(hit, localId, listenerPos); + break; + + case ContenderEliminatedEvent elim: + HandleContenderEliminated(state, elim, listenerPos); + break; + + case SpectatorDestroyedEvent sdet: + HandleSpectatorDestroyed(state, sdet, listenerPos); + break; + + case TerrainStampEvent stamp: + if (stamp.Kind == (byte)TerrainStampKind.Crater && stamp.Radius >= 3.0f) + { + if (!HasRecentExplosionNear(stamp.X, stamp.Z, 12f)) + { + float y = state.Terrain.SampleHeight(stamp.X, stamp.Z); + PlayOneShot3D( + "impact_explosion", + new Vector3(stamp.X, y, stamp.Z), + listenerPos, + PriorityNearCombat, + volumeDb: -4.0f, + pitchScale: NextPitchJitter(0.94f, 1.06f), + isLocalSource: false, + sourceEntityId: -1); + } + } + break; + + case DropPickedUpEvent pickup: + if (pickup.ContenderId == localId) + { + bool imperial = IsImperialDrop(state, pickup.DropId); + PlayUi(imperial ? "ui_pickup_imperial" : "ui_pickup_module", volumeDb: -3.0f, pitchScale: 1f); + } + break; + + case OverheatAlertEvent overheat: + if (overheat.ContenderId == localId && overheat.IsOverheating && _overheatAlarmCooldown <= 0f) + { + PlayUi("ui_overheat_alarm", volumeDb: -4.0f, pitchScale: 1f); + _overheatAlarmCooldown = OverheatAlarmPeriodSec; + } + break; + + case ContenderLoadoutEvent loadout: + HandleLoadoutChanged(state, loadout, localId, listenerPos); + break; + } + } + } + + public void ConsumeFootsteps(IReadOnlyList footsteps, int localId, Vector3 listenerPos) + { + EnsureInitialized(); + for (int i = 0; i < footsteps.Count; i++) + { + FootstepPulse pulse = footsteps[i]; + string clipKey = pulse.MassKg > 3600f + ? "footstep_heavy_thud" + : (pulse.MassKg > 2200f ? "footstep_med_step" : "footstep_light_step"); + + float pitch = Math.Clamp(1.18f - (pulse.MassKg - 1650f) / 6000f, 0.58f, 1.22f) + + Math.Clamp(0.08f * (pulse.LoadG - 1f), -0.06f, 0.08f); + float massNorm = Math.Clamp((pulse.MassKg - 1500f) / 3500f, 0f, 1f); + float loadNorm = Math.Clamp(pulse.LoadG, 0.4f, 2.2f); + float volDb = Math.Clamp(-12f + massNorm * 6f + (loadNorm - 1f) * 3.5f, -14f, 0f); + + bool isLocal = pulse.IsContender && pulse.EntityId == localId; + var pos = new Vector3(pulse.WorldPos.X, pulse.WorldPos.Y, pulse.WorldPos.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + int priority = isLocal + ? PriorityLocalAction + : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); + + PlayOneShot3D( + clipKey, + pos, + listenerPos, + priority, + volDb, + pitch, + isLocalSource: isLocal, + sourceEntityId: pulse.EntityId); + } + } + + private void HandleShotFired(ShotFiredEvent shot, int localId, Vector3 listenerPos) + { + var dedupeKey = (shot.IsSpectatorShooter, shot.ShooterId, shot.WeaponId ?? string.Empty); + if (_shotDedupeExpiry.TryGetValue(dedupeKey, out float expiry) && _audioTime < expiry) + { + DedupedCount++; + return; + } + _shotDedupeExpiry[dedupeKey] = _audioTime + ShotDedupeWindowSec; + PruneExpiredMap(_shotDedupeExpiry); + + string clipKey = SelectWeaponClipKey(shot.WeaponId, (WeaponVisualClass)shot.WeaponClass); + bool isLocal = !shot.IsSpectatorShooter && shot.ShooterId == localId; + Vector3 pos = new(shot.StartX, shot.StartY, shot.StartZ); + float distSq = pos.DistanceSquaredTo(listenerPos); + + int priority = isLocal + ? PriorityLocalAction + : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); + float volDb = isLocal ? -1.5f : -3.5f; + float pitch = NextPitchJitter(0.95f, 1.05f); + + PlayOneShot3D(clipKey, pos, listenerPos, priority, volDb, pitch, isLocal, shot.ShooterId); + } + + private void HandleHitImpact(HitImpactEvent hit, int localId, Vector3 listenerPos) + { + bool isLocalShooter = hit.IsContenderShooter && hit.ShooterId == localId; + bool isLocalTarget = hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localId; + bool targetIsVehicle = hit.TargetKind == (byte)HitTargetKind.Contender || hit.TargetKind == (byte)HitTargetKind.Spectator; + + if (isLocalShooter && targetIsVehicle) + { + string uiKey = hit.Killed + ? "ui_hit_kill" + : (hit.CoreDamage > 0f ? "ui_hit_core" : "ui_hit_armor"); + PlayUi(uiKey, volumeDb: hit.Killed ? -2.0f : -4.0f, pitchScale: 1f); + } + + var impactKey = (hit.TargetKind, hit.TargetId); + if (_impactDedupeExpiry.TryGetValue(impactKey, out float expiry) && _audioTime < expiry) + { + return; + } + _impactDedupeExpiry[impactKey] = _audioTime + ImpactDedupeWindowSec; + PruneExpiredMap(_impactDedupeExpiry); + + Vector3 pos = new(hit.HitX, hit.HitY, hit.HitZ); + float distSq = pos.DistanceSquaredTo(listenerPos); + int priority = (isLocalShooter || isLocalTarget) + ? PriorityLocalImpactOrKill + : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); + + string clipKey; + float volDb; + if (targetIsVehicle) + { + if (hit.CoreDamage > 0f) + { + clipKey = "impact_core"; + volDb = isLocalTarget ? -1.0f : -3.5f; + } + else if (hit.ArmorDamage > 0f) + { + clipKey = "impact_armor_crunch"; + volDb = isLocalTarget ? -2.0f : -4.5f; + } + else + { + clipKey = "impact_ricochet"; + volDb = -6.0f; + } + } + else if (hit.IsAirburst || hit.WeaponClass == (byte)WeaponVisualClass.Explosive) + { + clipKey = "impact_explosion"; + volDb = -4.0f; + RecordExplosionPoint(hit.HitX, hit.HitZ); + } + else + { + clipKey = "impact_ricochet"; + volDb = -8.5f; + } + + PlayOneShot3D(clipKey, pos, listenerPos, priority, volDb, NextPitchJitter(0.92f, 1.08f), isLocalTarget, hit.TargetId); + } + + private void HandleContenderEliminated(MatchState state, ContenderEliminatedEvent elim, Vector3 listenerPos) + { + if (elim.VictimId < 0 || elim.VictimId >= state.Contenders.Count) return; + var v = state.Contenders[elim.VictimId]; + Vector3 pos = new(v.X, v.Y, v.Z); + RecordExplosionPoint(v.X, v.Z); + + PlayOneShot3D("impact_explosion", pos, listenerPos, PriorityLocalImpactOrKill, volumeDb: -0.5f, pitchScale: NextPitchJitter(0.92f, 1.02f), isLocalSource: false, sourceEntityId: elim.VictimId); + PlayOneShot3D("mech_eject", pos, listenerPos, PriorityNearCombat, volumeDb: -3.5f, pitchScale: NextPitchJitter(0.96f, 1.04f), isLocalSource: false, sourceEntityId: elim.VictimId); + + if (!elim.IsSpectatorKiller && elim.KillerId == _localKillerFallback(state, elim.KillerId)) + { + // Local kill chime is already handled on HitImpactEvent.Killed, no double chime needed. + } + } + + private static int _localKillerFallback(MatchState state, int killerId) => killerId; + + private void HandleSpectatorDestroyed(MatchState state, SpectatorDestroyedEvent sdet, Vector3 listenerPos) + { + int sIdx = sdet.SpectatorId >= 1000 ? sdet.SpectatorId - 1000 : sdet.SpectatorId; + if (sIdx < 0 || sIdx >= state.Spectators.Spectators.Count) return; + var s = state.Spectators.Spectators[sIdx]; + Vector3 pos = new(s.X, s.Y, s.Z); + RecordExplosionPoint(s.X, s.Z); + + PlayOneShot3D("impact_explosion", pos, listenerPos, PriorityLocalImpactOrKill, volumeDb: -1.5f, pitchScale: NextPitchJitter(0.94f, 1.04f), isLocalSource: false, sourceEntityId: sdet.SpectatorId); + PlayOneShot3D("mech_eject", pos, listenerPos, PriorityNearCombat, volumeDb: -4.5f, pitchScale: 1f, isLocalSource: false, sourceEntityId: sdet.SpectatorId); + } + + private void HandleLoadoutChanged(MatchState state, ContenderLoadoutEvent loadout, int localId, Vector3 listenerPos) + { + int id = loadout.ContenderId; + bool hadPrevChassis = _lastContenderChassis.TryGetValue(id, out string? prevChassis); + bool hadPrevVer = _lastContenderLoadoutVer.TryGetValue(id, out int prevVer); + + _lastContenderChassis[id] = loadout.ChassisId; + _lastContenderLoadoutVer[id] = loadout.LoadoutVersion; + + if (!hadPrevChassis || !hadPrevVer || loadout.LoadoutVersion <= prevVer) + { + return; + } + + bool chassisChanged = !string.Equals(prevChassis, loadout.ChassisId, StringComparison.OrdinalIgnoreCase); + string clipKey = chassisChanged ? "mech_reload_bolt" : "mech_quick_bolt"; + + if (id == localId) + { + PlayUi(clipKey, volumeDb: -3.5f, pitchScale: 1f); + } + else if (id >= 0 && id < state.Contenders.Count) + { + var c = state.Contenders[id]; + PlayOneShot3D(clipKey, new Vector3(c.X, c.Y, c.Z), listenerPos, PriorityNearCombat, volumeDb: -5.0f, pitchScale: 1f, isLocalSource: false, sourceEntityId: id); + } + } + + private void UpdateLoopSlots(IClientArenaSession session, Vector3 listenerPos, float alpha) + { + var state = session.ViewState; + int localId = session.LocalContenderId; + + // Slot 0: Local player continuous engine / rotor / mech servo loop + var local = session.LocalContender; + if (local.Alive) + { + var (pPos, _, pVel) = session.GetInterpolatedContenderPose(localId, alpha); + Vector3 pos = new(pPos.X, pPos.Y, pPos.Z); + float speed = MathF.Sqrt(pVel.X * pVel.X + pVel.Z * pVel.Z); + ComputeLoopParams(local.Grid.Spec, speed, local.ThrottleCmd, local.VerticalThrottleCmd, out string clipKey, out float volDb, out float pitch); + AssignLoopSlot(0, isContender: true, localId, clipKey, pos, distSq: 0f, volDb, pitch); + } + else + { + SilenceLoopSlot(0); + } + + // Slots 1..4: nearest 4 live rivals/spectators within 160m (with 12m hysteresis) + _loopCandidates.Clear(); + float maxDistSq = MaxLoopDistance * MaxLoopDistance; + + var contenders = state.Contenders; + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (c.Id == localId || !c.Alive || !session.IsContenderVisible(c.Id)) continue; + var (cPos, _, cVel) = session.GetInterpolatedContenderPose(c.Id, alpha); + Vector3 pos = new(cPos.X, cPos.Y, cPos.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + if (distSq > maxDistSq) continue; + + float speed = MathF.Sqrt(cVel.X * cVel.X + cVel.Z * cVel.Z); + ComputeLoopParams(c.Grid.Spec, speed, c.ThrottleCmd, c.VerticalThrottleCmd, out string clipKey, out float volDb, out float pitch); + if (volDb <= -50f) continue; + + // Apply 12m hysteresis bonus if currently held in slots 1..4 + float scoreDistSq = IsHeldInRemoteLoopSlots(true, c.Id) + ? MathF.Max(0f, distSq - LoopHysteresisMeters * LoopHysteresisMeters) + : distSq; + _loopCandidates.Add(new LoopCandidate(true, c.Id, clipKey, pos, scoreDistSq, volDb - 3.5f, pitch)); + } + + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || !session.IsSpectatorVisible(s.Id)) continue; + var (sPos, _, sVel) = session.GetInterpolatedSpectatorPose(s.Id, alpha); + Vector3 pos = new(sPos.X, sPos.Y, sPos.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + if (distSq > maxDistSq) continue; + + float speed = MathF.Sqrt(sVel.X * sVel.X + sVel.Z * sVel.Z); + ComputeLoopParams(s.Grid.Spec, speed, 0.5f, 0f, out string clipKey, out float volDb, out float pitch); + if (volDb <= -50f) continue; + + float scoreDistSq = IsHeldInRemoteLoopSlots(false, s.Id) + ? MathF.Max(0f, distSq - LoopHysteresisMeters * LoopHysteresisMeters) + : distSq; + _loopCandidates.Add(new LoopCandidate(false, s.Id, clipKey, pos, scoreDistSq, volDb - 4.0f, pitch)); + } + + _loopCandidates.Sort((a, b) => a.DistSq.CompareTo(b.DistSq)); + int assigned = Math.Min(LoopVoiceCount - 1, _loopCandidates.Count); + for (int i = 0; i < assigned; i++) + { + var cand = _loopCandidates[i]; + AssignLoopSlot(1 + i, cand.IsContender, cand.EntityId, cand.ClipKey, cand.Position, cand.DistSq, cand.VolumeDb, cand.PitchScale); + } + for (int i = assigned; i < LoopVoiceCount - 1; i++) + { + SilenceLoopSlot(1 + i); + } + } + + private bool IsHeldInRemoteLoopSlots(bool isContender, int entityId) + { + for (int i = 1; i < LoopVoiceCount; i++) + { + if (_loopSlots[i].Active && _loopSlots[i].IsContender == isContender && _loopSlots[i].EntityId == entityId) + { + return true; + } + } + return false; + } + + private static void ComputeLoopParams( + ChassisSpec spec, + float speed, + float throttle, + float verticalThrottle, + out string clipKey, + out float volumeDb, + out float pitchScale) + { + float maxSpd = MathF.Max(6f, spec.MaxSpeed); + float speedRatio = Math.Clamp(speed / maxSpd, 0f, 1.3f); + float load = MathF.Max(speedRatio, MathF.Abs(throttle) * 0.65f); + + if (spec.IsWalker) + { + clipKey = "loop_mech_servo"; + // Fade mech hydraulic servo cleanly toward -60 dB when stationary + volumeDb = load < 0.04f ? -60f : Math.Clamp(-22f + load * 12f, -45f, -9f); + pitchScale = Math.Clamp(0.86f + speedRatio * 0.36f, 0.78f, 1.32f); + } + else if (spec.IsVtol) + { + clipKey = "loop_rotor_vtol"; + float liftBoost = MathF.Abs(verticalThrottle) * 0.35f; + volumeDb = Math.Clamp(-13f + (load + liftBoost) * 6.5f, -15f, -4f); + pitchScale = Math.Clamp(0.92f + speedRatio * 0.25f + liftBoost * 0.16f, 0.85f, 1.35f); + } + else if (spec.Mobility == MobilityKind.Tracked) + { + clipKey = "loop_engine_tracked"; + volumeDb = Math.Clamp(-16f + load * 8.5f, -18f, -6f); + pitchScale = Math.Clamp(0.78f + speedRatio * 0.50f, 0.72f, 1.42f); + } + else + { + clipKey = "loop_engine_wheeled"; + volumeDb = Math.Clamp(-17f + load * 8.5f, -19f, -7f); + pitchScale = Math.Clamp(0.80f + speedRatio * 0.56f, 0.74f, 1.48f); + } + } + + private void AssignLoopSlot( + int slotIdx, + bool isContender, + int entityId, + string clipKey, + Vector3 pos, + float distSq, + float volumeDb, + float pitchScale) + { + ref LoopSlot slot = ref _loopSlots[slotIdx]; + if (!_bank.TryGetStream(clipKey, out var stream)) + { + return; + } + + bool streamChanged = !slot.Active || !string.Equals(slot.ClipKey, clipKey, StringComparison.Ordinal); + slot.Active = true; + slot.IsContender = isContender; + slot.EntityId = entityId; + slot.ClipKey = clipKey; + slot.DistSq = distSq; + slot.VolumeDb = volumeDb; + slot.PitchScale = pitchScale; + + slot.Player.GlobalPosition = pos; + slot.Player.VolumeDb = volumeDb; + slot.Player.PitchScale = pitchScale; + if (streamChanged) + { + slot.Player.Stream = stream; + } + if (!_isDummyAudio && (streamChanged || !slot.Player.Playing)) + { + slot.Player.Play(); + } + } + + private void SilenceLoopSlot(int slotIdx) + { + ref LoopSlot slot = ref _loopSlots[slotIdx]; + if (!slot.Active) + { + return; + } + slot.Active = false; + slot.EntityId = -1; + slot.ClipKey = string.Empty; + slot.VolumeDb = -60f; + if (!_isDummyAudio && slot.Player.Playing) + { + slot.Player.Stop(); + } + } + + public bool PlayOneShot3D( + string clipKey, + Vector3 worldPos, + Vector3 listenerPos, + int priority, + float volumeDb, + float pitchScale, + bool isLocalSource, + int sourceEntityId) + { + EnsureInitialized(); + Total3DPlaysRequested++; + + float distSq = worldPos.DistanceSquaredTo(listenerPos); + if (distSq > MaxAudioDistance * MaxAudioDistance) + { + RejectedDistanceCount++; + return false; + } + + if (!_bank.TryGetStream(clipKey, out var stream)) + { + return false; + } + + int chosenIdx = -1; + long oldestIdleOrStealableSeq = long.MaxValue; + int lowestStealablePriority = priority; + + // First look for an inactive slot + for (int i = 0; i < _oneShotSlots.Length; i++) + { + if (!_oneShotSlots[i].Active) + { + chosenIdx = i; + break; + } + } + + // If full, strictly steal ONLY from a lower-priority slot (never steals from >= priority) + bool stealing = false; + if (chosenIdx < 0) + { + for (int i = 0; i < _oneShotSlots.Length; i++) + { + int slotPrio = _oneShotSlots[i].Priority; + if (slotPrio < lowestStealablePriority || + (slotPrio == lowestStealablePriority && slotPrio < priority && _oneShotSlots[i].AssignedSeq < oldestIdleOrStealableSeq)) + { + lowestStealablePriority = slotPrio; + oldestIdleOrStealableSeq = _oneShotSlots[i].AssignedSeq; + chosenIdx = i; + stealing = true; + } + } + } + + if (chosenIdx < 0) + { + return false; + } + + if (stealing) + { + StolenVoiceCount++; + } + + float dur = MathF.Max(0.10f, (float)stream.GetLength()); + ref OneShotSlot slot = ref _oneShotSlots[chosenIdx]; + slot.Active = true; + slot.Priority = priority; + slot.AssignedSeq = _voiceSeq++; + slot.DurationSec = dur; + slot.RemainingSec = dur / MathF.Max(0.25f, pitchScale); + slot.ClipKey = clipKey; + slot.IsLocalSource = isLocalSource; + slot.SourceEntityId = sourceEntityId; + slot.LastPitch = pitchScale; + slot.LastVolumeDb = volumeDb; + + slot.Player.Stream = stream; + slot.Player.GlobalPosition = worldPos; + slot.Player.VolumeDb = volumeDb; + slot.Player.PitchScale = pitchScale; + if (!_isDummyAudio) + { + slot.Player.Play(); + } + + LastAllocatedClipKey = clipKey; + LastAllocatedPitch = pitchScale; + return true; + } + + public bool PlayUi(string clipKey, float volumeDb = -3.0f, float pitchScale = 1.0f) + { + EnsureInitialized(); + if (!_bank.TryGetStream(clipKey, out var stream)) + { + return false; + } + + int chosenIdx = -1; + long oldestSeq = long.MaxValue; + for (int i = 0; i < _uiSlots.Length; i++) + { + if (!_uiSlots[i].Active) + { + chosenIdx = i; + break; + } + if (_uiSlots[i].AssignedSeq < oldestSeq) + { + oldestSeq = _uiSlots[i].AssignedSeq; + chosenIdx = i; + } + } + + if (chosenIdx < 0) + { + chosenIdx = 0; + } + + float dur = MathF.Max(0.08f, (float)stream.GetLength()); + ref UiSlot slot = ref _uiSlots[chosenIdx]; + slot.Active = true; + slot.AssignedSeq = _voiceSeq++; + slot.RemainingSec = dur / MathF.Max(0.25f, pitchScale); + slot.ClipKey = clipKey; + + slot.Player.Stream = stream; + slot.Player.VolumeDb = volumeDb; + slot.Player.PitchScale = pitchScale; + if (!_isDummyAudio) + { + slot.Player.Play(); + } + return true; + } + + private void AdvanceVoices(float dt) + { + if (dt <= 0f) + { + return; + } + + for (int i = 0; i < _oneShotSlots.Length; i++) + { + ref OneShotSlot slot = ref _oneShotSlots[i]; + if (!slot.Active) continue; + slot.RemainingSec -= dt; + if (slot.RemainingSec <= 0f || (!_isDummyAudio && !slot.Player.Playing && slot.RemainingSec < slot.DurationSec - 0.05f)) + { + slot.Active = false; + slot.Priority = 0; + slot.RemainingSec = 0f; + } + } + + for (int i = 0; i < _uiSlots.Length; i++) + { + ref UiSlot slot = ref _uiSlots[i]; + if (!slot.Active) continue; + slot.RemainingSec -= dt; + if (slot.RemainingSec <= 0f || (!_isDummyAudio && !slot.Player.Playing)) + { + slot.Active = false; + slot.RemainingSec = 0f; + } + } + } + + private string SelectWeaponClipKey(string? weaponId, WeaponVisualClass weaponClass) + { + uint v = _variantCounter++; + string id = (weaponId ?? string.Empty).ToLowerInvariant(); + return id switch + { + "mg_762" => (v & 1) == 0 ? "mg_shot_01" : "mg_shot_02", + "autocannon" => (v % 4) switch + { + 0 => "ac_light_01", + 1 => "ac_light_02", + 2 => "ac_med_01", + _ => "ac_rotary" + }, + "flak" => (v & 1) == 0 ? "flak_blast_01" : "flak_blast_02", + "pd_flak" => (v & 1) == 0 ? "pd_bark_01" : "pd_bark_02", + "aegis_pd" => "pd_laser", + "recoilless" => (v & 1) == 0 ? "cannon_heavy_01" : "cannon_heavy_02", + "touring_plasma" => (v & 1) == 0 ? "plasma_ppc_01" : "plasma_ppc_02", + "gilded_lance" => "lance_beam_01", + "rocket_pod" or "missile_pod" or "srm" or "mrm" => (v & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02", + "laser_heavy" or "heavy_laser" => "laser_heavy_01", + "gauss" or "gauss_rifle" => "gauss_rail_01", + _ => weaponClass switch + { + WeaponVisualClass.Autocannon => "ac_light_01", + WeaponVisualClass.Explosive => "cannon_heavy_01", + WeaponVisualClass.ThermalBeam => "lance_beam_01", + _ => "mg_shot_01" + } + }; + } + + private static bool IsImperialDrop(MatchState state, int dropId) + { + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.Id == dropId) + { + return d.Module is { IsImperial: true } || + (d.Chassis is { } cs && (cs.Id == "paladin" || cs.Id == "spectre" || cs.Id == "kestrel" || cs.Id == "condor")); + } + } + return false; + } + + private void RecordExplosionPoint(float x, float z) + { + _recentExplosionPoints.Add((x, z, _audioTime + 0.08f)); + if (_recentExplosionPoints.Count > 24) + { + _recentExplosionPoints.RemoveAt(0); + } + } + + private bool HasRecentExplosionNear(float x, float z, float radius) + { + float rSq = radius * radius; + for (int i = _recentExplosionPoints.Count - 1; i >= 0; i--) + { + var p = _recentExplosionPoints[i]; + if (_audioTime > p.Expiry) + { + _recentExplosionPoints.RemoveAt(i); + continue; + } + float dx = p.X - x; + float dz = p.Z - z; + if (dx * dx + dz * dz <= rSq) + { + return true; + } + } + return false; + } + + private void PruneExpiredMap(Dictionary dict) where TKey : notnull + { + if (dict.Count <= 64) return; + var toRemove = new List(); + foreach (var kv in dict) + { + if (_audioTime >= kv.Value) toRemove.Add(kv.Key); + } + for (int i = 0; i < toRemove.Count; i++) + { + dict.Remove(toRemove[i]); + } + } + + private float NextPitchJitter(float min, float max) + { + _rng ^= _rng << 13; + _rng ^= _rng >> 17; + _rng ^= _rng << 5; + float u = (_rng & 0xFFFFu) / 65535f; + return min + (max - min) * u; + } +} diff --git a/client/Main.cs b/client/Main.cs index 1e354e5..d32ff9a 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -24,6 +24,7 @@ public partial class Main : Node3D private TerrainRenderer _terrain = null!; private SionMapRenderer _sionMap = null!; private ArenaRenderer _arena = null!; + private ArenaAudioSystem _audio = null!; private Camera3D _camera = null!; private Hud _hud = null!; private DirectionalLight3D _sun = null!; @@ -32,6 +33,9 @@ public partial class Main : Node3D private IClientArenaSession? _session; private MatchState? _boundViewState; private bool _wasNetConnected; + private readonly WalkerFootstepTracker _footsteps = new(); + private readonly List _frameEvents = new(128); + private readonly List _frameFootsteps = new(32); private ArenaMapKind _mapKind = ArenaMapKind.Sion; private string _callsign = "Pilot"; private string _lastEndpoint = $"127.0.0.1:{DefaultNetPort}"; @@ -74,6 +78,8 @@ public partial class Main : Node3D public TerrainRenderer Terrain => _terrain; public SionMapRenderer SionMap => _sionMap; public ArenaRenderer Arena => _arena; + public ArenaAudioSystem Audio => _audio; + public WalkerFootstepTracker Footsteps => _footsteps; public Hud Hud => _hud; public ArenaMapKind MapKind => _mapKind; public ArenaMapKind? InitialMapKindOverride { get; set; } @@ -94,6 +100,9 @@ public partial class Main : Node3D _arena = new ArenaRenderer { Name = "Arena" }; AddChild(_arena); + _audio = new ArenaAudioSystem { Name = "ArenaAudio" }; + AddChild(_audio); + _camera = new Camera3D { Name = "ShoulderCamera", @@ -392,6 +401,10 @@ public partial class Main : Node3D _cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f); _cameraZoom = 1.0f; _lastCamChassisId = null; + _footsteps.Clear(); + _frameEvents.Clear(); + _frameFootsteps.Clear(); + _audio.ClearAll(); } _camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f; @@ -711,6 +724,7 @@ public partial class Main : Node3D long tc0 = Stopwatch.GetTimestamp(); UpdateCamera((float)delta, alpha); + StepAudioAndFootsteps((float)delta, alpha); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); @@ -763,6 +777,7 @@ public partial class Main : Node3D } _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); UpdateCamera((float)delta, alpha); + StepAudioAndFootsteps((float)delta, alpha); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); @@ -775,6 +790,43 @@ public partial class Main : Node3D } } + private void StepAudioAndFootsteps(float dt, float alpha) + { + if (_session is null) + { + return; + } + _frameEvents.Clear(); + _session.DrainSimEvents(_frameEvents); + + _frameFootsteps.Clear(); + _footsteps.StepSession(_session, dt, alpha, _frameFootsteps, ResolveLiveWalkerFootWorld); + + _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, dt, alpha); + } + + private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex) + { + VehicleVisualInstance? vis = isContender + ? _arena.GetContenderVisual(id) + : _arena.GetSpectatorVisual(id); + if (vis is null || vis.IsStaticLod || vis.RigState?.WalkerRig is not { } rig) + { + return null; + } + if ((uint)legIndex >= (uint)rig.Legs.Length) + { + return null; + } + Node3D footNode = rig.Legs[legIndex].Foot.Node; + if (!GodotObject.IsInstanceValid(footNode) || !footNode.IsInsideTree()) + { + return null; + } + Vector3 p = footNode.GlobalPosition; + return new System.Numerics.Vector3(p.X, p.Y, p.Z); + } + private void PrintPerfSummaryAndQuit() { static double Avg(List v) diff --git a/client/ProceduralAudioBank.cs b/client/ProceduralAudioBank.cs new file mode 100644 index 0000000..ee5db96 --- /dev/null +++ b/client/ProceduralAudioBank.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Godot; +using RustToDust.Core; +using RustToDust.Core.Audio; + +namespace RustToDust.Client; + +/// +/// Owns all immutable assets built once at client startup: +/// 25 curated Haven Kendrick WAVs from assets/audio/haven/ plus all deterministic +/// procedural clips (with separable ). +/// Zero .import sidecar dependency. +/// +public sealed class ProceduralAudioBank +{ + public static readonly string[] ExpectedHavenClips = + { + "mg_shot_01", "mg_shot_02", "mg_tail", + "ac_light_01", "ac_light_02", "ac_med_01", "ac_rotary", + "flak_blast_01", "flak_blast_02", "cannon_heavy_01", "cannon_heavy_02", + "pd_bark_01", "pd_bark_02", "pd_laser", + "rocket_salvo_01", "rocket_salvo_02", + "plasma_ppc_01", "plasma_ppc_02", "lance_beam_01", "laser_heavy_01", "gauss_rail_01", + "mech_reload_bolt", "mech_quick_bolt", "mech_eject", "mech_turret_servo" + }; + + private readonly Dictionary _streams = new(StringComparer.OrdinalIgnoreCase); + + public ProceduralAudioBank(bool wetMixMode = true, string? havenDirOverride = null) + { + WetMixMode = wetMixMode; + LoadHavenClips(havenDirOverride ?? LocateHavenAudioDirectory()); + BuildProceduralClips(wetMixMode); + } + + public bool WetMixMode { get; private set; } + public int HavenClipCount { get; private set; } + public int ProceduralClipCount { get; private set; } + public int TotalClipCount => _streams.Count; + + public bool TryGetStream(string key, out AudioStreamWav stream) => + _streams.TryGetValue(key, out stream!); + + public AudioStreamWav GetStream(string key) => + _streams.TryGetValue(key, out var stream) + ? stream + : throw new KeyNotFoundException($"Missing audio clip '{key}' in ProceduralAudioBank."); + + public void RebuildProcedural(bool wetMixMode) + { + WetMixMode = wetMixMode; + BuildProceduralClips(wetMixMode); + } + + public static string LocateHavenAudioDirectory() + { + string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + string assetsDir = Directory.GetParent(vehiclesDir)?.FullName + ?? throw new DirectoryNotFoundException("Could not locate assets directory."); + string havenDir = Path.Combine(assetsDir, "audio", "haven"); + if (!Directory.Exists(havenDir)) + { + throw new DirectoryNotFoundException($"Curated Haven audio directory not found: {havenDir}"); + } + return havenDir; + } + + private void LoadHavenClips(string havenDir) + { + int loaded = 0; + for (int i = 0; i < ExpectedHavenClips.Length; i++) + { + string key = ExpectedHavenClips[i]; + string path = Path.Combine(havenDir, key + ".wav"); + if (!File.Exists(path)) + { + throw new FileNotFoundException($"Missing curated Haven WAV '{path}'.", path); + } + + WavPcmInfo wav = WavFileReader.ReadMonoOrStereo16(path); + var stream = new AudioStreamWav + { + Format = AudioStreamWav.FormatEnum.Format16Bits, + MixRate = wav.SampleRate, + Stereo = wav.Channels == 2, + LoopMode = AudioStreamWav.LoopModeEnum.Disabled, + Data = wav.PcmBytes + }; + _streams[key] = stream; + loaded++; + } + HavenClipCount = loaded; + } + + private void BuildProceduralClips(bool wetMixMode) + { + Dictionary clips = PcmSynth.SynthesizeAll(wetMixMode); + int count = 0; + foreach (var kv in clips) + { + PcmClipData clip = kv.Value; + var stream = new AudioStreamWav + { + Format = AudioStreamWav.FormatEnum.Format16Bits, + MixRate = clip.SampleRate, + Stereo = false, + LoopMode = clip.IsLoop ? AudioStreamWav.LoopModeEnum.Forward : AudioStreamWav.LoopModeEnum.Disabled, + LoopBegin = 0, + LoopEnd = clip.IsLoop ? clip.Samples.Length : 0, + Data = clip.Pcm16Bytes + }; + _streams[clip.Key] = stream; + count++; + } + ProceduralClipCount = count; + } +} diff --git a/client/WalkerFootstepTracker.cs b/client/WalkerFootstepTracker.cs new file mode 100644 index 0000000..0d84046 --- /dev/null +++ b/client/WalkerFootstepTracker.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +public readonly record struct FootstepPulse( + bool IsContender, + int EntityId, + int LegIndex, + string ChassisId, + float MassKg, + float LoadG, + Vector3 WorldPos); + +/// +/// Tracks per-walker leg GRF hysteresis (LoadG arming < 0.10, touchdown >= 0.24, +/// 0.18 s cooldown) from interpolated s across both Solo and +/// Multiplayer (). Zero Godot dependency so xUnit and headless +/// Godot tests run the exact same edge detector. +/// +public sealed class WalkerFootstepTracker +{ + public const float ArmLoadGThreshold = 0.10f; + public const float TriggerLoadGThreshold = 0.24f; + public const float LegCooldownSec = 0.18f; + + private struct LegHysteresis + { + public bool Armed; + public float Cooldown; + } + + private sealed class WalkerTrackState + { + public string ChassisId = string.Empty; + public int LegCount; + public readonly LegHysteresis[] Legs = new LegHysteresis[4]; + } + + private readonly Dictionary<(bool IsContender, int Id), WalkerTrackState> _walkers = new(); + + public int TrackedWalkerCount => _walkers.Count; + + public void Clear() => _walkers.Clear(); + + public void StepSession( + IClientArenaSession session, + float dt, + float alpha, + List outPulses, + Func? resolveLiveFootWorld = null) + { + var state = session.ViewState; + var contenders = state.Contenders; + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (!c.Alive || !c.Grid.Spec.IsWalker || !session.IsContenderVisible(c.Id)) + { + _walkers.Remove((true, c.Id)); + continue; + } + if (!session.TrySampleInterpolatedWalkerPose(true, c.Id, alpha, out var snap)) + { + continue; + } + StepActor( + isContender: true, + entityId: c.Id, + chassisId: c.Grid.Spec.Id, + massKg: c.Grid.Spec.MassKg, + in snap, + state.Terrain, + dt, + outPulses, + resolveLiveFootWorld); + } + + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || !s.Grid.Spec.IsWalker || !session.IsSpectatorVisible(s.Id)) + { + _walkers.Remove((false, s.Id)); + continue; + } + if (!session.TrySampleInterpolatedWalkerPose(false, s.Id, alpha, out var snap)) + { + continue; + } + StepActor( + isContender: false, + entityId: s.Id, + chassisId: s.Grid.Spec.Id, + massKg: s.Grid.Spec.MassKg, + in snap, + state.Terrain, + dt, + outPulses, + resolveLiveFootWorld); + } + } + + public void StepActor( + bool isContender, + int entityId, + string chassisId, + float massKg, + in WalkerVisualSnapshot snap, + TerrainField terrain, + float dt, + List outPulses, + Func? resolveLiveFootWorld = null) + { + int legCount = Math.Clamp(snap.LegCount, 0, 4); + if (legCount == 0) + { + return; + } + + var key = (isContender, entityId); + if (!_walkers.TryGetValue(key, out var track) || + !string.Equals(track.ChassisId, chassisId, StringComparison.OrdinalIgnoreCase) || + track.LegCount != legCount) + { + track = new WalkerTrackState + { + ChassisId = chassisId, + LegCount = legCount + }; + // First sighting initializes Armed = false for zero spawn / swap pop + _walkers[key] = track; + return; + } + + float stepDt = MathF.Max(0f, dt); + WalkerGeometrySpec? geom = null; + float geomScale = snap.GeomScale > 0.01f ? snap.GeomScale : 1f; + Quaternion comRot = snap.ComRot.LengthSquared() > 1e-6f + ? Quaternion.Normalize(snap.ComRot) + : Quaternion.Identity; + + for (int i = 0; i < legCount; i++) + { + ref LegHysteresis leg = ref track.Legs[i]; + if (leg.Cooldown > 0f) + { + leg.Cooldown = MathF.Max(0f, leg.Cooldown - stepDt); + } + + float loadG = snap.LoadG[i]; + if (loadG < ArmLoadGThreshold) + { + leg.Armed = true; + continue; + } + + if (leg.Armed && loadG >= TriggerLoadGThreshold && leg.Cooldown <= 0f) + { + leg.Armed = false; + leg.Cooldown = LegCooldownSec; + + Vector3? liveFoot = resolveLiveFootWorld?.Invoke(isContender, entityId, i); + Vector3 footWorld; + if (liveFoot.HasValue) + { + float fy = terrain.SampleHeight(liveFoot.Value.X, liveFoot.Value.Z); + footWorld = new Vector3(liveFoot.Value.X, fy, liveFoot.Value.Z); + } + else + { + geom ??= WalkerGeometrySpec.GetForChassis(chassisId); + Vector2 restXZ = geom.Legs[i].RestFootXZ * geomScale; + Vector3 offset = Vector3.Transform(new Vector3(restXZ.X, 0f, restXZ.Y), comRot); + float fx = snap.ComPos.X + offset.X; + float fz = snap.ComPos.Z + offset.Z; + float fy = terrain.SampleHeight(fx, fz); + footWorld = new Vector3(fx, fy, fz); + } + + outPulses.Add(new FootstepPulse( + isContender, + entityId, + i, + chassisId, + massKg, + loadG, + footWorld)); + } + } + } +} diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index cc08f66..afea217 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -1283,6 +1283,116 @@ public partial class Smoke : Node Check(remoteIface.LocalContender.Alive, "Expected loopback RemoteArenaSession LocalContender alive"); } + // 14. Cut 5d-1: Headless AudioBank, voice-cap/priority/dedupe, and mass-scaled GRF footstep pitch falsification + { + var audio = _main.Audio; + audio.EnsureInitialized(); + Check(audio.Bank.HavenClipCount == 25, $"Expected 25 curated Haven clips in ProceduralAudioBank, got {audio.Bank.HavenClipCount}"); + Check(audio.Bank.ProceduralClipCount == 18, $"Expected 18 procedural clips in ProceduralAudioBank, got {audio.Bank.ProceduralClipCount}"); + + audio.ClearAll(); + audio.ResetStatsForTest(); + var localC = _main.Session.LocalContender; + Vector3 listener = new(localC.X, localC.Y, localC.Z); + + var burstEvents = new List(); + // Local player shot first (priority 10) + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90001, + IsSpectatorShooter = false, + ShooterId = _main.Session.LocalContenderId, + StartX = listener.X, + StartY = listener.Y + 1f, + StartZ = listener.Z, + EndX = listener.X + 40f, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.KineticLight, + WeaponId = "mg_762" + }); + + // 5-pellet flak salvo from contender 1 -> must dedupe to 1 audio voice + for (int p = 0; p < 5; p++) + { + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90010 + p, + IsSpectatorShooter = false, + ShooterId = 1, + StartX = listener.X + 18f, + StartY = listener.Y + 1f, + StartZ = listener.Z, + EndX = listener.X, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "flak" + }); + } + + // 30 simultaneous distant AI shots (>150m, <240m) trying to saturate all 19 one-shot voices + for (int a = 2; a < 32; a++) + { + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90100 + a, + IsSpectatorShooter = false, + ShooterId = a, + StartX = listener.X + 175f, + StartY = listener.Y + 1f, + StartZ = listener.Z + (a % 5), + EndX = listener.X, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.Autocannon, + WeaponId = "autocannon" + }); + } + + // 1 event beyond MaxAudioDistance (260m) -> must be culled (0 voices) + burstEvents.Add(new ShotFiredEvent + { + TracerId = 90999, + IsSpectatorShooter = false, + ShooterId = 99, + StartX = listener.X + 320f, + StartY = listener.Y + 1f, + StartZ = listener.Z, + EndX = listener.X, + EndY = listener.Y + 1f, + EndZ = listener.Z, + WeaponClass = (byte)WeaponVisualClass.Explosive, + WeaponId = "recoilless" + }); + + audio.ConsumeSimEvents(_main.Session, burstEvents, listener); + Check(audio.Active3DVoiceCount <= ArenaAudioSystem.Total3DVoiceCount, + $"Active 3D voices exceeded 24 cap: {audio.Active3DVoiceCount}"); + Check(audio.ActiveOneShotVoiceCount == ArenaAudioSystem.OneShotVoiceCount, + $"Expected 19 saturated one-shot voices, got {audio.ActiveOneShotVoiceCount}"); + Check(audio.DedupedCount == 4, + $"Expected 5-pellet flak salvo to dedupe 4 pellets, got DedupedCount={audio.DedupedCount}"); + Check(audio.RejectedDistanceCount == 1, + $"Expected >260m event to be distance-culled, got RejectedDistanceCount={audio.RejectedDistanceCount}"); + Check(audio.HasActiveVoiceForSource(isLocalSource: true, sourceEntityId: _main.Session.LocalContenderId), + "Expected local player priority-10 voice never to be stolen by distant AI shots"); + + // Footstep mass-scaled pitch verification: Bastion (4600 kg) pitch < Kestrel (1650 kg) pitch + audio.ClearAll(); + var kestrelPulse = new FootstepPulse(true, 0, 0, "kestrel", Catalog.Kestrel.MassKg, 1.0f, new System.Numerics.Vector3(listener.X, listener.Y, listener.Z)); + audio.ConsumeFootsteps(new[] { kestrelPulse }, _main.Session.LocalContenderId, listener); + float? kestrelPitch = audio.GetLastPitchForClipPrefix("footstep_"); + + var bastionPulse = new FootstepPulse(true, 1, 0, "bastion", Catalog.Bastion.MassKg, 1.0f, new System.Numerics.Vector3(listener.X + 10f, listener.Y, listener.Z)); + audio.ConsumeFootsteps(new[] { bastionPulse }, _main.Session.LocalContenderId, listener); + float? bastionPitch = audio.GetLastPitchForClipPrefix("footstep_heavy_"); + + Check(kestrelPitch.HasValue && bastionPitch.HasValue && bastionPitch.Value < kestrelPitch.Value, + $"Expected Bastion pitch ({bastionPitch}) < Kestrel pitch ({kestrelPitch})"); + GD.Print($"SMOKE INFO: Audio verified (haven={audio.Bank.HavenClipCount}, proc={audio.Bank.ProceduralClipCount}, dummy={audio.IsDummyAudio}, kestrelPitch={kestrelPitch:F3}, bastionPitch={bastionPitch:F3})"); + } + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); } diff --git a/src/RustToDust.Core/Audio/PcmSynth.cs b/src/RustToDust.Core/Audio/PcmSynth.cs new file mode 100644 index 0000000..282662e --- /dev/null +++ b/src/RustToDust.Core/Audio/PcmSynth.cs @@ -0,0 +1,860 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace RustToDust.Core.Audio +{ + public enum ProceduralCueId + { + FootstepHeavyThud, + FootstepMedStep, + FootstepLightStep, + LoopEngineWheeled, + LoopEngineTracked, + LoopEngineHover, + LoopRotorVtol, + LoopMechServo, + ImpactRicochet, + ImpactArmorCrunch, + ImpactCore, + ImpactExplosion, + UiHitArmor, + UiHitCore, + UiHitKill, + UiOverheatAlarm, + UiPickupModule, + UiPickupImperial + } + + public sealed record PcmClipData( + string Key, + ProceduralCueId CueId, + bool IsLoop, + int SampleRate, + float[] Samples, + byte[] Pcm16Bytes, + int DrySampleCount); + + public readonly record struct WavPcmInfo( + int SampleRate, + int Channels, + int BitsPerSample, + byte[] PcmBytes, + float[] FloatSamples); + + public static class WavFileReader + { + public static WavPcmInfo ReadMonoOrStereo16(string path) + { + byte[] raw = File.ReadAllBytes(path); + return Parse(raw, path); + } + + public static WavPcmInfo Parse(ReadOnlySpan raw, string sourceLabel = "") + { + if (raw.Length < 44) + { + throw new InvalidDataException($"WAV '{sourceLabel}' too short ({raw.Length} bytes)."); + } + if (Encoding.ASCII.GetString(raw[0..4]) != "RIFF" || + Encoding.ASCII.GetString(raw[8..12]) != "WAVE") + { + throw new InvalidDataException($"WAV '{sourceLabel}' missing RIFF/WAVE header."); + } + + int offset = 12; + bool hasFmt = false; + bool hasData = false; + int audioFormat = 0; + int channels = 0; + int sampleRate = 0; + int bitsPerSample = 0; + byte[] pcmBytes = Array.Empty(); + + while (offset + 8 <= raw.Length) + { + string chunkId = Encoding.ASCII.GetString(raw.Slice(offset, 4)); + int chunkSize = BitConverter.ToInt32(raw.Slice(offset + 4, 4)); + int dataStart = offset + 8; + if (chunkSize < 0 || dataStart + chunkSize > raw.Length) + { + throw new InvalidDataException($"WAV '{sourceLabel}' has invalid chunk '{chunkId}' size {chunkSize}."); + } + + if (chunkId == "fmt ") + { + if (chunkSize < 16) + { + throw new InvalidDataException($"WAV '{sourceLabel}' fmt chunk too small ({chunkSize})."); + } + audioFormat = BitConverter.ToUInt16(raw.Slice(dataStart, 2)); + channels = BitConverter.ToUInt16(raw.Slice(dataStart + 2, 2)); + sampleRate = BitConverter.ToInt32(raw.Slice(dataStart + 4, 4)); + bitsPerSample = BitConverter.ToUInt16(raw.Slice(dataStart + 14, 2)); + hasFmt = true; + } + else if (chunkId == "data") + { + pcmBytes = raw.Slice(dataStart, chunkSize).ToArray(); + hasData = true; + } + + int paddedSize = chunkSize + (chunkSize & 1); + offset = dataStart + paddedSize; + } + + if (!hasFmt || !hasData) + { + throw new InvalidDataException($"WAV '{sourceLabel}' missing fmt or data chunk."); + } + if (audioFormat != 1 || bitsPerSample != 16) + { + throw new InvalidDataException($"WAV '{sourceLabel}' must be 16-bit PCM (got fmt={audioFormat}, bits={bitsPerSample})."); + } + + int sampleCount = pcmBytes.Length / 2; + var floats = new float[sampleCount]; + for (int i = 0; i < sampleCount; i++) + { + short s = BitConverter.ToInt16(pcmBytes, i * 2); + floats[i] = s / 32768f; + } + + return new WavPcmInfo(sampleRate, channels, bitsPerSample, pcmBytes, floats); + } + } + + /// + /// Pure-C# deterministic 44.1 kHz mono PCM synthesizer with a cleanly separable + /// wetMixMode room/saturation post-stage. Zero Godot dependency so xUnit + /// and headless client tests validate the exact same waveforms. + /// + public static class PcmSynth + { + public const int SampleRate = 44100; + private const float MaxSafePeak = 0.92f; + + private static readonly (ProceduralCueId Cue, string Key)[] AllCues = + { + (ProceduralCueId.FootstepHeavyThud, "footstep_heavy_thud"), + (ProceduralCueId.FootstepMedStep, "footstep_med_step"), + (ProceduralCueId.FootstepLightStep, "footstep_light_step"), + (ProceduralCueId.LoopEngineWheeled, "loop_engine_wheeled"), + (ProceduralCueId.LoopEngineTracked, "loop_engine_tracked"), + (ProceduralCueId.LoopEngineHover, "loop_engine_hover"), + (ProceduralCueId.LoopRotorVtol, "loop_rotor_vtol"), + (ProceduralCueId.LoopMechServo, "loop_mech_servo"), + (ProceduralCueId.ImpactRicochet, "impact_ricochet"), + (ProceduralCueId.ImpactArmorCrunch, "impact_armor_crunch"), + (ProceduralCueId.ImpactCore, "impact_core"), + (ProceduralCueId.ImpactExplosion, "impact_explosion"), + (ProceduralCueId.UiHitArmor, "ui_hit_armor"), + (ProceduralCueId.UiHitCore, "ui_hit_core"), + (ProceduralCueId.UiHitKill, "ui_hit_kill"), + (ProceduralCueId.UiOverheatAlarm, "ui_overheat_alarm"), + (ProceduralCueId.UiPickupModule, "ui_pickup_module"), + (ProceduralCueId.UiPickupImperial, "ui_pickup_imperial") + }; + + public static IReadOnlyList<(ProceduralCueId Cue, string Key)> CueRegistry => AllCues; + + public static Dictionary SynthesizeAll(bool wetMixMode = true) + { + var dict = new Dictionary(AllCues.Length, StringComparer.OrdinalIgnoreCase); + for (int i = 0; i < AllCues.Length; i++) + { + var clip = Synthesize(AllCues[i].Cue, wetMixMode); + dict[clip.Key] = clip; + } + return dict; + } + + public static PcmClipData Synthesize(ProceduralCueId cue, bool wetMixMode = true) + { + GenerateDry(cue, out float[] dry, out bool isLoop, out string key); + int dryLen = dry.Length; + + float[] finalSamples; + if (wetMixMode) + { + finalSamples = ApplyWetRoomStage(dry, isLoop); + } + else + { + finalSamples = dry; + ClampNormalizePeak(finalSamples, MaxSafePeak); + } + + byte[] pcmBytes = FloatToPcm16(finalSamples); + return new PcmClipData(key, cue, isLoop, SampleRate, finalSamples, pcmBytes, dryLen); + } + + public static float[] ApplyWetRoomStage(ReadOnlySpan dry, bool isLoop) + { + if (isLoop) + { + return ApplyWetRoomLoop(dry); + } + + const int tailSamples = (int)(0.20f * SampleRate); + int outLen = dry.Length + tailSamples; + var wet = new float[outLen]; + + // Early reflections (11ms, 19ms, 29ms, 43ms) + ReadOnlySpan tapDelays = stackalloc int[] { 485, 838, 1279, 1896 }; + ReadOnlySpan tapGains = stackalloc float[] { 0.30f, -0.24f, 0.19f, -0.14f }; + + // 4-comb Schroeder/Moorer diffused room tail with one-pole damping + ReadOnlySpan combDelays = stackalloc int[] { 1327, 1621, 1949, 2269 }; + ReadOnlySpan combGains = stackalloc float[] { 0.72f, 0.69f, 0.66f, 0.63f }; + + var combBuf0 = new float[combDelays[0]]; + var combBuf1 = new float[combDelays[1]]; + var combBuf2 = new float[combDelays[2]]; + var combBuf3 = new float[combDelays[3]]; + int idx0 = 0, idx1 = 0, idx2 = 0, idx3 = 0; + float lp0 = 0f, lp1 = 0f, lp2 = 0f, lp3 = 0f; + + const int apDelay = 347; + var apBuf = new float[apDelay]; + int apIdx = 0; + + for (int i = 0; i < outLen; i++) + { + float d = i < dry.Length ? dry[i] : 0f; + + float early = 0f; + for (int t = 0; t < tapDelays.Length; t++) + { + int srcIdx = i - tapDelays[t]; + if (srcIdx >= 0 && srcIdx < dry.Length) + { + early += dry[srcIdx] * tapGains[t]; + } + } + + float c0 = combBuf0[idx0]; + lp0 = lp0 * 0.42f + c0 * 0.58f; + combBuf0[idx0] = d + lp0 * combGains[0]; + idx0 = (idx0 + 1) % combDelays[0]; + + float c1 = combBuf1[idx1]; + lp1 = lp1 * 0.42f + c1 * 0.58f; + combBuf1[idx1] = d + lp1 * combGains[1]; + idx1 = (idx1 + 1) % combDelays[1]; + + float c2 = combBuf2[idx2]; + lp2 = lp2 * 0.42f + c2 * 0.58f; + combBuf2[idx2] = d + lp2 * combGains[2]; + idx2 = (idx2 + 1) % combDelays[2]; + + float c3 = combBuf3[idx3]; + lp3 = lp3 * 0.42f + c3 * 0.58f; + combBuf3[idx3] = d + lp3 * combGains[3]; + idx3 = (idx3 + 1) % combDelays[3]; + + float combSum = (c0 + c1 + c2 + c3) * 0.25f; + + // Allpass diffusion + float apOut = apBuf[apIdx]; + float apIn = combSum + apOut * 0.45f; + apBuf[apIdx] = apIn; + float diffused = apOut - apIn * 0.45f; + apIdx = (apIdx + 1) % apDelay; + + float mixed = d * 0.92f + early * 0.46f + diffused * 0.44f; + wet[i] = MathF.Tanh(mixed * 1.12f); + } + + // Smooth 16ms cosine fade on very end of tail so no abrupt cut + int fadeLen = Math.Min(tailSamples, (int)(0.016f * SampleRate)); + int fadeStart = outLen - fadeLen; + for (int i = 0; i < fadeLen; i++) + { + float g = 0.5f * (1f + MathF.Cos(MathF.PI * (i + 1) / fadeLen)); + wet[fadeStart + i] *= g; + } + + ClampNormalizePeak(wet, MaxSafePeak); + return wet; + } + + private static float[] ApplyWetRoomLoop(ReadOnlySpan dry) + { + int len = dry.Length; + var wet = new float[len]; + + // Circular early reflections + 2-tap circular diffusion preserve exact periodicity at wrap (sample N-1 -> 0) + ReadOnlySpan taps = stackalloc int[] { 331, 617, 1019, 1511 }; + ReadOnlySpan gains = stackalloc float[] { 0.16f, -0.12f, 0.09f, -0.06f }; + + float lp = 0f; + for (int pass = 0; pass < 2; pass++) + { + for (int i = 0; i < len; i++) + { + float d = dry[i]; + float room = 0f; + for (int t = 0; t < taps.Length; t++) + { + int src = (i - taps[t] + len) % len; + room += dry[src] * gains[t]; + } + lp = lp * 0.65f + room * 0.35f; + float mixed = d * 0.90f + room * 0.55f + lp * 0.40f; + wet[i] = MathF.Tanh(mixed * 1.08f); + } + } + + ClampNormalizePeak(wet, MaxSafePeak); + return wet; + } + + private static void GenerateDry(ProceduralCueId cue, out float[] buf, out bool isLoop, out string key) + { + switch (cue) + { + case ProceduralCueId.FootstepHeavyThud: + key = "footstep_heavy_thud"; + isLoop = false; + buf = GenFootstep(durSec: 0.38f, fStart: 88f, fEnd: 32f, clackFreq: 380f, clackMix: 0.22f, gravelMix: 0.34f, seed: 101u); + break; + case ProceduralCueId.FootstepMedStep: + key = "footstep_med_step"; + isLoop = false; + buf = GenFootstep(durSec: 0.30f, fStart: 112f, fEnd: 40f, clackFreq: 520f, clackMix: 0.28f, gravelMix: 0.28f, seed: 102u); + break; + case ProceduralCueId.FootstepLightStep: + key = "footstep_light_step"; + isLoop = false; + buf = GenFootstep(durSec: 0.24f, fStart: 135f, fEnd: 48f, clackFreq: 690f, clackMix: 0.36f, gravelMix: 0.22f, seed: 103u); + break; + case ProceduralCueId.LoopEngineWheeled: + key = "loop_engine_wheeled"; + isLoop = true; + buf = GenLoopWheeled(); + break; + case ProceduralCueId.LoopEngineTracked: + key = "loop_engine_tracked"; + isLoop = true; + buf = GenLoopTracked(); + break; + case ProceduralCueId.LoopEngineHover: + key = "loop_engine_hover"; + isLoop = true; + buf = GenLoopHover(); + break; + case ProceduralCueId.LoopRotorVtol: + key = "loop_rotor_vtol"; + isLoop = true; + buf = GenLoopVtol(); + break; + case ProceduralCueId.LoopMechServo: + key = "loop_mech_servo"; + isLoop = true; + buf = GenLoopServo(); + break; + case ProceduralCueId.ImpactRicochet: + key = "impact_ricochet"; + isLoop = false; + buf = GenRicochet(); + break; + case ProceduralCueId.ImpactArmorCrunch: + key = "impact_armor_crunch"; + isLoop = false; + buf = GenArmorCrunch(); + break; + case ProceduralCueId.ImpactCore: + key = "impact_core"; + isLoop = false; + buf = GenCoreImpact(); + break; + case ProceduralCueId.ImpactExplosion: + key = "impact_explosion"; + isLoop = false; + buf = GenExplosion(); + break; + case ProceduralCueId.UiHitArmor: + key = "ui_hit_armor"; + isLoop = false; + buf = GenUiHitArmor(); + break; + case ProceduralCueId.UiHitCore: + key = "ui_hit_core"; + isLoop = false; + buf = GenUiHitCore(); + break; + case ProceduralCueId.UiHitKill: + key = "ui_hit_kill"; + isLoop = false; + buf = GenUiHitKill(); + break; + case ProceduralCueId.UiOverheatAlarm: + key = "ui_overheat_alarm"; + isLoop = false; + buf = GenUiOverheatAlarm(); + break; + case ProceduralCueId.UiPickupModule: + key = "ui_pickup_module"; + isLoop = false; + buf = GenUiPickupModule(); + break; + case ProceduralCueId.UiPickupImperial: + key = "ui_pickup_imperial"; + isLoop = false; + buf = GenUiPickupImperial(); + break; + default: + throw new ArgumentOutOfRangeException(nameof(cue), cue, null); + } + } + + private static float[] GenFootstep( + float durSec, + float fStart, + float fEnd, + float clackFreq, + float clackMix, + float gravelMix, + uint seed) + { + int n = (int)(durSec * SampleRate); + var s = new float[n]; + uint rng = seed; + float phase = 0f; + float lp = 0f; + float hpPrev = 0f; + float hpOut = 0f; + + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float envAttack = MathF.Min(1f, t / 0.004f); + float subEnv = envAttack * MathF.Exp(-t * (10.5f / durSec * 0.38f)); + float freq = fEnd + (fStart - fEnd) * MathF.Exp(-t * 28f); + phase += MathF.Tau * freq / SampleRate; + float sub = MathF.Sin(phase) * subEnv; + + float clackEnv = envAttack * MathF.Exp(-t * 48f); + float clack = (MathF.Sin(MathF.Tau * clackFreq * t) + 0.5f * MathF.Sin(MathF.Tau * clackFreq * 1.47f * t)) * clackEnv; + + float white = NextSignedNoise(ref rng); + lp = lp * 0.84f + white * 0.16f; + hpOut = 0.90f * (hpOut + lp - hpPrev); + hpPrev = lp; + float gravelEnv = envAttack * MathF.Exp(-t * 16f); + float damperHiss = white * 0.12f * MathF.Exp(-t * 11f); + + float fadeOut = u > 0.85f ? (1f - (u - 0.85f) / 0.15f) : 1f; + s[i] = (sub * 0.82f + clack * clackMix + hpOut * gravelMix + damperHiss) * fadeOut; + } + NormalizePeak(s, 0.86f); + return s; + } + + private static float[] GenLoopWheeled() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x201u, lpAlpha: 0.06f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + // Integer harmonic cosines -> exact 1.000s periodicity with zero-slope wrap + float baseOsc = + MathF.Cos(MathF.Tau * 42f * t) * 0.48f + + MathF.Cos(MathF.Tau * 84f * t) * 0.30f + + MathF.Cos(MathF.Tau * 126f * t) * 0.18f + + MathF.Cos(MathF.Tau * 168f * t) * 0.10f; + float lfo = 0.82f + 0.18f * MathF.Cos(MathF.Tau * 14f * t); + s[i] = baseOsc * lfo + noise[i] * 0.22f; + } + NormalizePeak(s, 0.78f); + return s; + } + + private static float[] GenLoopTracked() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x202u, lpAlpha: 0.10f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float diesel = + MathF.Cos(MathF.Tau * 32f * t) * 0.52f + + MathF.Cos(MathF.Tau * 64f * t) * 0.34f + + MathF.Cos(MathF.Tau * 96f * t) * 0.20f + + MathF.Cos(MathF.Tau * 160f * t) * 0.10f; + float treadMod = 0.5f + 0.5f * MathF.Cos(MathF.Tau * 18f * t); + float treadClick = MathF.Pow(treadMod, 4f) * MathF.Cos(MathF.Tau * 240f * t) * 0.22f; + s[i] = diesel * (0.85f + 0.15f * treadMod) + treadClick + noise[i] * 0.25f; + } + NormalizePeak(s, 0.80f); + return s; + } + + private static float[] GenLoopHover() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x203u, lpAlpha: 0.20f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float turbine = + MathF.Cos(MathF.Tau * 55f * t) * 0.36f + + MathF.Cos(MathF.Tau * 110f * t) * 0.26f + + MathF.Cos(MathF.Tau * 220f * t) * 0.14f; + s[i] = turbine + noise[i] * 0.28f; + } + NormalizePeak(s, 0.72f); + return s; + } + + private static float[] GenLoopVtol() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x204u, lpAlpha: 0.15f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float chop = 0.55f + 0.45f * MathF.Cos(MathF.Tau * 16f * t); + float thump = MathF.Cos(MathF.Tau * 32f * t) * 0.40f + MathF.Cos(MathF.Tau * 64f * t) * 0.24f; + float whine = MathF.Cos(MathF.Tau * 210f * t) * 0.24f + MathF.Cos(MathF.Tau * 420f * t) * 0.10f; + s[i] = (thump + noise[i] * 0.42f) * chop + whine; + } + NormalizePeak(s, 0.80f); + return s; + } + + private static float[] GenLoopServo() + { + int n = SampleRate; + var s = new float[n]; + float[] noise = GeneratePeriodicFilteredNoise(n, 0x205u, lpAlpha: 0.28f); + for (int i = 0; i < n; i++) + { + float t = i / (float)n; + float hum = + MathF.Cos(MathF.Tau * 140f * t) * 0.34f + + MathF.Cos(MathF.Tau * 280f * t) * 0.26f + + MathF.Cos(MathF.Tau * 420f * t) * 0.10f; + float pulse = 0.88f + 0.12f * MathF.Cos(MathF.Tau * 6f * t); + s[i] = hum * pulse + noise[i] * 0.24f; + } + NormalizePeak(s, 0.74f); + return s; + } + + private static float[] GenRicochet() + { + int n = (int)(0.22f * SampleRate); + var s = new float[n]; + float p1 = 0f; + float p2 = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.002f); + float env = attack * MathF.Exp(-t * 18f); + float f1 = 1650f + 420f * MathF.Exp(-t * 32f); + float f2 = 2480f + 580f * MathF.Exp(-t * 28f); + float fm = MathF.Sin(MathF.Tau * 410f * t) * 0.35f * MathF.Exp(-t * 20f); + p1 += MathF.Tau * f1 / SampleRate; + p2 += MathF.Tau * f2 / SampleRate; + float fadeOut = u > 0.82f ? (1f - (u - 0.82f) / 0.18f) : 1f; + s[i] = (MathF.Sin(p1 + fm) * 0.58f + MathF.Sin(p2) * 0.42f) * env * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + + private static float[] GenArmorCrunch() + { + int n = (int)(0.30f * SampleRate); + var s = new float[n]; + uint rng = 0x302u; + float phase = 0f; + float lp = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.003f); + float freq = 52f + 88f * MathF.Exp(-t * 30f); + phase += MathF.Tau * freq / SampleRate; + float body = MathF.Sin(phase) * MathF.Exp(-t * 14f); + float clang = (MathF.Sin(MathF.Tau * 610f * t) + 0.6f * MathF.Sin(MathF.Tau * 945f * t)) * MathF.Exp(-t * 26f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.78f + white * 0.22f; + float crunch = lp * MathF.Exp(-t * 17f); + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = attack * (body * 0.68f + clang * 0.28f + crunch * 0.55f) * fadeOut; + } + NormalizePeak(s, 0.86f); + return s; + } + + private static float[] GenCoreImpact() + { + int n = (int)(0.34f * SampleRate); + var s = new float[n]; + uint rng = 0x303u; + float phase = 0f; + float lp = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.0025f); + float freq = 38f + 72f * MathF.Exp(-t * 24f); + phase += MathF.Tau * freq / SampleRate; + float punch = MathF.Sin(phase) * MathF.Exp(-t * 11f); + float snap = MathF.Sin(MathF.Tau * 1180f * t) * MathF.Exp(-t * 34f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.82f + white * 0.18f; + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = attack * (punch * 0.76f + snap * 0.34f + lp * 0.45f * MathF.Exp(-t * 14f)) * fadeOut; + } + NormalizePeak(s, 0.88f); + return s; + } + + private static float[] GenExplosion() + { + int n = (int)(1.15f * SampleRate); + var s = new float[n]; + uint rng = 0x304u; + float phase = 0f; + float lp = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float attack = MathF.Min(1f, t / 0.006f); + float freq = 22f + 43f * MathF.Exp(-t * 9f); + phase += MathF.Tau * freq / SampleRate; + float sub = MathF.Sin(phase) * MathF.Exp(-t * 3.8f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.88f + white * 0.12f; + float roar = lp * MathF.Exp(-t * 3.1f); + float crackle = white * 0.25f * MathF.Exp(-t * 9.5f); + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = attack * (sub * 0.70f + roar * 0.78f + crackle) * fadeOut; + } + NormalizePeak(s, 0.88f); + return s; + } + + private static float[] GenUiHitArmor() + { + int n = (int)(0.07f * SampleRate); + var s = new float[n]; + uint rng = 0x401u; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float env = MathF.Min(1f, t / 0.0015f) * MathF.Exp(-t * 58f); + float tone = MathF.Sin(MathF.Tau * 1380f * t) * 0.65f + MathF.Sin(MathF.Tau * 2240f * t) * 0.35f; + float tick = NextSignedNoise(ref rng) * 0.30f * MathF.Exp(-t * 90f); + float fadeOut = u > 0.78f ? (1f - (u - 0.78f) / 0.22f) : 1f; + s[i] = (tone * env + tick) * fadeOut; + } + NormalizePeak(s, 0.80f); + return s; + } + + private static float[] GenUiHitCore() + { + int n = (int)(0.11f * SampleRate); + var s = new float[n]; + uint rng = 0x402u; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float env = MathF.Min(1f, t / 0.0015f) * MathF.Exp(-t * 36f); + float tone = + MathF.Sin(MathF.Tau * 420f * t) * 0.50f + + MathF.Sin(MathF.Tau * 1080f * t) * 0.45f + + MathF.Sin(MathF.Tau * 1760f * t) * 0.25f; + float crunch = NextSignedNoise(ref rng) * 0.25f * MathF.Exp(-t * 60f); + float fadeOut = u > 0.80f ? (1f - (u - 0.80f) / 0.20f) : 1f; + s[i] = (tone * env + crunch) * fadeOut; + } + NormalizePeak(s, 0.84f); + return s; + } + + private static float[] GenUiHitKill() + { + int n = (int)(0.22f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float g1 = MathF.Min(1f, t / 0.002f) * MathF.Exp(-t * 24f); + float t2 = t - 0.075f; + float g2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.002f) * MathF.Exp(-t2 * 18f) : 0f; + float tone1 = MathF.Sin(MathF.Tau * 740f * t) + 0.35f * MathF.Sin(MathF.Tau * 1480f * t); + float tone2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 1110f * t2) + 0.35f * MathF.Sin(MathF.Tau * 2220f * t2)) : 0f; + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = (tone1 * g1 * 0.55f + tone2 * g2 * 0.65f) * fadeOut; + } + NormalizePeak(s, 0.85f); + return s; + } + + private static float[] GenUiOverheatAlarm() + { + int n = (int)(0.42f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + // Dual-pulse cockpit buzzer + float pulseA = (t < 0.16f) ? MathF.Sin(MathF.PI * (t / 0.16f)) : 0f; + float tB = t - 0.21f; + float pulseB = (tB >= 0f && tB < 0.17f) ? MathF.Sin(MathF.PI * (tB / 0.17f)) : 0f; + float env = pulseA + pulseB; + float wave = + MathF.Sin(MathF.Tau * 880f * t) * 0.55f + + MathF.Sin(MathF.Tau * 1175f * t) * 0.45f; + float fadeOut = u > 0.90f ? (1f - (u - 0.90f) / 0.10f) : 1f; + s[i] = wave * env * fadeOut; + } + NormalizePeak(s, 0.78f); + return s; + } + + private static float[] GenUiPickupModule() + { + int n = (int)(0.18f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float clunk = MathF.Sin(MathF.Tau * 240f * t) * MathF.Min(1f, t / 0.002f) * MathF.Exp(-t * 32f); + float t2 = t - 0.055f; + float latch = t2 >= 0f + ? (MathF.Sin(MathF.Tau * 580f * t2) + 0.4f * MathF.Sin(MathF.Tau * 870f * t2)) * MathF.Min(1f, t2 / 0.002f) * MathF.Exp(-t2 * 26f) + : 0f; + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = (clunk * 0.65f + latch * 0.55f) * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + + private static float[] GenUiPickupImperial() + { + int n = (int)(0.28f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float e1 = MathF.Min(1f, t / 0.003f) * MathF.Exp(-t * 13f); + float t2 = t - 0.055f; + float e2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.003f) * MathF.Exp(-t2 * 12f) : 0f; + float c1 = MathF.Sin(MathF.Tau * 880f * t) + 0.3f * MathF.Sin(MathF.Tau * 1760f * t); + float c2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 1320f * t2) + 0.35f * MathF.Sin(MathF.Tau * 2640f * t2)) : 0f; + float fadeOut = u > 0.86f ? (1f - (u - 0.86f) / 0.14f) : 1f; + s[i] = (c1 * e1 * 0.48f + c2 * e2 * 0.56f) * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + + private static float[] GeneratePeriodicFilteredNoise(int n, uint seed, float lpAlpha) + { + int fade = Math.Min(2048, n / 4); + var raw = new float[n + fade]; + uint rng = seed; + float lp = 0f; + float lp2 = 0f; + float smooth = Math.Clamp(lpAlpha, 0.02f, 0.12f); + for (int i = 0; i < raw.Length; i++) + { + float white = NextSignedNoise(ref rng); + lp = lp * (1f - smooth) + white * smooth; + lp2 = lp2 * 0.90f + lp * 0.10f; + raw[i] = lp2; + } + var result = new float[n]; + Array.Copy(raw, result, n); + for (int i = 0; i < fade; i++) + { + float w = i / (float)fade; + result[i] = raw[i] * w + raw[n + i] * (1f - w); + } + return result; + } + + private static float NextSignedNoise(ref uint state) + { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return ((state & 0xFFFFu) / 32767.5f) - 1f; + } + + private static void NormalizePeak(float[] samples, float targetPeak) + { + float peak = 0f; + for (int i = 0; i < samples.Length; i++) + { + float a = MathF.Abs(samples[i]); + if (a > peak) peak = a; + } + if (peak > 1e-6f) + { + float scale = targetPeak / peak; + for (int i = 0; i < samples.Length; i++) + { + samples[i] *= scale; + } + } + } + + private static void ClampNormalizePeak(float[] samples, float maxPeak) + { + float peak = 0f; + for (int i = 0; i < samples.Length; i++) + { + float a = MathF.Abs(samples[i]); + if (a > peak) peak = a; + } + if (peak > maxPeak && peak > 1e-6f) + { + float scale = maxPeak / peak; + for (int i = 0; i < samples.Length; i++) + { + samples[i] *= scale; + } + } + } + + private static byte[] FloatToPcm16(ReadOnlySpan samples) + { + var bytes = new byte[samples.Length * 2]; + for (int i = 0; i < samples.Length; i++) + { + float clamped = Math.Clamp(samples[i], -1f, 1f); + short val = (short)MathF.Round(clamped * 32767f); + bytes[i * 2] = (byte)(val & 0xFF); + bytes[i * 2 + 1] = (byte)((val >> 8) & 0xFF); + } + return bytes; + } + } +} diff --git a/src/RustToDust.Core/IClientArenaSession.cs b/src/RustToDust.Core/IClientArenaSession.cs index 06f14e3..1d1a449 100644 --- a/src/RustToDust.Core/IClientArenaSession.cs +++ b/src/RustToDust.Core/IClientArenaSession.cs @@ -50,6 +50,7 @@ namespace RustToDust.Core void BeginRenderFrame(double dt, float physicsAlpha); void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick); + void DrainSimEvents(List dest); bool RequestEquipCargo(int cargoIndex, string hardpointId); void RequestNewMatch(int seed, ArenaMapKind mapKind); diff --git a/src/RustToDust.Net/ListenHostArenaSession.cs b/src/RustToDust.Net/ListenHostArenaSession.cs index a95663c..e5dfc7a 100644 --- a/src/RustToDust.Net/ListenHostArenaSession.cs +++ b/src/RustToDust.Net/ListenHostArenaSession.cs @@ -70,8 +70,10 @@ namespace RustToDust.Net _host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); } + public void DrainSimEvents(List dest) => _host.DrainHostEvents(dest); + public bool RequestEquipCargo(int cargoIndex, string hardpointId) => - _host.Session.TryEquipCargo(0, cargoIndex, hardpointId); + _host.TryEquipHostCargo(cargoIndex, hardpointId); public void RequestNewMatch(int seed, ArenaMapKind mapKind) => _host.ResetMatch(seed, mapKind); diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index f39bbda..3bcf51a 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -48,6 +48,7 @@ namespace RustToDust.Net private readonly Dictionary> _contenderWalkerTimelines = new(); private readonly Dictionary> _spectatorWalkerTimelines = new(); private readonly Dictionary _pingSamples = new(); + private readonly List _pendingClientEvents = new(); private MatchState _viewState; private Box3DSoaWorld? _predWorld; @@ -238,6 +239,16 @@ namespace RustToDust.Net } } + public void DrainSimEvents(List dest) + { + if (_pendingClientEvents.Count == 0) + { + return; + } + dest.AddRange(_pendingClientEvents); + _pendingClientEvents.Clear(); + } + public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick) { ObjectDisposedException.ThrowIf(_disposed, this); @@ -676,6 +687,7 @@ namespace RustToDust.Net _prevInteractPressed = false; _pendingChassisSwapSnap = false; _unackedInputs.Clear(); + _pendingClientEvents.Clear(); _predErrorPos = Vector3.Zero; _predErrorRot = Quaternion.Identity; Array.Clear(_lastCombatSpecSeenSeq); @@ -1324,6 +1336,11 @@ namespace RustToDust.Net ApplyInitialMatchState(reset.FullInitialState, reset.AssignedContenderId); break; } + _pendingClientEvents.Add(batch.Events[i]); + } + if (_pendingClientEvents.Count > 4096) + { + _pendingClientEvents.RemoveRange(0, _pendingClientEvents.Count - 4096); } } diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs index 6bdbf18..ceabc2b 100644 --- a/src/RustToDust.Net/ServerMatchHost.cs +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -46,6 +46,7 @@ namespace RustToDust.Net private readonly HashSet _retiredTransportPeers = new(); private readonly Dictionary _reconnectTokens = new(); private readonly List _stepEvents = new(); + private readonly List _hostPendingEvents = new(); private readonly List _terrainStampHistory = new(); private readonly int _maxHumans; private readonly double _autoRestartSec; @@ -120,6 +121,27 @@ namespace RustToDust.Net } } + public void DrainHostEvents(List dest) + { + if (_hostPendingEvents.Count == 0) + { + return; + } + dest.AddRange(_hostPendingEvents); + _hostPendingEvents.Clear(); + } + + public bool TryEquipHostCargo(int cargoIndex, string hardpointId) + { + if (!_hostContenderId.HasValue) return false; + bool ok = _session.TryEquipCargo(_hostContenderId.Value, cargoIndex, hardpointId); + if (ok) + { + _session.DrainStepEvents(_hostPendingEvents); + } + return ok; + } + public void ResetMatch(int seed, ArenaMapKind mapKind) { if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count) @@ -133,6 +155,7 @@ namespace RustToDust.Net _roundCompletedElapsed = 0f; _terrainStampHistory.Clear(); _stepEvents.Clear(); + _hostPendingEvents.Clear(); _reconnectTokens.Clear(); if (_hostContenderId.HasValue) @@ -180,6 +203,14 @@ namespace RustToDust.Net _simTick++; _session.DrainStepEvents(_stepEvents); + if (_hostContenderId.HasValue && _stepEvents.Count > 0) + { + _hostPendingEvents.AddRange(_stepEvents); + if (_hostPendingEvents.Count > 4096) + { + _hostPendingEvents.RemoveRange(0, _hostPendingEvents.Count - 4096); + } + } for (int i = 0; i < _stepEvents.Count; i++) { if (_stepEvents[i] is TerrainStampEvent ts) diff --git a/src/RustToDust.Ymir/LocalArenaSession.cs b/src/RustToDust.Ymir/LocalArenaSession.cs index 242be7c..53f59d2 100644 --- a/src/RustToDust.Ymir/LocalArenaSession.cs +++ b/src/RustToDust.Ymir/LocalArenaSession.cs @@ -7,7 +7,7 @@ namespace RustToDust.Ymir { public sealed class LocalArenaSession : IClientArenaSession { - private readonly List _discardEvents = new(); + private readonly List _pendingEvents = new(); public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null) { @@ -55,16 +55,37 @@ namespace RustToDust.Ymir } Inner.SetHumanInput(0, input); Inner.Step(); - _discardEvents.Clear(); - Inner.DrainStepEvents(_discardEvents); + Inner.DrainStepEvents(_pendingEvents); + if (_pendingEvents.Count > 4096) + { + _pendingEvents.RemoveRange(0, _pendingEvents.Count - 4096); + } } - public bool RequestEquipCargo(int cargoIndex, string hardpointId) => - Inner.TryEquipCargo(0, cargoIndex, hardpointId); + public void DrainSimEvents(List dest) + { + if (_pendingEvents.Count == 0) + { + return; + } + dest.AddRange(_pendingEvents); + _pendingEvents.Clear(); + } + + public bool RequestEquipCargo(int cargoIndex, string hardpointId) + { + bool ok = Inner.TryEquipCargo(0, cargoIndex, hardpointId); + if (ok) + { + Inner.DrainStepEvents(_pendingEvents); + } + return ok; + } public void RequestNewMatch(int seed, ArenaMapKind mapKind) { string? name = LocalContender.Name; + _pendingEvents.Clear(); Inner.Dispose(); Inner = new ArenaSession(seed, mapKind, slot0Human: true); if (!string.IsNullOrWhiteSpace(name)) diff --git a/tests/RustToDust.Tests/AudioSynthTests.cs b/tests/RustToDust.Tests/AudioSynthTests.cs new file mode 100644 index 0000000..ea110ff --- /dev/null +++ b/tests/RustToDust.Tests/AudioSynthTests.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Numerics; +using RustToDust.Client; +using RustToDust.Core; +using RustToDust.Core.Audio; +using RustToDust.Net; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class AudioSynthTests +{ + private static readonly string[] ExpectedHavenWavs = + { + "mg_shot_01.wav", "mg_shot_02.wav", "mg_tail.wav", + "ac_light_01.wav", "ac_light_02.wav", "ac_med_01.wav", "ac_rotary.wav", + "flak_blast_01.wav", "flak_blast_02.wav", "cannon_heavy_01.wav", "cannon_heavy_02.wav", + "pd_bark_01.wav", "pd_bark_02.wav", "pd_laser.wav", + "rocket_salvo_01.wav", "rocket_salvo_02.wav", + "plasma_ppc_01.wav", "plasma_ppc_02.wav", "lance_beam_01.wav", "laser_heavy_01.wav", "gauss_rail_01.wav", + "mech_reload_bolt.wav", "mech_quick_bolt.wav", "mech_eject.wav", "mech_turret_servo.wav" + }; + + private static string LocateAssetsAudioDir() + { + string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + string assetsDir = Directory.GetParent(vehiclesDir)?.FullName + ?? throw new DirectoryNotFoundException("Could not locate assets directory."); + return Path.Combine(assetsDir, "audio"); + } + + [Fact] + public void CuratedHavenWavs_AreExactly25ValidMono44100PcmUnderBudgetWithZeroThirdPartyFiles() + { + string audioDir = LocateAssetsAudioDir(); + string havenDir = Path.Combine(audioDir, "haven"); + Assert.True(Directory.Exists(havenDir), $"Missing curated Haven directory: {havenDir}"); + + string[] allAudioFiles = Directory.GetFiles(audioDir, "*", SearchOption.AllDirectories); + foreach (string filePath in allAudioFiles) + { + string name = Path.GetFileName(filePath); + Assert.False(name.StartsWith("SW01_", StringComparison.OrdinalIgnoreCase), $"Forbidden SW01 file found: {name}"); + Assert.False(name.StartsWith("MW4", StringComparison.OrdinalIgnoreCase), $"Forbidden MW4 file found: {name}"); + Assert.False(name.StartsWith("Utilities", StringComparison.OrdinalIgnoreCase), $"Forbidden Utilities file found: {name}"); + Assert.False(string.Equals(name, "desktop.ini", StringComparison.OrdinalIgnoreCase), $"Forbidden desktop.ini found: {filePath}"); + } + + string[] havenFiles = Directory.GetFiles(havenDir); + Assert.Equal(25, havenFiles.Length); + + var actualNames = havenFiles.Select(Path.GetFileName).OrderBy(x => x, StringComparer.Ordinal).ToArray(); + var expectedSorted = ExpectedHavenWavs.OrderBy(x => x, StringComparer.Ordinal).ToArray(); + Assert.Equal(expectedSorted, actualNames); + + long totalBytes = 0; + foreach (string wavPath in havenFiles) + { + totalBytes += new FileInfo(wavPath).Length; + WavPcmInfo info = WavFileReader.ReadMonoOrStereo16(wavPath); + + Assert.Equal(44100, info.SampleRate); + Assert.Equal(1, info.Channels); + Assert.Equal(16, info.BitsPerSample); + Assert.True(info.FloatSamples.Length >= 4410, $"{Path.GetFileName(wavPath)} unexpectedly short."); + + float peak = 0f; + double sumSq = 0.0; + for (int i = 0; i < info.FloatSamples.Length; i++) + { + float s = info.FloatSamples[i]; + Assert.True(float.IsFinite(s)); + float a = MathF.Abs(s); + if (a > peak) peak = a; + sumSq += s * s; + } + double rms = Math.Sqrt(sumSq / info.FloatSamples.Length); + Assert.True(rms > 0.01, $"{Path.GetFileName(wavPath)} is silent (RMS={rms:F5})."); + Assert.True(peak <= 0.95f, $"{Path.GetFileName(wavPath)} clips/exceeds 0.95 (peak={peak:F4})."); + } + + Assert.True(totalBytes < 4L * 1024L * 1024L, $"Curated Haven WAV total size {totalBytes} bytes exceeds 4 MB."); + } + + [Fact] + public void AttributionFile_ExistsAndCreditsHavenKendrick() + { + string attributionPath = Path.Combine(LocateAssetsAudioDir(), "ATTRIBUTION.md"); + Assert.True(File.Exists(attributionPath), $"Missing attribution file: {attributionPath}"); + string text = File.ReadAllText(attributionPath); + Assert.Contains("Haven Kendrick", text, StringComparison.Ordinal); + Assert.Contains("WetMixMode", text, StringComparison.Ordinal); + } + + [Fact] + public void PcmSynth_AllCuesAreFiniteNonSilentNonClippingInBothWetAndDryModes_AndWetAddsTailEnergy() + { + Dictionary wetClips = PcmSynth.SynthesizeAll(wetMixMode: true); + Dictionary dryClips = PcmSynth.SynthesizeAll(wetMixMode: false); + + Assert.Equal(PcmSynth.CueRegistry.Count, wetClips.Count); + Assert.Equal(PcmSynth.CueRegistry.Count, dryClips.Count); + + foreach (var (_, key) in PcmSynth.CueRegistry) + { + PcmClipData wet = wetClips[key]; + PcmClipData dry = dryClips[key]; + + Assert.Equal(44100, wet.SampleRate); + Assert.Equal(44100, dry.SampleRate); + Assert.Equal(wet.IsLoop, dry.IsLoop); + + AssertValidPcmBounds(wet, key + " (wet)"); + AssertValidPcmBounds(dry, key + " (dry)"); + + if (wet.IsLoop) + { + Assert.Equal(44100, wet.Samples.Length); + Assert.Equal(44100, dry.Samples.Length); + float wetWrapDiff = MathF.Abs(wet.Samples[^1] - wet.Samples[0]); + float dryWrapDiff = MathF.Abs(dry.Samples[^1] - dry.Samples[0]); + Assert.True(wetWrapDiff < 0.02f, $"Wet loop '{key}' wrap click: {wetWrapDiff:F5}"); + Assert.True(dryWrapDiff < 0.02f, $"Dry loop '{key}' wrap click: {dryWrapDiff:F5}"); + + // Wet room stage alters loop signal measurably vs dry + double diffSq = 0.0; + for (int i = 0; i < wet.Samples.Length; i++) + { + double d = wet.Samples[i] - dry.Samples[i]; + diffSq += d * d; + } + Assert.True(Math.Sqrt(diffSq / wet.Samples.Length) > 0.005, $"Wet loop '{key}' did not measurably differ from dry."); + } + else + { + // Wet one-shots carry real diffused reverb tail beyond the pure dry buffer length + // and measurably higher late/tail energy than the pure dry buffer. + Assert.True(wet.Samples.Length > dry.Samples.Length, $"Wet one-shot '{key}' should include reverb tail."); + int lateStart = (int)(dry.Samples.Length * 0.90); + double dryLateEnergy = 0.0; + for (int i = lateStart; i < dry.Samples.Length; i++) + { + dryLateEnergy += dry.Samples[i] * dry.Samples[i]; + } + double wetLateEnergy = 0.0; + for (int i = lateStart; i < wet.Samples.Length; i++) + { + wetLateEnergy += wet.Samples[i] * wet.Samples[i]; + } + double postDryEnergy = 0.0; + for (int i = dry.Samples.Length; i < wet.Samples.Length; i++) + { + postDryEnergy += wet.Samples[i] * wet.Samples[i]; + } + Assert.True(postDryEnergy > 0.001, $"Wet one-shot '{key}' has zero post-dry tail energy ({postDryEnergy:F6})."); + Assert.True(wetLateEnergy > dryLateEnergy * 1.15 + 0.001, + $"Wet one-shot '{key}' lacks measurable reverb tail energy (dryLate={dryLateEnergy:F4}, wetLate={wetLateEnergy:F4})."); + } + } + } + + [Fact] + public void WalkerFootstepTracker_TriggersStrictlyOnStanceTouchdownEdges() + { + var tracker = new WalkerFootstepTracker(); + var terrain = new TerrainField(seed: 42); + var pulses = new List(); + + var snap = new WalkerVisualSnapshot + { + LegCount = 2, + GeomScale = 1f, + ComPos = new Vector3(10f, 3f, 20f), + ComRot = Quaternion.Identity + }; + + // 1. Standing still with high load: first sighting + 20 frames -> 0 footsteps (no spawn pop, no spam) + snap.LoadG[0] = 1.0f; + snap.LoadG[1] = 1.0f; + for (int f = 0; f < 20; f++) + { + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + } + Assert.Empty(pulses); + + // 2. Airborne (swing) across 20 frames -> 0 footsteps, legs become armed + snap.LoadG[0] = 0.0f; + snap.LoadG[1] = 0.0f; + for (int f = 0; f < 20; f++) + { + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + } + Assert.Empty(pulses); + + // 3. Touchdown leg 0 rising across sub-frames -> fires EXACTLY ONCE + snap.LoadG[0] = 0.25f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + snap.LoadG[0] = 0.80f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + snap.LoadG[0] = 1.40f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses); + Assert.Single(pulses); + Assert.Equal(0, pulses[0].LegIndex); + Assert.InRange(MathF.Abs(pulses[0].WorldPos.Y - terrain.SampleHeight(pulses[0].WorldPos.X, pulses[0].WorldPos.Z)), 0f, 0.01f); + + // 4. Re-arm and bounce faster than 0.18s cooldown -> suppressed by cooldown + pulses.Clear(); + snap.LoadG[0] = 0.02f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses); + snap.LoadG[0] = 0.50f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses); + Assert.Empty(pulses); + + // 5. After cooldown expires (> 0.18s), re-arm + touchdown fires again + snap.LoadG[0] = 0.02f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.20f, pulses); + snap.LoadG[0] = 0.60f; + tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses); + Assert.Single(pulses); + } + + [Fact] + public void ClientArenaSession_DrainSimEvents_WorksInSoloAndLoopbackRemote() + { + using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "AudioTester"); + IClientArenaSession localIface = local; + var events = new List(); + + var player = local.Inner.State.Contenders[0]; + var input = new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: player.X + 25f, + AimWorldZ: player.Z, + Fire: true, + InteractPickup: false, + Brake: false); + + for (int i = 0; i < 10; i++) + { + localIface.SubmitLocalInput(in input, isPhysicsTick: true); + } + localIface.DrainSimEvents(events); + Assert.Contains(events, e => e is ShotFiredEvent s && !s.IsSpectatorShooter && s.ShooterId == 0); + + // Draining again returns empty until new steps occur + events.Clear(); + localIface.DrainSimEvents(events); + Assert.Empty(events); + + // Loopback host + remote receives ShotFiredEvent through IClientArenaSession.DrainSimEvents + using var host = new ServerMatchHost(IPAddress.Loopback, port: 0, seed: 42, mapKind: ArenaMapKind.Desert); + using var remote = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "AudioRemote"); + IClientArenaSession remoteIface = remote; + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + for (int t = 0; t < 15 && !remote.IsJoined; t++) + { + host.StepOnce(nowMs + t * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + Assert.True(remote.IsJoined); + + var rLocal = remoteIface.LocalContender; + var fireInput = new PlayerInput(0f, 0f, rLocal.X + 30f, rLocal.Z, true, false, false); + for (int t = 0; t < 10; t++) + { + remoteIface.SubmitLocalInput(in fireInput, isPhysicsTick: true); + host.StepOnce(nowMs + 300 + t * 16); + remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f); + } + events.Clear(); + remoteIface.DrainSimEvents(events); + Assert.Contains(events, e => e is ShotFiredEvent); + } + + private static void AssertValidPcmBounds(PcmClipData clip, string label) + { + Assert.True(clip.Samples.Length > 0, $"{label} empty"); + float peak = 0f; + double sumSq = 0.0; + for (int i = 0; i < clip.Samples.Length; i++) + { + float s = clip.Samples[i]; + Assert.True(float.IsFinite(s), $"{label} has non-finite sample at {i}"); + float a = MathF.Abs(s); + if (a > peak) peak = a; + sumSq += s * s; + } + double rms = Math.Sqrt(sumSq / clip.Samples.Length); + Assert.True(rms > 0.01, $"{label} is silent (RMS={rms:F5})"); + Assert.True(peak <= 0.98f, $"{label} clips (peak={peak:F4})"); + } +} diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj index 9fabf52..4a60325 100644 --- a/tests/RustToDust.Tests/RustToDust.Tests.csproj +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -14,6 +14,10 @@ + + + + diff --git a/tools/audio/curate_haven_audio.py b/tools/audio/curate_haven_audio.py new file mode 100644 index 0000000..1204b79 --- /dev/null +++ b/tools/audio/curate_haven_audio.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Curate 25 original Haven Kendrick MWO WAVs into mono 44.1 kHz 16-bit PCM WAVs. + +Strictly read-only on D:\\Google Drive\\Gamecult\\Aetheria\\Audio\\WIP & Ideas\\Haven\\MWO Soundpack. +Explicitly excludes SW01_*, MW4*, Utilities-*, and desktop.ini. +""" + +from __future__ import annotations + +import array +import math +import os +import subprocess +import sys +import wave +from dataclasses import dataclass +from pathlib import Path + +SOURCE_DIR = Path(r"D:\Google Drive\Gamecult\Aetheria\Audio\WIP & Ideas\Haven\MWO Soundpack") +REPO_ROOT = Path(__file__).resolve().parents[2] +DEST_DIR = REPO_ROOT / "assets" / "audio" / "haven" +TARGET_SAMPLE_RATE = 44100 +TARGET_PEAK = 0.89 + +FORBIDDEN_PREFIXES = ("SW01_", "MW4", "Utilities-") +FORBIDDEN_EXACT = {"desktop.ini"} + + +@dataclass(frozen=True) +class ClipSpec: + dest_name: str + src_name: str + lead_trim_s: float + max_dur_s: float + fade_out_s: float + auto_trim_lead: bool = True + + +CLIPS: tuple[ClipSpec, ...] = ( + # Machine guns (mg_762) + ClipSpec("mg_shot_01.wav", "ClanMG3_fixed.wav", 0.0, 0.24, 0.035), + ClipSpec("mg_shot_02.wav", "New_MG 2.wav", 0.0, 0.24, 0.035), + ClipSpec("mg_tail.wav", "mgtail.wav", 0.0, 0.66, 0.030), + # Autocannons (autocannon) + ClipSpec("ac_light_01.wav", "AC5.wav", 0.0, 0.85, 0.040), + ClipSpec("ac_light_02.wav", "AC5_2.wav", 0.065, 0.80, 0.040, auto_trim_lead=False), + ClipSpec("ac_med_01.wav", "AC10.wav", 0.0, 0.95, 0.040), + ClipSpec("ac_rotary.wav", "RAC5.wav", 0.0, 1.01, 0.040), + # Flak & heavy recoilless (flak, recoilless) + ClipSpec("flak_blast_01.wav", "ClanLBX7_2019.wav", 0.0, 1.15, 0.045), + ClipSpec("flak_blast_02.wav", "IS_LBX20_2.wav", 0.0, 1.35, 0.045), + ClipSpec("cannon_heavy_01.wav", "BigCannon1.wav", 0.070, 1.80, 0.050, auto_trim_lead=False), + ClipSpec("cannon_heavy_02.wav", "AC20.wav", 0.0, 1.50, 0.050), + # Point defense (pd_flak, aegis_pd) + ClipSpec("pd_bark_01.wav", "AMS3.wav", 0.0, 0.28, 0.030), + ClipSpec("pd_bark_02.wav", "amsTP.wav", 0.0, 0.28, 0.030), + ClipSpec("pd_laser.wav", "laserams.wav", 0.0, 0.32, 0.030), + # Missiles / Rockets (Cut 7) + ClipSpec("rocket_salvo_01.wav", "MRM1.wav", 0.0, 1.20, 0.045), + ClipSpec("rocket_salvo_02.wav", "NEWSRM1.wav", 0.0, 1.35, 0.045), + # Energy / Plasma / Thermal Lance / Gauss (touring_plasma, gilded_lance, Cut 7) + ClipSpec("plasma_ppc_01.wav", "Snub_PPC2.wav", 0.0, 1.25, 0.045), + ClipSpec("plasma_ppc_02.wav", "PPcSWEET.wav", 0.045, 0.78, 0.040, auto_trim_lead=False), + ClipSpec("lance_beam_01.wav", "CPPC_DEC2018_2.wav", 0.0, 1.55, 0.050), + ClipSpec("laser_heavy_01.wav", "CLL3.wav", 0.0, 1.20, 0.045), + ClipSpec("gauss_rail_01.wav", "Gauss Sweet 1.wav", 0.015, 1.15, 0.045, auto_trim_lead=False), + # Mechanical / Bolt-clank / Chassis swap + ClipSpec("mech_reload_bolt.wav", "CannonReload2.wav", 0.0, 1.25, 0.045), + ClipSpec("mech_quick_bolt.wav", "reload.wav", 0.0, 0.94, 0.040), + ClipSpec("mech_eject.wav", "eject.wav", 0.0, 0.74, 0.035), + ClipSpec("mech_turret_servo.wav", "turret9.wav", 0.0, 1.10, 0.040), +) + + +def validate_source_name(name: str) -> None: + if name in FORBIDDEN_EXACT or any(name.startswith(p) for p in FORBIDDEN_PREFIXES): + raise ValueError(f"Refusing forbidden third-party/system file: {name}") + + +def decode_mono_f32(src_path: Path) -> list[float]: + cmd = [ + "ffmpeg", + "-v", + "error", + "-i", + str(src_path), + "-ac", + "1", + "-ar", + str(TARGET_SAMPLE_RATE), + "-f", + "f32le", + "-", + ] + proc = subprocess.run(cmd, capture_output=True, check=False) + if proc.returncode != 0: + err = proc.stderr.decode("utf-8", errors="replace").strip() + raise RuntimeError(f"ffmpeg failed on '{src_path}': {err}") + arr = array.array("f") + arr.frombytes(proc.stdout) + if sys.byteorder != "little": + arr.byteswap() + return list(arr) + + +def process_clip(spec: ClipSpec, src_path: Path, dst_path: Path) -> tuple[float, float, int]: + samples = decode_mono_f32(src_path) + if not samples: + raise RuntimeError(f"Decoded zero samples from '{src_path}'") + + lead_idx = int(round(spec.lead_trim_s * TARGET_SAMPLE_RATE)) + if lead_idx > 0 and lead_idx < len(samples): + samples = samples[lead_idx:] + + if spec.auto_trim_lead: + # Trim only genuinely silent leading padding (>10 ms below -54 dBFS) + silence_thresh = 0.002 + first_active = 0 + for idx, s in enumerate(samples): + if abs(s) >= silence_thresh: + first_active = idx + break + if first_active > int(0.010 * TARGET_SAMPLE_RATE): + samples = samples[first_active:] + + max_samples = int(round(spec.max_dur_s * TARGET_SAMPLE_RATE)) + if len(samples) > max_samples: + samples = samples[:max_samples] + + # Trim trailing near-silence beyond 15ms if tail is quieter than -60 dBFS, keeping at least 150ms + min_keep = min(len(samples), int(0.15 * TARGET_SAMPLE_RATE)) + last_active = len(samples) - 1 + while last_active > min_keep and abs(samples[last_active]) < 0.001: + last_active -= 1 + samples = samples[: min(len(samples), last_active + int(0.015 * TARGET_SAMPLE_RATE))] + + n = len(samples) + if n < 256: + raise RuntimeError(f"Clip '{spec.dest_name}' became too short ({n} samples)") + + # Short 4ms fade-in only if attack begins non-zero, avoiding click + fade_in = min(n // 8, int(0.004 * TARGET_SAMPLE_RATE)) + if fade_in > 0 and abs(samples[0]) > 0.005: + for i in range(fade_in): + gain = 0.5 * (1.0 - math.cos(math.pi * (i + 0.5) / fade_in)) + samples[i] *= gain + + # Smooth cosine fade-out on tail + fade_out = min(n // 2, int(round(spec.fade_out_s * TARGET_SAMPLE_RATE))) + if fade_out > 0: + start = n - fade_out + for i in range(fade_out): + gain = 0.5 * (1.0 + math.cos(math.pi * (i + 1) / fade_out)) + samples[start + i] *= gain + + peak = max(abs(x) for x in samples) + if peak < 1e-4: + raise RuntimeError(f"Clip '{spec.dest_name}' is silent (peak={peak})") + + scale = TARGET_PEAK / peak + pcm = array.array("h") + final_peak = 0.0 + for s in samples: + v = max(-1.0, min(1.0, s * scale)) + final_peak = max(final_peak, abs(v)) + pcm.append(int(round(v * 32767.0))) + + if sys.byteorder != "little": + pcm.byteswap() + + with wave.open(str(dst_path), "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) + wf.setframerate(TARGET_SAMPLE_RATE) + wf.writeframes(pcm.tobytes()) + + size_bytes = dst_path.stat().st_size + dur_s = n / TARGET_SAMPLE_RATE + return dur_s, final_peak, size_bytes + + +def main() -> int: + if len(CLIPS) != 25: + raise AssertionError(f"Expected exactly 25 clips, got {len(CLIPS)}") + if not SOURCE_DIR.is_dir(): + raise FileNotFoundError(f"Source directory not found: {SOURCE_DIR}") + + DEST_DIR.mkdir(parents=True, exist_ok=True) + expected_names = {c.dest_name for c in CLIPS} + for existing in DEST_DIR.glob("*"): + if existing.is_file() and existing.name not in expected_names: + existing.unlink() + + total_bytes = 0 + for spec in CLIPS: + validate_source_name(spec.src_name) + src_path = SOURCE_DIR / spec.src_name + if not src_path.is_file(): + raise FileNotFoundError(f"Missing Haven source WAV: {src_path}") + dst_path = DEST_DIR / spec.dest_name + dur_s, peak, size_bytes = process_clip(spec, src_path, dst_path) + total_bytes += size_bytes + print(f" {spec.dest_name:<22} <- {spec.src_name:<22} {dur_s:5.2f}s peak={peak:.3f} {size_bytes/1024:6.1f} KiB") + + produced = sorted(p.name for p in DEST_DIR.glob("*.wav")) + if len(produced) != 25: + raise RuntimeError(f"Expected 25 WAVs in {DEST_DIR}, found {len(produced)}") + + total_mib = total_bytes / (1024.0 * 1024.0) + print(f"Curated {len(produced)} WAVs into {DEST_DIR} (total {total_mib:.2f} MiB)") + if total_mib >= 4.0: + raise RuntimeError(f"Total audio size {total_mib:.2f} MiB exceeds 4.0 MiB budget") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())