F6: audio con bus, volumi, effetti, ambienti e musica per era #48
No files matched your search
@@ -677,3 +677,12 @@ una leva non oltre {0} (rimborsando {1}),,leverage no higher than {0} (by repayi
|
||||
Per il gradino {0} serve un punteggio di {1}: {2}.,,To reach {0} you need a score of {1}: {2}.
|
||||
In bancarotta non si possono chiedere prestiti,,Loans cannot be requested while bankrupt
|
||||
Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni.,,Available credit {0} of {1}. Rate of a new loan: {2} fixed (base {3} + rating {4} {5}) for {6} years.
|
||||
Audio,,Audio
|
||||
Volume generale,,Master volume
|
||||
Musica,,Music
|
||||
Ambiente,,Ambience
|
||||
Effetti,,Effects
|
||||
Interfaccia,,Interface
|
||||
Muto,,Mute
|
||||
Il tasto M attiva e toglie il muto durante la partita.,,The M key toggles mute during the game.
|
||||
Audio (M: muto),,Audio (M: mute)
|
||||
|
@@ -0,0 +1,643 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Regia dell'audio, figlia di <c>Main</c> 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, <c>DailyDigest</c>, moti dei treni) e alla vista.
|
||||
/// I suoni si sintetizzano all'avvio su un altro thread (<see cref="Synth"/>, <see cref="MusicComposer"/>);
|
||||
/// nel ciclo per fotogramma non si alloca (elenchi preparati, nessuna LINQ).
|
||||
/// </summary>
|
||||
public partial class AudioManager : Node
|
||||
{
|
||||
/// <summary>Unica istanza (nulla prima dell'avvio del client).</summary>
|
||||
public static AudioManager? Instance { get; private set; }
|
||||
|
||||
/// <summary>Volumi e muto attuali (anche con l'audio disattivato, per il pannello).</summary>
|
||||
public AudioSettings Settings { get; private set; } = new();
|
||||
|
||||
/// <summary>Cambio di volumi o muto (per aggiornare il pannello e l'icona della barra).</summary>
|
||||
public event Action? SettingsChanged;
|
||||
|
||||
private readonly bool _enabled;
|
||||
private Task<SoundBank>? _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];
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<int, AudioStreamWav> _themes = [];
|
||||
private readonly HashSet<int> _failedThemes = [];
|
||||
private Task<float[]>? _composing;
|
||||
private int _composingEra;
|
||||
private string[] _eraIds = ["steam"];
|
||||
private int[] _eraFroms = [0];
|
||||
|
||||
// partita in corso
|
||||
private GameSession? _session;
|
||||
private MapView? _map;
|
||||
private Dictionary<string, VehicleDef> _vehicles = [];
|
||||
private SynthRng _rng = new(0xA0D10);
|
||||
private ulong _lastUiMs, _lastNotifyMs;
|
||||
private bool _settingsDirty;
|
||||
|
||||
// pannello delle impostazioni
|
||||
private CanvasLayer? _overlay;
|
||||
private AudioSettingsPanel? _panel;
|
||||
|
||||
/// <param name="enabled">Falso nel pilota automatico e senza schermo: niente sintesi né riproduzione, Master muto.</param>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Ere di eras.json (id e anno d'inizio, crescenti): scelgono il tema musicale.</summary>
|
||||
public void SetEras(IReadOnlyList<EraDef> 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);
|
||||
}
|
||||
|
||||
/// <summary>Cambia il volume di un bus (indice in <see cref="AudioBuses.All"/>) e lo applica subito.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Scrive volumi e muto in <c>user://settings.cfg</c> se sono cambiati dall'ultimo salvataggio.</summary>
|
||||
public void SaveSettings()
|
||||
{
|
||||
if (!_settingsDirty) return;
|
||||
_settingsDirty = false;
|
||||
Settings.Save();
|
||||
}
|
||||
|
||||
/// <summary>Apre il pannello «Audio» sopra a tutto (menu o partita).</summary>
|
||||
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
|
||||
|
||||
/// <summary>Collega la partita: messaggi della sessione e vista della mappa.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Codice di EventKind.Construction nel protocollo (cantiere completato, sempre informativo).</summary>
|
||||
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
|
||||
|
||||
/// <summary>Campioni di tutti gli effetti e degli anelli, sintetizzati fuori dal thread principale.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frazioni del terreno su una griglia 8×8 della vista (allargata di un quarto per sentire l'acqua vicina).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Trazione della prima locomotiva del treno (vapore se non si sa).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>Frazioni del terreno sotto la telecamera (somma 1 sui campioni letti).</summary>
|
||||
public struct TerrainMix
|
||||
{
|
||||
public float River;
|
||||
public float Lake;
|
||||
public float Sea;
|
||||
public float Town;
|
||||
public float Forest;
|
||||
public float Open;
|
||||
}
|
||||
|
||||
/// <summary>Guadagni lineari (0–1) dei quattro anelli d'ambiente e probabilità relativa degli uccelli.</summary>
|
||||
public readonly record struct AmbienceGains(float Wind, float Water, float Sea, float City, float Birds);
|
||||
|
||||
/// <summary>
|
||||
/// Miscelazione dell'audio senza dipendenze da Godot: guadagni dell'ambiente dal terreno e dallo
|
||||
/// zoom, volume e intonazione dei treni dalla distanza sullo schermo e dalla velocità, scelta dei
|
||||
/// treni più vicini senza allocazioni, ere dall'anno, dissolvenze e conversione in PCM. Le costanti
|
||||
/// sono di resa sonora del client, non della simulazione.
|
||||
/// </summary>
|
||||
public static class AudioMix
|
||||
{
|
||||
/// <summary>Zoom (pixel per metro) sotto il quale si sente quasi solo il vento della vista d'insieme.</summary>
|
||||
public const float FarZoom = 0.02f;
|
||||
/// <summary>Zoom da cui ambiente e treni sono al massimo.</summary>
|
||||
public const float NearZoom = 0.5f;
|
||||
/// <summary>Canali dei treni: al più tanti treni suonano insieme.</summary>
|
||||
public const int TrainChannels = 3;
|
||||
/// <summary>Velocità (m/s) a cui il rotolamento è al massimo.</summary>
|
||||
public const float FullSpeedMs = 25f;
|
||||
/// <summary>Sbuffi al secondo da fermo (al passo) e alla velocità <see cref="ChuffFullSpeedMs"/>.</summary>
|
||||
public const float ChuffMinRate = 1.2f, ChuffMaxRate = 10f;
|
||||
/// <summary>Velocità (m/s, circa 110 km/h) a cui gli sbuffi sono più fitti.</summary>
|
||||
public const float ChuffFullSpeedMs = 30f;
|
||||
|
||||
public static float Clamp01(float x) => x < 0 ? 0 : x > 1 ? 1 : x;
|
||||
|
||||
public static float SmoothStep(float x)
|
||||
{
|
||||
x = Clamp01(x);
|
||||
return x * x * (3 - 2 * x);
|
||||
}
|
||||
|
||||
/// <summary>Vicinanza della telecamera (0 = vista d'insieme, 1 = da vicino) su scala logaritmica dello zoom.</summary>
|
||||
public static float Closeness(float zoom)
|
||||
{
|
||||
if (zoom <= 0) return 0;
|
||||
return SmoothStep((MathF.Log(zoom) - MathF.Log(FarZoom)) / (MathF.Log(NearZoom) - MathF.Log(FarZoom)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ambiente: il vento c'è sempre (più forte da lontano), acqua, mare e città seguono la
|
||||
/// frazione del terreno visibile e si attenuano allontanandosi; gli uccelli solo da vicino in
|
||||
/// campagna e nei boschi.
|
||||
/// </summary>
|
||||
public static AmbienceGains Ambience(float zoom, in TerrainMix t)
|
||||
{
|
||||
float close = Closeness(zoom);
|
||||
float wind = 0.35f + 0.35f * (1 - close) + 0.15f * t.Open;
|
||||
float water = Clamp01((t.River * 3 + t.Lake * 1.5f) * (0.25f + 0.75f * close));
|
||||
float sea = Clamp01(t.Sea * 1.6f * (0.45f + 0.55f * close));
|
||||
float city = Clamp01(t.Town * 4 * (0.15f + 0.85f * close));
|
||||
float birds = Clamp01((t.Forest + t.Open * 0.6f) * close * close * (1 - t.Town * 2));
|
||||
// l'acqua e la città coprono un po' il vento
|
||||
wind *= 1 - 0.4f * MathF.Max(sea, city);
|
||||
return new AmbienceGains(Clamp01(wind), water, sea, city, birds);
|
||||
}
|
||||
|
||||
/// <summary>Volume di un treno: vicinanza al centro dello schermo, velocità e zoom.</summary>
|
||||
/// <param name="distancePx">Distanza in pixel dal centro dello schermo.</param>
|
||||
/// <param name="radiusPx">Raggio oltre il quale non si sente (di solito metà della diagonale).</param>
|
||||
public static float TrainGain(float distancePx, float radiusPx, float speedMs, float zoom)
|
||||
{
|
||||
if (radiusPx <= 0) return 0;
|
||||
float near = 1 - Clamp01(distancePx / radiusPx);
|
||||
float speed = Clamp01(speedMs / FullSpeedMs);
|
||||
return near * near * (0.25f + 0.75f * speed) * (0.15f + 0.85f * Closeness(zoom));
|
||||
}
|
||||
|
||||
/// <summary>Intonazione del rotolamento: più rapido e acuto con la velocità.</summary>
|
||||
public static float RumblePitch(float speedMs) => 0.55f + 1.0f * Clamp01(speedMs / FullSpeedMs);
|
||||
|
||||
/// <summary>Intonazione del motore (diesel o elettrico) con la velocità.</summary>
|
||||
public static float EnginePitch(float speedMs) => 0.8f + 0.5f * Clamp01(speedMs / FullSpeedMs);
|
||||
|
||||
/// <summary>
|
||||
/// Secondi tra due sbuffi della vaporiera alla velocità data: la frequenza cresce in modo lineare
|
||||
/// da <see cref="ChuffMinRate"/> a <see cref="ChuffMaxRate"/> fino a <see cref="ChuffFullSpeedMs"/>,
|
||||
/// così segue la velocità su tutto l'esercizio normale. È una resa sonora, non il passo reale della
|
||||
/// ruota: sullo schermo il tempo dei treni corre decine di volte più veloce e gli sbuffi reali
|
||||
/// sarebbero un ronzio continuo.
|
||||
/// </summary>
|
||||
public static float ChuffInterval(float speedMs) => 1f / (ChuffMinRate + (ChuffMaxRate - ChuffMinRate) * Clamp01(speedMs / ChuffFullSpeedMs));
|
||||
|
||||
/// <summary>
|
||||
/// Inserisce un candidato nell'elenco ordinato dei più vicini (al più ids.Length): nessuna
|
||||
/// allocazione, gli elenchi sono preparati una volta sola. Restituisce il nuovo conteggio.
|
||||
/// </summary>
|
||||
public static int InsertNearest(int[] ids, float[] distances, int count, int id, float distance)
|
||||
{
|
||||
int capacity = ids.Length;
|
||||
if (count == capacity && distance >= distances[capacity - 1]) return count;
|
||||
int i = Math.Min(count, capacity - 1);
|
||||
while (i > 0 && distances[i - 1] > distance)
|
||||
{
|
||||
ids[i] = ids[i - 1];
|
||||
distances[i] = distances[i - 1];
|
||||
i--;
|
||||
}
|
||||
ids[i] = id;
|
||||
distances[i] = distance;
|
||||
return Math.Min(count + 1, capacity);
|
||||
}
|
||||
|
||||
/// <summary>Era dell'anno: l'ultima il cui inizio («from» di eras.json, crescente) non è dopo l'anno.</summary>
|
||||
public static int EraIndex(int year, IReadOnlyList<int> froms)
|
||||
{
|
||||
int index = 0;
|
||||
for (int i = 0; i < froms.Count; i++)
|
||||
{
|
||||
if (froms[i] <= year) index = i;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>Avvicina un valore al bersaglio con velocità costante (unità al secondo).</summary>
|
||||
public static float Approach(float current, float target, float ratePerSecond, float dt)
|
||||
{
|
||||
float step = ratePerSecond * dt;
|
||||
return current < target ? MathF.Min(target, current + step) : MathF.Max(target, current - step);
|
||||
}
|
||||
|
||||
/// <summary>Lineare → decibel, con −80 dB come silenzio.</summary>
|
||||
public static float LinearToDb(float linear) => linear <= 0.0001f ? -80f : 20f * MathF.Log10(linear);
|
||||
|
||||
/// <summary>Campioni in [−1, 1] → PCM a 16 bit little-endian (formato di AudioStreamWAV).</summary>
|
||||
public static byte[] ToPcm16(float[] samples)
|
||||
{
|
||||
var bytes = new byte[samples.Length * 2];
|
||||
for (int i = 0; i < samples.Length; i++)
|
||||
{
|
||||
short s = (short)Math.Clamp((int)MathF.Round(samples[i] * 32767f), short.MinValue, short.MaxValue);
|
||||
bytes[2 * i] = (byte)s;
|
||||
bytes[2 * i + 1] = (byte)(s >> 8);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Godot;
|
||||
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>Bus audio del client: Master e quattro bus che vi confluiscono.</summary>
|
||||
public static class AudioBuses
|
||||
{
|
||||
public const string Master = "Master";
|
||||
public const string Music = "Music";
|
||||
public const string Ambience = "Ambience";
|
||||
public const string Sfx = "Sfx";
|
||||
public const string Ui = "Ui";
|
||||
|
||||
/// <summary>Nell'ordine dei cursori delle impostazioni.</summary>
|
||||
public static readonly string[] All = [Master, Music, Ambience, Sfx, Ui];
|
||||
|
||||
/// <summary>
|
||||
/// Crea i bus che mancano (idempotente: chiamarla più volte non ne aggiunge altri) e un
|
||||
/// limitatore sul Master, così la somma di musica, ambiente ed effetti non satura.
|
||||
/// </summary>
|
||||
public static void Ensure()
|
||||
{
|
||||
foreach (string name in All)
|
||||
{
|
||||
if (name == Master || AudioServer.GetBusIndex(name) >= 0) continue;
|
||||
int index = AudioServer.BusCount;
|
||||
AudioServer.AddBus(index);
|
||||
AudioServer.SetBusName(index, name);
|
||||
AudioServer.SetBusSend(index, Master);
|
||||
}
|
||||
bool limited = false;
|
||||
for (int i = 0; i < AudioServer.GetBusEffectCount(0); i++)
|
||||
{
|
||||
if (AudioServer.GetBusEffect(0, i) is AudioEffectHardLimiter) limited = true;
|
||||
}
|
||||
if (!limited) AudioServer.AddBusEffect(0, new AudioEffectHardLimiter { CeilingDb = -0.5f });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Volumi per bus (0–1) e muto generale, salvati nella sezione «audio» di
|
||||
/// <c>user://settings.cfg</c> (lo stesso file della lingua e del server).
|
||||
/// </summary>
|
||||
public sealed class AudioSettings
|
||||
{
|
||||
public const string Path = "user://settings.cfg";
|
||||
private const string Section = "audio";
|
||||
|
||||
private static readonly float[] Defaults = [0.8f, 0.55f, 0.7f, 0.8f, 0.7f];
|
||||
|
||||
/// <summary>Volumi nell'ordine di <see cref="AudioBuses.All"/>.</summary>
|
||||
public float[] Volumes { get; } = (float[])Defaults.Clone();
|
||||
|
||||
public bool Muted { get; set; }
|
||||
|
||||
public static AudioSettings Load()
|
||||
{
|
||||
var s = new AudioSettings();
|
||||
var cfg = new ConfigFile();
|
||||
if (cfg.Load(Path) != Error.Ok) return s;
|
||||
for (int i = 0; i < AudioBuses.All.Length; i++)
|
||||
{
|
||||
float v = (float)(double)cfg.GetValue(Section, Key(i), Defaults[i]);
|
||||
s.Volumes[i] = Math.Clamp(v, 0, 1);
|
||||
}
|
||||
s.Muted = (bool)cfg.GetValue(Section, "muted", false);
|
||||
return s;
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(Path);
|
||||
for (int i = 0; i < AudioBuses.All.Length; i++) cfg.SetValue(Section, Key(i), Volumes[i]);
|
||||
cfg.SetValue(Section, "muted", Muted);
|
||||
cfg.Save(Path);
|
||||
}
|
||||
|
||||
private static string Key(int i) => AudioBuses.All[i].ToLowerInvariant();
|
||||
|
||||
/// <summary>Applica volumi e muto ai bus (il cursore segue il volume percepito: guadagno = valore²).</summary>
|
||||
public void Apply()
|
||||
{
|
||||
for (int i = 0; i < AudioBuses.All.Length; i++)
|
||||
{
|
||||
int bus = AudioServer.GetBusIndex(AudioBuses.All[i]);
|
||||
if (bus >= 0) AudioServer.SetBusVolumeDb(bus, AudioMix.LinearToDb(Volumes[i] * Volumes[i]));
|
||||
}
|
||||
AudioServer.SetBusMute(0, Muted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>
|
||||
/// Pannello «Audio» sopra a tutto: un cursore per bus (generale, musica, ambiente, effetti,
|
||||
/// interfaccia) e il muto generale. I cambi si sentono subito; quando il pannello esce dall'albero
|
||||
/// (anche chiudendo la finestra del gioco) si salvano in <c>user://settings.cfg</c>. Esc o un clic
|
||||
/// sinistro fuori chiudono.
|
||||
/// </summary>
|
||||
public partial class AudioSettingsPanel : Control
|
||||
{
|
||||
private readonly AudioManager _audio;
|
||||
private readonly List<(HSlider Slider, Label Value)> _rows = [];
|
||||
private readonly CheckBox _mute = new() { Text = T("Muto") };
|
||||
|
||||
private static readonly string[] Captions = ["Volume generale", "Musica", "Ambiente", "Effetti", "Interfaccia"];
|
||||
|
||||
public AudioSettingsPanel(AudioManager audio) => _audio = audio;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
UiTheme.Apply(this);
|
||||
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.5f), MouseFilter = MouseFilterEnum.Stop };
|
||||
shade.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
shade.GuiInput += e =>
|
||||
{
|
||||
// solo il clic sinistro: la rotella e il tasto destro arrivano anch'essi come pressioni
|
||||
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) Close();
|
||||
};
|
||||
AddChild(shade);
|
||||
var center = new CenterContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||||
center.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
AddChild(center);
|
||||
var panel = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
|
||||
center.AddChild(panel);
|
||||
var col = new VBoxContainer();
|
||||
col.AddThemeConstantOverride("separation", 12);
|
||||
panel.AddChild(col);
|
||||
col.AddChild(UiTheme.TitleLabel(T("Audio"), 34));
|
||||
|
||||
for (int i = 0; i < Captions.Length; i++)
|
||||
{
|
||||
int bus = i;
|
||||
var row = new HBoxContainer();
|
||||
row.AddThemeConstantOverride("separation", 12);
|
||||
var caption = UiTheme.Text(T(Captions[i]), 14, Palette.TextSecondary);
|
||||
caption.CustomMinimumSize = new Vector2(150, 0);
|
||||
row.AddChild(caption);
|
||||
var slider = new HSlider
|
||||
{
|
||||
MinValue = 0, MaxValue = 1, Step = 0.05, SizeFlagsHorizontal = SizeFlags.ExpandFill,
|
||||
SizeFlagsVertical = SizeFlags.ShrinkCenter, Value = _audio.Settings.Volumes[i],
|
||||
};
|
||||
var value = UiTheme.Text("", 14, bold: true);
|
||||
value.CustomMinimumSize = new Vector2(48, 0);
|
||||
value.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
slider.ValueChanged += v => _audio.SetVolume(bus, (float)v);
|
||||
row.AddChild(slider);
|
||||
row.AddChild(value);
|
||||
col.AddChild(row);
|
||||
_rows.Add((slider, value));
|
||||
}
|
||||
_mute.ButtonPressed = _audio.Settings.Muted;
|
||||
_mute.Toggled += on => _audio.SetMuted(on);
|
||||
col.AddChild(_mute);
|
||||
var hint = UiTheme.Text(T("Il tasto M attiva e toglie il muto durante la partita."), 13, Palette.TextSecondary);
|
||||
hint.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(hint);
|
||||
var close = UiTheme.Primary(T("Chiudi"));
|
||||
close.Pressed += Close;
|
||||
col.AddChild(close);
|
||||
_audio.SettingsChanged += Refresh;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
_audio.SettingsChanged -= Refresh;
|
||||
_audio.SaveSettings();
|
||||
}
|
||||
|
||||
private void Refresh()
|
||||
{
|
||||
for (int i = 0; i < _rows.Count; i++)
|
||||
{
|
||||
_rows[i].Slider.SetValueNoSignal(_audio.Settings.Volumes[i]);
|
||||
_rows[i].Value.Text = $"{Math.Round(_audio.Settings.Volumes[i] * 100):0} %";
|
||||
}
|
||||
_mute.SetPressedNoSignal(_audio.Settings.Muted);
|
||||
}
|
||||
|
||||
public override void _Input(InputEvent e)
|
||||
{
|
||||
if (e is InputEventKey { Pressed: true, Keycode: Key.Escape })
|
||||
{
|
||||
Close();
|
||||
GetViewport().SetInputAsHandled();
|
||||
}
|
||||
}
|
||||
|
||||
private void Close()
|
||||
{
|
||||
if (IsQueuedForDeletion()) return;
|
||||
QueueFree();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>
|
||||
/// Temi musicali procedurali per era, senza dipendenze da Godot. Ogni era ha uno stile (tempo,
|
||||
/// metro, scala, timbri: valzer da carillon e fisarmonica per il vapore, organo e basso che
|
||||
/// cammina per il diesel, vibrafono e archi per l'elettrico, arpeggi a impulsi per l'alta
|
||||
/// velocità); progressione, arpeggio e melodia escono da un seme fisso (hash dell'id dell'era),
|
||||
/// quindi lo stesso tema a ogni avvio. Forma in 16 battute: introduzione (accompagnamento),
|
||||
/// melodia, melodia variata, coda; le code delle note rientrano dall'inizio, così l'anello si
|
||||
/// ripete senza scatti. Uscita mono a <see cref="Synth.Rate"/> Hz.
|
||||
/// </summary>
|
||||
public static class MusicComposer
|
||||
{
|
||||
public const int Bars = 16;
|
||||
|
||||
public enum Timbre { MusicBox, Accordion, Organ, Vibraphone, Strings, Pulse, Saw, SoftBass, PluckBass }
|
||||
|
||||
public enum Comping { Held, Waltz }
|
||||
|
||||
/// <summary>Stile di un'era.</summary>
|
||||
public sealed record Style(int Bpm, int BeatsPerBar, int[] Scale, int RootMidi, Timbre Pad, Comping Comping,
|
||||
Timbre Arp, int ArpPerBeat, Timbre Lead, Timbre Bass, bool WalkingBass, float Swing);
|
||||
|
||||
private static readonly int[] Major = [0, 2, 4, 5, 7, 9, 11];
|
||||
private static readonly int[] Mixolydian = [0, 2, 4, 5, 7, 9, 10];
|
||||
private static readonly int[] Dorian = [0, 2, 3, 5, 7, 9, 10];
|
||||
|
||||
/// <summary>Progressioni per grado della scala (0 = primo grado), una battuta per accordo.</summary>
|
||||
private static readonly int[][] Progressions =
|
||||
[
|
||||
[0, 3, 4, 0], [0, 5, 3, 4], [0, 4, 5, 3], [1, 4, 0, 5], [5, 3, 0, 4], [0, 3, 1, 4],
|
||||
];
|
||||
|
||||
/// <summary>Stile dell'era per posizione nell'elenco di eras.json (le ere oltre la quarta riprendono il ciclo).</summary>
|
||||
public static Style StyleFor(int eraIndex) => (Math.Max(0, eraIndex) % 4) switch
|
||||
{
|
||||
0 => new Style(116, 3, Major, 62, Timbre.Accordion, Comping.Waltz, Timbre.MusicBox, 0, Timbre.MusicBox, Timbre.SoftBass, false, 0),
|
||||
1 => new Style(96, 4, Mixolydian, 60, Timbre.Organ, Comping.Held, Timbre.Vibraphone, 1, Timbre.Organ, Timbre.PluckBass, true, 0.18f),
|
||||
2 => new Style(104, 4, Major, 65, Timbre.Strings, Comping.Held, Timbre.Vibraphone, 2, Timbre.Vibraphone, Timbre.SoftBass, false, 0),
|
||||
_ => new Style(124, 4, Dorian, 57, Timbre.Saw, Comping.Held, Timbre.Pulse, 4, Timbre.Saw, Timbre.SoftBass, false, 0),
|
||||
};
|
||||
|
||||
/// <summary>Seme fisso del tema: hash dell'id dell'era e della sua posizione.</summary>
|
||||
public static ulong Seed(int eraIndex, string eraId) => SynthRng.Hash(eraId) ^ ((ulong)(eraIndex + 1) * 0x9E3779B97F4A7C15UL);
|
||||
|
||||
/// <summary>Durata dell'anello in secondi.</summary>
|
||||
public static float LengthSeconds(Style style) => Bars * style.BeatsPerBar * 60f / style.Bpm;
|
||||
|
||||
// ------------------------------------------------------------------ timbri
|
||||
|
||||
private sealed class Voice
|
||||
{
|
||||
/// <summary>Ampiezza della n-esima armonica in Harmonics[n−1].</summary>
|
||||
public required float[] Harmonics { get; init; }
|
||||
public float Attack { get; init; } = 0.005f;
|
||||
/// <summary>Decadimento verso il sostegno (s).</summary>
|
||||
public float Decay { get; init; } = 0.3f;
|
||||
public float Sustain { get; init; }
|
||||
public float Release { get; init; } = 0.1f;
|
||||
/// <summary>Copie leggermente scordate (coro).</summary>
|
||||
public float[] Detune { get; init; } = [0];
|
||||
public float TremoloHz { get; init; }
|
||||
public float TremoloDepth { get; init; }
|
||||
public float VibratoDepth { get; init; }
|
||||
|
||||
// tabelle per numero di armoniche tenute (una per registro, costruite al primo uso)
|
||||
private readonly Dictionary<int, float[]> _tables = [];
|
||||
|
||||
/// <summary>
|
||||
/// Forma d'onda per una nota alla frequenza data, con le sole armoniche sotto
|
||||
/// <see cref="MaxHarmonicShare"/> della frequenza di campionamento: quelle oltre Nyquist
|
||||
/// tornerebbero indietro come toni stonati.
|
||||
/// </summary>
|
||||
public float[] TableFor(float frequency)
|
||||
{
|
||||
int n = Math.Clamp((int)(MaxHarmonicShare * Synth.Rate / frequency), 1, Harmonics.Length);
|
||||
if (!_tables.TryGetValue(n, out var table))
|
||||
{
|
||||
table = Table(Harmonics, n);
|
||||
_tables[n] = table;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frazione della frequenza di campionamento sotto cui stanno le armoniche (margine per vibrato e coro).</summary>
|
||||
private const float MaxHarmonicShare = 0.45f;
|
||||
|
||||
private const int TableSize = 2048;
|
||||
|
||||
/// <summary>Forma d'onda di un periodo dalla somma delle prime «count» armoniche (ampiezza della n-esima in harmonics[n−1]).</summary>
|
||||
private static float[] Table(float[] harmonics, int count)
|
||||
{
|
||||
var t = new float[TableSize];
|
||||
for (int i = 0; i < TableSize; i++)
|
||||
{
|
||||
float x = MathF.PI * 2 * i / TableSize;
|
||||
float v = 0;
|
||||
for (int h = 0; h < count; h++) v += harmonics[h] * MathF.Sin(x * (h + 1));
|
||||
t[i] = v;
|
||||
}
|
||||
Synth.Normalize(t, 1);
|
||||
return t;
|
||||
}
|
||||
|
||||
private static float[] SawHarmonics(int n)
|
||||
{
|
||||
var h = new float[n];
|
||||
for (int i = 0; i < n; i++) h[i] = 1f / (i + 1);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static float[] PulseHarmonics(int n, float duty)
|
||||
{
|
||||
var h = new float[n];
|
||||
for (int i = 0; i < n; i++) h[i] = MathF.Abs(MathF.Sin(MathF.PI * (i + 1) * duty)) / (i + 1);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static Voice VoiceFor(Timbre timbre) => timbre switch
|
||||
{
|
||||
Timbre.MusicBox => new Voice { Harmonics = [1, 0.1f, 0.35f, 0, 0.12f], Attack = 0.002f, Decay = 0.7f, Sustain = 0, Release = 0.6f },
|
||||
Timbre.Accordion => new Voice { Harmonics = [1, 0.5f, 0.6f, 0.3f, 0.25f, 0.15f], Attack = 0.03f, Decay = 0.2f, Sustain = 0.8f, Release = 0.08f, Detune = [0, 0.004f], TremoloHz = 5, TremoloDepth = 0.12f },
|
||||
Timbre.Organ => new Voice { Harmonics = [1, 0.8f, 0.6f, 0.4f, 0, 0.3f, 0, 0.2f], Attack = 0.01f, Decay = 0.1f, Sustain = 0.9f, Release = 0.06f, TremoloHz = 6, TremoloDepth = 0.1f },
|
||||
Timbre.Vibraphone => new Voice { Harmonics = [1, 0, 0, 0.25f], Attack = 0.003f, Decay = 1.1f, Sustain = 0, Release = 0.8f, TremoloHz = 5, TremoloDepth = 0.3f },
|
||||
Timbre.Strings => new Voice { Harmonics = SawHarmonics(8), Attack = 0.3f, Decay = 0.5f, Sustain = 0.85f, Release = 0.35f, Detune = [-0.003f, 0, 0.003f], VibratoDepth = 0.003f },
|
||||
Timbre.Pulse => new Voice { Harmonics = PulseHarmonics(9, 0.25f), Attack = 0.004f, Decay = 0.22f, Sustain = 0, Release = 0.15f },
|
||||
Timbre.Saw => new Voice { Harmonics = SawHarmonics(10), Attack = 0.08f, Decay = 0.4f, Sustain = 0.7f, Release = 0.25f, Detune = [-0.005f, 0.005f], VibratoDepth = 0.002f },
|
||||
Timbre.PluckBass => new Voice { Harmonics = [1, 0.5f, 0.25f, 0.1f], Attack = 0.005f, Decay = 0.35f, Sustain = 0.15f, Release = 0.08f },
|
||||
_ => new Voice { Harmonics = [1, 0.3f, 0.1f], Attack = 0.01f, Decay = 0.4f, Sustain = 0.6f, Release = 0.1f },
|
||||
};
|
||||
|
||||
private static float Frequency(float midi) => 440f * MathF.Pow(2, (midi - 69) / 12f);
|
||||
|
||||
/// <summary>Suona una nota nell'anello (con la coda che rientra dall'inizio).</summary>
|
||||
private static void Note(float[] loop, Voice v, float startS, float durS, float midi, float gain)
|
||||
{
|
||||
int rate = Synth.Rate;
|
||||
float f = Frequency(midi);
|
||||
var table = v.TableFor(f);
|
||||
int start = (int)(startS * rate);
|
||||
float total = durS + v.Release;
|
||||
int samples = Math.Min(loop.Length, (int)(total * rate));
|
||||
foreach (float detune in v.Detune)
|
||||
{
|
||||
float inc = f * (1 + detune) * TableSize / rate;
|
||||
float phase = (detune + 0.5f) * 97 % TableSize;
|
||||
float g = gain / v.Detune.Length;
|
||||
for (int i = 0; i < samples; i++)
|
||||
{
|
||||
float t = i / (float)rate;
|
||||
float env = t < v.Attack ? t / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(t - v.Attack) / v.Decay);
|
||||
if (t > durS)
|
||||
{
|
||||
// rilascio dal livello raggiunto alla fine della nota
|
||||
float atEnd = durS < v.Attack ? durS / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(durS - v.Attack) / v.Decay);
|
||||
env = atEnd * MathF.Max(0, 1 - (t - durS) / v.Release);
|
||||
}
|
||||
if (v.TremoloDepth > 0) env *= 1 - v.TremoloDepth * (0.5f + 0.5f * MathF.Sin(MathF.PI * 2 * v.TremoloHz * t));
|
||||
float step = v.VibratoDepth > 0 ? inc * (1 + v.VibratoDepth * MathF.Sin(MathF.PI * 2 * 5.5f * t)) : inc;
|
||||
phase += step;
|
||||
if (phase >= TableSize) phase -= TableSize;
|
||||
int i0 = (int)phase;
|
||||
float frac = phase - i0;
|
||||
float s = table[i0] + (table[(i0 + 1) & (TableSize - 1)] - table[i0]) * frac;
|
||||
loop[(start + i) % loop.Length] += s * env * g;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Altezza MIDI del grado della scala (i gradi oltre la scala salgono d'ottava).</summary>
|
||||
private static int Degree(Style s, int degree)
|
||||
{
|
||||
int n = s.Scale.Length;
|
||||
int octave = (int)Math.Floor(degree / (double)n);
|
||||
int d = degree - octave * n;
|
||||
return s.RootMidi + s.Scale[d] + 12 * octave;
|
||||
}
|
||||
|
||||
/// <summary>Compone e sintetizza il tema dell'era: campioni mono in [−1, 1].</summary>
|
||||
public static float[] Compose(int eraIndex, string eraId)
|
||||
{
|
||||
var style = StyleFor(eraIndex);
|
||||
var rng = new SynthRng(Seed(eraIndex, eraId));
|
||||
float beat = 60f / style.Bpm;
|
||||
float bar = beat * style.BeatsPerBar;
|
||||
var loop = new float[(int)(LengthSeconds(style) * Synth.Rate)];
|
||||
var progression = Progressions[rng.Next(Progressions.Length)];
|
||||
var pad = VoiceFor(style.Pad);
|
||||
var arp = VoiceFor(style.Arp);
|
||||
var lead = VoiceFor(style.Lead);
|
||||
var bass = VoiceFor(style.Bass);
|
||||
bool arpDown = rng.Next(2) == 0;
|
||||
|
||||
// motivo di quattro battute: un ritmo per battuta (in ottavi) e gradi vicini all'accordo
|
||||
int eighths = style.BeatsPerBar * 2;
|
||||
var motif = new List<(int Bar, int Eighth, int Length, int Degree)>();
|
||||
int current = 7 + progression[0];
|
||||
for (int b = 0; b < 4; b++)
|
||||
{
|
||||
int chord = progression[b];
|
||||
int e = 0;
|
||||
while (e < eighths)
|
||||
{
|
||||
int len = rng.Next(4) switch { 0 => 1, 1 or 2 => 2, _ => 3 };
|
||||
len = Math.Min(len, eighths - e);
|
||||
if (rng.Next(5) == 0 && e > 0)
|
||||
{
|
||||
e += len; // pausa
|
||||
continue;
|
||||
}
|
||||
bool strong = e % (style.BeatsPerBar == 3 ? 6 : 4) == 0;
|
||||
if (strong)
|
||||
{
|
||||
// sui tempi forti una nota dell'accordo vicina alla precedente
|
||||
int best = current, bestD = int.MaxValue;
|
||||
for (int k = -1; k <= 2; k++)
|
||||
{
|
||||
foreach (int ct in new[] { 0, 2, 4 })
|
||||
{
|
||||
int cand = chord + ct + 7 * k;
|
||||
int dist = Math.Abs(cand - current);
|
||||
if (cand >= 4 && cand <= 13 && dist < bestD)
|
||||
{
|
||||
bestD = dist;
|
||||
best = cand;
|
||||
}
|
||||
}
|
||||
}
|
||||
current = best;
|
||||
}
|
||||
else current = Math.Clamp(current + rng.Next(5) - 2, 4, 13);
|
||||
motif.Add((b, e, len, current));
|
||||
e += len;
|
||||
}
|
||||
}
|
||||
// l'ultima nota del motivo torna sulla tonica
|
||||
if (motif.Count > 0) motif[^1] = motif[^1] with { Degree = 7 };
|
||||
|
||||
for (int barIndex = 0; barIndex < Bars; barIndex++)
|
||||
{
|
||||
int chord = progression[barIndex % 4];
|
||||
float t0 = barIndex * bar;
|
||||
int[] tones = [Degree(style, chord), Degree(style, chord + 2), Degree(style, chord + 4)];
|
||||
|
||||
// accompagnamento
|
||||
if (style.Comping == Comping.Waltz)
|
||||
{
|
||||
for (int k = 1; k < style.BeatsPerBar; k++)
|
||||
foreach (int m in tones) Note(loop, pad, t0 + k * beat, beat * 0.55f, m, 0.11f);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (int m in tones) Note(loop, pad, t0, bar * 0.95f, m, 0.12f);
|
||||
}
|
||||
|
||||
// basso: fondamentale (e quinta) o basso che cammina sulle note dell'accordo
|
||||
int root = Degree(style, chord) - 24;
|
||||
if (style.WalkingBass)
|
||||
{
|
||||
int next = Degree(style, progression[(barIndex + 1) % 4]) - 24;
|
||||
int[] walk = [root, root + (tones[1] - tones[0]), root + 7, next + (next > root ? -1 : 1)];
|
||||
for (int k = 0; k < style.BeatsPerBar; k++) Note(loop, bass, t0 + k * beat, beat * 0.9f, walk[k % walk.Length], 0.32f);
|
||||
}
|
||||
else if (style.Comping == Comping.Waltz) Note(loop, bass, t0, beat * 0.9f, root, 0.34f);
|
||||
else
|
||||
{
|
||||
Note(loop, bass, t0, beat * 1.8f, root, 0.32f);
|
||||
Note(loop, bass, t0 + 2 * beat, beat * 1.8f, root + 7, 0.26f);
|
||||
}
|
||||
|
||||
// arpeggio (in introduzione e coda più presente)
|
||||
if (style.ArpPerBeat > 0)
|
||||
{
|
||||
int steps = style.BeatsPerBar * style.ArpPerBeat;
|
||||
float step = beat / style.ArpPerBeat;
|
||||
float gain = barIndex is < 4 or >= 12 ? 0.13f : 0.08f;
|
||||
for (int k = 0; k < steps; k++)
|
||||
{
|
||||
int idx = arpDown ? 3 - k % 4 : k % 4;
|
||||
int m = idx < 3 ? tones[idx] + 12 : tones[0] + 24;
|
||||
float swing = style.Swing > 0 && k % 2 == 1 ? style.Swing * step : 0;
|
||||
Note(loop, arp, t0 + k * step + swing, step * 0.8f, m, gain);
|
||||
}
|
||||
}
|
||||
|
||||
// melodia nelle battute 4–11 (la seconda volta un'ottava sopra le ultime due battute)
|
||||
if (barIndex is >= 4 and < 12)
|
||||
{
|
||||
int motifBar = barIndex % 4;
|
||||
bool variation = barIndex >= 8;
|
||||
foreach (var n in motif)
|
||||
{
|
||||
if (n.Bar != motifBar) continue;
|
||||
float eighth = beat / 2;
|
||||
float swing = style.Swing > 0 && n.Eighth % 2 == 1 ? style.Swing * eighth : 0;
|
||||
int midi = Degree(style, n.Degree) + (variation && motifBar >= 2 ? 12 : 0);
|
||||
Note(loop, lead, t0 + n.Eighth * eighth + swing, n.Length * eighth * 0.92f, midi, 0.2f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// un po' di spazio: due echi smorzati sull'anello, poi limitazione morbida
|
||||
Echo(loop, 0.27f, 0.22f);
|
||||
Echo(loop, 0.41f, 0.15f);
|
||||
Synth.Normalize(loop, 1);
|
||||
for (int i = 0; i < loop.Length; i++) loop[i] = MathF.Tanh(loop[i] * 1.2f) * 0.7f;
|
||||
return loop;
|
||||
}
|
||||
|
||||
/// <summary>Eco con retroazione su un anello (due giri per la continuità all'inizio).</summary>
|
||||
private static void Echo(float[] loop, float delayS, float feedback)
|
||||
{
|
||||
int d = Math.Max(1, (int)(delayS * Synth.Rate));
|
||||
var lp = Biquad.LowPass(2500, 0.7f, Synth.Rate);
|
||||
var wet = new float[loop.Length];
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < loop.Length; i++)
|
||||
{
|
||||
int j = (i - d + loop.Length) % loop.Length;
|
||||
wet[i] = lp.Process(loop[j] + wet[j] * feedback) * feedback;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < loop.Length; i++) loop[i] += wet[i];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>Altoparlante nella barra superiore: apre il pannello «Audio»; barrato quando il muto è attivo.</summary>
|
||||
public partial class SpeakerButton : Button
|
||||
{
|
||||
public SpeakerButton()
|
||||
{
|
||||
Flat = true;
|
||||
CustomMinimumSize = new Vector2(40, 40);
|
||||
TooltipText = T("Audio (M: muto)");
|
||||
Pressed += () => AudioManager.Instance?.ShowSettings();
|
||||
MouseEntered += QueueRedraw;
|
||||
MouseExited += QueueRedraw;
|
||||
}
|
||||
|
||||
public override void _EnterTree()
|
||||
{
|
||||
if (AudioManager.Instance is { } audio) audio.SettingsChanged += QueueRedraw;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
if (AudioManager.Instance is { } audio) audio.SettingsChanged -= QueueRedraw;
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
bool muted = AudioManager.Instance?.Settings.Muted ?? false;
|
||||
var col = IsHovered() ? Palette.AmberLight : muted ? Palette.TextSecondary : Palette.Text;
|
||||
var c = Size / 2;
|
||||
const float w = 2f;
|
||||
// cassa e cono
|
||||
DrawColoredPolygon([c + new Vector2(-10, -4), c + new Vector2(-5, -4), c + new Vector2(1, -10), c + new Vector2(1, 10), c + new Vector2(-5, 4), c + new Vector2(-10, 4)], col);
|
||||
if (muted)
|
||||
{
|
||||
DrawLine(c + new Vector2(5, -5), c + new Vector2(13, 5), Palette.Danger, w);
|
||||
DrawLine(c + new Vector2(13, -5), c + new Vector2(5, 5), Palette.Danger, w);
|
||||
}
|
||||
else
|
||||
{
|
||||
DrawArc(c + new Vector2(1, 0), 6, -0.9f, 0.9f, 10, col, w);
|
||||
DrawArc(c + new Vector2(1, 0), 11, -0.9f, 0.9f, 14, col, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
namespace RailEnterprise.Client.Audio;
|
||||
|
||||
/// <summary>
|
||||
/// Generatore pseudo-casuale xorshift64* per la sintesi dei suoni. Non è il <c>Rng</c> della
|
||||
/// simulazione: serve solo a rendere ripetibili rumori, variazioni e temi musicali del client.
|
||||
/// </summary>
|
||||
public struct SynthRng
|
||||
{
|
||||
private ulong _s;
|
||||
|
||||
public SynthRng(ulong seed) => _s = seed == 0 ? 0x9E3779B97F4A7C15UL : seed;
|
||||
|
||||
public ulong NextU64()
|
||||
{
|
||||
_s ^= _s >> 12;
|
||||
_s ^= _s << 25;
|
||||
_s ^= _s >> 27;
|
||||
return _s * 2685821657736338717UL;
|
||||
}
|
||||
|
||||
/// <summary>Numero in [0, 1).</summary>
|
||||
public float Next01() => (NextU64() >> 40) * (1f / (1 << 24));
|
||||
|
||||
/// <summary>Numero in [−1, 1).</summary>
|
||||
public float NextSigned() => Next01() * 2f - 1f;
|
||||
|
||||
/// <summary>Intero in [0, n).</summary>
|
||||
public int Next(int n) => (int)((NextU64() >> 33) % (ulong)n);
|
||||
|
||||
/// <summary>Numero in [a, b).</summary>
|
||||
public float Range(float a, float b) => a + (b - a) * Next01();
|
||||
|
||||
/// <summary>FNV-1a a 64 bit di una stringa: semi fissi derivati da un identificatore (per esempio l'id dell'era).</summary>
|
||||
public static ulong Hash(string text)
|
||||
{
|
||||
ulong h = 14695981039346656037UL;
|
||||
foreach (char c in text)
|
||||
{
|
||||
h ^= c;
|
||||
h *= 1099511628211UL;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Filtro biquadratico (formule RBJ): passa-basso, passa-alto, passa-banda a guadagno di picco unitario.</summary>
|
||||
public struct Biquad
|
||||
{
|
||||
private float _b0, _b1, _b2, _a1, _a2, _z1, _z2;
|
||||
|
||||
private static Biquad Make(float b0, float b1, float b2, float a0, float a1, float a2) =>
|
||||
new() { _b0 = b0 / a0, _b1 = b1 / a0, _b2 = b2 / a0, _a1 = a1 / a0, _a2 = a2 / a0 };
|
||||
|
||||
private static (float Cos, float Alpha) W(float freq, float q, int rate)
|
||||
{
|
||||
float w0 = 2 * MathF.PI * Math.Clamp(freq, 1, rate * 0.45f) / rate;
|
||||
return (MathF.Cos(w0), MathF.Sin(w0) / (2 * q));
|
||||
}
|
||||
|
||||
public static Biquad LowPass(float freq, float q, int rate)
|
||||
{
|
||||
var (c, a) = W(freq, q, rate);
|
||||
return Make((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + a, -2 * c, 1 - a);
|
||||
}
|
||||
|
||||
public static Biquad HighPass(float freq, float q, int rate)
|
||||
{
|
||||
var (c, a) = W(freq, q, rate);
|
||||
return Make((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + a, -2 * c, 1 - a);
|
||||
}
|
||||
|
||||
public static Biquad BandPass(float freq, float q, int rate)
|
||||
{
|
||||
var (c, a) = W(freq, q, rate);
|
||||
return Make(a, 0, -a, 1 + a, -2 * c, 1 - a);
|
||||
}
|
||||
|
||||
/// <summary>Cambia i coefficienti mantenendo lo stato (filtri a frequenza variabile).</summary>
|
||||
public void Retune(Biquad coefficients)
|
||||
{
|
||||
_b0 = coefficients._b0;
|
||||
_b1 = coefficients._b1;
|
||||
_b2 = coefficients._b2;
|
||||
_a1 = coefficients._a1;
|
||||
_a2 = coefficients._a2;
|
||||
}
|
||||
|
||||
public float Process(float x)
|
||||
{
|
||||
float y = _b0 * x + _z1;
|
||||
_z1 = _b1 * x - _a1 * y + _z2;
|
||||
_z2 = _b2 * x - _a2 * y;
|
||||
return y;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sintesi procedurale di tutti gli effetti del gioco, senza dipendenze da Godot: ogni funzione
|
||||
/// restituisce campioni mono in virgola mobile a <see cref="Rate"/> Hz, da convertire in PCM a
|
||||
/// 16 bit con <see cref="AudioMix.ToPcm16"/>. Gli anelli («Loop») si ripetono senza scatti: i
|
||||
/// filtri girano due volte sullo stesso rumore (la seconda passata parte dallo stato della fine),
|
||||
/// le modulazioni hanno un numero intero di periodi nell'anello e le code degli eventi brevi
|
||||
/// rientrano dall'inizio. Semi fissi: stesso suono a ogni avvio.
|
||||
/// </summary>
|
||||
public static class Synth
|
||||
{
|
||||
/// <summary>Frequenza di campionamento di tutti i suoni (Hz).</summary>
|
||||
public const int Rate = 22050;
|
||||
|
||||
private const float Tau = MathF.PI * 2;
|
||||
|
||||
public static float[] Buffer(float seconds) => new float[Math.Max(1, (int)(seconds * Rate))];
|
||||
|
||||
/// <summary>Inviluppo attacco lineare e decadimento esponenziale.</summary>
|
||||
public static float Env(float t, float attack, float decay) =>
|
||||
t < 0 ? 0 : t < attack ? t / attack : MathF.Exp(-(t - attack) / decay);
|
||||
|
||||
/// <summary>Porta il picco al valore indicato.</summary>
|
||||
public static void Normalize(float[] buffer, float peak)
|
||||
{
|
||||
float max = 0;
|
||||
foreach (float s in buffer) max = Math.Max(max, Math.Abs(s));
|
||||
if (max < 1e-6f) return;
|
||||
float k = peak / max;
|
||||
for (int i = 0; i < buffer.Length; i++) buffer[i] *= k;
|
||||
}
|
||||
|
||||
/// <summary>Sfuma gli ultimi millisecondi di un suono singolo (niente scatto alla fine).</summary>
|
||||
public static void FadeOut(float[] buffer, float seconds = 0.01f)
|
||||
{
|
||||
int n = Math.Min(buffer.Length, (int)(seconds * Rate));
|
||||
for (int i = 0; i < n; i++) buffer[buffer.Length - 1 - i] *= i / (float)n;
|
||||
}
|
||||
|
||||
/// <summary>Rumore bianco ripetibile.</summary>
|
||||
public static float[] Noise(int length, ulong seed)
|
||||
{
|
||||
var rng = new SynthRng(seed);
|
||||
var n = new float[length];
|
||||
for (int i = 0; i < length; i++) n[i] = rng.NextSigned();
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>Filtra un anello due volte: la seconda passata riparte dallo stato della fine della prima.</summary>
|
||||
public static float[] LoopFilter(float[] input, Biquad filter)
|
||||
{
|
||||
var output = new float[input.Length];
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < input.Length; i++) output[i] = filter.Process(input[i]);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>Rumore marrone in anello: integrazione con perdita del rumore bianco, due passate.</summary>
|
||||
public static float[] BrownLoop(int length, ulong seed, float leak)
|
||||
{
|
||||
var white = Noise(length, seed);
|
||||
var brown = new float[length];
|
||||
float acc = 0;
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
acc = acc * leak + white[i] * (1 - leak) * 10;
|
||||
brown[i] = acc;
|
||||
}
|
||||
}
|
||||
return brown;
|
||||
}
|
||||
|
||||
/// <summary>Somma un suono breve nell'anello a partire da «at» campioni, con la coda che rientra dall'inizio.</summary>
|
||||
public static void MixWrapped(float[] loop, float[] sound, int at, float gain)
|
||||
{
|
||||
for (int i = 0; i < sound.Length; i++) loop[(at + i) % loop.Length] += sound[i] * gain;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ interfaccia
|
||||
|
||||
/// <summary>Clic dell'interfaccia: un colpetto secco e brillante.</summary>
|
||||
public static float[] Click()
|
||||
{
|
||||
var b = Buffer(0.035f);
|
||||
var noise = Noise(b.Length, 11);
|
||||
var hp = Biquad.HighPass(2500, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
b[i] = MathF.Sin(Tau * 1800 * t) * MathF.Exp(-t / 0.006f) * 0.6f + hp.Process(noise[i]) * MathF.Exp(-t / 0.003f) * 0.5f;
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
FadeOut(b, 0.005f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Nota con armoniche (ampiezze in «harmonics», la prima è la fondamentale) e decadimento esponenziale.</summary>
|
||||
private static void Tone(float[] b, float start, float freq, float decay, float gain, float[] harmonics)
|
||||
{
|
||||
int s0 = (int)(start * Rate);
|
||||
for (int i = s0; i < b.Length; i++)
|
||||
{
|
||||
float t = (i - s0) / (float)Rate;
|
||||
float env = Env(t, 0.005f, decay);
|
||||
if (env < 1e-4f && t > 0.01f) break;
|
||||
float v = 0;
|
||||
for (int h = 0; h < harmonics.Length; h++)
|
||||
{
|
||||
float f = freq * (h + 1);
|
||||
if (harmonics[h] != 0 && f < Rate * 0.45f) v += harmonics[h] * MathF.Sin(Tau * f * t);
|
||||
}
|
||||
b[i] += v * env * gain;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Esito positivo di un comando: due note ascendenti (la, mi).</summary>
|
||||
public static float[] Confirm()
|
||||
{
|
||||
var b = Buffer(0.32f);
|
||||
float[] h = [1, 0.3f];
|
||||
Tone(b, 0, 880, 0.09f, 1, h);
|
||||
Tone(b, 0.07f, 1318.5f, 0.11f, 0.9f, h);
|
||||
Normalize(b, 0.42f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Comando rifiutato: due note scure discendenti.</summary>
|
||||
public static float[] Error()
|
||||
{
|
||||
var b = Buffer(0.38f);
|
||||
float[] h = [1, 0, 0.33f, 0, 0.2f];
|
||||
Tone(b, 0, 330, 0.12f, 1, h);
|
||||
Tone(b, 0.1f, 247, 0.14f, 1, h);
|
||||
var lp = Biquad.LowPass(1800, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++) b[i] = lp.Process(b[i]);
|
||||
Normalize(b, 0.45f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Campana in modulazione di frequenza (portante f, modulante 1,4·f, indice che decade).</summary>
|
||||
private static void Bell(float[] b, float start, float freq, float gain, float decay = 0.6f)
|
||||
{
|
||||
int s0 = (int)(start * Rate);
|
||||
for (int i = s0; i < b.Length; i++)
|
||||
{
|
||||
float t = (i - s0) / (float)Rate;
|
||||
float index = 2.5f * MathF.Exp(-t / 0.3f);
|
||||
b[i] += MathF.Sin(Tau * freq * t + index * MathF.Sin(Tau * freq * 1.4f * t)) * Env(t, 0.003f, decay) * gain;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Notifica: 0 = informazione o opportunità, 1 = avviso, 2 = critica.</summary>
|
||||
public static float[] Notify(int level)
|
||||
{
|
||||
float[] b;
|
||||
switch (level)
|
||||
{
|
||||
case <= 0:
|
||||
b = Buffer(1.0f);
|
||||
Bell(b, 0, 1046.5f, 1);
|
||||
Bell(b, 0.12f, 1568f, 0.6f);
|
||||
break;
|
||||
case 1:
|
||||
b = Buffer(1.2f);
|
||||
Bell(b, 0, 784f, 1, 0.7f);
|
||||
Bell(b, 0.18f, 622.3f, 1, 0.7f);
|
||||
break;
|
||||
default:
|
||||
// tre impulsi dissonanti: si distinguono anche sopra la musica
|
||||
b = Buffer(1.0f);
|
||||
float[] h = [1, 0, 0.33f, 0, 0.2f];
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
Tone(b, k * 0.22f, 523.3f, 0.09f, 0.8f, h);
|
||||
Tone(b, k * 0.22f, 554.4f, 0.09f, 0.6f, h);
|
||||
}
|
||||
break;
|
||||
}
|
||||
Normalize(b, 0.55f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Cantiere completato: due colpi metallici e un arpeggio maggiore.</summary>
|
||||
public static float[] BuildComplete()
|
||||
{
|
||||
var b = Buffer(1.5f);
|
||||
var noise = Noise(b.Length, 23);
|
||||
foreach (var (at, gain) in new[] { (0f, 1f), (0.16f, 0.7f) })
|
||||
{
|
||||
int s0 = (int)(at * Rate);
|
||||
var bp = Biquad.BandPass(2500, 4, Rate);
|
||||
for (int i = s0; i < b.Length; i++)
|
||||
{
|
||||
float t = (i - s0) / (float)Rate;
|
||||
float metal = MathF.Sin(Tau * 420 * t + 3 * MathF.Exp(-t / 0.08f) * MathF.Sin(Tau * 420 * 2.76f * t));
|
||||
b[i] += (bp.Process(noise[i]) * 2 * Env(t, 0.001f, 0.04f) + metal * Env(t, 0.002f, 0.25f)) * gain * 0.6f;
|
||||
}
|
||||
}
|
||||
float[] pluck = [1, 0.4f, 0.15f];
|
||||
float[] notes = [523.3f, 659.3f, 784f, 1046.5f];
|
||||
for (int k = 0; k < notes.Length; k++) Tone(b, 0.32f + k * 0.08f, notes[k], k == notes.Length - 1 ? 0.35f : 0.15f, 0.7f, pluck);
|
||||
Normalize(b, 0.55f);
|
||||
FadeOut(b, 0.05f);
|
||||
return b;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ treni
|
||||
|
||||
/// <summary>Fischio a vapore all'arrivo: accordo 4:5:6 con salita d'intonazione, vibrato e soffio.</summary>
|
||||
public static float[] SteamWhistle()
|
||||
{
|
||||
var b = Buffer(1.35f);
|
||||
var noise = Noise(b.Length, 31);
|
||||
var bp = Biquad.BandPass(1500, 1.2f, Rate);
|
||||
float[] freqs = [520, 650, 780];
|
||||
float[] phase = new float[freqs.Length];
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float amp = t < 0.06f ? t / 0.06f : t < 1.05f ? 1 : MathF.Max(0, 1 - (t - 1.05f) / 0.3f);
|
||||
float bend = 0.94f + 0.06f * MathF.Min(1, t / 0.08f) - (t > 1.0f ? 0.03f * (t - 1.0f) : 0);
|
||||
float vib = 1 + 0.004f * MathF.Sin(Tau * 5.5f * t);
|
||||
float v = 0;
|
||||
for (int k = 0; k < freqs.Length; k++)
|
||||
{
|
||||
phase[k] += Tau * freqs[k] * bend * vib / Rate;
|
||||
v += MathF.Sin(phase[k]) / (k + 1.5f);
|
||||
}
|
||||
b[i] = (v + bp.Process(noise[i]) * 0.25f) * amp;
|
||||
}
|
||||
Normalize(b, 0.6f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Tromba bitonale delle locomotive diesel ed elettriche.</summary>
|
||||
public static float[] Horn()
|
||||
{
|
||||
var b = Buffer(0.95f);
|
||||
float[] freqs = [311.1f, 370f];
|
||||
var lp = Biquad.LowPass(2500, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float amp = t < 0.03f ? t / 0.03f : t < 0.78f ? 1 : MathF.Max(0, 1 - (t - 0.78f) / 0.15f);
|
||||
float v = 0;
|
||||
foreach (float f in freqs)
|
||||
{
|
||||
for (int h = 1; h <= 6; h++) v += MathF.Sin(Tau * f * h * t) / h;
|
||||
}
|
||||
b[i] = lp.Process(v) * amp;
|
||||
}
|
||||
Normalize(b, 0.55f);
|
||||
FadeOut(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Sbuffo del vapore: rumore filtrato a banda con un tonfo grave.</summary>
|
||||
public static float[] Chuff()
|
||||
{
|
||||
var b = Buffer(0.17f);
|
||||
var noise = Noise(b.Length, 41);
|
||||
var bp = Biquad.BandPass(900, 0.8f, Rate);
|
||||
var lp = Biquad.LowPass(2500, 0.7f, Rate);
|
||||
for (int i = 0; i < b.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
b[i] = lp.Process(bp.Process(noise[i])) * Env(t, 0.004f, 0.05f) + MathF.Sin(Tau * 70 * t) * Env(t, 0.002f, 0.04f) * 0.5f;
|
||||
}
|
||||
Normalize(b, 0.6f);
|
||||
FadeOut(b, 0.02f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Rotolamento in anello (1,6 s a intonazione 1): rumore grave e il «tu-tum» dei carrelli sui giunti.</summary>
|
||||
public static float[] RailRumbleLoop()
|
||||
{
|
||||
int n = (int)(1.6f * Rate);
|
||||
var loop = LoopFilter(BrownLoop(n, 53, 0.995f), Biquad.LowPass(300, 0.7f, Rate));
|
||||
Normalize(loop, 0.5f);
|
||||
var clack = Buffer(0.08f);
|
||||
var cn = Noise(clack.Length, 59);
|
||||
var bp = Biquad.BandPass(1800, 2, Rate);
|
||||
for (int i = 0; i < clack.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
clack[i] = bp.Process(cn[i]) * 1.5f * Env(t, 0.001f, 0.012f) + MathF.Sin(Tau * 90 * t) * Env(t, 0.002f, 0.03f) * 0.6f;
|
||||
}
|
||||
MixWrapped(loop, clack, (int)(0.20f * Rate), 0.8f);
|
||||
MixWrapped(loop, clack, (int)(0.32f * Rate), 0.7f);
|
||||
MixWrapped(loop, clack, (int)(1.00f * Rate), 0.75f);
|
||||
MixWrapped(loop, clack, (int)(1.12f * Rate), 0.65f);
|
||||
Normalize(loop, 0.6f);
|
||||
return loop;
|
||||
}
|
||||
|
||||
/// <summary>Motore diesel in anello (1 s): 48 Hz con armoniche e scoppi a 8 Hz.</summary>
|
||||
public static float[] DieselDroneLoop()
|
||||
{
|
||||
int n = Rate;
|
||||
var b = new float[n];
|
||||
var noise = LoopFilter(Noise(n, 61), Biquad.LowPass(900, 0.7f, Rate));
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float v = 0;
|
||||
for (int h = 1; h <= 10; h++) v += MathF.Sin(Tau * 48 * h * t) / h;
|
||||
float firing = 0.7f + 0.3f * MathF.Sin(Tau * 8 * t);
|
||||
b[i] = v * firing * 0.5f + noise[i] * 0.4f;
|
||||
}
|
||||
Normalize(b, 0.6f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Ronzio elettrico in anello (1 s): 100, 200 e 300 Hz e un fischio dei motori.</summary>
|
||||
public static float[] ElectricHumLoop()
|
||||
{
|
||||
int n = Rate;
|
||||
var b = new float[n];
|
||||
var hiss = LoopFilter(Noise(n, 67), Biquad.LowPass(3000, 0.7f, Rate));
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
b[i] = 0.4f * MathF.Sin(Tau * 100 * t) + 0.2f * MathF.Sin(Tau * 200 * t) + 0.25f * MathF.Sin(Tau * 300 * t)
|
||||
+ 0.06f * MathF.Sin(Tau * 1150 * t) * (0.6f + 0.4f * MathF.Sin(Tau * t)) + hiss[i] * 0.12f;
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ ambiente
|
||||
|
||||
/// <summary>Vento e campagna in anello (8 s): rumore con passa-basso mobile e raffiche.</summary>
|
||||
public static float[] WindLoop()
|
||||
{
|
||||
const float seconds = 8;
|
||||
int n = (int)(seconds * Rate);
|
||||
var white = Noise(n, 71);
|
||||
var b = new float[n];
|
||||
var f = Biquad.LowPass(400, 0.9f, Rate);
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float g = 0.55f + 0.25f * MathF.Sin(Tau * t / seconds) + 0.2f * MathF.Sin(Tau * 3 * t / seconds + 1.3f);
|
||||
if ((i & 127) == 0) f.Retune(Biquad.LowPass(250 + 550 * g, 0.9f, Rate));
|
||||
b[i] = f.Process(white[i]) * g;
|
||||
}
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Acqua di fiume in anello (6 s): rumore a banda con un gorgoglio lento e bolle.</summary>
|
||||
public static float[] RiverLoop()
|
||||
{
|
||||
const float seconds = 6;
|
||||
int n = (int)(seconds * Rate);
|
||||
var main = LoopFilter(Noise(n, 73), Biquad.BandPass(1200, 0.7f, Rate));
|
||||
var mod = LoopFilter(Noise(n, 79), Biquad.LowPass(6, 0.7f, Rate));
|
||||
Normalize(mod, 1);
|
||||
var b = new float[n];
|
||||
for (int i = 0; i < n; i++) b[i] = main[i] * (0.6f + 0.4f * mod[i]);
|
||||
Normalize(b, 1);
|
||||
var rng = new SynthRng(83);
|
||||
var bubble = Buffer(0.05f);
|
||||
for (int k = 0; k < 60; k++)
|
||||
{
|
||||
float f0 = rng.Range(400, 1000);
|
||||
for (int i = 0; i < bubble.Length; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
bubble[i] = MathF.Sin(Tau * f0 * (1 + 4 * t) * t) * Env(t, 0.002f, 0.012f);
|
||||
}
|
||||
MixWrapped(b, bubble, rng.Next(n), rng.Range(0.1f, 0.3f));
|
||||
}
|
||||
Normalize(b, 0.45f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Mare in anello (10 s): due onde con risacca e schiuma.</summary>
|
||||
public static float[] SeaLoop()
|
||||
{
|
||||
const float seconds = 10;
|
||||
int n = (int)(seconds * Rate);
|
||||
var low = LoopFilter(Noise(n, 89), Biquad.LowPass(700, 0.7f, Rate));
|
||||
var foam = LoopFilter(Noise(n, 97), Biquad.HighPass(3000, 0.7f, Rate));
|
||||
var b = new float[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float t = i / (float)Rate;
|
||||
float s = 0.5f + 0.5f * MathF.Sin(Tau * 2 * t / seconds - MathF.PI / 2);
|
||||
float swell = 0.35f + 0.65f * s * s;
|
||||
b[i] = low[i] * swell + foam[i] * swell * swell * 0.3f;
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Città in anello (8 s): brusio grave, voci lontane e qualche colpo di carri e porte.</summary>
|
||||
public static float[] CityLoop()
|
||||
{
|
||||
const float seconds = 8;
|
||||
int n = (int)(seconds * Rate);
|
||||
var rumble = LoopFilter(BrownLoop(n, 101, 0.996f), Biquad.LowPass(200, 0.7f, Rate));
|
||||
Normalize(rumble, 1);
|
||||
var murmur = LoopFilter(Noise(n, 103), Biquad.BandPass(500, 1, Rate));
|
||||
Normalize(murmur, 1);
|
||||
var mod = LoopFilter(Noise(n, 107), Biquad.LowPass(3, 0.7f, Rate));
|
||||
Normalize(mod, 1);
|
||||
var b = new float[n];
|
||||
for (int i = 0; i < n; i++) b[i] = rumble[i] * 0.5f + murmur[i] * (0.2f + 0.15f * mod[i]);
|
||||
var rng = new SynthRng(109);
|
||||
var knock = Buffer(0.06f);
|
||||
for (int k = 0; k < 24; k++)
|
||||
{
|
||||
var kn = Noise(knock.Length, 200 + (ulong)k);
|
||||
var bp = Biquad.BandPass(rng.Range(1500, 3000), 3, Rate);
|
||||
float decay = rng.Range(0.01f, 0.03f);
|
||||
for (int i = 0; i < knock.Length; i++) knock[i] = bp.Process(kn[i]) * 3 * Env(i / (float)Rate, 0.001f, decay);
|
||||
MixWrapped(b, knock, rng.Next(n), rng.Range(0.2f, 0.5f));
|
||||
}
|
||||
Normalize(b, 0.45f);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Cinguettio (varianti per numero): due–quattro brevi glissati acuti.</summary>
|
||||
public static float[] Bird(int variant)
|
||||
{
|
||||
var rng = new SynthRng(300 + (ulong)variant);
|
||||
int chirps = 2 + rng.Next(3);
|
||||
float chirp = rng.Range(0.05f, 0.08f);
|
||||
float gap = rng.Range(0.03f, 0.07f);
|
||||
var b = Buffer(chirps * (chirp + gap) + 0.02f);
|
||||
float f0 = rng.Range(2800, 3600), f1 = f0 * rng.Range(1.15f, 1.45f);
|
||||
if (rng.Next(2) == 0) (f0, f1) = (f1, f0);
|
||||
for (int k = 0; k < chirps; k++)
|
||||
{
|
||||
int s0 = (int)(k * (chirp + gap) * Rate);
|
||||
float phase = 0;
|
||||
for (int i = 0; i < (int)(chirp * Rate) && s0 + i < b.Length; i++)
|
||||
{
|
||||
float u = i / (chirp * Rate);
|
||||
phase += Tau * (f0 + (f1 - f0) * u) / Rate;
|
||||
b[s0 + i] += MathF.Sin(phase) * MathF.Sin(MathF.PI * u);
|
||||
}
|
||||
}
|
||||
Normalize(b, 0.5f);
|
||||
return b;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
|
||||
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server.</summary>
|
||||
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server, audio.</summary>
|
||||
public partial class TopBar : PanelContainer
|
||||
{
|
||||
private GameSession? _session;
|
||||
@@ -82,6 +82,9 @@ public partial class TopBar : PanelContainer
|
||||
var chipCenter = new CenterContainer();
|
||||
chipCenter.AddChild(chip);
|
||||
row.AddChild(chipCenter);
|
||||
var audio = new CenterContainer();
|
||||
audio.AddChild(new Audio.SpeakerButton());
|
||||
row.AddChild(audio);
|
||||
}
|
||||
|
||||
private static VBoxContainer Stat(string caption, Label value)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Audio;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Client.Screens;
|
||||
using RailEnterprise.Core.Data;
|
||||
@@ -27,17 +28,21 @@ public partial class Main : Node
|
||||
Localization.Load(locale);
|
||||
GetWindow().Theme = UiTheme.Build();
|
||||
GetWindow().Title = "Rail Enterprise";
|
||||
var args = OS.GetCmdlineUserArgs();
|
||||
int i = Array.IndexOf(args, "--autopilot");
|
||||
// audio: niente nel pilota automatico e senza schermo (non rallenta il collaudo)
|
||||
var audio = new AudioManager(enabled: i < 0 && DisplayServer.GetName() != "headless");
|
||||
AddChild(audio);
|
||||
try
|
||||
{
|
||||
_data = GodotDataSource.LoadGameData();
|
||||
audio.SetEras(_data.Eras.Eras);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
|
||||
}
|
||||
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "");
|
||||
var args = OS.GetCmdlineUserArgs();
|
||||
int i = Array.IndexOf(args, "--autopilot");
|
||||
if (i >= 0 && _data is not null)
|
||||
{
|
||||
// collaudo: mappa piccola e seme fisso per il server locale
|
||||
@@ -61,6 +66,7 @@ public partial class Main : Node
|
||||
var menu = new MenuScreen();
|
||||
menu.LocalGame += StartLocal;
|
||||
menu.ConnectToServer += ShowConnect;
|
||||
menu.AudioRequested += () => AudioManager.Instance?.ShowSettings();
|
||||
menu.LanguageChanged += code =>
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Audio;
|
||||
using RailEnterprise.Client.Hud;
|
||||
using RailEnterprise.Client.Map;
|
||||
using RailEnterprise.Client.Net;
|
||||
@@ -240,13 +241,18 @@ public partial class GameScreen : Node
|
||||
_session.MessageApplied += OnMessage;
|
||||
_session.Notified += e => _ticker.Add(e);
|
||||
_session.CommandFailed += r => Toast(r.Message, error: true);
|
||||
AudioManager.Instance?.Bind(_session, _map);
|
||||
SelectTool(Tool.None);
|
||||
SendViewport(force: true);
|
||||
// il Registro degli impieghi alimenta anche le schede di industrie e città
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
|
||||
}
|
||||
|
||||
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
|
||||
public override void _ExitTree()
|
||||
{
|
||||
_session.MessageApplied -= OnMessage;
|
||||
AudioManager.Instance?.Unbind(_session);
|
||||
}
|
||||
|
||||
/// <summary>Codice di EventKind.World nel protocollo (notizie degli eventi del mondo, ADR 0017).</summary>
|
||||
private const byte WorldEventKind = 10;
|
||||
|
||||
@@ -4,12 +4,13 @@ using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Screens;
|
||||
|
||||
/// <summary>Menu iniziale: partita locale (server figlio), collegamento a un server, lingua, uscita.</summary>
|
||||
/// <summary>Menu iniziale: partita locale (server figlio), collegamento a un server, lingua, audio, uscita.</summary>
|
||||
public partial class MenuScreen : Control
|
||||
{
|
||||
public event Action? LocalGame;
|
||||
public event Action? ConnectToServer;
|
||||
public event Action<string>? LanguageChanged;
|
||||
public event Action? AudioRequested;
|
||||
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
|
||||
public override void _Ready()
|
||||
@@ -44,6 +45,9 @@ public partial class MenuScreen : Control
|
||||
b.Pressed += () => LanguageChanged?.Invoke(code);
|
||||
lang.AddChild(b);
|
||||
}
|
||||
var audio = new Button { Text = T("Audio"), ToggleMode = false };
|
||||
audio.Pressed += () => AudioRequested?.Invoke();
|
||||
lang.AddChild(audio);
|
||||
col.AddChild(lang);
|
||||
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(0, 40) };
|
||||
quit.Pressed += () => GetTree().Quit();
|
||||
|
||||
@@ -127,7 +127,8 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- `Main` → `MenuScreen` / `ConnectScreen` / `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
|
||||
- `GameSession` applica i messaggi a `ClientWorld` (Protocol) sul thread principale; i comandi sono l'unico modo di cambiare il mondo; le anteprime del tracciato usano `TrackPreview` di Core.
|
||||
- `MapView` (Node2D + Camera2D): `TerrainLayer` (texture per chunk con fasce, ombreggiatura, sponde e curve di livello; shader per le rive), `EntityLayer` (case, industrie, stazioni, depositi, alberi in MultiMesh), `TrackLayer` (massicciata, traversine, rotaie, opere, cantieri, segnali), `TrainLayer` (veicoli interpolati, fumo, avvisi), `ToolOverlay`; `LabelLayer` disegna le etichette in coordinate schermo.
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze; a tutto schermo «Compagnie e borsa», «Mercato globale» (`MarketPanel`, immagine 06) e «La tua scalata» (`ClimbPanel`, immagine 08: binario dei livelli, storico del patrimonio con `SeriesChart` e i livelli segnati, requisiti, stato patrimoniale, conto economico, prestiti), che si apre anche dal livello nella `TopBar`; scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
|
||||
- HUD: `TopBar` (con l'altoparlante dell'audio), `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze; a tutto schermo «Compagnie e borsa», «Mercato globale» (`MarketPanel`, immagine 06) e «La tua scalata» (`ClimbPanel`, immagine 08: binario dei livelli, storico del patrimonio con `SeriesChart` e i livelli segnati, requisiti, stato patrimoniale, conto economico, prestiti), che si apre anche dal livello nella `TopBar`; scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
|
||||
- Audio (`scripts/Audio/`, ADR 0022): `AudioManager`, figlio di `Main` con `AudioManager.Instance`, crea i bus `Music`, `Ambience`, `Sfx`, `Ui` (`AudioBuses.Ensure`, idempotente), applica i volumi di `AudioSettings` (`user://settings.cfg`, sezione `audio`) e reagisce a ciò che il client riceve: clic dei pulsanti (segnale `node_added`), esiti dei comandi, `Notification`, cantieri completati nel `DailyDigest`, treni visibili in moto vicini al centro (`TrainLayer.Heads`, al più 3 canali, solo con un moto recente in `GameSession.MotionReceivedMs`), terreno e zoom della vista per l'ambiente, anno corrente per il tema dell'era. I suoni si sintetizzano su un altro thread con classi senza Godot: `Synth` (effetti e anelli senza scatti), `MusicComposer` (temi per era da un seme fisso), `AudioMix` (miscelazione, scelta dei treni senza allocazioni, PCM). Pannello `AudioSettingsPanel` (dal menu e da `SpeakerButton` nella `TopBar`), tasto M per il muto; nel pilota automatico l'audio è spento.
|
||||
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
|
||||
|
||||
## 10. Prestazioni
|
||||
|
||||
+9
-2
@@ -141,11 +141,17 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- client: pannello «Finanze» a tutto schermo (`FinancePanel`): conto economico con «Mesi» e «Anni», rating con misure e «per salire…», soglie e tassi, prestiti con rata, interessi, scadenza, «Rimborsa» ed «Estingui», richiesta con fido e tasso, barra dei giorni di cassa negativa solo con lo scoperto; frasi intere con segnaposto in `strings.csv`; schermata `18_finanze` nel pilota automatico (non provata qui: manca l'editor);
|
||||
- IA invariate: usano gli stessi comandi di prestito; accettazione F5 (un'IA al livello 3 in 15 anni) e F4 (35 / 20 guasti senza la linea, 75 / 2 con la linea) invariate;
|
||||
- test (`Economy/FinanceTests.cs`, 19, più il quadro via WebSocket in `ServerTests` e il round-trip di `FinanceReport`): tasso per rating e fisso, fido dal livello e rifiuti, interessi e quota capitale sul registro, rimborso parziale e totale, rating dalle due misure e leva infinita, spiegazione che porta al gradino sopra e rimborso possibile con la cassa, punteggio che basta già (senza infiniti), margine neutro ai primi incassi, finestra di 12 mesi, conto economico che somma all'utile, stipendi dei depositi, dazi, magazzini, dividendi incassati nell'utile, avvisi e bancarotta ai giorni di ogni preset (lento), rientro e oscillazioni senza notizie, quota dei trasporti senza dividendi, salvataggio versione 7 e migrazione dalla 6, determinismo con gli invarianti, proiezione. 194 test (175 senza i lenti).
|
||||
- Restano della F6: ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
- **Audio (issue #46, ADR 0022)**:
|
||||
- solo client, nessun file audio: effetti, anelli e temi sintetizzati in memoria all'avvio su un altro thread da classi senza dipendenze da Godot (`Synth`, `MusicComposer`, `AudioMix` in `scripts/Audio/`), semi fissi, PCM a 16 bit in `AudioStreamWav`;
|
||||
- bus `Master`, `Music`, `Ambience`, `Sfx`, `Ui` creati da codice in modo idempotente, limitatore sul Master; volumi per bus e muto generale nella sezione `audio` di `user://settings.cfg`; pannello «Audio» dal menu e dall'altoparlante nella barra superiore, tasto M per il muto;
|
||||
- `AudioManager` (figlio di `Main`): clic di ogni pulsante, conferma ed errore dagli esiti dei comandi, campanelle per opportunità, avvisi e notizie critiche, «cantiere completato» dal `DailyDigest`; fino a 3 treni in moto vicini al centro dello schermo con rotolamento, motore diesel o ronzio elettrico e sbuffi del vapore modulati dalla velocità (solo con un moto ricevuto da meno di 500 ms ed entro metà della diagonale dello schermo); ambiente (vento e uccelli in campagna, fiume e lago, mare, città) dalla griglia del terreno visibile e dallo zoom; tema per era dall'anno corrente con dissolvenza incrociata di 3 s;
|
||||
- nel pilota automatico e senza schermo niente sintesi e Master muto; testi in `strings.csv`;
|
||||
- nessun test nel harness (il client non è referenziato): le funzioni pure sono state provate a parte (nessun NaN, picchi entro i limiti, anelli senza salti, temi identici a ogni composizione; circa 0,1 s per gli effetti, 0,1–0,4 s per tema). Non ascoltato: qui manca l'editor. 194 test (175 senza i lenti), invariati.
|
||||
- Restano della F6: ere e obsolescenza, pannello 07, tooltip «perché», tutorial, bilanciamento con i bot.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F6: ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
- F6: ere e obsolescenza, pannello 07, tooltip «perché», tutorial, bilanciamento con i bot su `simulate`.
|
||||
|
||||
## Limiti noti
|
||||
|
||||
@@ -155,6 +161,7 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 e «La tua scalata» alla 08 (F6, non ancora provati in Godot: qui manca l'editor); Industria e la schermata di connessione vanno allineati in F6.
|
||||
- Compravendita in proprio (ADR 0016): la quotazione nel pannello non considera la cassa delle industrie compratrici; una spedizione tiene occupato lo spazio di destinazione per tutto il viaggio; se una linea sparisce durante il viaggio la merce si ferma nel magazzino della stazione dove si trova anche oltre la capacità; un treno che lascia la linea in viaggio lascia la merce propria alla prossima fermata senza percorrere il tratto; la merce in attesa in stazione scade come le altre merci (la scadenza riparte a ogni trasbordo); il riquadro non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- Eventi del mondo (ADR 0017): le medie mobili (coperture a 30 giorni, margini) si riprendono gradualmente dopo un evento; il maltempo prende un arco per intero secondo il suo punto medio; la notizia di fine arriva la sera dell'ultimo giorno; il riquadro mostra al massimo quattro eventi; le IA non reagiscono; client non ancora provato in Godot (qui manca l'editor).
|
||||
- Audio (ADR 0022): suoni mono senza panoramica; timbri semplici di sintesi, da tarare all'ascolto (non ancora provati in Godot: qui manca l'editor); niente fischio all'arrivo in stazione: il client non riceve moti `Loading` (all'arrivo il server non manda moti), serve una modifica del protocollo con una decisione a parte.
|
||||
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
|
||||
- Scalata (ADR 0018): il livello non scende; lo storico del patrimonio ha un punto all'anno (più la fondazione e oggi); il capitale iniziale mostrato è quello della difficoltà; il valore contabile si aggiorna a inizio mese, mentre cassa, partecipazioni e debiti sono del giorno; i salvataggi delle versioni 1–5 ripartiscono il totale degli attivi in proporzione alle voci del giorno di caricamento fino al ricalcolo del mese; il pannello non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# ADR 0022 — Audio del client: bus, volumi, suoni sintetizzati, ambiente e musica per era (F6)
|
||||
|
||||
Stato: accettato (F6, issue #46).
|
||||
|
||||
## Contesto
|
||||
|
||||
La roadmap della F6 (guida §16, punto 14) chiede «audio» senza altri dettagli. Il client non contiene
|
||||
logica di gioco (§14.3) e il repository non ha file audio; scaricarne durante la build o includere file
|
||||
con licenze incerte non è accettabile. Godot non è eseguibile nell'ambiente di sviluppo, quindi i suoni
|
||||
non si possono ascoltare qui: il codice deve essere verificabile almeno nella parte di sintesi.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Tutto sintetizzato nel client, niente file audio.** `Synth` (effetti e anelli) e `MusicComposer`
|
||||
(temi) sono classi C# senza dipendenze da Godot in `client/RailEnterprise.Client/scripts/Audio/`;
|
||||
producono campioni mono a 22 050 Hz convertiti in PCM a 16 bit (`AudioMix.ToPcm16`) e caricati in
|
||||
`AudioStreamWav` in memoria. Semi fissi (xorshift64* `SynthRng`, FNV-1a dell'id dell'era): stessi
|
||||
suoni e stessi temi a ogni avvio. Nessuna licenza da documentare.
|
||||
2. **Bus**: `Master`, `Music`, `Ambience`, `Sfx`, `Ui`, creati da codice all'avvio (`AudioBuses.Ensure`,
|
||||
idempotente: un bus esistente non si duplica) con un `AudioEffectHardLimiter` sul Master; niente
|
||||
`default_bus_layout.tres`, così il progetto resta senza risorse da importare con l'editor.
|
||||
3. **Impostazioni**: volume per bus (0–1, guadagno = valore², cioè circa il volume percepito) e muto
|
||||
generale nella sezione `audio` di `user://settings.cfg`, lo stesso file di lingua e server. Pannello
|
||||
«Audio» sopra a tutto (dal menu e dall'altoparlante nella barra superiore; si chiude con Esc, «Chiudi»
|
||||
o un clic sinistro fuori); il tasto **M** attiva e toglie il muto (solo se nessun campo di testo ha il
|
||||
fuoco: è un input non gestito). I cambi si salvano quando il pannello esce dall'albero e all'uscita
|
||||
di `AudioManager`, anche chiudendo la finestra con il pannello aperto (solo se qualcosa è cambiato).
|
||||
4. **`AudioManager`** è un figlio di `Main` (non un autoload: nessuna modifica a `project.godot`), con
|
||||
`AudioManager.Instance`. Reagisce solo a ciò che il client riceve già:
|
||||
- clic di ogni `BaseButton` (agganciato dal segnale `node_added` dell'albero: i pannelli non cambiano;
|
||||
un pulsante staccato e riattaccato non si ricollega, si controlla `IsConnected`);
|
||||
- `CommandResultMessage`: conferma o errore;
|
||||
- `Notification`: campanella per opportunità, avviso, critica (una sola ogni 0,6 s, le critiche sempre);
|
||||
- `DailyDigest`: «cantiere completato» se c'è un evento `Construction` della compagnia del giocatore
|
||||
(gli eventi informativi arrivano solo dal resoconto, non come `Notification`);
|
||||
- vista: fino a 3 treni in moto tra quelli disegnati (`TrainLayer.Heads`), i più vicini al centro
|
||||
dello schermo ed entro metà della diagonale (oltre non si sentirebbero), hanno un canale con
|
||||
rotolamento (intonazione dalla velocità), motore diesel o ronzio elettrico, e sbuffi per il vapore
|
||||
da 1,2 al secondo al passo a 10 al secondo a 30 m/s (circa 110 km/h), in modo lineare: è una resa
|
||||
sonora, non il passo della ruota, perché sullo schermo il tempo dei treni corre decine di volte più
|
||||
veloce e non dipende dalla velocità di gioco; il volume scende con la distanza in pixel e
|
||||
allontanando lo zoom; in pausa tacciono. Un treno suona solo se il suo ultimo moto ha meno di
|
||||
500 ms (il server li manda ogni 100 ms ai treni in marcia): durante la sosta in stazione il server
|
||||
non manda moti e l'ultimo ricevuto, ancora `Moving` con la velocità di frenata, resterebbe
|
||||
nel mondo del client; lo stesso per un treno uscito dalla zona sottoscritta;
|
||||
- ambiente: ogni 0,25 s una griglia 8×8 sulla vista (allargata di un quarto) conta fiume, lago, mare,
|
||||
città e industrie, bosco, campagna; `AudioMix.Ambience` ne ricava i guadagni di vento, acqua, mare e
|
||||
città con lo zoom (da lontano quasi solo vento) e la probabilità degli uccelli da vicino in campagna;
|
||||
- musica: l'era viene dall'anno corrente (`ClientWorld.Year`) e da `eras.json`; al cambio d'era il tema
|
||||
nuovo entra con una dissolvenza incrociata di 3 s su due riproduttori; nel menu suona il tema della
|
||||
prima era. Le tabelle d'onda dei temi tengono per ogni nota solo le armoniche sotto il 45 % della
|
||||
frequenza di campionamento (una tabella per numero di armoniche), così le note acute non
|
||||
ripiegano oltre Nyquist.
|
||||
5. **Prestazioni**: la sintesi gira su un altro thread (`Task.Run`: circa 0,1 s per gli effetti, 0,1–0,4 s
|
||||
per tema, solo quando serve); nel ciclo per fotogramma niente LINQ né allocazioni (elenchi dei treni
|
||||
preparati, `StringName` dei bus già pronti, un riproduttore polifonico per bus per i suoni brevi).
|
||||
6. **Pilota automatico e server senza schermo**: `AudioManager` non sintetizza né riproduce nulla e il
|
||||
Master resta muto, senza scrivere il file delle impostazioni.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il client non ha file audio e la build non scarica nulla; il timbro dei suoni è semplice (sintesi
|
||||
additiva, FM, rumore filtrato) e si può cambiare solo nel codice.
|
||||
- I suoni sono mono, senza panoramica destra–sinistra: i treni si distinguono per volume, non per lato.
|
||||
- Le costanti di resa sonora (livelli, zoom di riferimento, numero di canali) stanno in `AudioMix` e in
|
||||
`AudioManager`: sono del client, non della simulazione, e non vanno in `data/*.json`.
|
||||
- **Niente fischio né tromba all'arrivo in stazione.** All'arrivo il server svuota il percorso del
|
||||
treno e `Projection.Motion` non produce moti per un treno senza percorso: il client non riceve mai
|
||||
un moto `Loading`, quindi il passaggio `Moving` → `Loading` non è osservabile. Dedurre l'arrivo nel
|
||||
client (moti che smettono di arrivare) sarebbe logica di gioco. Il fischio tornerà quando il protocollo
|
||||
manderà lo stato del treno fermo (decisione e issue a parte, perché tocca il server);
|
||||
`Synth.SteamWhistle` e `Synth.Horn` restano pronti per allora, ma non si sintetizzano all'avvio.
|
||||
- Nessun test nel harness: le classi pure sono nel progetto Godot, che il harness non referenzia; sono
|
||||
state provate a parte (nessun NaN, picchi entro i limiti, anelli senza salti, temi identici a ogni
|
||||
composizione). Nessun ascolto possibile qui.
|
||||
Reference in new issue
Block a user