Files
Rail_Enterprise/client/RailEnterprise.Client/scripts/Audio/Synth.cs
T
Alby96andClaude Opus 5.5 b1ee6879a7 F6: audio con bus, volumi, effetti, ambienti e musica per era
Il client ora ha l'audio della F6 senza file esterni né download: effetti,
anelli d'ambiente e temi musicali si sintetizzano in memoria all'avvio, su un
altro thread, con classi senza dipendenze da Godot (Synth, MusicComposer,
AudioMix) e semi fissi.

- Bus Master, Music, Ambience, Sfx, Ui creati da codice in modo idempotente,
  limitatore sul Master; volumi per bus e muto in user://settings.cfg; pannello
  «Audio» dal menu e dall'altoparlante della barra superiore, tasto M.
- AudioManager (figlio di Main) reagisce solo a ciò che il client riceve: clic
  dei pulsanti, esiti dei comandi, notifiche per gravità, cantieri completati
  dal DailyDigest, fischio o tromba all'arrivo in stazione, fino a 3 treni
  vicini al centro con rotolamento, motore e sbuffi modulati dalla velocità,
  ambiente dal terreno visibile e dallo zoom, tema per era con dissolvenza.
- Nessuna allocazione nel ciclo per fotogramma; audio spento nel pilota
  automatico e senza schermo.
- ADR 0022, STATE e ARCHITECTURE aggiornati; testi in strings.csv.

Non ascoltato: Godot non è eseguibile qui. Funzioni pure provate a parte.

Refs #46.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:50:07 +01:00

555 lines
21 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
}