1
0

ContentAudioSystem.AmbientMusic.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System.Linq;
  2. using Content.Client.Gameplay;
  3. using Content.Shared.Audio;
  4. using Content.Shared.CCVar;
  5. using Content.Shared.GameTicking;
  6. using Content.Shared.Random;
  7. using Content.Shared.Random.Rules;
  8. using Robust.Client.GameObjects;
  9. using Robust.Client.Player;
  10. using Robust.Client.ResourceManagement;
  11. using Robust.Client.State;
  12. using Robust.Shared.Audio;
  13. using Robust.Shared.Audio.Components;
  14. using Robust.Shared.Audio.Systems;
  15. using Robust.Shared.Configuration;
  16. using Robust.Shared.Player;
  17. using Robust.Shared.Prototypes;
  18. using Robust.Shared.Random;
  19. using Robust.Shared.Timing;
  20. using Robust.Shared.Utility;
  21. namespace Content.Client.Audio;
  22. public sealed partial class ContentAudioSystem
  23. {
  24. [Dependency] private readonly IConfigurationManager _configManager = default!;
  25. [Dependency] private readonly IGameTiming _timing = default!;
  26. [Dependency] private readonly IPlayerManager _player = default!;
  27. [Dependency] private readonly IPrototypeManager _proto = default!;
  28. [Dependency] private readonly IRobustRandom _random = default!;
  29. [Dependency] private readonly IStateManager _state = default!;
  30. [Dependency] private readonly RulesSystem _rules = default!;
  31. [Dependency] private readonly SharedAudioSystem _audio = default!;
  32. private readonly TimeSpan _minAmbienceTime = TimeSpan.FromSeconds(30);
  33. private readonly TimeSpan _maxAmbienceTime = TimeSpan.FromSeconds(60);
  34. private const float AmbientMusicFadeTime = 10f;
  35. private static float _volumeSlider;
  36. // Don't need to worry about this being serializable or pauseable as it doesn't affect the sim.
  37. private TimeSpan _nextAudio;
  38. private EntityUid? _ambientMusicStream;
  39. private AmbientMusicPrototype? _musicProto;
  40. /// <summary>
  41. /// If we find a better ambient music proto can we interrupt this one.
  42. /// </summary>
  43. private bool _interruptable;
  44. /// <summary>
  45. /// Track what ambient sounds we've played. This is so they all get played an even
  46. /// number of times.
  47. /// When we get to the end of the list we'll re-shuffle
  48. /// </summary>
  49. private readonly Dictionary<string, List<ResPath>> _ambientSounds = new();
  50. private ISawmill _sawmill = default!;
  51. private void InitializeAmbientMusic()
  52. {
  53. Subs.CVar(_configManager, CCVars.AmbientMusicVolume, AmbienceCVarChanged, true);
  54. _sawmill = IoCManager.Resolve<ILogManager>().GetSawmill("audio.ambience");
  55. // Reset audio
  56. _nextAudio = TimeSpan.MaxValue;
  57. SetupAmbientSounds();
  58. SubscribeLocalEvent<PrototypesReloadedEventArgs>(OnProtoReload);
  59. _state.OnStateChanged += OnStateChange;
  60. // On round end summary OR lobby cut audio.
  61. SubscribeNetworkEvent<RoundEndMessageEvent>(OnRoundEndMessage);
  62. }
  63. private void AmbienceCVarChanged(float obj)
  64. {
  65. _volumeSlider = SharedAudioSystem.GainToVolume(obj);
  66. if (_ambientMusicStream != null && _musicProto != null)
  67. {
  68. _audio.SetVolume(_ambientMusicStream, _musicProto.Sound.Params.Volume + _volumeSlider);
  69. }
  70. }
  71. private void ShutdownAmbientMusic()
  72. {
  73. _state.OnStateChanged -= OnStateChange;
  74. _ambientMusicStream = _audio.Stop(_ambientMusicStream);
  75. }
  76. private void OnProtoReload(PrototypesReloadedEventArgs obj)
  77. {
  78. if (obj.WasModified<AmbientMusicPrototype>() || obj.WasModified<RulesPrototype>())
  79. SetupAmbientSounds();
  80. }
  81. private void OnStateChange(StateChangedEventArgs obj)
  82. {
  83. if (obj.NewState is not GameplayState)
  84. return;
  85. // If they go to game then reset the ambience timer.
  86. _nextAudio = _timing.CurTime + _random.Next(_minAmbienceTime, _maxAmbienceTime);
  87. }
  88. private void SetupAmbientSounds()
  89. {
  90. _ambientSounds.Clear();
  91. foreach (var ambience in _proto.EnumeratePrototypes<AmbientMusicPrototype>())
  92. {
  93. var tracks = _ambientSounds.GetOrNew(ambience.ID);
  94. RefreshTracks(ambience.Sound, tracks, null);
  95. _random.Shuffle(tracks);
  96. }
  97. }
  98. private void OnRoundEndMessage(RoundEndMessageEvent ev)
  99. {
  100. // If scoreboard shows then just stop the music
  101. _ambientMusicStream = _audio.Stop(_ambientMusicStream);
  102. _nextAudio = TimeSpan.FromMinutes(3);
  103. }
  104. private void RefreshTracks(SoundSpecifier sound, List<ResPath> tracks, ResPath? lastPlayed)
  105. {
  106. DebugTools.Assert(tracks.Count == 0);
  107. switch (sound)
  108. {
  109. case SoundCollectionSpecifier collection:
  110. if (collection.Collection == null)
  111. break;
  112. var slothCud = _proto.Index<SoundCollectionPrototype>(collection.Collection);
  113. tracks.AddRange(slothCud.PickFiles);
  114. break;
  115. case SoundPathSpecifier path:
  116. tracks.Add(path.Path);
  117. break;
  118. }
  119. // Just so the same track doesn't play twice
  120. if (tracks.Count > 1 && tracks[^1] == lastPlayed)
  121. {
  122. (tracks[0], tracks[^1]) = (tracks[^1], tracks[0]);
  123. }
  124. }
  125. private void UpdateAmbientMusic()
  126. {
  127. // Update still runs in lobby so just ignore it.
  128. if (_state.CurrentState is not GameplayState)
  129. {
  130. _ambientMusicStream = Audio.Stop(_ambientMusicStream);
  131. _musicProto = null;
  132. return;
  133. }
  134. bool? isDone = null;
  135. if (TryComp(_ambientMusicStream, out AudioComponent? audioComp))
  136. {
  137. isDone = !audioComp.Playing;
  138. }
  139. if (_interruptable)
  140. {
  141. var player = _player.LocalSession?.AttachedEntity;
  142. if (player == null || _musicProto == null || !_rules.IsTrue(player.Value, _proto.Index<RulesPrototype>(_musicProto.Rules)))
  143. {
  144. FadeOut(_ambientMusicStream, duration: AmbientMusicFadeTime);
  145. _musicProto = null;
  146. _interruptable = false;
  147. isDone = true;
  148. }
  149. }
  150. // Still running existing ambience
  151. if (isDone == false)
  152. return;
  153. // If ambience finished reset the CD (this also means if we have long ambience it won't clip)
  154. if (isDone == true)
  155. {
  156. // Also don't need to worry about rounding here as it doesn't affect the sim
  157. _nextAudio = _timing.CurTime + _random.Next(_minAmbienceTime, _maxAmbienceTime);
  158. }
  159. _ambientMusicStream = null;
  160. if (_nextAudio > _timing.CurTime)
  161. return;
  162. _musicProto = GetAmbience();
  163. if (_musicProto == null)
  164. {
  165. _interruptable = false;
  166. return;
  167. }
  168. _interruptable = _musicProto.Interruptable;
  169. var tracks = _ambientSounds[_musicProto.ID];
  170. var track = tracks[^1];
  171. tracks.RemoveAt(tracks.Count - 1);
  172. var strim = _audio.PlayGlobal(
  173. track.ToString(),
  174. Filter.Local(),
  175. false,
  176. AudioParams.Default.WithVolume(_musicProto.Sound.Params.Volume + _volumeSlider));
  177. _ambientMusicStream = strim?.Entity;
  178. if (_musicProto.FadeIn && strim != null)
  179. {
  180. FadeIn(_ambientMusicStream, strim.Value.Component, AmbientMusicFadeTime);
  181. }
  182. // Refresh the list
  183. if (tracks.Count == 0)
  184. {
  185. RefreshTracks(_musicProto.Sound, tracks, track);
  186. }
  187. }
  188. private AmbientMusicPrototype? GetAmbience()
  189. {
  190. var player = _player.LocalEntity;
  191. if (player == null)
  192. return null;
  193. var ev = new PlayAmbientMusicEvent();
  194. RaiseLocalEvent(ref ev);
  195. if (ev.Cancelled)
  196. return null;
  197. var ambiences = _proto.EnumeratePrototypes<AmbientMusicPrototype>().ToList();
  198. ambiences.Sort((x, y) => y.Priority.CompareTo(x.Priority));
  199. foreach (var amb in ambiences)
  200. {
  201. if (!_rules.IsTrue(player.Value, _proto.Index<RulesPrototype>(amb.Rules)))
  202. continue;
  203. return amb;
  204. }
  205. _sawmill.Warning($"Unable to find fallback ambience track");
  206. return null;
  207. }
  208. /// <summary>
  209. /// Fades out the current ambient music temporarily.
  210. /// </summary>
  211. public void DisableAmbientMusic()
  212. {
  213. FadeOut(_ambientMusicStream);
  214. _ambientMusicStream = null;
  215. }
  216. }