using System; using System.Collections.Generic; using Godot; using RustToDust.Core; using RustToDust.Ymir; 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<(byte Kind, int ShooterId, byte NodeIdx), float> _ordnanceDedupeExpiry = 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 _pendingCraterStamps = new(8); 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(); _ordnanceDedupeExpiry.Clear(); _lastContenderChassis.Clear(); _lastContenderLoadoutVer.Clear(); _recentExplosionPoints.Clear(); _pendingCraterStamps.Clear(); _overheatAlarmCooldown = 0f; } public void ResetForSession(IClientArenaSession? session) { ClearAll(); SeedLoadoutBaselines(session); } private void SeedLoadoutBaselines(IClientArenaSession? session) { if (session is null) { return; } var contenders = session.ViewState.Contenders; for (int i = 0; i < contenders.Count; i++) { var c = contenders[i]; if (string.IsNullOrEmpty(c.Grid.Spec.Id)) { continue; } if (!_lastContenderChassis.ContainsKey(c.Id)) { _lastContenderChassis[c.Id] = c.Grid.Spec.Id; } if (!_lastContenderLoadoutVer.ContainsKey(c.Id)) { _lastContenderLoadoutVer[c.Id] = c.LoadoutVersion; } } } 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 int CountActiveVoicesForClip(string clipKey) { int count = 0; for (int i = 0; i < _oneShotSlots.Length; i++) { if (_oneShotSlots[i].Active && string.Equals(_oneShotSlots[i].ClipKey, clipKey, StringComparison.Ordinal)) { count++; } } return count; } public int CountActiveUiVoicesForClip(string clipKey) { int count = 0; for (int i = 0; i < _uiSlots.Length; i++) { if (_uiSlots[i].Active && string.Equals(_uiSlots[i].ClipKey, clipKey, StringComparison.Ordinal)) { count++; } } return count; } 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; SeedLoadoutBaselines(session); 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; _pendingCraterStamps.Clear(); for (int i = 0; i < events.Count; i++) { switch (events[i]) { case MatchResetEvent: ClearAll(); SeedLoadoutBaselines(session); break; case ShotFiredEvent shot: HandleShotFired(shot, localId, listenerPos); break; case HitImpactEvent hit: HandleHitImpact(hit, localId, listenerPos); break; case ContenderEliminatedEvent elim: HandleContenderEliminated(session, state, elim, listenerPos); break; case SpectatorDestroyedEvent sdet: HandleSpectatorDestroyed(session, state, sdet, listenerPos); break; case TerrainStampEvent stamp: if (stamp.Kind == (byte)TerrainStampKind.Crater && stamp.Radius >= 3.0f) { _pendingCraterStamps.Add(stamp); } 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(session, state, loadout, localId, listenerPos); break; case DropPodEvent dpe: HandleDropPodEvent(dpe, localId, listenerPos); break; case OrdnanceNodeEvent ord: HandleOrdnanceNodeEvent(ord, localId, listenerPos); break; } } for (int i = 0; i < _pendingCraterStamps.Count; i++) { var stamp = _pendingCraterStamps[i]; 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); } } _pendingCraterStamps.Clear(); } 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(IClientArenaSession session, MatchState state, ContenderEliminatedEvent elim, Vector3 listenerPos) { if (elim.VictimId != session.LocalContenderId && !session.IsContenderVisible(elim.VictimId)) return; 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(IClientArenaSession session, MatchState state, SpectatorDestroyedEvent sdet, Vector3 listenerPos) { if (!session.IsSpectatorVisible(sdet.SpectatorId)) return; SpectatorState? s = null; var specs = state.Spectators.Spectators; for (int i = 0; i < specs.Count; i++) { if (specs[i].Id == sdet.SpectatorId) { s = specs[i]; break; } } if (s is null) { int sIdx = sdet.SpectatorId >= 1000 ? sdet.SpectatorId - 1000 : sdet.SpectatorId; if (sIdx >= 0 && sIdx < specs.Count) { s = specs[sIdx]; } } if (s is null) return; 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(IClientArenaSession session, 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 (session.IsContenderVisible(id) && 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 HandleDropPodEvent(DropPodEvent dpe, int localId, Vector3 listenerPos) { var kind = (DropPodEventKind)dpe.Kind; Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); bool isLocal = dpe.ContenderId == localId; switch (kind) { case DropPodEventKind.WaveAnnounced: if (dpe.WaveIndex > 0 || dpe.RespawnsClosed) { PlayUi("ui_drop_wave", volumeDb: -3.5f, pitchScale: dpe.RespawnsClosed ? 0.85f : 1.0f); } break; case DropPodEventKind.PodLaunched: if (isLocal) { PlayUi("pod_petal_pop", volumeDb: -7.5f, pitchScale: 0.72f); } break; case DropPodEventKind.PodRetroBurnStart: PlayOneShot3D( "impact_explosion", pos, listenerPos, isLocal ? PriorityLocalAction : PriorityNearCombat, volumeDb: isLocal ? -3.0f : -6.5f, pitchScale: 0.68f, isLocalSource: isLocal, sourceEntityId: dpe.PodId); break; case DropPodEventKind.PodTouchdownBlowPetals: RecordExplosionPoint(dpe.X, dpe.Z); int prio = isLocal ? PriorityLocalAction : PriorityLocalImpactOrKill; PlayOneShot3D( "pod_slam", pos, listenerPos, prio, volumeDb: isLocal ? -0.5f : -4.0f, pitchScale: NextPitchJitter(0.94f, 1.06f), isLocalSource: isLocal, sourceEntityId: dpe.PodId); PlayOneShot3D( "pod_petal_pop", pos, listenerPos, prio, volumeDb: isLocal ? -1.5f : -5.5f, pitchScale: NextPitchJitter(0.95f, 1.05f), isLocalSource: isLocal, sourceEntityId: dpe.PodId); break; } } private void HandleOrdnanceNodeEvent(OrdnanceNodeEvent ord, int localId, Vector3 listenerPos) { var dedupeKey = (ord.Kind, ord.ShooterId, ord.NodeDefIndex); if (_ordnanceDedupeExpiry.TryGetValue(dedupeKey, out float expiry) && _audioTime < expiry) { DedupedCount++; return; } _ordnanceDedupeExpiry[dedupeKey] = _audioTime + 0.065f; PruneExpiredMap(_ordnanceDedupeExpiry); OrdnanceNodeDef? def = null; if (ord.WeaponKey is { } wk) { var spec = ProceduralWeaponGenerator.Generate(wk); def = ord.NodeDefIndex < spec.FlattenedNodes.Length ? spec.FlattenedNodes[ord.NodeDefIndex] : spec.RootNode; } var kind = (OrdnanceEventKind)ord.Kind; bool isLocal = !ord.IsSpectatorShooter && ord.ShooterId == localId; Vector3 pos = new(ord.PosX, ord.PosY, ord.PosZ); float distSq = pos.DistanceSquaredTo(listenerPos); int priority = isLocal ? PriorityLocalAction : (distSq <= 90f * 90f ? PriorityNearCombat : PriorityDistantCombat); string? clipKey = null; float volDb = isLocal ? -2.0f : -4.2f; float pitch = NextPitchJitter(0.94f, 1.06f); uint v = _variantCounter++; switch (kind) { case OrdnanceEventKind.Spawned: if (ord.ParentOrdnanceId != 0) { return; // Split event already provides audio cue } clipKey = SelectAudioClassClip(def?.AudioClass ?? OrdnanceAudioClass.RocketSalvo, v); break; case OrdnanceEventKind.StageTransition: if (def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile) { clipKey = (v & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02"; volDb = isLocal ? -1.5f : -3.5f; } else if (def?.Motion == OrdnanceMotion.LoiterOrbit) { clipKey = "pd_laser"; pitch = NextPitchJitter(1.12f, 1.24f); volDb = -5.5f; } else if (def?.Motion == OrdnanceMotion.StationaryMine) { clipKey = "mech_quick_bolt"; pitch = NextPitchJitter(1.25f, 1.38f); volDb = -6.5f; } break; case OrdnanceEventKind.Split: clipKey = (v & 1) == 0 ? "flak_blast_01" : "pod_petal_pop"; volDb = isLocal ? -2.5f : -4.5f; break; case OrdnanceEventKind.Detonated: if (def?.AudioClass == OrdnanceAudioClass.PlasmaPpc) { clipKey = "plasma_ppc_02"; } else { clipKey = "impact_explosion"; RecordExplosionPoint(pos.X, pos.Z); } volDb = isLocal ? -2.0f : -3.8f; break; case OrdnanceEventKind.Intercepted: clipKey = "mech_eject"; volDb = -5.5f; break; } if (!string.IsNullOrEmpty(clipKey)) { PlayOneShot3D(clipKey, pos, listenerPos, priority, volDb, pitch, isLocal, ord.ShooterId); } } private static string SelectAudioClassClip(OrdnanceAudioClass audioClass, uint variant) => audioClass switch { OrdnanceAudioClass.CannonLight => (variant & 1) == 0 ? "ac_light_01" : "ac_light_02", OrdnanceAudioClass.CannonHeavy => (variant & 1) == 0 ? "cannon_heavy_01" : "cannon_heavy_02", OrdnanceAudioClass.RocketSalvo => (variant & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02", OrdnanceAudioClass.LaserHeavy => "laser_heavy_01", OrdnanceAudioClass.GaussRail => "gauss_rail_01", OrdnanceAudioClass.PlasmaPpc => (variant & 1) == 0 ? "plasma_ppc_01" : "plasma_ppc_02", _ => "rocket_salvo_01" }; 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 / drop-pod retro loop var local = session.LocalContender; if (local.IsInDropPod) { var (pPos, _, _) = session.GetInterpolatedContenderPose(localId, alpha); Vector3 pos = new(pPos.X, pPos.Y, pPos.Z); OrbitalPod? localPod = null; var pods = session.ActivePods; for (int i = 0; i < pods.Count; i++) { if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == localId) { localPod = pods[i]; break; } } bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; AssignLoopSlot( 0, isContender: true, localId, "pod_retro_burn", pos, distSq: 0f, volumeDb: burning ? -1.5f : -13.5f, pitchScale: burning ? 0.96f : 1.42f); } else if (local.IsGroundedActive) { 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/burning-pods 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.IsGroundedActive || !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)); } var activePods = session.ActivePods; for (int i = 0; i < activePods.Count; i++) { var pod = activePods[i]; if (pod.Phase != OrbitalPodPhase.RetroBurn || (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == localId)) { continue; } Vector3 pos = new(pod.X, pod.Y, pod.Z); float distSq = pos.DistanceSquaredTo(listenerPos); if (distSq > maxDistSq) continue; int candId = 100000 + pod.PodId; float scoreDistSq = IsHeldInRemoteLoopSlots(false, candId) ? MathF.Max(0f, distSq - LoopHysteresisMeters * LoopHysteresisMeters) : distSq; _loopCandidates.Add(new LoopCandidate(false, candId, "pod_retro_burn", pos, scoreDistSq, -4.5f, 1.0f)); } _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++; if (ProceduralWeaponGenerator.TryParseId(weaponId, out ProceduralWeaponKey pKey)) { var spec = ProceduralWeaponGenerator.Generate(pKey); return SelectAudioClassClip(spec.AudioClass, v); } 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", WeaponVisualClass.GaussRail => "gauss_rail_01", WeaponVisualClass.PlasmaPpc => (v & 1) == 0 ? "plasma_ppc_01" : "plasma_ppc_02", WeaponVisualClass.RocketSalvo => (v & 1) == 0 ? "rocket_salvo_01" : "rocket_salvo_02", WeaponVisualClass.SwarmSmart => "pd_laser", _ => "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; } }