using Godot; using RailEnterprise.Client.Map; using RailEnterprise.Client.Net; using RailEnterprise.Core.Data; using RailEnterprise.Core.Map; using RailEnterprise.Core.Rail; using RailEnterprise.Protocol; using RailEnterprise.Protocol.Messages; namespace RailEnterprise.Client.Audio; /// /// Regia dell'audio, figlia di Main per tutta la vita del client: bus e volumi, effetti /// dell'interfaccia (clic di ogni pulsante, esito dei comandi), notifiche, cantieri completati, /// treni in moto vicini al centro della telecamera (rotolamento, motore, sbuffi), ambiente dal /// terreno sotto la telecamera e musica per era. Non decide nulla del gioco: reagisce a ciò che il /// client riceve (esiti, notifiche, DailyDigest, moti dei treni) e alla vista. /// I suoni si sintetizzano all'avvio su un altro thread (, ); /// nel ciclo per fotogramma non si alloca (elenchi preparati, nessuna LINQ). /// public partial class AudioManager : Node { /// Unica istanza (nulla prima dell'avvio del client). public static AudioManager? Instance { get; private set; } /// Volumi e muto attuali (anche con l'audio disattivato, per il pannello). public AudioSettings Settings { get; private set; } = new(); /// Cambio di volumi o muto (per aggiornare il pannello e l'icona della barra). public event Action? SettingsChanged; private readonly bool _enabled; private Task? _bankTask; private bool _loaded; // suoni singoli private AudioStreamWav? _click, _confirm, _error, _build, _chuff; private readonly Callable _clickCallable; private readonly AudioStreamWav?[] _notify = new AudioStreamWav?[3]; private AudioStreamWav[] _birds = []; private AudioStreamWav? _diesel, _hum; // riproduttori polifonici per bus e nomi dei bus già pronti (niente StringName per chiamata) private readonly StringName _busUi = AudioBuses.Ui, _busSfx = AudioBuses.Sfx, _busAmbience = AudioBuses.Ambience; private AudioStreamPlaybackPolyphonic? _ui, _sfx, _ambience; // ambiente: vento, acqua, mare, città private const int AmbienceLoops = 4; private static readonly float[] AmbienceLevel = [0.55f, 0.6f, 0.6f, 0.5f]; private readonly AudioStreamPlayer[] _ambiencePlayers = new AudioStreamPlayer[AmbienceLoops]; private readonly float[] _ambienceGain = new float[AmbienceLoops]; private readonly float[] _ambienceTarget = new float[AmbienceLoops]; private float _birdsChance; private float _sinceAmbience = 1, _birdTimer = 3; // treni private sealed class TrainChannel { public int Train = -1; public Traction Traction; public float Gain, Target, ChuffTimer; public bool Kept; public required AudioStreamPlayer Rumble { get; init; } public required AudioStreamPlayer Engine { get; init; } } private readonly TrainChannel[] _channels = new TrainChannel[AudioMix.TrainChannels]; private readonly int[] _nearIds = new int[AudioMix.TrainChannels]; private readonly float[] _nearDistances = new float[AudioMix.TrainChannels]; /// /// Età massima (ms) dell'ultimo moto di un treno perché suoni: il server manda i moti dei treni /// in marcia ogni 100 ms; un moto più vecchio è di un treno fermo in stazione (durante la sosta /// non arrivano moti) o uscito dalla zona sottoscritta, e non va più ascoltato. /// private const long StaleMotionMs = 500; // musica: due riproduttori per la dissolvenza incrociata private const float MusicLevel = 0.6f; private const float FadeSeconds = 3f; private readonly AudioStreamPlayer[] _music = new AudioStreamPlayer[2]; private readonly float[] _musicGain = new float[2]; private int _activeMusic; private int _musicEra = -1; private readonly Dictionary _themes = []; private readonly HashSet _failedThemes = []; private Task? _composing; private int _composingEra; private string[] _eraIds = ["steam"]; private int[] _eraFroms = [0]; // partita in corso private GameSession? _session; private MapView? _map; private Dictionary _vehicles = []; private SynthRng _rng = new(0xA0D10); private ulong _lastUiMs, _lastNotifyMs; private bool _settingsDirty; // pannello delle impostazioni private CanvasLayer? _overlay; private AudioSettingsPanel? _panel; /// Falso nel pilota automatico e senza schermo: niente sintesi né riproduzione, Master muto. public AudioManager(bool enabled) { _enabled = enabled; Name = "AudioManager"; _clickCallable = Callable.From(PlayClick); } public AudioManager() : this(true) { } public override void _Ready() { Instance = this; AudioBuses.Ensure(); Settings = AudioSettings.Load(); ApplySettings(); if (!_enabled) return; _bankTask = Task.Run(SoundBank.Create); GetTree().NodeAdded += OnNodeAdded; } public override void _ExitTree() { if (Instance == this) Instance = null; Unbind(); // chiusura della finestra con un volume appena cambiato: si salva comunque SaveSettings(); } /// Ere di eras.json (id e anno d'inizio, crescenti): scelgono il tema musicale. public void SetEras(IReadOnlyList eras) { if (eras.Count == 0) return; _eraIds = new string[eras.Count]; _eraFroms = new int[eras.Count]; for (int i = 0; i < eras.Count; i++) { _eraIds[i] = eras[i].Id; _eraFroms[i] = eras[i].From; } } // ------------------------------------------------------------------ impostazioni private void ApplySettings() { Settings.Apply(); // senza audio (collaudo, server senza schermo) il Master resta muto, senza toccare il file if (!_enabled) AudioServer.SetBusMute(0, true); } /// Cambia il volume di un bus (indice in ) e lo applica subito. public void SetVolume(int bus, float value) { Settings.Volumes[bus] = Math.Clamp(value, 0, 1); _settingsDirty = true; ApplySettings(); SettingsChanged?.Invoke(); } public void SetMuted(bool muted) { Settings.Muted = muted; _settingsDirty = true; ApplySettings(); SettingsChanged?.Invoke(); } public void ToggleMute() { SetMuted(!Settings.Muted); SaveSettings(); } /// Scrive volumi e muto in user://settings.cfg se sono cambiati dall'ultimo salvataggio. public void SaveSettings() { if (!_settingsDirty) return; _settingsDirty = false; Settings.Save(); } /// Apre il pannello «Audio» sopra a tutto (menu o partita). public void ShowSettings() { if (_panel is not null && IsInstanceValid(_panel)) return; if (_overlay is null) { _overlay = new CanvasLayer { Layer = 50 }; AddChild(_overlay); } _panel = new AudioSettingsPanel(this); _panel.TreeExited += () => _panel = null; _overlay.AddChild(_panel); } public override void _UnhandledKeyInput(InputEvent e) { if (e is InputEventKey { Pressed: true, Echo: false, Keycode: Key.M } key && !key.CtrlPressed && !key.AltPressed && !key.MetaPressed) { ToggleMute(); GetViewport().SetInputAsHandled(); } } // ------------------------------------------------------------------ partita /// Collega la partita: messaggi della sessione e vista della mappa. public void Bind(GameSession session, MapView map) { Unbind(); _session = session; _map = map; _vehicles = session.World.Data.Vehicles.ToDictionary(v => v.Id); SetEras(session.World.Data.Eras.Eras); session.MessageApplied += OnMessage; } /// /// Scollega la partita (ritorno al menu): treni e ambiente sfumano. Con «only» scollega solo /// se è ancora quella sessione (la schermata vecchia esce dall'albero dopo l'arrivo della nuova). /// public void Unbind(GameSession? only = null) { if (only is not null && !ReferenceEquals(only, _session)) return; if (_session is not null) _session.MessageApplied -= OnMessage; _session = null; _map = null; } private void OnMessage(IMessage message) { if (!_loaded) return; switch (message) { case CommandResultMessage r: PlayUi(r.Ok ? _confirm : _error, r.Ok ? 0.7f : 0.85f); break; case Notification n: Notify(n.Event); break; case DailyDigest d: int me = _session?.World.Summary?.CompanyId ?? -1; for (int i = 0; i < d.Events.Count; i++) { var e = d.Events[i]; if (e.Kind == ConstructionEventKind && e.Company == me && me >= 0) { Play(_sfx, _build, 0.8f, 1, _busSfx); break; } } break; } } /// Codice di EventKind.Construction nel protocollo (cantiere completato, sempre informativo). private const byte ConstructionEventKind = 5; private void Notify(EventInfo e) { int me = _session?.World.Summary?.CompanyId ?? -1; if (e.Company >= 0 && e.Company != me) return; int level = e.Severity switch { 3 => 2, 2 => 1, _ => 0 }; ulong now = Time.GetTicksMsec(); // più notizie insieme: una sola campanella (le critiche suonano sempre) if (level < 2 && now - _lastNotifyMs < 600) return; _lastNotifyMs = now; Play(_ui, _notify[level], level == 2 ? 0.9f : 0.75f, 1, _busUi); } private void OnNodeAdded(Node node) { // un pulsante staccato e riattaccato (MarketPanel lo fa a ogni resoconto) è già collegato if (node is BaseButton button && !button.IsConnected(BaseButton.SignalName.Pressed, _clickCallable)) button.Connect(BaseButton.SignalName.Pressed, _clickCallable); } private void PlayClick() => PlayUi(_click, 0.6f); private void PlayUi(AudioStreamWav? stream, float gain) { ulong now = Time.GetTicksMsec(); if (stream == _click && now - _lastUiMs < 40) return; _lastUiMs = now; Play(_ui, stream, gain, 1, _busUi); } private static void Play(AudioStreamPlaybackPolyphonic? playback, AudioStreamWav? stream, float gain, float pitch, StringName bus) { if (playback is null || stream is null || gain <= 0.001f) return; playback.PlayStream(stream, 0, AudioMix.LinearToDb(gain), pitch, AudioServer.PlaybackType.Default, bus); } // ------------------------------------------------------------------ caricamento /// Campioni di tutti gli effetti e degli anelli, sintetizzati fuori dal thread principale. private sealed class SoundBank { public required float[] Click, Confirm, Error, Construction, Chuff, Rumble, Diesel, Hum, Wind, River, Sea, City; public required float[][] Notify, Birds; public static SoundBank Create() => new() { Click = Synth.Click(), Confirm = Synth.Confirm(), Error = Synth.Error(), Construction = Synth.BuildComplete(), Chuff = Synth.Chuff(), Rumble = Synth.RailRumbleLoop(), Diesel = Synth.DieselDroneLoop(), Hum = Synth.ElectricHumLoop(), Wind = Synth.WindLoop(), River = Synth.RiverLoop(), Sea = Synth.SeaLoop(), City = Synth.CityLoop(), Notify = [Synth.Notify(0), Synth.Notify(1), Synth.Notify(2)], Birds = [Synth.Bird(0), Synth.Bird(1), Synth.Bird(2)], }; } private static AudioStreamWav Wav(float[] samples, bool loop = false) { var w = new AudioStreamWav { Format = AudioStreamWav.FormatEnum.Format16Bits, MixRate = Synth.Rate, Stereo = false, Data = AudioMix.ToPcm16(samples), }; if (loop) { w.LoopMode = AudioStreamWav.LoopModeEnum.Forward; w.LoopBegin = 0; w.LoopEnd = samples.Length; } return w; } private AudioStreamPlayer Player(string bus, AudioStream? stream = null) { var p = new AudioStreamPlayer { Bus = bus, Stream = stream }; AddChild(p); return p; } private AudioStreamPlaybackPolyphonic? Polyphonic(string bus, int voices) { var p = Player(bus, new AudioStreamPolyphonic { Polyphony = voices }); p.Play(); return p.GetStreamPlayback() as AudioStreamPlaybackPolyphonic; } private void Load(SoundBank bank) { _click = Wav(bank.Click); _confirm = Wav(bank.Confirm); _error = Wav(bank.Error); _build = Wav(bank.Construction); _chuff = Wav(bank.Chuff); for (int i = 0; i < _notify.Length; i++) _notify[i] = Wav(bank.Notify[i]); _birds = bank.Birds.Select(b => Wav(b)).ToArray(); _diesel = Wav(bank.Diesel, loop: true); _hum = Wav(bank.Hum, loop: true); var rumble = Wav(bank.Rumble, loop: true); _ui = Polyphonic(AudioBuses.Ui, 8); _sfx = Polyphonic(AudioBuses.Sfx, 16); _ambience = Polyphonic(AudioBuses.Ambience, 4); float[][] loops = [bank.Wind, bank.River, bank.Sea, bank.City]; for (int i = 0; i < AmbienceLoops; i++) { var p = Player(AudioBuses.Ambience, Wav(loops[i], loop: true)); p.VolumeLinear = 0; _ambiencePlayers[i] = p; } for (int i = 0; i < _channels.Length; i++) { var r = Player(AudioBuses.Sfx, rumble); var e = Player(AudioBuses.Sfx); r.VolumeLinear = e.VolumeLinear = 0; _channels[i] = new TrainChannel { Rumble = r, Engine = e }; } for (int i = 0; i < _music.Length; i++) _music[i] = Player(AudioBuses.Music); _loaded = true; } // ------------------------------------------------------------------ ciclo public override void _Process(double delta) { if (!_enabled) return; if (!_loaded) { if (_bankTask is not { IsCompleted: true }) return; if (_bankTask.IsCompletedSuccessfully) Load(_bankTask.Result); else { GD.PrintErr($"Audio: sintesi non riuscita: {_bankTask.Exception?.GetBaseException().Message}"); _bankTask = null; return; } } float dt = (float)Math.Min(delta, 0.1); UpdateMusic(dt); UpdateAmbience(dt); UpdateTrains(dt); } private int WantedEra() { var w = _session?.World; if (w?.Calendar is null) return 0; return AudioMix.EraIndex(w.Year, _eraFroms); } private void UpdateMusic(float dt) { int want = WantedEra(); if (_composing is { IsCompleted: true }) { if (_composing.IsCompletedSuccessfully) _themes[_composingEra] = Wav(_composing.Result, loop: true); else { _failedThemes.Add(_composingEra); GD.PrintErr($"Audio: tema dell'era non composto: {_composing.Exception?.GetBaseException().Message}"); } _composing = null; } if (want != _musicEra) { if (_themes.TryGetValue(want, out var theme)) { // dissolvenza incrociata: il nuovo tema entra sull'altro riproduttore _activeMusic = 1 - _activeMusic; var p = _music[_activeMusic]; p.Stream = theme; _musicGain[_activeMusic] = 0; p.VolumeLinear = 0; p.Play(); _musicEra = want; } else if (_composing is null && !_failedThemes.Contains(want)) { int era = want; string id = _eraIds[Math.Clamp(era, 0, _eraIds.Length - 1)]; _composingEra = era; _composing = Task.Run(() => MusicComposer.Compose(era, id)); } } for (int i = 0; i < _music.Length; i++) { float target = i == _activeMusic && _musicEra >= 0 ? 1 : 0; _musicGain[i] = AudioMix.Approach(_musicGain[i], target, 1 / FadeSeconds, dt); _music[i].VolumeLinear = _musicGain[i] * MusicLevel; if (_musicGain[i] <= 0 && i != _activeMusic && _music[i].Playing) _music[i].Stop(); } } private void UpdateAmbience(float dt) { _sinceAmbience += dt; if (_sinceAmbience >= 0.25f) { _sinceAmbience = 0; var gains = _map is not null && _session?.World.Terrain is { } terrain ? AudioMix.Ambience(_map.Zoom, SampleTerrain(terrain, _map.VisibleRect())) : default; _ambienceTarget[0] = gains.Wind; _ambienceTarget[1] = gains.Water; _ambienceTarget[2] = gains.Sea; _ambienceTarget[3] = gains.City; _birdsChance = gains.Birds; } for (int i = 0; i < AmbienceLoops; i++) { _ambienceGain[i] = AudioMix.Approach(_ambienceGain[i], _ambienceTarget[i], 0.5f, dt); var p = _ambiencePlayers[i]; p.VolumeLinear = _ambienceGain[i] * AmbienceLevel[i]; if (_ambienceGain[i] > 0 && !p.Playing) p.Play(_rng.Next01() * 4); else if (_ambienceGain[i] <= 0 && p.Playing) p.Stop(); } if (_birdsChance > 0.05f && _birds.Length > 0) { _birdTimer -= dt; if (_birdTimer <= 0) { Play(_ambience, _birds[_rng.Next(_birds.Length)], _birdsChance * 0.45f, _rng.Range(0.9f, 1.15f), _busAmbience); _birdTimer = _rng.Range(1.5f, 6f) / (0.3f + _birdsChance); } } } /// Frazioni del terreno su una griglia 8×8 della vista (allargata di un quarto per sentire l'acqua vicina). private static TerrainMix SampleTerrain(Terrain t, Rect2 view) { const int grid = 8; view = view.Grow(Math.Max(view.Size.X, view.Size.Y) * 0.125f); int river = 0, lake = 0, sea = 0, town = 0, forest = 0, open = 0, total = 0; for (int gy = 0; gy < grid; gy++) { for (int gx = 0; gx < grid; gx++) { double x = view.Position.X + (gx + 0.5) / grid * view.Size.X; double y = view.Position.Y + (gy + 0.5) / grid * view.Size.Y; int cx = (int)Math.Floor(x / t.CellSizeM), cy = (int)Math.Floor(y / t.CellSizeM); if (!t.InBounds(cx, cy)) continue; int i = t.Index(cx, cy); total++; switch ((CellType)t.Types[i]) { case CellType.Water when t.RiverWidth[i] > 0: river++; break; case CellType.Water: lake++; break; case CellType.Sea: sea++; break; case CellType.Town or CellType.Industry: town++; break; case CellType.Forest: forest++; break; default: open++; break; } } } if (total == 0) return default; float k = 1f / total; return new TerrainMix { River = river * k, Lake = lake * k, Sea = sea * k, Town = town * k, Forest = forest * k, Open = open * k }; } private void UpdateTrains(float dt) { var w = _session?.World; var map = _map; int count = 0; Vector2 center = default; float zoom = 1, radius = 1; if (w is not null && map is not null && _session is { } session && w.Speed > 0) { center = map.Camera.GetScreenCenterPosition(); zoom = map.Zoom; radius = map.GetViewportRect().Size.Length() / 2; long now = (long)Time.GetTicksMsec(); foreach (var (id, head) in map.Trains.Heads) { if (!w.Motions.TryGetValue(id, out var m) || m.State != (byte)TrainState.Moving || m.Speed < 0.5f) continue; if (!session.MotionReceivedMs.TryGetValue(id, out long at) || now - at > StaleMotionMs) continue; // oltre il raggio non si sentirebbe: niente canale (eviterebbe Play e Stop a ogni fotogramma) float distance = head.DistanceTo(center) * zoom; if (distance >= radius) continue; count = AudioMix.InsertNearest(_nearIds, _nearDistances, count, id, distance); } } // i canali restano ai loro treni finché sono tra i più vicini; gli altri sfumano foreach (var ch in _channels) ch.Kept = ch.Train >= 0 && Contains(_nearIds, count, ch.Train); for (int k = 0; k < count; k++) { int id = _nearIds[k]; if (HasChannel(id)) continue; foreach (var ch in _channels) { if (ch.Train >= 0 && (ch.Kept || ch.Gain > 0.01f)) continue; Assign(ch, id, w!); ch.Kept = true; break; } } foreach (var ch in _channels) { float speed = 0; if (ch.Kept && w is not null && map is not null && w.Motions.TryGetValue(ch.Train, out var m) && map.Trains.Heads.TryGetValue(ch.Train, out var head)) { speed = m.Speed; ch.Target = AudioMix.TrainGain(head.DistanceTo(center) * zoom, radius, speed, zoom); } else ch.Target = 0; ch.Gain = AudioMix.Approach(ch.Gain, ch.Target, 2.5f, dt); if (ch.Train < 0) continue; if (ch.Gain <= 0 && ch.Target <= 0) { ch.Train = -1; ch.Rumble.Stop(); ch.Engine.Stop(); continue; } if (speed > 0) { ch.Rumble.PitchScale = AudioMix.RumblePitch(speed); ch.Engine.PitchScale = AudioMix.EnginePitch(speed); } ch.Rumble.VolumeLinear = ch.Gain * 0.7f; bool steam = ch.Traction == Traction.Steam; ch.Engine.VolumeLinear = steam ? 0 : ch.Gain * 0.45f; if (steam && speed > 0 && ch.Gain > 0.02f) { ch.ChuffTimer -= dt; if (ch.ChuffTimer <= 0) { Play(_sfx, _chuff, ch.Gain * 0.9f, _rng.Range(0.92f, 1.08f), _busSfx); ch.ChuffTimer = Math.Max(ch.ChuffTimer, 0) + AudioMix.ChuffInterval(speed); } } } } private static bool Contains(int[] ids, int count, int id) { for (int i = 0; i < count; i++) { if (ids[i] == id) return true; } return false; } private bool HasChannel(int train) { foreach (var ch in _channels) { if (ch.Train == train) return true; } return false; } private void Assign(TrainChannel ch, int train, Protocol.Client.ClientWorld w) { ch.Train = train; ch.Traction = TractionOf(train, w); ch.Gain = 0; ch.ChuffTimer = _rng.Next01() * 0.2f; ch.Rumble.VolumeLinear = 0; ch.Rumble.Play(_rng.Next01() * 1.5f); ch.Engine.VolumeLinear = 0; if (ch.Traction == Traction.Steam) ch.Engine.Stop(); else { ch.Engine.Stream = ch.Traction == Traction.Diesel ? _diesel : _hum; ch.Engine.Play(_rng.Next01() * 0.9f); } } /// Trazione della prima locomotiva del treno (vapore se non si sa). private Traction TractionOf(int train, Protocol.Client.ClientWorld w) { if (!w.Trains.TryGetValue(train, out var info)) return Traction.Steam; foreach (int vid in info.Vehicles) { if (w.Vehicles.TryGetValue(vid, out var v) && _vehicles.TryGetValue(v.Type, out var def) && def.Kind == VehicleKind.Locomotive && def.Traction is { } traction) return traction; } return Traction.Steam; } }