Compare commits
14
Commits
v0.6.0
...
e1d47fff54
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1d47fff54 | ||
|
|
e75c8e1586 | ||
|
|
b1ee6879a7 | ||
|
|
7eec322202 | ||
|
|
8b3a9bdb9c | ||
|
|
1f8830337a | ||
|
|
9bf64b9286 | ||
|
|
c041afd8f7 | ||
|
|
2e5215c570 | ||
|
|
d473e21708 | ||
|
|
a61bf1dc27 | ||
|
|
640d4423d7 | ||
|
|
208faf625f | ||
|
|
d6b631405b |
No files matched your search
@@ -550,3 +550,139 @@ entro,,within
|
||||
fino al,,until
|
||||
da domani,,from tomorrow
|
||||
dal,,from
|
||||
La tua scalata,,Your climb
|
||||
Stato patrimoniale,,Balance sheet
|
||||
Chiedi un prestito,,Request a loan
|
||||
In attesa del quadro dal server…,,Waiting for the report from the server…
|
||||
Fido fino a,,Credit up to
|
||||
squadre di cantiere,,construction crews
|
||||
Acquisto di industrie,,Industry purchases
|
||||
Scalate ai concorrenti,,Takeovers of rivals
|
||||
Concessioni,,Concessions
|
||||
fondata nel,,founded in
|
||||
con,,with
|
||||
verso,,towards
|
||||
raggiunta nel,,reached in
|
||||
raggiunta,,reached
|
||||
avanzamento,,progress
|
||||
patrimonio,,net worth
|
||||
Lo storico cresce anno dopo anno,,The history grows year by year
|
||||
a,,to
|
||||
in,,in
|
||||
anno,,year
|
||||
Hai raggiunto il livello più alto,,You have reached the highest tier
|
||||
Per diventare,,To become
|
||||
Patrimonio netto di,,Net worth of
|
||||
città oltre,,towns over
|
||||
collegata su,,connected out of
|
||||
collegate su,,connected out of
|
||||
Rating creditizio,,Credit rating
|
||||
attuale,,current
|
||||
Binari e opere,,Track and structures
|
||||
Stazioni e depositi,,Stations and depots
|
||||
Materiale rotabile,,Rolling stock
|
||||
Industrie possedute,,Owned industries
|
||||
Merce propria,,Own goods
|
||||
Partecipazioni,,Shareholdings
|
||||
Totale attivo,,Total assets
|
||||
Prestiti al,,Loans at
|
||||
Prestiti,,Loans
|
||||
Scoperto di cassa,,Overdraft
|
||||
Conto economico,,Income statement
|
||||
(finora),,(so far)
|
||||
Ricavi da tariffe e noli,,Fares and freight revenue
|
||||
Altri ricavi,,Other income
|
||||
Costi operativi,,Operating costs
|
||||
Interessi,,Interest
|
||||
Utile netto,,Net profit
|
||||
Rimborsa,,Repay
|
||||
Fido disponibile,,Available credit
|
||||
su,,of
|
||||
al,,at
|
||||
In amministrazione controllata non si possono chiedere prestiti,,Loans cannot be requested under receivership
|
||||
livello più alto,,highest tier
|
||||
prossimo,,next
|
||||
Clic per aprire «La tua scalata»,,Click to open «Your climb»
|
||||
Scalata,,Climb
|
||||
Mesi,,Months
|
||||
Anni,,Years
|
||||
patrimonio netto,,net worth
|
||||
Bancarotta dichiarata,,Bankruptcy declared
|
||||
La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà.,,The company did not bring its cash back above zero within the difficulty limit.
|
||||
in corso,,in progress
|
||||
finora,,so far
|
||||
Voce,,Item
|
||||
Utile operativo,,Operating profit
|
||||
Flusso di cassa,,Cash flow
|
||||
I mesi e gli anni chiusi compaiono qui man mano che passano.,,Closed months and years appear here as they go by.
|
||||
"L'utile operativo comprende ricavi e costi d'esercizio; investimenti, prestiti e azioni cambiano solo la cassa.",,"Operating profit includes revenue and operating costs; investments, loans and shares only change cash."
|
||||
Costi,,Costs
|
||||
Investimenti e finanziamenti,,Investments and financing
|
||||
Noli merci,,Freight fares
|
||||
Biglietti passeggeri,,Passenger tickets
|
||||
Commercio in proprio,,Own trading
|
||||
Contratti,,Contracts
|
||||
Controllate,,Subsidiaries
|
||||
Dividendi incassati,,Dividends received
|
||||
Esercizio dei treni,,Train operation
|
||||
Manutenzione dei treni,,Train maintenance
|
||||
Manutenzione dei binari,,Track maintenance
|
||||
Stipendi,,Wages
|
||||
Dazi,,Duties
|
||||
Magazzini,,Storage
|
||||
Penali,,Penalties
|
||||
Costruzioni,,Construction
|
||||
Acquisto di treni,,Train purchases
|
||||
Vendita di treni,,Train sales
|
||||
Prestiti ricevuti,,Loans received
|
||||
Prestiti rimborsati,,Loans repaid
|
||||
Azioni,,Shares
|
||||
Dividendi pagati,,Dividends paid
|
||||
Altro,,Other
|
||||
Rating iniziale: il primo calcolo arriva a inizio mese. Le misure qui sotto sono quelle di oggi.,,Initial rating: the first calculation comes at the start of the month. The measures below are today's.
|
||||
Calcolato a inizio mese sugli ultimi,,Calculated at the start of the month over the last
|
||||
mese chiuso,,closed month
|
||||
mesi chiusi,,closed months
|
||||
Punteggio,,Score
|
||||
Margine (utile / ricavi),,Margin (profit / revenue)
|
||||
patrimonio non positivo,,non-positive equity
|
||||
Leva (debiti / patrimonio netto),,Leverage (debt / net worth)
|
||||
In bancarotta il rating è D finché la situazione non si risolve.,,While bankrupt the rating is D until the situation is resolved.
|
||||
È il rating più alto: i prestiti costano il minimo.,,This is the highest rating: loans cost the least.
|
||||
serve migliorare insieme margine e leva,,margin and leverage must improve together
|
||||
oppure,,or
|
||||
Punteggio da,,Score from
|
||||
Tasso,,Rate
|
||||
componente,,component
|
||||
peso,,weight
|
||||
Nessun prestito in corso.,,No loans outstanding.
|
||||
Residuo,,Outstanding
|
||||
fisso,,fixed
|
||||
Rata mensile,,Monthly payment
|
||||
interessi,,interest
|
||||
scadenza,,maturity
|
||||
Estingui,,Pay off
|
||||
La cassa è tornata positiva,,Cash is back above zero
|
||||
"Dopo {0} di cassa negativa il conto alla rovescia della bancarotta si azzera domani.",,"After {0} of negative cash, the bankruptcy countdown resets tomorrow."
|
||||
Cassa negativa da oggi: bancarotta tra {0},,Cash negative since today: bankruptcy in {0}
|
||||
Cassa negativa da {0}: bancarotta tra {1},,Cash negative for {0}: bankruptcy in {1}
|
||||
"Scoperto {0}. Il limite della difficoltà è di {1}; riporta la cassa sopra zero con un prestito, vendendo treni o riducendo i costi.",,"Overdraft {0}. The difficulty limit is {1}; bring cash back above zero with a loan, by selling trains or by cutting costs."
|
||||
neutro,,neutral
|
||||
"Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating.",,"The margin counts once there are at least {0} closed months with revenue (now {1}): until then it is 0, so the first takings do not sink the rating."
|
||||
"Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese.",,"The score {0} is already worth {1}: the rating is updated at the next monthly calculation, at the start of the month."
|
||||
un margine di almeno {0},,a margin of at least {0}
|
||||
una leva non oltre {0},,leverage no higher than {0}
|
||||
una leva non oltre {0} (rimborsando {1}),,leverage no higher than {0} (by repaying {1})
|
||||
"una leva non oltre {0} (servirebbe rimborsare {1}, più di quanto la cassa consenta oggi)",,"leverage no higher than {0} (it would take repaying {1}, more than cash allows today)"
|
||||
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)
|
||||
|
@@ -240,6 +240,16 @@ public partial class AutoPilot : Node
|
||||
await Until(() => World.Market is not null, "quadro del mercato", 30);
|
||||
await Shot("16_mercato", 40);
|
||||
|
||||
// La tua scalata (immagine 08): livelli, sblocchi, requisiti, stato patrimoniale
|
||||
_game.OpenClimb();
|
||||
await Until(() => World.Climb is not null, "quadro della scalata", 30);
|
||||
await Shot("17_scalata", 40);
|
||||
|
||||
// Finanze: conto economico per voce, rating spiegato, prestiti
|
||||
_game.OpenFinance();
|
||||
await Until(() => World.Finance is not null, "quadro delle finanze", 30);
|
||||
await Shot("18_finanze", 40);
|
||||
|
||||
// Cronaca provvisoria
|
||||
_game.OpenChronicle();
|
||||
await Until(() => _game.ChronicleVisible, "cronaca", 30);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ using static RailEnterprise.Client.App.Localization;
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
|
||||
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
|
||||
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Finance, Demolish }
|
||||
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Climb, Finance, Demolish }
|
||||
|
||||
/// <summary>
|
||||
/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. I pulsanti
|
||||
@@ -37,7 +37,7 @@ public partial class Toolbar : PanelContainer
|
||||
{
|
||||
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
|
||||
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
|
||||
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Finance, "Finanze"),
|
||||
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Climb, "Scalata"), (Tool.Finance, "Finanze"),
|
||||
(Tool.Demolish, "Demolisci"),
|
||||
})
|
||||
{
|
||||
@@ -159,6 +159,13 @@ public partial class Toolbar : PanelContainer
|
||||
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
|
||||
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
|
||||
break;
|
||||
case Tool.Climb:
|
||||
// gradini che salgono verso una bandierina
|
||||
DrawPolyline([c + new Vector2(-11, 11), c + new Vector2(-11, 5), c + new Vector2(-4, 5), c + new Vector2(-4, -1),
|
||||
c + new Vector2(3, -1), c + new Vector2(3, -7), c + new Vector2(10, -7), c + new Vector2(10, 11), c + new Vector2(-11, 11)], col, w);
|
||||
DrawLine(c + new Vector2(10, -7), c + new Vector2(10, -13), col, w);
|
||||
DrawColoredPolygon([c + new Vector2(10, -13), c + new Vector2(4, -11), c + new Vector2(10, -9)], col);
|
||||
break;
|
||||
case Tool.Finance:
|
||||
DrawArc(c + new Vector2(0, -7), 9, 0, MathF.Tau, 24, col, w);
|
||||
DrawLine(c + new Vector2(-9, -7), c + new Vector2(-9, 7), col, w);
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Client.Panels;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
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;
|
||||
private readonly Label _company = UiTheme.TitleLabel("", 30);
|
||||
private readonly PanelContainer _tier = UiTheme.Badge("");
|
||||
private readonly Label _climb = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private long _climbRequestedMonth = long.MinValue;
|
||||
private double _sinceClimbRequest = double.MaxValue;
|
||||
|
||||
/// <summary>Clic sul livello: apre «La tua scalata».</summary>
|
||||
public event Action? ClimbRequested;
|
||||
private readonly Label _date = UiTheme.Text("", 17, bold: true);
|
||||
private readonly Label _cash = UiTheme.Text("", 20, Palette.AmberLight, bold: true);
|
||||
private readonly Label _worth = UiTheme.Text("", 20, bold: true);
|
||||
@@ -18,6 +26,7 @@ public partial class TopBar : PanelContainer
|
||||
private readonly Label _server = UiTheme.Text("", 14);
|
||||
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
|
||||
private readonly List<Button> _speeds = [];
|
||||
private VBoxContainer? _tierBox;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
@@ -28,9 +37,22 @@ public partial class TopBar : PanelContainer
|
||||
AddChild(row);
|
||||
row.AddChild(new Logo { CustomMinimumSize = new Vector2(40, 40) });
|
||||
row.AddChild(_company);
|
||||
var tierBox = new CenterContainer();
|
||||
tierBox.AddChild(_tier);
|
||||
// livello attuale e avanzamento verso il prossimo (dal quadro della scalata): un clic apre il pannello
|
||||
var tierBox = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.Center, MouseFilter = MouseFilterEnum.Stop };
|
||||
tierBox.AddThemeConstantOverride("separation", 2);
|
||||
tierBox.MouseDefaultCursorShape = CursorShape.PointingHand;
|
||||
var badgeRow = new HBoxContainer();
|
||||
badgeRow.AddChild(_tier);
|
||||
tierBox.AddChild(badgeRow);
|
||||
tierBox.AddChild(_climb);
|
||||
tierBox.GuiInput += e =>
|
||||
{
|
||||
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) ClimbRequested?.Invoke();
|
||||
};
|
||||
_tier.MouseFilter = MouseFilterEnum.Pass;
|
||||
_climb.MouseFilter = MouseFilterEnum.Pass;
|
||||
row.AddChild(tierBox);
|
||||
_tierBox = tierBox;
|
||||
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
row.AddChild(_date);
|
||||
var speeds = new HBoxContainer();
|
||||
@@ -60,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)
|
||||
@@ -83,7 +108,24 @@ public partial class TopBar : PanelContainer
|
||||
var me = w.Companies.GetValueOrDefault(w.Summary.CompanyId);
|
||||
_company.Text = me?.Name ?? w.Summary.CompanyName;
|
||||
int tier = Math.Clamp(me?.Tier ?? 1, 1, w.Data.Tiers.Tiers.Count);
|
||||
((Label)_tier.GetChild(0)).Text = TranslationServer.GetLocale().StartsWith("en") ? w.Data.Tiers.Tiers[tier - 1].NameEn : w.Data.Tiers.Tiers[tier - 1].NameIt;
|
||||
((Label)_tier.GetChild(0)).Text = $"{tier} · {Fmt.Tier(w, tier)}";
|
||||
// il quadro della scalata si chiede una volta al mese di gioco (il pannello lo chiede ogni giorno), e
|
||||
// di nuovo dopo 5 s se manca: uno stato completo (ripresa della sessione, nuova partita) lo azzera
|
||||
_sinceClimbRequest += delta;
|
||||
long month = w.Calendar is { } cal ? Fmt.Today(w) / cal.DaysPerMonth : 0;
|
||||
if ((month != _climbRequestedMonth || (w.Climb is null && _sinceClimbRequest > 5)) && _session!.IsOpen)
|
||||
{
|
||||
_climbRequestedMonth = month;
|
||||
_sinceClimbRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
}
|
||||
var climb = w.Climb;
|
||||
bool top = tier >= w.Data.Tiers.Tiers.Count;
|
||||
_climb.Text = top ? T("livello più alto")
|
||||
: climb is not null && climb.Tier == tier ? $"{Fmt.Progress(climb.Progress)} {T("verso")} {Fmt.Tier(w, tier + 1)}"
|
||||
: $"{T("prossimo")}: {Fmt.Tier(w, tier + 1)}";
|
||||
if (_tierBox is not null)
|
||||
_tierBox.TooltipText = $"{T("Livello")} {tier} {T("di")} {w.Data.Tiers.Tiers.Count}. {T("Clic per aprire «La tua scalata»")}";
|
||||
_date.Text = w.LastDigest?.Date ?? w.Summary.Date;
|
||||
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
|
||||
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString("short");
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// «La tua scalata» a tutto schermo (immagine di riferimento 08): in alto il binario dei livelli con
|
||||
/// il treno che avanza verso il prossimo, sotto ogni stazione il nome, quando è stato raggiunto (o
|
||||
/// l'avanzamento, o il patrimonio richiesto) e gli sblocchi; a sinistra lo storico del patrimonio
|
||||
/// netto con i livelli raggiunti e i requisiti del prossimo livello; a destra lo stato patrimoniale,
|
||||
/// il conto economico e i prestiti. Tutti i numeri arrivano dal server (ClimbReport, ADR 0018): il
|
||||
/// pannello li chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e li mostra com'è.
|
||||
/// </summary>
|
||||
public partial class ClimbPanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _worth = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||||
private readonly TierTrack _track = new();
|
||||
private readonly HBoxContainer _stations = PanelKit.Row(8);
|
||||
private readonly Label _historyCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly SeriesChart _chart = new(250);
|
||||
private readonly Label _nextTitle = UiTheme.Text("", 16, bold: true);
|
||||
private readonly HBoxContainer _requirements = PanelKit.Row(24);
|
||||
private readonly VBoxContainer _balance = PanelKit.Column(6);
|
||||
private readonly Label _incomeTitle = UiTheme.Text("", 20, bold: true);
|
||||
private readonly VBoxContainer _income = PanelKit.Column(6);
|
||||
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||||
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Button _repay = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private ClimbReport? _shown;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action? CloseRequested;
|
||||
|
||||
public ClimbPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 16);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
var header = PanelKit.Row(24);
|
||||
var titles = PanelKit.Column(0);
|
||||
titles.AddChild(UiTheme.TitleLabel(T("La tua scalata"), 44));
|
||||
titles.AddChild(_subtitle);
|
||||
header.AddChild(titles);
|
||||
var worth = PanelKit.Column(0);
|
||||
worth.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
|
||||
worth.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var worthCaption = UiTheme.Text(T("Patrimonio netto"), 13, Palette.TextSecondary);
|
||||
worthCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_worth.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
worth.AddChild(worthCaption);
|
||||
worth.AddChild(_worth);
|
||||
header.AddChild(worth);
|
||||
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||||
close.Pressed += () => CloseRequested?.Invoke();
|
||||
header.AddChild(close);
|
||||
AddChild(header);
|
||||
|
||||
// binario dei livelli
|
||||
var trackCard = Card();
|
||||
var trackCol = (VBoxContainer)trackCard.GetChild(0);
|
||||
trackCol.AddChild(_track);
|
||||
trackCol.AddChild(_stations);
|
||||
AddChild(trackCard);
|
||||
|
||||
var body = PanelKit.Row(20);
|
||||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
AddChild(body);
|
||||
|
||||
var left = Column(body, 1.15f);
|
||||
var historyHeader = PanelKit.Row(8);
|
||||
var historyTitle = UiTheme.Text(T("Patrimonio netto"), 20, bold: true);
|
||||
historyTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
historyHeader.AddChild(historyTitle);
|
||||
_historyCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
historyHeader.AddChild(_historyCaption);
|
||||
left.AddChild(historyHeader);
|
||||
left.AddChild(_chart);
|
||||
left.AddChild(_nextTitle);
|
||||
left.AddChild(_requirements);
|
||||
|
||||
var right = Column(body, 0.85f);
|
||||
right.AddChild(UiTheme.Text(T("Stato patrimoniale"), 20, bold: true));
|
||||
right.AddChild(_balance);
|
||||
right.AddChild(new Control { CustomMinimumSize = new Vector2(0, 6) });
|
||||
right.AddChild(_incomeTitle);
|
||||
right.AddChild(_income);
|
||||
right.AddChild(new Control { SizeFlagsVertical = SizeFlags.ExpandFill });
|
||||
var loanRow = PanelKit.Row(10);
|
||||
loanRow.AddChild(_amount);
|
||||
loanRow.AddChild(_borrow);
|
||||
loanRow.AddChild(_repay);
|
||||
right.AddChild(loanRow);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
right.AddChild(_status);
|
||||
_borrow.Text = T("Chiedi un prestito");
|
||||
_borrow.Pressed += Borrow;
|
||||
_repay.Pressed += Repay;
|
||||
_amount.ValueChanged += _ => UpdateLoanButtons();
|
||||
|
||||
_subtitle.Text = T("In attesa del quadro dal server…");
|
||||
}
|
||||
|
||||
private static PanelContainer Card()
|
||||
{
|
||||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
card.AddChild(PanelKit.Column(10));
|
||||
return card;
|
||||
}
|
||||
|
||||
private static VBoxContainer Column(HBoxContainer body, float ratio)
|
||||
{
|
||||
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
frame.AddChild(scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
scroll.AddChild(margin);
|
||||
var col = PanelKit.Column(12);
|
||||
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
margin.AddChild(col);
|
||||
body.AddChild(frame);
|
||||
return col;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session.World;
|
||||
_sinceRequest += delta;
|
||||
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _requestedDay || (w.Climb is null && _sinceRequest > 5)) Request(today);
|
||||
if (w.Climb is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||
}
|
||||
|
||||
private void Request(long day)
|
||||
{
|
||||
_requestedDay = day;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ dati di comodo (solo lettura)
|
||||
|
||||
private static int YearOf(ClientWorld w, long day) =>
|
||||
w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).Year : 0;
|
||||
|
||||
private static string TierName(TierInfo t) =>
|
||||
TranslationServer.GetLocale().StartsWith("en") ? t.NameEn : t.NameIt;
|
||||
|
||||
private static string Short(Money m) => m.ToString("short");
|
||||
|
||||
/// <summary>Sblocco nella lingua dell'interfaccia (i valori arrivano dal server).</summary>
|
||||
public static string UnlockText(UnlockInfo u) => u.Kind switch
|
||||
{
|
||||
UnlockInfo.LoanLimit => $"{T("Fido fino a")} {Short(new Money(u.Value))}",
|
||||
UnlockInfo.Crews => $"{u.Value} {T("squadre di cantiere")}",
|
||||
UnlockInfo.Trading => T("Compravendita in proprio"),
|
||||
UnlockInfo.BuyIndustry => T("Acquisto di industrie"),
|
||||
UnlockInfo.Ipo => T("Quotazione in borsa"),
|
||||
UnlockInfo.HostileTakeover => T("Scalate ai concorrenti"),
|
||||
UnlockInfo.Concessions => T("Concessioni"),
|
||||
_ => "",
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ aggiornamento
|
||||
|
||||
private void Refresh(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
_shown = report;
|
||||
string company = Fmt.Company(w, report.Company);
|
||||
_subtitle.Text = $"{company}, {T("fondata nel")} {YearOf(w, report.FoundedDay)} {T("con")} {report.InitialCapital}";
|
||||
_worth.Text = report.BalanceNetWorth.ToString();
|
||||
RefreshTrack(w, report);
|
||||
RefreshHistory(w, report);
|
||||
RefreshRequirements(report);
|
||||
RefreshBalance(report);
|
||||
RefreshIncome(report);
|
||||
UpdateLoanButtons();
|
||||
}
|
||||
|
||||
private void RefreshTrack(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||
_track.Set(report.Tiers.Count, report.Tier, report.NextTier > 0 ? report.Progress : 1,
|
||||
next is null ? "" : $"{Fmt.Progress(report.Progress)} {T("verso")} {TierName(next)}");
|
||||
foreach (var c in _stations.GetChildren()) c.QueueFree();
|
||||
foreach (var t in report.Tiers)
|
||||
{
|
||||
bool current = t.Level == report.Tier, isNext = t.Level == report.NextTier;
|
||||
var col = PanelKit.Column(2);
|
||||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var name = UiTheme.TitleLabel(TierName(t), 30, current ? Palette.AmberLight : t.Reached || isNext ? Palette.Text : Palette.TextSecondary);
|
||||
name.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
col.AddChild(name);
|
||||
string status = t.Level == 1 ? $"{T("dal")} {YearOf(w, t.ReachedDay)}"
|
||||
: t.Reached ? (t.ReachedDay >= 0 ? $"{T("raggiunta nel")} {YearOf(w, t.ReachedDay)}" : T("raggiunta"))
|
||||
: isNext ? $"{T("avanzamento")} {Fmt.Progress(report.Progress)}"
|
||||
: $"{T("patrimonio")} {Short(t.NetWorthRequired)}";
|
||||
var statusLabel = UiTheme.Text(status, 14, current ? Palette.AmberLight : Palette.Text, bold: true);
|
||||
statusLabel.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
col.AddChild(statusLabel);
|
||||
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 8) });
|
||||
foreach (var u in t.Unlocks)
|
||||
{
|
||||
var l = UiTheme.Text(UnlockText(u), 13, Palette.TextSecondary);
|
||||
l.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(l);
|
||||
}
|
||||
_stations.AddChild(col);
|
||||
}
|
||||
}
|
||||
|
||||
private void RefreshHistory(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
var values = report.History.Select(p => (double)p.Value.Cents).ToList();
|
||||
var labels = report.History.Select(p => YearOf(w, p.Day).ToString()).ToList();
|
||||
_chart.Show(values, labels, v => new Money((long)v).ToString("short"), SeriesChart.Style.Line, Palette.Amber, T("Lo storico cresce anno dopo anno"));
|
||||
// i livelli raggiunti si segnano sul punto dell'anno della promozione (un punto per anno di
|
||||
// calendario, l'ultimo è oggi); in mancanza sul primo punto dopo la promozione
|
||||
var markers = new List<(int Index, string Label)>();
|
||||
foreach (var t in report.Tiers.Where(t => t.Level > 1 && t.Reached && t.ReachedDay >= 0))
|
||||
{
|
||||
int year = YearOf(w, t.ReachedDay);
|
||||
int index = report.History.FindIndex(p => YearOf(w, p.Day) == year);
|
||||
if (index < 0) index = report.History.FindIndex(p => p.Day >= t.ReachedDay);
|
||||
if (index >= 0) markers.Add((index, TierName(t)));
|
||||
}
|
||||
_chart.SetMarkers(markers);
|
||||
if (report.History.Count >= 2)
|
||||
{
|
||||
var first = report.History[0];
|
||||
var last = report.History[^1];
|
||||
int years = Math.Max(0, YearOf(w, last.Day) - YearOf(w, first.Day));
|
||||
_historyCaption.Text = $"{T("da")} {first.Value} {T("a")} {Short(last.Value)} {T("in")} {years} {(years == 1 ? T("anno") : T("anni"))}";
|
||||
}
|
||||
else _historyCaption.Text = "";
|
||||
}
|
||||
|
||||
private void RefreshRequirements(ClimbReport report)
|
||||
{
|
||||
foreach (var c in _requirements.GetChildren()) c.QueueFree();
|
||||
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||
if (next is null)
|
||||
{
|
||||
_nextTitle.Text = T("Hai raggiunto il livello più alto");
|
||||
return;
|
||||
}
|
||||
_nextTitle.Text = $"{T("Per diventare")} {TierName(next)}";
|
||||
_requirements.AddChild(Requirement($"{T("Patrimonio netto di")} {Short(report.NetWorthRequired)}", report.NetWorthFraction, report.NetWorthMet,
|
||||
$"{Short(report.NetWorth)}, {Fmt.Progress(report.NetWorthFraction)}"));
|
||||
_requirements.AddChild(Requirement($"{report.TownsRequired} {T("città oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}",
|
||||
report.TownsFraction, report.TownsMet, $"{report.Towns} {(report.Towns == 1 ? T("collegata su") : T("collegate su"))} {report.TownsRequired}"));
|
||||
_requirements.AddChild(Requirement($"{T("Rating creditizio")} {report.RatingRequired}", report.RatingFraction, report.RatingMet,
|
||||
$"{T("attuale")} {report.Rating}"));
|
||||
}
|
||||
|
||||
private static Control Requirement(string caption, float fraction, bool met, string value)
|
||||
{
|
||||
var col = PanelKit.Column(6);
|
||||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
col.AddChild(UiTheme.Text(caption, 14));
|
||||
var color = met ? Palette.Ok : Palette.Amber;
|
||||
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
|
||||
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 4, 0));
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||
col.AddChild(bar);
|
||||
col.AddChild(UiTheme.Text((met ? "✓ " : "") + value, 13, met ? Palette.Ok : Palette.TextSecondary));
|
||||
return col;
|
||||
}
|
||||
|
||||
private static string AssetName(byte kind) => kind switch
|
||||
{
|
||||
ClimbReport.AssetTrack => T("Binari e opere"),
|
||||
ClimbReport.AssetStations => T("Stazioni e depositi"),
|
||||
ClimbReport.AssetVehicles => T("Materiale rotabile"),
|
||||
ClimbReport.AssetIndustries => T("Industrie possedute"),
|
||||
ClimbReport.AssetGoods => T("Merce propria"),
|
||||
_ => "",
|
||||
};
|
||||
|
||||
private void RefreshBalance(ClimbReport report)
|
||||
{
|
||||
foreach (var c in _balance.GetChildren()) c.QueueFree();
|
||||
foreach (var a in report.Assets)
|
||||
{
|
||||
// le voci di base si vedono sempre, industrie e merce solo se ci sono
|
||||
bool always = a.Kind is ClimbReport.AssetTrack or ClimbReport.AssetStations or ClimbReport.AssetVehicles;
|
||||
if (always || a.Value.Cents != 0) _balance.AddChild(Line(AssetName(a.Kind), a.Value.ToString()));
|
||||
}
|
||||
if (report.Portfolio.Cents != 0) _balance.AddChild(Line(T("Partecipazioni"), report.Portfolio.ToString()));
|
||||
_balance.AddChild(Line(T("Cassa"), report.Cash.ToString()));
|
||||
_balance.AddChild(PanelKit.Separator());
|
||||
_balance.AddChild(Line(T("Totale attivo"), report.TotalAssets.ToString(), bold: true));
|
||||
string loans = report.Loans.Cents > 0 ? $"{T("Prestiti al")} {Fmt.Pct(report.LoansRate, 1)}" : T("Prestiti");
|
||||
_balance.AddChild(Line(loans, report.Loans.ToString()));
|
||||
if (report.Overdraft.Cents > 0) _balance.AddChild(Line(T("Scoperto di cassa"), report.Overdraft.ToString(), color: Palette.Danger));
|
||||
_balance.AddChild(Line(T("Patrimonio netto"), report.BalanceNetWorth.ToString(), bold: true, color: Palette.AmberLight));
|
||||
}
|
||||
|
||||
private void RefreshIncome(ClimbReport report)
|
||||
{
|
||||
_incomeTitle.Text = $"{T("Conto economico")} {report.IncomeYear}{(report.IncomePartial ? " " + T("(finora)") : "")}";
|
||||
foreach (var c in _income.GetChildren()) c.QueueFree();
|
||||
foreach (var i in report.Income)
|
||||
{
|
||||
string name = i.Kind switch
|
||||
{
|
||||
ClimbReport.IncomeFares => T("Ricavi da tariffe e noli"),
|
||||
ClimbReport.IncomeOther => T("Altri ricavi"),
|
||||
ClimbReport.IncomeOperating => T("Costi operativi"),
|
||||
ClimbReport.IncomeMaintenance => T("Manutenzione"),
|
||||
ClimbReport.IncomeInterest => T("Interessi"),
|
||||
_ => "",
|
||||
};
|
||||
if (i.Kind == ClimbReport.IncomeOther && i.Value.Cents == 0) continue;
|
||||
// i costi si mostrano in valore assoluto: l'etichetta dice già che sono costi
|
||||
bool cost = i.Kind is ClimbReport.IncomeOperating or ClimbReport.IncomeMaintenance or ClimbReport.IncomeInterest;
|
||||
var value = cost ? new Money(Math.Abs(i.Value.Cents)) : i.Value;
|
||||
_income.AddChild(Line(name, value.ToString()));
|
||||
}
|
||||
_income.AddChild(PanelKit.Separator());
|
||||
_income.AddChild(Line(T("Utile netto"), report.Profit.ToString(), bold: true, color: report.Profit.IsNegative ? Palette.Danger : Palette.AmberLight));
|
||||
}
|
||||
|
||||
private static Control Line(string caption, string value, bool bold = false, Color? color = null)
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
var c = UiTheme.Text(caption, 14, bold ? Palette.Text : Palette.TextSecondary, bold);
|
||||
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var v = UiTheme.Text(value, 14, color ?? Palette.Text, bold);
|
||||
v.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
row.AddChild(c);
|
||||
row.AddChild(v);
|
||||
return row;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||||
|
||||
/// <summary>Prestito da rimborsare per primo: quello con il tasso più alto (scelta dell'interfaccia).</summary>
|
||||
private LoanInfo? LoanToRepay() => _shown?.LoanList.OrderByDescending(l => l.AnnualRate).ThenBy(l => l.Loan).FirstOrDefault();
|
||||
|
||||
private Money Amount => Money.FromLire((long)_amount.Value);
|
||||
|
||||
private void UpdateLoanButtons()
|
||||
{
|
||||
var report = _shown;
|
||||
var loan = LoanToRepay();
|
||||
var repay = loan is null ? Amount : Money.Min(Amount, loan.Remaining);
|
||||
_repay.Text = $"{T("Rimborsa")} {repay}";
|
||||
_repay.Disabled = loan is null;
|
||||
_borrow.Disabled = report is null || !report.LoansAllowed;
|
||||
bool bankrupt = report is not null && _session.World.Companies.TryGetValue(report.Company, out var me) && me.Bankrupt;
|
||||
_borrow.TooltipText = report is null ? "" : report.LoansAllowed
|
||||
? $"{T("Fido disponibile")} {report.LoanAvailable} {T("su")} {report.MaxLoan}, {T("al")} {Fmt.Pct(report.NewLoanRate, 1)}"
|
||||
: bankrupt ? T("In bancarotta non si possono chiedere prestiti") : T("In amministrazione controllata non si possono chiedere prestiti");
|
||||
}
|
||||
|
||||
private void Borrow() =>
|
||||
_session.Command(new TakeLoanCommand(Amount), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
|
||||
private void Repay()
|
||||
{
|
||||
var loan = LoanToRepay();
|
||||
if (loan is null) return;
|
||||
_session.Command(new RepayLoanCommand(new LoanId(loan.Loan), Money.Min(Amount, loan.Remaining)), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binario dei livelli (immagine 08): rotaie e traversine da una stazione all'altra, ambra fino al
|
||||
/// treno, cerchi pieni per i livelli raggiunti, anello per quello attuale, il treno e la sua etichetta.
|
||||
/// </summary>
|
||||
private sealed partial class TierTrack : Control
|
||||
{
|
||||
private int _count = 5, _tier = 1;
|
||||
private float _progress;
|
||||
private string _label = "";
|
||||
|
||||
public TierTrack()
|
||||
{
|
||||
CustomMinimumSize = new Vector2(0, 112);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
}
|
||||
|
||||
public void Set(int count, int tier, float progress, string label)
|
||||
{
|
||||
_count = Math.Max(1, count);
|
||||
_tier = Math.Clamp(tier, 1, _count);
|
||||
_progress = Math.Clamp(progress, 0, 1);
|
||||
_label = label;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
private float X(int level) => (level - 0.5f) * Size.X / _count;
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
const float y = 78;
|
||||
float x0 = X(1), x1 = X(_count);
|
||||
float trainX = _tier >= _count ? x1 : X(_tier) + (X(_tier + 1) - X(_tier)) * _progress;
|
||||
var dim = Palette.Rails.Lerp(Palette.Border, 0.4f);
|
||||
// traversine, poi le due rotaie
|
||||
for (float x = x0; x <= x1; x += 12)
|
||||
DrawLine(new Vector2(x, y - 9), new Vector2(x, y + 9), x <= trainX ? Palette.WithAlpha(Palette.Amber, 0.45f) : Palette.Border, 3);
|
||||
foreach (float dy in new[] { -5f, 5f })
|
||||
{
|
||||
DrawLine(new Vector2(x0, y + dy), new Vector2(trainX, y + dy), Palette.Amber, 3);
|
||||
if (trainX < x1) DrawLine(new Vector2(trainX, y + dy), new Vector2(x1, y + dy), dim, 3);
|
||||
}
|
||||
for (int level = 1; level <= _count; level++)
|
||||
{
|
||||
var c = new Vector2(X(level), y);
|
||||
bool reached = level <= _tier;
|
||||
if (level == _tier)
|
||||
{
|
||||
DrawCircle(c, 32, Palette.Panel);
|
||||
DrawArc(c, 31, 0, MathF.Tau, 48, Palette.Amber, 2.5f, true);
|
||||
}
|
||||
DrawCircle(c, 21, reached ? Palette.Amber : Palette.Panel);
|
||||
DrawArc(c, 21, 0, MathF.Tau, 40, reached ? Palette.AppBackground : Palette.Border.Lerp(Palette.TextSecondary, 0.35f), 3, true);
|
||||
}
|
||||
if (_label.Length > 0 && _tier < _count) DrawTrain(new Vector2(trainX, y - 16));
|
||||
}
|
||||
|
||||
/// <summary>Locomotiva stilizzata con l'etichetta dell'avanzamento sopra.</summary>
|
||||
private void DrawTrain(Vector2 at)
|
||||
{
|
||||
var body = Palette.AmberLight;
|
||||
DrawRect(new Rect2(at.X - 30, at.Y - 22, 46, 20), body);
|
||||
DrawRect(new Rect2(at.X + 10, at.Y - 34, 20, 32), body);
|
||||
DrawRect(new Rect2(at.X - 24, at.Y - 32, 8, 10), body);
|
||||
foreach (float dx in new[] { -18f, -2f, 14f })
|
||||
{
|
||||
DrawCircle(new Vector2(at.X + dx, at.Y + 4), 6, Palette.AppBackground);
|
||||
DrawArc(new Vector2(at.X + dx, at.Y + 4), 6, 0, MathF.Tau, 16, body, 2.5f, true);
|
||||
}
|
||||
var font = UiTheme.BodyBold;
|
||||
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 15);
|
||||
float x = Math.Clamp(at.X - dims.X / 2, 4, Size.X - dims.X - 4);
|
||||
DrawString(font, new Vector2(x, at.Y - 44), _label, HorizontalAlignment.Left, -1, 15, Palette.AmberLight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
using RailEnterprise.Client.App;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// «Finanze» a tutto schermo (palette 05, stile del pannello 08): a sinistra il conto economico per
|
||||
/// voce con le colonne del mese in corso, dei mesi chiusi e dell'anno (o degli anni chiusi); a destra
|
||||
/// il rating con la sua spiegazione, i prestiti con rimborso e richiesta, e, se la cassa è negativa, la
|
||||
/// barra dei giorni che restano prima della bancarotta. Tutti i numeri arrivano dal server
|
||||
/// (FinanceReport, ADR 0019): il pannello li chiede all'apertura, a ogni nuovo giorno e dopo un
|
||||
/// comando, e li mostra com'è, senza calcolare utili, rating o rate.
|
||||
/// </summary>
|
||||
public partial class FinancePanel : VBoxContainer
|
||||
{
|
||||
/// <summary>Mesi chiusi e anni chiusi mostrati accanto alla colonna in corso.</summary>
|
||||
private const int ClosedColumns = 5;
|
||||
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _cash = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||||
private readonly PanelContainer _danger = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, Visible = false };
|
||||
private readonly Label _dangerText = UiTheme.Text("", 15, Palette.Danger, bold: true);
|
||||
private readonly ProgressBar _dangerBar = new() { MinValue = 0, MaxValue = 1, Step = 0.001, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
|
||||
private readonly Label _dangerDetail = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly Button _months = new() { Text = "", ToggleMode = true, ButtonPressed = true, CustomMinimumSize = new Vector2(90, 36) };
|
||||
private readonly Button _years = new() { Text = "", ToggleMode = true, CustomMinimumSize = new Vector2(90, 36) };
|
||||
private readonly GridContainer _table = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _tableNote = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private readonly Label _rating = UiTheme.TitleLabel("", 56, Palette.AmberLight);
|
||||
private readonly Label _ratingCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly VBoxContainer _ratingBody = PanelKit.Column(6);
|
||||
private readonly VBoxContainer _loans = PanelKit.Column(8);
|
||||
private readonly Label _credit = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||||
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 44), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private FinanceReport? _shown;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action? CloseRequested;
|
||||
|
||||
public FinancePanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 16);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
var header = PanelKit.Row(24);
|
||||
var titles = PanelKit.Column(0);
|
||||
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
titles.AddChild(UiTheme.TitleLabel(T("Finanze"), 44));
|
||||
titles.AddChild(_subtitle);
|
||||
header.AddChild(titles);
|
||||
var cash = PanelKit.Column(0);
|
||||
cash.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var cashCaption = UiTheme.Text(T("Cassa"), 13, Palette.TextSecondary);
|
||||
cashCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_cash.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
cash.AddChild(cashCaption);
|
||||
cash.AddChild(_cash);
|
||||
header.AddChild(cash);
|
||||
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||||
close.Pressed += () => CloseRequested?.Invoke();
|
||||
header.AddChild(close);
|
||||
AddChild(header);
|
||||
|
||||
// barra della cassa negativa: giorni passati sul limite della difficoltà
|
||||
_danger.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Danger, 12, 18));
|
||||
var dangerCol = PanelKit.Column(8);
|
||||
dangerCol.AddChild(_dangerText);
|
||||
_dangerBar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 5, 0));
|
||||
_dangerBar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Danger, Palette.Danger, 5, 0));
|
||||
dangerCol.AddChild(_dangerBar);
|
||||
_dangerDetail.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
dangerCol.AddChild(_dangerDetail);
|
||||
_danger.AddChild(dangerCol);
|
||||
AddChild(_danger);
|
||||
|
||||
var body = PanelKit.Row(20);
|
||||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
AddChild(body);
|
||||
|
||||
// conto economico
|
||||
var left = Column(body, 1.35f);
|
||||
var incomeHeader = PanelKit.Row(8);
|
||||
var incomeTitle = UiTheme.Text(T("Conto economico"), 20, bold: true);
|
||||
incomeTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
incomeHeader.AddChild(incomeTitle);
|
||||
var group = new ButtonGroup();
|
||||
_months.ButtonGroup = group;
|
||||
_years.ButtonGroup = group;
|
||||
_months.Text = T("Mesi");
|
||||
_years.Text = T("Anni");
|
||||
_months.Pressed += () => RefreshTable(_shown);
|
||||
_years.Pressed += () => RefreshTable(_shown);
|
||||
incomeHeader.AddChild(_months);
|
||||
incomeHeader.AddChild(_years);
|
||||
left.AddChild(incomeHeader);
|
||||
_table.AddThemeConstantOverride("h_separation", 18);
|
||||
_table.AddThemeConstantOverride("v_separation", 6);
|
||||
left.AddChild(_table);
|
||||
_tableNote.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
left.AddChild(_tableNote);
|
||||
|
||||
// rating e prestiti
|
||||
var right = Column(body, 0.9f);
|
||||
right.AddChild(UiTheme.Text(T("Rating creditizio"), 20, bold: true));
|
||||
var ratingRow = PanelKit.Row(16);
|
||||
ratingRow.AddChild(_rating);
|
||||
_ratingCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
_ratingCaption.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_ratingCaption.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
ratingRow.AddChild(_ratingCaption);
|
||||
right.AddChild(ratingRow);
|
||||
right.AddChild(_ratingBody);
|
||||
right.AddChild(PanelKit.Separator());
|
||||
right.AddChild(UiTheme.Text(T("Prestiti"), 20, bold: true));
|
||||
right.AddChild(_loans);
|
||||
_credit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
right.AddChild(_credit);
|
||||
var loanRow = PanelKit.Row(10);
|
||||
loanRow.AddChild(_amount);
|
||||
loanRow.AddChild(_borrow);
|
||||
right.AddChild(loanRow);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
right.AddChild(_status);
|
||||
_borrow.Text = T("Chiedi un prestito");
|
||||
_borrow.Pressed += Borrow;
|
||||
_amount.ValueChanged += _ => RefreshLoans(_shown);
|
||||
|
||||
_subtitle.Text = T("In attesa del quadro dal server…");
|
||||
}
|
||||
|
||||
private static VBoxContainer Column(HBoxContainer body, float ratio)
|
||||
{
|
||||
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Auto, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
frame.AddChild(scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
scroll.AddChild(margin);
|
||||
var col = PanelKit.Column(12);
|
||||
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
margin.AddChild(col);
|
||||
body.AddChild(frame);
|
||||
return col;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session.World;
|
||||
_sinceRequest += delta;
|
||||
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _requestedDay || (w.Finance is null && _sinceRequest > 5)) Request(today);
|
||||
if (w.Finance is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||
}
|
||||
|
||||
private void Request(long day)
|
||||
{
|
||||
_requestedDay = day;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ aggiornamento
|
||||
|
||||
private void Refresh(ClientWorld w, FinanceReport report)
|
||||
{
|
||||
_shown = report;
|
||||
_subtitle.Text = $"{Fmt.Company(w, report.Company)} · {Fmt.Date(w, report.Day)} · {T("patrimonio netto")} {report.NetWorth}";
|
||||
_cash.Text = report.Cash.ToString();
|
||||
_cash.AddThemeColorOverride("font_color", report.Cash.IsNegative ? Palette.Danger : Palette.AmberLight);
|
||||
RefreshDanger(report);
|
||||
RefreshTable(report);
|
||||
RefreshRating(report);
|
||||
RefreshLoans(report);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Barra della cassa negativa. Il motore conta i giorni una volta al giorno, quindi dopo un prestito il
|
||||
/// contatore può restare indietro di un giorno rispetto alla cassa: il conto alla rovescia si mostra solo
|
||||
/// con la cassa davvero negativa (scoperto) o in bancarotta.
|
||||
/// </summary>
|
||||
private void RefreshDanger(FinanceReport r)
|
||||
{
|
||||
bool overdraft = r.Overdraft.Cents > 0;
|
||||
bool recovering = !overdraft && !r.Bankrupt && r.NegativeCashDays > 0;
|
||||
_danger.Visible = overdraft || r.Bankrupt || recovering;
|
||||
_dangerBar.Visible = overdraft || r.Bankrupt;
|
||||
if (!_danger.Visible) return;
|
||||
_dangerBar.Value = r.BankruptcyDays > 0 ? Math.Clamp((double)r.NegativeCashDays / r.BankruptcyDays, 0, 1) : 1;
|
||||
if (r.Bankrupt)
|
||||
{
|
||||
_dangerText.Text = T("Bancarotta dichiarata");
|
||||
_dangerDetail.Text = T("La compagnia non ha riportato la cassa sopra zero entro il limite della difficoltà.");
|
||||
return;
|
||||
}
|
||||
if (recovering)
|
||||
{
|
||||
_dangerText.Text = T("La cassa è tornata positiva");
|
||||
_dangerDetail.Text = string.Format(T("Dopo {0} di cassa negativa il conto alla rovescia della bancarotta si azzera domani."), Days(r.NegativeCashDays));
|
||||
return;
|
||||
}
|
||||
int left = Math.Max(0, r.BankruptcyDays - r.NegativeCashDays);
|
||||
_dangerText.Text = r.NegativeCashDays == 0
|
||||
? string.Format(T("Cassa negativa da oggi: bancarotta tra {0}"), Days(r.BankruptcyDays))
|
||||
: string.Format(T("Cassa negativa da {0}: bancarotta tra {1}"), Days(r.NegativeCashDays), Days(left));
|
||||
_dangerDetail.Text = string.Format(T("Scoperto {0}. Il limite della difficoltà è di {1}; riporta la cassa sopra zero con un prestito, vendendo treni o riducendo i costi."),
|
||||
r.Overdraft, Days(r.BankruptcyDays));
|
||||
}
|
||||
|
||||
private static string Days(int n) => n == 1 ? $"1 {T("giorno")}" : $"{n} {T("giorni")}";
|
||||
|
||||
// ------------------------------------------------------------------ conto economico
|
||||
|
||||
private static string[] MonthNames() =>
|
||||
[T("gen"), T("feb"), T("mar"), T("apr"), T("mag"), T("giu"), T("lug"), T("ago"), T("set"), T("ott"), T("nov"), T("dic")];
|
||||
|
||||
/// <summary>Colonne da mostrare: il mese in corso e i mesi chiusi, poi l'anno in corso; oppure l'anno in corso e gli anni chiusi.</summary>
|
||||
private List<IncomeColumnInfo> ShownColumns(FinanceReport r)
|
||||
{
|
||||
if (_years.ButtonPressed)
|
||||
{
|
||||
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)
|
||||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedYear).Take(ClosedColumns)).ToList();
|
||||
}
|
||||
return r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentMonth)
|
||||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.ClosedMonth).Take(ClosedColumns))
|
||||
.Concat(r.Columns.Where(c => c.Kind == IncomeColumnInfo.CurrentYear)).ToList();
|
||||
}
|
||||
|
||||
private static string ColumnTitle(IncomeColumnInfo c)
|
||||
{
|
||||
string month = c.Month is >= 1 and <= 12 ? MonthNames()[c.Month - 1] : "";
|
||||
return c.Kind switch
|
||||
{
|
||||
IncomeColumnInfo.CurrentMonth => $"{month} {c.Year}\n{T("in corso")}",
|
||||
IncomeColumnInfo.ClosedMonth => $"{month} {c.Year}\n ",
|
||||
IncomeColumnInfo.CurrentYear => $"{c.Year}\n{T("finora")}",
|
||||
_ => $"{c.Year}\n ",
|
||||
};
|
||||
}
|
||||
|
||||
private void RefreshTable(FinanceReport? r)
|
||||
{
|
||||
foreach (var c in _table.GetChildren()) c.QueueFree();
|
||||
if (r is null) return;
|
||||
var columns = ShownColumns(r);
|
||||
_table.Columns = columns.Count + 1;
|
||||
Cell(T("Voce"), Palette.TextSecondary, bold: true, left: true);
|
||||
foreach (var c in columns)
|
||||
Cell(ColumnTitle(c), c.Kind is IncomeColumnInfo.CurrentMonth or IncomeColumnInfo.CurrentYear ? Palette.AmberLight : Palette.TextSecondary, bold: true);
|
||||
|
||||
foreach (byte section in new[] { FinanceLineInfo.SectionRevenue, FinanceLineInfo.SectionCost, FinanceLineInfo.SectionCapital })
|
||||
{
|
||||
// le voci sempre a zero nelle colonne mostrate non occupano righe
|
||||
var lines = r.Lines.Where(l => l.Section == section && columns.Any(c => c.Value(l.Kind).Cents != 0)).ToList();
|
||||
if (lines.Count == 0) continue;
|
||||
Cell(SectionName(section), Palette.Amber, bold: true, left: true);
|
||||
foreach (var _ in columns) Cell("", Palette.Text);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
Cell(EntryName((LedgerEntry)line.Kind), Palette.Text, left: true, indent: true);
|
||||
foreach (var c in columns)
|
||||
{
|
||||
var v = c.Value(line.Kind);
|
||||
Cell(v.Cents == 0 ? "—" : v.ToString(), v.IsNegative ? Palette.Danger : v.Cents == 0 ? Palette.TextSecondary : Palette.Text);
|
||||
}
|
||||
}
|
||||
if (section == FinanceLineInfo.SectionCost)
|
||||
{
|
||||
Cell(T("Utile operativo"), Palette.Text, bold: true, left: true);
|
||||
foreach (var c in columns) Cell(c.Profit.ToString(), c.Profit.IsNegative ? Palette.Danger : Palette.AmberLight, bold: true);
|
||||
}
|
||||
}
|
||||
Cell(T("Flusso di cassa"), Palette.Text, bold: true, left: true);
|
||||
foreach (var c in columns) Cell(c.CashFlow.ToString(), c.CashFlow.IsNegative ? Palette.Danger : Palette.Ok, bold: true);
|
||||
_tableNote.Text = columns.Count <= 1
|
||||
? T("I mesi e gli anni chiusi compaiono qui man mano che passano.")
|
||||
: T("L'utile operativo comprende ricavi e costi d'esercizio; investimenti, prestiti e azioni cambiano solo la cassa.");
|
||||
}
|
||||
|
||||
private void Cell(string text, Color color, bool bold = false, bool left = false, bool indent = false)
|
||||
{
|
||||
var l = UiTheme.Text(indent ? " " + text : text, 14, color, bold);
|
||||
l.HorizontalAlignment = left ? HorizontalAlignment.Left : HorizontalAlignment.Right;
|
||||
if (left) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
else l.CustomMinimumSize = new Vector2(110, 0);
|
||||
_table.AddChild(l);
|
||||
}
|
||||
|
||||
private static string SectionName(byte section) => section switch
|
||||
{
|
||||
FinanceLineInfo.SectionRevenue => T("Ricavi"),
|
||||
FinanceLineInfo.SectionCost => T("Costi"),
|
||||
_ => T("Investimenti e finanziamenti"),
|
||||
};
|
||||
|
||||
/// <summary>Nome della voce del registro nella lingua dell'interfaccia.</summary>
|
||||
public static string EntryName(LedgerEntry e) => e switch
|
||||
{
|
||||
LedgerEntry.FreightRevenue => T("Noli merci"),
|
||||
LedgerEntry.PassengerRevenue => T("Biglietti passeggeri"),
|
||||
LedgerEntry.Trading => T("Commercio in proprio"),
|
||||
LedgerEntry.Contracts => T("Contratti"),
|
||||
LedgerEntry.Industries => T("Industrie possedute"),
|
||||
LedgerEntry.Subsidiaries => T("Controllate"),
|
||||
LedgerEntry.DividendsReceived => T("Dividendi incassati"),
|
||||
LedgerEntry.RunningCosts => T("Esercizio dei treni"),
|
||||
LedgerEntry.StationUpkeep => T("Stazioni e depositi"),
|
||||
LedgerEntry.FleetMaintenance => T("Manutenzione dei treni"),
|
||||
LedgerEntry.TrackMaintenance => T("Manutenzione dei binari"),
|
||||
LedgerEntry.Wages => T("Stipendi"),
|
||||
LedgerEntry.Interest => T("Interessi"),
|
||||
LedgerEntry.Duties => T("Dazi"),
|
||||
LedgerEntry.Storage => T("Magazzini"),
|
||||
LedgerEntry.Penalties => T("Penali"),
|
||||
LedgerEntry.Construction => T("Costruzioni"),
|
||||
LedgerEntry.VehiclePurchase => T("Acquisto di treni"),
|
||||
LedgerEntry.VehicleSale => T("Vendita di treni"),
|
||||
LedgerEntry.IndustryPurchase => T("Acquisto di industrie"),
|
||||
LedgerEntry.LoanTaken => T("Prestiti ricevuti"),
|
||||
LedgerEntry.LoanRepaid => T("Prestiti rimborsati"),
|
||||
LedgerEntry.Shares => T("Azioni"),
|
||||
LedgerEntry.Dividends => T("Dividendi pagati"),
|
||||
_ => T("Altro"),
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ rating
|
||||
|
||||
private static string Ratio(double value) => Fmt.Number(value, 2);
|
||||
|
||||
private void RefreshRating(FinanceReport r)
|
||||
{
|
||||
_rating.Text = r.Rating;
|
||||
_ratingCaption.Text = r.RatingInitial
|
||||
? T("Rating iniziale: il primo calcolo arriva a inizio mese. Le misure qui sotto sono quelle di oggi.")
|
||||
: $"{T("Calcolato a inizio mese sugli ultimi")} {r.RatingMonths} {(r.RatingMonths == 1 ? T("mese chiuso") : T("mesi chiusi"))}. "
|
||||
+ $"{T("Punteggio")} {Ratio(r.Score)}.";
|
||||
foreach (var c in _ratingBody.GetChildren()) c.QueueFree();
|
||||
|
||||
_ratingBody.AddChild(Measure(T("Margine (utile / ricavi)"), r.MarginNeutral ? T("neutro") : Fmt.Pct(r.Margin, 1), r.MarginWeight, r.MarginComponent));
|
||||
if (r.MarginNeutral)
|
||||
_ratingBody.AddChild(Note(string.Format(T("Il margine conta da quando ci sono almeno {0} mesi chiusi con ricavi (ora {1}): fino ad allora vale 0, così i primi incassi non fanno crollare il rating."),
|
||||
r.MinRevenueMonths, r.RevenueMonths)));
|
||||
string leverage = r.LeverageUnbounded ? T("patrimonio non positivo") : Ratio(r.Leverage);
|
||||
_ratingBody.AddChild(Measure(T("Leva (debiti / patrimonio netto)"), leverage, r.LeverageWeight, r.LeverageComponent));
|
||||
|
||||
if (r.Bankrupt)
|
||||
{
|
||||
_ratingBody.AddChild(Note(T("In bancarotta il rating è D finché la situazione non si risolve.")));
|
||||
}
|
||||
else if (r.NextRating.Length == 0)
|
||||
{
|
||||
_ratingBody.AddChild(Note(T("È il rating più alto: i prestiti costano il minimo.")));
|
||||
}
|
||||
else if (r.NextAlreadyMet)
|
||||
{
|
||||
_ratingBody.AddChild(Note(string.Format(T("Il punteggio {0} vale già {1}: il rating si aggiorna al prossimo calcolo mensile, a inizio mese."),
|
||||
Ratio(r.Score), r.ScoreRating)));
|
||||
}
|
||||
else
|
||||
{
|
||||
var ways = new List<string>();
|
||||
if (r.MarginReachable) ways.Add(string.Format(T("un margine di almeno {0}"), Fmt.Pct(r.MarginNeeded, 1)));
|
||||
if (r.LeverageReachable)
|
||||
{
|
||||
string way = r.DebtToRepay.Cents <= 0 ? T("una leva non oltre {0}")
|
||||
: r.RepayAffordable ? T("una leva non oltre {0} (rimborsando {1})")
|
||||
: T("una leva non oltre {0} (servirebbe rimborsare {1}, più di quanto la cassa consenta oggi)");
|
||||
ways.Add(string.Format(way, Ratio(r.LeverageMax), r.DebtToRepay));
|
||||
}
|
||||
string how = ways.Count == 0 ? T("serve migliorare insieme margine e leva") : string.Join($" {T("oppure")} ", ways);
|
||||
_ratingBody.AddChild(Note(string.Format(T("Per il gradino {0} serve un punteggio di {1}: {2}."), r.NextRating, Ratio(r.NextThreshold), how)));
|
||||
}
|
||||
|
||||
// soglie e tassi per rating
|
||||
var grid = new GridContainer { Columns = 3 };
|
||||
grid.AddThemeConstantOverride("h_separation", 24);
|
||||
grid.AddChild(UiTheme.Text(T("Rating"), 12, Palette.TextSecondary, bold: true));
|
||||
grid.AddChild(UiTheme.Text(T("Punteggio da"), 12, Palette.TextSecondary, bold: true));
|
||||
grid.AddChild(UiTheme.Text(T("Tasso"), 12, Palette.TextSecondary, bold: true));
|
||||
foreach (var t in r.Thresholds)
|
||||
{
|
||||
bool current = t.Rating == r.Rating;
|
||||
var color = current ? Palette.AmberLight : Palette.TextSecondary;
|
||||
grid.AddChild(UiTheme.Text(t.Rating, 12, color, current));
|
||||
grid.AddChild(UiTheme.Text(Ratio(t.MinScore), 12, color, current));
|
||||
grid.AddChild(UiTheme.Text(Fmt.Pct(t.LoanRate, 1), 12, color, current));
|
||||
}
|
||||
_ratingBody.AddChild(grid);
|
||||
}
|
||||
|
||||
private static Control Measure(string caption, string value, float weight, float component)
|
||||
{
|
||||
var col = PanelKit.Column(4);
|
||||
var row = PanelKit.Row(8);
|
||||
var c = UiTheme.Text(caption, 14, Palette.Text);
|
||||
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
row.AddChild(c);
|
||||
row.AddChild(UiTheme.Text(value, 14, Palette.Text, bold: true));
|
||||
col.AddChild(row);
|
||||
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(component, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 6) };
|
||||
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 3, 0));
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
|
||||
col.AddChild(bar);
|
||||
col.AddChild(UiTheme.Text($"{T("componente")} {Ratio(component)} × {T("peso")} {Ratio(weight)}", 12, Palette.TextSecondary));
|
||||
return col;
|
||||
}
|
||||
|
||||
private static Label Note(string text)
|
||||
{
|
||||
var l = UiTheme.Text(text, 13, Palette.Text);
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
return l;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||||
|
||||
private Money Amount => Money.FromLire((long)_amount.Value);
|
||||
|
||||
private void RefreshLoans(FinanceReport? r)
|
||||
{
|
||||
foreach (var c in _loans.GetChildren()) c.QueueFree();
|
||||
if (r is null) return;
|
||||
var w = _session.World;
|
||||
if (r.LoanList.Count == 0) _loans.AddChild(UiTheme.Text(T("Nessun prestito in corso."), 13, Palette.TextSecondary));
|
||||
foreach (var loan in r.LoanList)
|
||||
{
|
||||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 8, 12));
|
||||
var col = PanelKit.Column(4);
|
||||
var head = PanelKit.Row(8);
|
||||
var title = UiTheme.Text($"{T("Residuo")} {loan.Remaining} {T("su")} {loan.Principal}", 14, Palette.Text, bold: true);
|
||||
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
head.AddChild(title);
|
||||
head.AddChild(UiTheme.Text($"{Fmt.Pct(loan.AnnualRate, 1)} {T("fisso")}", 14, Palette.AmberLight, bold: true));
|
||||
col.AddChild(head);
|
||||
col.AddChild(UiTheme.Text(
|
||||
$"{T("Rata mensile")} {loan.Payment} ({T("interessi")} {loan.NextInterest}) · {loan.MonthsLeft} {T("mesi")} · {T("scadenza")} {Fmt.Date(w, loan.MaturityDay)}",
|
||||
12, Palette.TextSecondary));
|
||||
var buttons = PanelKit.Row(8);
|
||||
var part = Money.Min(Amount, loan.Remaining);
|
||||
var repay = new Button { Text = $"{T("Rimborsa")} {part}", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
repay.Disabled = part >= loan.Remaining;
|
||||
int id = loan.Loan;
|
||||
repay.Pressed += () => Repay(id, part);
|
||||
var all = new Button { Text = $"{T("Estingui")} ({loan.Remaining})", CustomMinimumSize = new Vector2(0, 34), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
var remaining = loan.Remaining;
|
||||
all.Pressed += () => Repay(id, remaining);
|
||||
buttons.AddChild(repay);
|
||||
buttons.AddChild(all);
|
||||
col.AddChild(buttons);
|
||||
card.AddChild(col);
|
||||
_loans.AddChild(card);
|
||||
}
|
||||
|
||||
_borrow.Disabled = !r.LoansAllowed || r.LoanAvailable.Cents <= 0;
|
||||
_credit.Text = r.Bankrupt ? T("In bancarotta non si possono chiedere prestiti")
|
||||
: r.Receivership ? T("In amministrazione controllata non si possono chiedere prestiti")
|
||||
: string.Format(T("Fido disponibile {0} su {1}. Tasso di un nuovo prestito: {2} fisso (base {3} + rating {4} {5}) per {6} anni."),
|
||||
r.LoanAvailable, r.MaxLoan, Fmt.Pct(r.NewLoanRate, 1), Fmt.Pct(r.BaseRate, 1), r.Rating, Fmt.Pct(r.Spread, 1), r.LoanTermMonths / 12);
|
||||
}
|
||||
|
||||
private void Borrow() =>
|
||||
_session.Command(new TakeLoanCommand(Amount), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
|
||||
private void Repay(int loan, Money amount) =>
|
||||
_session.Command(new RepayLoanCommand(new LoanId(loan), amount), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
}
|
||||
@@ -26,6 +26,12 @@ public static class Fmt
|
||||
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
|
||||
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
|
||||
|
||||
/// <summary>
|
||||
/// Avanzamento (0–1) in percentuale intera per difetto («99%»): il 100 % compare solo quando la
|
||||
/// frazione è piena, cioè con il requisito o il livello davvero raggiunto (ADR 0018).
|
||||
/// </summary>
|
||||
public static string Progress(double fraction) => Number(Math.Floor(Math.Clamp(fraction, 0, 1) * 100 + 1e-9), 0) + "%";
|
||||
|
||||
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
|
||||
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
|
||||
|
||||
|
||||
@@ -523,7 +523,7 @@ public partial class MarketPanel : VBoxContainer
|
||||
}
|
||||
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello")} {tier}.", 13, Palette.Text));
|
||||
col.AddChild(Bar(report.TradingProgress, Palette.Amber));
|
||||
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Pct(report.TradingProgress, 0)}", 12, Palette.TextSecondary));
|
||||
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Progress(report.TradingProgress)}", 12, Palette.TextSecondary));
|
||||
// merce già in magazzino (per esempio ereditata da una fusione): si vende e si spedisce anche senza lo sblocco
|
||||
if (report.Warehouses.Any(h => h.Incoming > 0 || h.Goods.Any(g => g.Units > 0)))
|
||||
{
|
||||
|
||||
@@ -21,6 +21,7 @@ public partial class SeriesChart : Control
|
||||
private string _empty = "";
|
||||
private IReadOnlyList<double> _forecast = [], _low = [], _high = [];
|
||||
private string _todayLabel = "", _forecastLabel = "";
|
||||
private IReadOnlyList<(int Index, string Label)> _markers = [];
|
||||
|
||||
public SeriesChart(float height = 150)
|
||||
{
|
||||
@@ -38,6 +39,17 @@ public partial class SeriesChart : Control
|
||||
_color = color;
|
||||
_empty = empty;
|
||||
_forecast = _low = _high = [];
|
||||
_markers = [];
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Segni sulla serie a linea (dopo <see cref="Show"/>): un punto con l'etichetta sopra, per
|
||||
/// esempio i livelli raggiunti nello storico del patrimonio (immagine 08).
|
||||
/// </summary>
|
||||
public void SetMarkers(IReadOnlyList<(int Index, string Label)> markers)
|
||||
{
|
||||
_markers = markers;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
@@ -118,6 +130,19 @@ public partial class SeriesChart : Control
|
||||
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
|
||||
DrawPolyline(points, _color, 2.5f, true);
|
||||
if (f > 0) DrawForecast(area, points[^1], step, Y, font, fontSize);
|
||||
foreach (var (index, label) in _markers)
|
||||
{
|
||||
if (index < 0 || index >= n) continue;
|
||||
var p = points[index];
|
||||
bool atEnd = index == n - 1;
|
||||
DrawCircle(p, 5, Palette.AmberLight);
|
||||
DrawArc(p, 5, 0, MathF.Tau, 16, Palette.AppBackground, 1.5f, true);
|
||||
var dims = font.GetStringSize(label, HorizontalAlignment.Left, -1, 12);
|
||||
// sull'ultimo punto (che ha sopra il suo valore) l'etichetta va a sinistra, alla sua altezza
|
||||
float mx = atEnd ? Math.Max(area.Position.X, p.X - dims.X - 10) : Math.Clamp(p.X - dims.X / 2, area.Position.X, Size.X - dims.X - 4);
|
||||
float my = atEnd ? p.Y + 16 : p.Y - 12 < area.Position.Y + 10 ? p.Y + 20 : p.Y - 12;
|
||||
DrawString(font, new Vector2(mx, my), label, HorizontalAlignment.Left, -1, 12, Palette.AmberLight);
|
||||
}
|
||||
DrawCircle(points[^1], 4, Palette.AmberLight);
|
||||
string last = _format(_values[^1]);
|
||||
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
|
||||
|
||||
@@ -77,41 +77,3 @@ public partial class HelpPanel : VBoxContainer
|
||||
AddChild(l);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Conti della compagnia e prestiti.</summary>
|
||||
public partial class FinancePanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _cash = PanelKit.Value();
|
||||
private readonly Label _worth = PanelKit.Value();
|
||||
private readonly Label _rating = PanelKit.Value();
|
||||
private readonly SpinBox _loan = new() { MinValue = 10_000, MaxValue = 10_000_000, Step = 10_000, Value = 100_000, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
|
||||
public FinancePanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 10);
|
||||
AddChild(UiTheme.TitleLabel(T("Finanze"), 34));
|
||||
AddChild(PanelKit.Pair(T("Cassa"), _cash));
|
||||
AddChild(PanelKit.Pair(T("Patrimonio netto"), _worth));
|
||||
AddChild(PanelKit.Pair(T("Rating"), _rating));
|
||||
AddChild(PanelKit.Separator());
|
||||
AddChild(UiTheme.Text(T("Prestito"), 14, bold: true));
|
||||
AddChild(_loan);
|
||||
var take = UiTheme.Primary(T("Chiedi il prestito"));
|
||||
take.Pressed += () => _session.Command(new TakeLoanCommand(Money.FromLire((long)_loan.Value)), r => _status.Text = r.Message);
|
||||
AddChild(take);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
AddChild(_status);
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session.World;
|
||||
var me = w.Summary is null ? null : w.Companies.GetValueOrDefault(w.Summary.CompanyId);
|
||||
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
|
||||
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString();
|
||||
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -43,6 +44,8 @@ public partial class GameScreen : Node
|
||||
private IndustryPanel? _industryPanel;
|
||||
private CompaniesPanel? _companies;
|
||||
private MarketPanel? _market;
|
||||
private ClimbPanel? _climb;
|
||||
private FinancePanel? _finance;
|
||||
// pannelli a tutto schermo (Compagnie e borsa, Mercato globale): coprono mappa e pannello destro, la barra resta
|
||||
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
|
||||
private Control? _mapArea;
|
||||
@@ -117,6 +120,18 @@ public partial class GameScreen : Node
|
||||
if (good >= 0) _market?.Select(good);
|
||||
}
|
||||
|
||||
/// <summary>Apre «La tua scalata» a tutto schermo (dal pulsante o dal livello nella barra superiore).</summary>
|
||||
public void OpenClimb()
|
||||
{
|
||||
if (_tool != Tool.Climb) _toolbar.Select(Tool.Climb);
|
||||
}
|
||||
|
||||
/// <summary>Apre le «Finanze» a tutto schermo: conto economico, rating e prestiti.</summary>
|
||||
public void OpenFinance()
|
||||
{
|
||||
if (_tool != Tool.Finance) _toolbar.Select(Tool.Finance);
|
||||
}
|
||||
|
||||
/// <summary>Dal Mercato globale: strumento binari con la mappa centrata sull'hub da collegare.</summary>
|
||||
private void PlanLineToHub(int hub)
|
||||
{
|
||||
@@ -218,6 +233,7 @@ public partial class GameScreen : Node
|
||||
_map.Bind(_session);
|
||||
_minimap.Bind(_session.World, _map);
|
||||
_top.Bind(_session);
|
||||
_top.ClimbRequested += OpenClimb;
|
||||
_toolbar.Selected += SelectTool;
|
||||
_map.Clicked += OnMapClicked;
|
||||
_map.Hovered += OnMapHovered;
|
||||
@@ -225,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;
|
||||
@@ -393,8 +414,10 @@ public partial class GameScreen : Node
|
||||
_industryPanel = null;
|
||||
_companies = null;
|
||||
_market = null;
|
||||
_climb = null;
|
||||
_finance = null;
|
||||
foreach (var c in _full.GetChildren()) c.QueueFree();
|
||||
bool full = tool is Tool.Companies or Tool.Market;
|
||||
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance;
|
||||
_full.Visible = full;
|
||||
if (_mapArea is not null) _mapArea.Visible = !full;
|
||||
if (_side is not null) _side.Visible = !full;
|
||||
@@ -464,8 +487,17 @@ public partial class GameScreen : Node
|
||||
_full.AddChild(_market);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Climb:
|
||||
_climb = new ClimbPanel(_session);
|
||||
_climb.CloseRequested += () => _toolbar.Select(Tool.None);
|
||||
_full.AddChild(_climb);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Finance:
|
||||
panel = new FinancePanel(_session);
|
||||
_finance = new FinancePanel(_session);
|
||||
_finance.CloseRequested += () => _toolbar.Select(Tool.None);
|
||||
_full.AddChild(_finance);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
default:
|
||||
panel = NewInfoPanel();
|
||||
|
||||
@@ -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();
|
||||
|
||||
+6
-1
@@ -139,7 +139,12 @@
|
||||
"loanStep": 5000000,
|
||||
"startingRating": "BB",
|
||||
"depreciationYearsTrack": 50,
|
||||
"bookValueFloor": 0.1
|
||||
"bookValueFloor": 0.1,
|
||||
"incomeMonths": 12,
|
||||
"incomeYears": 10,
|
||||
"bankruptcyWarningDaysLeft": [ 30, 14, 7, 3, 1 ],
|
||||
"ratingMinRevenueMonths": 3,
|
||||
"negativeCashNoticeDays": 3
|
||||
},
|
||||
"stockMarket": {
|
||||
"shares": 1000000,
|
||||
|
||||
@@ -31,6 +31,10 @@
|
||||
"maxItems": 10,
|
||||
"uniqueItems": true
|
||||
},
|
||||
"ratingProgressSteps": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"tiers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -152,6 +156,7 @@
|
||||
"required": [
|
||||
"version",
|
||||
"ratingScale",
|
||||
"ratingProgressSteps",
|
||||
"tiers"
|
||||
],
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"$schema": "schema/tiers.schema.json",
|
||||
"version": 1,
|
||||
"ratingScale": [ "AAA", "AA", "A", "BBB", "BB", "B", "CCC", "CC", "C", "D" ],
|
||||
"ratingProgressSteps": 2.5,
|
||||
"tiers": [
|
||||
{ "level": 1, "name_it": "Compagnia locale", "name_en": "Local company",
|
||||
"requirements": { "netWorth": 0, "connectedTownsOver": { "count": 0, "population": 0 }, "creditRating": "D" },
|
||||
|
||||
@@ -60,7 +60,7 @@ Sistemi implementati (F1–F5), nella loro posizione:
|
||||
| `IndustryMaintenanceSystem` | giorno/mese | condizione degli impianti (usura con l'utilizzo, recupero del budget), consumo di ricambi, fermi e incidenti, revisioni e ammodernamenti in attesa di macchinari, scelte dei proprietari privati, conguaglio con il proprietario (ADR 0011) |
|
||||
| `TownSystem` | giorno/mese/anno | consumo e soddisfazione, crescita, migrazione, espansione dell'abitato |
|
||||
| `MarketSystem` | giorno | prezzi globali con componente mondiale e shock, domanda insoddisfatta |
|
||||
| `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro, cassa negativa e bancarotta, rate dei prestiti, rating, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
|
||||
| `FinanceSystem` | giorno/mese/anno | costi di esercizio dei veicoli (`RunningCosts`) e di stazioni e depositi (`StationUpkeep`), stipendi del personale presente nei depositi (`Wages`), valori di libro per voce (`BookValues`, ADR 0018), cassa negativa con gli avvisi e bancarotta ai giorni della difficoltà, rate dei prestiti a tasso fisso, chiusura del mese nel conto economico per voce (`IncomeMonths`, `IncomeYears`) e nell'anello dei 12 mesi, rating da margine (12 mesi) e leva (debiti / patrimonio) con le misure conservate, livelli (`Tiers`), chiusura dei conti (ADR 0019) |
|
||||
| `StockMarketSystem` | giorno/mese/anno | prezzi e sentiment, valore delle partecipazioni, offerte pubbliche (adesioni, esito), controllo e utili delle controllate, amministrazione controllata del giocatore, fallimenti e aste, storico annuale, nuovi concorrenti (ADR 0012) |
|
||||
| `AiSystem` | giorno/mese | agenti delle compagnie IA: progetti, stalli, offerte; una volta al mese (giorno diverso per IA) finanza, treni aggiuntivi, borsa, industrie, linee dei ricambi e nuovi progetti, tutto con i comandi (ADR 0013) |
|
||||
| `EventSystem` | giorno | eventi del mondo (F6, ADR 0017): chiude quelli scaduti, estrae i nuovi dal catalogo `events.json` con il flusso «events» e la frequenza della difficoltà, notizie d'inizio e di fine (posto di «Events») |
|
||||
@@ -92,8 +92,8 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
|
||||
## 6. Economia e contabilità
|
||||
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio.
|
||||
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno.
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio. `ClimbOutlook` (F6, ADR 0018) è l'analisi in sola lettura per «La tua scalata»: livelli con gli sblocchi dai dati (`Tiers.NewUnlocks`), requisiti del prossimo livello con l'avanzamento (media delle tre frazioni, usata anche dal Mercato globale), stato patrimoniale per voce che somma al patrimonio netto del motore, conto economico, prestiti, storico del patrimonio dalla Cronaca. `FinanceOutlook` (F6, ADR 0019) è l'analisi in sola lettura per il pannello «Finanze»: conto economico per voce (mese in corso, mesi chiusi, anno in corso, anni chiusi) che somma all'utile operativo del motore, spiegazione del rating (misure, componenti, soglie, cosa serve per salire), prestiti con rata e scadenza, fido, giorni di cassa negativa sul limite della difficoltà.
|
||||
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno; `LedgerEntries` ne fissa l'ordine e le sezioni (ricavi, costi, investimenti e finanziamenti) e `Company.OperatingProfit` è la somma di ricavi e costi (ADR 0019). Un trasferimento può usare voci diverse per chi paga e chi incassa (dividendi pagati e incassati).
|
||||
- Ogni unità di merce sta in un magazzino tracciato (industrie, città, magazzini delle compagnie nelle stazioni, pacchetti in stazione e a bordo dei treni) e `GoodsCounters` registra prodotto, consumato, deperito, importato, esportato: giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci».
|
||||
- Compravendita in proprio (F6, ADR 0016): `TradingCommandHandlers` esegue `BuyGoods`, `SellGoods` e `ShipGoods` con il prezzo locale marginale di `Systems/TradingMath` (unità per unità, controparti ordinate per prezzo). La merce comprata sta in `Station.Stock`; quella spedita viaggia in pacchetti con `Packet.Owned`, senza tariffa né consumatore, ed entra nel magazzino della stazione d'arrivo. Gli scambi con le industrie passano dal registro sulla voce «Commercio», quelli con gli hub contano come importazione ed esportazione; `StationSystem` addebita ogni mese la giacenza dei magazzini.
|
||||
- Eventi del mondo (F6, ADR 0017): `World.WorldEvents` (`WorldEventState`) è l'unica sorgente dei loro effetti. I sistemi chiedono un moltiplicatore per entità (1 senza eventi): `IndustryCapacity` in `IndustrySystem` e nella domanda di input di `DemandSystem`, `TownDemand` in `DemandSystem.TownDemand`, `Attendance` nelle presenze dei pendolari di `EmploymentSystem`, `EdgeSpeed` in `TrainSystem` ed `EdgeWear` nell'usura del binario di `ConstructionSystem` (traffico del giorno prima). Contano solo gli eventi in vigore nel giorno dell'orologio, [inizio, fine). Nessuno stato di base viene modificato: a evento finito il moltiplicatore torna 1. Le stime dei candidati delle IA leggono i valori senza eventi.
|
||||
@@ -108,6 +108,8 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- Corpo versione 3 (F5): `CorporateSerializer` aggiunge manutenzione e proprietà delle industrie, libro dei soci, prezzi, controllo e storico delle compagnie, offerte, aste, fine partita e stato degli agenti IA (progetti, candidati scartati); i salvataggi precedenti si migrano (ADR 0012).
|
||||
- Corpo versione 4 (F6): `TradingSerializer` aggiunge i magazzini delle compagnie nelle stazioni (beni per id testuale) e gli id dei pacchetti di merce propria in stazione e a bordo; i salvataggi precedenti si caricano con i magazzini vuoti. `WorldSerializer.Write(w, s, versione)` scrive un corpo di una versione precedente per i test di migrazione (ADR 0016).
|
||||
- Corpo versione 5 (F6): `EventSerializer` aggiunge il prossimo id e gli eventi del mondo attivi (tipo e bene per id testuale, bersaglio, giorni, intensità; la zona si ricalcola dal catalogo); le impostazioni salvano `eventFrequencyMultiplier`. I salvataggi precedenti si caricano senza eventi e con la frequenza del preset (ADR 0017).
|
||||
- Corpo versione 6 (F6): `BalanceSheetSerializer` aggiunge per ogni compagnia il valore contabile per voce (`AssetCategory`) e il giorno in cui ha raggiunto ogni livello. I salvataggi precedenti ripartiscono il totale salvato in proporzione alle voci calcolate al caricamento (stesso patrimonio netto) e ricostruiscono i giorni dai fatti salienti o dallo storico (ADR 0018).
|
||||
- Corpo versione 7 (F6): `FinanceSerializer` aggiunge per ogni compagnia i mesi e gli anni chiusi per voce del registro e le misure dell'ultimo calcolo del rating. I salvataggi precedenti partono senza mesi chiusi, con l'ultimo anno chiuso dal registro e la spiegazione del rating sulle misure del giorno fino al primo calcolo mensile (ADR 0019).
|
||||
|
||||
## 8. Server
|
||||
|
||||
@@ -125,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, 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
|
||||
|
||||
+8
-2
@@ -77,7 +77,7 @@ costMultiplier: f64 }`
|
||||
| 7 | Save | `name: string` |
|
||||
| 8 | Load | `saveId: string` |
|
||||
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
|
||||
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca; dalla F6: 7 quadro del mercato globale), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6 e 7). Aggiunto in F4 |
|
||||
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca; dalla F6: 7 quadro del mercato globale, 8 quadro della scalata, 9 quadro delle finanze), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6, 7, 8 e 9). Aggiunto in F4 |
|
||||
|
||||
### Comandi (`Command.type`, payload in ordine)
|
||||
|
||||
@@ -160,6 +160,8 @@ loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emi
|
||||
| 131 | Notification | `EventInfo` |
|
||||
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
|
||||
| 133 | SaveList | `saves: [SaveInfo]` |
|
||||
| 134 | ClimbReport | `day: i64, company: i32, foundedDay: i64, initialCapital: Money, tier: u8, nextTier: u8 (0 all'ultimo livello), tiers: [TierInfo]`; requisiti del prossimo livello: `netWorth, netWorthRequired: Money, netWorthFraction: f32, netWorthMet: bool, towns, townsRequired, townPopulation: i32, townsFraction: f32, townsMet: bool, rating, ratingRequired: string, ratingFraction: f32, ratingMet: bool, progress: f32` (media delle tre frazioni); stato patrimoniale: `assets: [AmountInfo]` (kind 0 binari e opere, 1 stazioni e depositi, 2 veicoli, 3 industrie possedute, 4 merce propria), `portfolio, cash (positiva), totalAssets, loans: Money, loansRate: f32 (medio), overdraft (scoperto), totalLiabilities, balanceNetWorth: Money` (= totalAssets − totalLiabilities = patrimonio netto del motore); conto economico: `incomeYear: i32, incomePartial: bool, income: [AmountInfo]` (kind 0 tariffe e noli, 1 altri ricavi, 2 costi operativi, 3 manutenzione, 4 interessi; con segno), `profit: Money`; prestiti: `loanList: [LoanInfo], maxLoan, loanAvailable: Money, newLoanRate: f32, loansAllowed: bool`; `history: [NetWorthPointInfo]` (fondazione, fine di ogni anno, oggi) (su richiesta, F6; ADR 0018) |
|
||||
| 135 | FinanceReport | `day: i64, company: i32, cash, netWorth, loans, overdraft: Money`; conto economico: `lines: [FinanceLineInfo]` (voci in ordine di presentazione), `columns: [IncomeColumnInfo]` (mese in corso, mesi chiusi dal più recente, anno in corso, anni chiusi dal più recente); rating: `rating: string, ratingInitial: bool, ratingMonths, revenueMonths: u8, marginNeutral: bool (margine 0 finché la finestra non è piena e ha meno di minRevenueMonths mesi con ricavi), minRevenueMonths: u8, margin, leverage: f32, leverageUnbounded: bool, marginWeight, leverageWeight, marginComponent, leverageComponent, score: f32, thresholds: [RatingThresholdInfo], nextRating: string ("" ad AAA), nextThreshold: f32, nextAlreadyMet: bool (il punteggio basta già: rating scoreRating al prossimo calcolo mensile, obiettivi a zero), scoreRating: string, marginNeeded: f32, marginReachable: bool, leverageMax: f32 (sempre finita), leverageReachable: bool, debtToRepay: Money, repayAffordable: bool (il rimborso non supera la cassa né il residuo dei prestiti; lo scoperto non si rimborsa)`; prestiti: `loanList: [FinanceLoanInfo], maxLoan, loanAvailable: Money, newLoanRate, baseRate, spread: f32, loanTermMonths: i32, loanStep: Money, loansAllowed: bool`; bancarotta: `negativeCashDays, bankruptcyDays: i32, bankrupt, receivership: bool` (su richiesta, F6; ADR 0019) |
|
||||
|
||||
Record (ognuno chiude con `flags`):
|
||||
|
||||
@@ -196,6 +198,10 @@ Record (ognuno chiude con `flags`):
|
||||
- `IndustryStopInfo { day: i64, days, kind: u8 }`, `RecordInfo { title, value: string, year }`
|
||||
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
|
||||
- `GoodMarketInfo { good, available, price: f64 (centesimi), change: f32 (30 giorni), supplyMonth, demandMonth, worldSupplyMonth, worldDemandMonth, stockUnits: f64, stockMonths: f32 (−1 senza domanda), history: [PricePointInfo { day: i64, price: f64 }] (un campione per mese, l'ultimo è oggi), forecast: [ForecastInfo { months: u8, price, low, high: f64 }], sellPlaces: [SellPlaceInfo { kind: u8 (0 industria, 1 hub), target, price: f64, line: i32 (−1 non collegato) }] }`
|
||||
- `TierInfo { level: u8, nameIt, nameEn: string, netWorthRequired: Money, townsRequired, townPopulation: i32, ratingRequired: string, reached: bool, reachedDay: i64 (fondazione per il livello 1; −1 se non raggiunto o sconosciuto), unlocks: [UnlockInfo] }`; `UnlockInfo { kind: u8 (0 fido, 1 squadre di cantiere, 2 compravendita in proprio, 3 acquisto di industrie, 4 quotazione, 5 scalate ostili, 6 concessioni), value: i64 (fido in centesimi o numero di squadre; 0 per gli altri) }`: gli sblocchi che il livello aggiunge al precedente
|
||||
- `AmountInfo { kind: u8, value: Money }`, `LoanInfo { loan, remaining: Money, annualRate: f32, monthsLeft: i32 }`, `NetWorthPointInfo { day: i64, value: Money }`
|
||||
- `LedgerEntry` (voce del registro, u8): 0 FreightRevenue (noli merci), 1 PassengerRevenue (biglietti), 2 Construction (costruzioni), 3 VehiclePurchase (acquisto di treni), 4 VehicleSale (vendita di treni), 5 RunningCosts (esercizio dei treni), 6 TrackMaintenance (manutenzione dei binari), 7 FleetMaintenance (manutenzione dei treni), 8 Wages (stipendi), 9 Interest (interessi), 10 LoanTaken (prestiti ricevuti), 11 LoanRepaid (prestiti rimborsati), 12 Trading (commercio in proprio), 13 IndustryPurchase (acquisto di industrie), 14 Dividends (dividendi pagati), 15 Shares (azioni), 16 Contracts (contratti), 17 Penalties (penali), 18 Other (altro), 19 Industries (industrie possedute), 20 Subsidiaries (controllate), 21 StationUpkeep (stazioni e depositi), 22 Storage (magazzini), 23 Duties (dazi), 24 DividendsReceived (dividendi incassati). Sezione: ricavi 0, 1, 12, 16, 19, 20, 24; costi 5–9, 17, 21–23; investimenti e finanziamenti gli altri (ADR 0019)
|
||||
- `FinanceLineInfo { kind: u8 (LedgerEntry), section: u8 (0 ricavi, 1 costi, 2 investimenti e finanziamenti) }`, `IncomeColumnInfo { kind: u8 (0 mese in corso, 1 mese chiuso, 2 anno in corso, 3 anno chiuso), year: i32, month: u8 (1–12, 0 per gli anni), values: [AmountInfo] (solo le voci diverse da zero, kind = LedgerEntry, con segno), profit: Money (utile operativo del motore), cashFlow: Money }`, `RatingThresholdInfo { rating: string, minScore, loanRate: f32 }`, `FinanceLoanInfo { loan: i32, principal, remaining: Money, annualRate: f32 (fisso), monthsLeft: i32, payment, nextInterest: Money, maturityDay: i64 }`
|
||||
- `HubMarketInfo { hub, kind: u8 (0 porto, 1 valico), monthlyCapacity, duty: f32, usedThisMonth, line: i32 (−1 non collegato) }`
|
||||
- `WarehouseInfo { station, capacity, incoming: i32 (merce propria in viaggio verso la stazione), goods: [WarehouseGoodInfo] }` (stazioni vive della compagnia)
|
||||
- `WarehouseGoodInfo { good, units: i32 (in magazzino), buyPrice: f64 (centesimi, prossima unità; −1 nessun venditore), buyUnits: i32, sellPrice: f64 (−1 nessun compratore), sellUnits: i32 }` (beni in magazzino o scambiabili nel bacino)
|
||||
@@ -219,7 +225,7 @@ Record (ognuno chiude con `flags`):
|
||||
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
|
||||
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce. Dalla F6
|
||||
`MarketReport` (quadro del mercato globale per la compagnia della sessione), che il pannello chiede
|
||||
all'apertura e a ogni nuovo giorno; il server non lo manda da solo.
|
||||
all'apertura e a ogni nuovo giorno; il server non lo manda da solo. Così anche `ClimbReport` (quadro della scalata), che il pannello chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e la barra superiore una volta al mese, e `FinanceReport` (quadro delle finanze), che il pannello «Finanze» chiede all'apertura, a ogni nuovo giorno e dopo un prestito o un rimborso.
|
||||
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
|
||||
sessione si chiude (il client può riprenderla).
|
||||
- Obiettivo di banda in regime: < 100 KB/s per client.
|
||||
+33
-5
@@ -89,9 +89,9 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Immagini di riferimento 06–09 aggiunte in `reference/`.
|
||||
- Primo rilascio **v0.5.0** (7/11/2026): CI verde, release Gitea con server Windows/Linux e immagine `rail-enterprise-server:0.5.0`/`latest`; collaudo `smoke` contro il server reale superato (ponte di 175 m, scarto 0,00 m). Il gioco desktop di v0.5.0 però parte senza codice C#: mancava la soluzione `client/RailEnterprise.Client/RailEnterprise.Client.sln` che Godot richiede per esportare. Aggiunta la soluzione e un controllo che fa fallire il rilascio senza assembly; correzione in **v0.5.1**.
|
||||
- **v0.5.1** (7/11/2026): il gioco desktop scaricato dalla release funziona. Il pilota automatico (`RailEnterprise.exe -- --autopilot <cartella>`) avvia il server incluso, costruisce linea, ponte e treni e salva le 17 schermate; esce con codice 0. Restava un difetto: `strings.csv` non era nel gioco esportato (avviso «Traduzioni non trovate», inglese assente), corretto con l'importatore «keep».
|
||||
- Test instabile sotto carico (issue #24): `BuildLineWithBridgeOverTheNetworkAndWatchTheTrain` (scarto 884 m una volta sul runner), causa ancora da trovare.
|
||||
- Test instabile sotto carico (issue #24): `BuildLineWithBridgeOverTheNetworkAndWatchTheTrain` (scarto 884 m una volta sul runner). Causa nel test: `TestClient.WaitUntil` ingoiava il tempo scaduto (`ContinueWith(_ => true)`), quindi se il moto dell'ultimo tick non arrivava in 10 s il test confrontava un moto vecchio (il run fallito durò 19 s invece di 7). Il moto non arriva quando la pausa coglie il treno fermo: il server rimanda solo i moti dei treni in marcia. Ora `WaitUntil` fa fallire il test allo scadere e la pausa si ripete finché il treno è in marcia; 24 esecuzioni dei test del server su 24 verdi con 8 processi in parallelo.
|
||||
- `MaintenanceDetailsOnRequest` falliva a volte per un difetto del test: leggeva il registro degli impieghi che il server manda da solo a inizio mese (giorno 0, prima dell'officina) invece della risposta alla richiesta; in locale falliva 2 volte su 4, dopo la correzione 6 su 6 verdi.
|
||||
- **v0.6.0** (7/11/2026): prima versione con i pezzi della F6: Mercato globale (ADR 0015), compravendita in proprio (ADR 0016) ed eventi del mondo (ADR 0017).
|
||||
- **v0.6.0** (7/11/2026): prima versione con i pezzi della F6: Mercato globale (ADR 0015), compravendita in proprio (ADR 0016) ed eventi del mondo (ADR 0017). Il gioco scaricato dalla release passa il pilota automatico (18 schermate, codice 0): il pannello «Mercato globale» si disegna come l'immagine 06, con storico, previsione e banda, offerta, domanda, scorte, «Dove conviene vendere», hub, evento e riquadro della compravendita bloccato al livello 1 (`docs/screenshots/f6-mercato-globale.jpg`). Il riquadro «Eventi in corso» non compare nelle schermate perché nei primi tre mesi della partita del pilota non scatta nessun evento.
|
||||
|
||||
## In corso
|
||||
|
||||
@@ -121,21 +121,49 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- le IA non reagiscono agli eventi: ne subiscono gli effetti attraverso i sistemi, ma stimano i candidati sui valori senza eventi (domanda delle città, posti scoperti, efficienza delle industrie di trasformazione; ADR 0017 §9);
|
||||
- correzioni della revisione: un evento è in vigore nei giorni [inizio, fine) per tutti (sistemi giornalieri, treni a ogni tick, usura del traffico del giorno prima) ed esce dall'elenco il mattino del primo giorno libero con la notizia di fine; nessuna sovrapposizione di zone tra due maltempi o tra due eventi sulla domanda dello stesso bene; `{until}` è l'ultimo giorno; client: conto alla rovescia dalla durata a 1 e «da domani» per gli eventi estratti oggi, avviso anche nelle città della zona e nel Registro officina del deposito, notiziario senza doppioni (dal resoconto solo le notizie di fine, le altre arrivano come `Notification`);
|
||||
- test (`Simulation/EventTests.cs`, 19): catalogo e validazione, effetti di ogni tipo e loro fine, solo la zona per domanda e maltempo, treni rallentati, officina senza personale, durata, niente doppioni né zone sovrapposte, giorni del maltempo per treni, usura e resoconto con il conto alla rovescia, presenti senza eventi per l'IA, frequenza 0, stesso seme stessi eventi, salvataggio con eventi attivi, migrazione dalla versione 4, un anno di eventi frequenti con gli invarianti (lento), eventi nel `DailyDigest` e nel `MarketReport`. 162 test (144 senza i lenti).
|
||||
- Restano della F6: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
- **Livelli e sblocchi visibili, «La tua scalata» (issue #38, ADR 0018)**:
|
||||
- `ClimbOutlook` (Core, sola lettura): livelli con gli sblocchi letti dai dati (`Tiers.NewUnlocks`: fido, squadre di cantiere, compravendita, acquisto di industrie, quotazione, scalate, concessioni), quando sono stati raggiunti, requisiti del prossimo livello con valore, soglia, frazione e avanzamento complessivo (media delle tre frazioni, ora anche nel Mercato globale al posto del minimo dell'ADR 0015), stato patrimoniale, conto economico dell'ultimo anno chiuso, prestiti, storico del patrimonio netto dalla Cronaca;
|
||||
- stato patrimoniale per voce con una sola fonte: `FinanceSystem.BookValues` (binari e opere, stazioni e depositi, veicoli, industrie possedute, merce propria) scritto ogni mese in `Company.BookValues`; `AssetBookValue` ne è la somma e la scomposizione (con partecipazioni, cassa, prestiti e scoperto) somma al centesimo al patrimonio netto del motore; le industrie possedute entrano nel patrimonio al valore degli impianti più la loro cassa (prezzo d'acquisto senza avviamento);
|
||||
- notizia di promozione con gli sblocchi ottenuti e giorno annotato (`Company.TierReachedDay`); rifiuti con il livello che serve e il suo nome dai dati (compravendita, acquisto di industrie, quotazione, scalate ostili, concessioni, fido insufficiente con il livello che alza il fido); il validatore pretende squadre per livello uguali in `tiers.json` e `construction.json`;
|
||||
- salvataggio: corpo versione 6 (`BalanceSheetSerializer`) con voci e giorni dei livelli nell'hash; le versioni 1–5 ripartiscono il totale salvato (stesso patrimonio netto) e ricostruiscono i giorni dai fatti salienti o dallo storico;
|
||||
- protocollo: `DetailKind.Climb` (8) e `ClimbReport` (134); server: quadro su richiesta; `ClientWorld.Climb`;
|
||||
- client: pannello «La tua scalata» a tutto schermo come l'immagine 08 (`ClimbPanel`: binario dei livelli con il treno e l'avanzamento, sblocchi sotto ogni livello, storico del patrimonio con i livelli segnati in `SeriesChart`, «Per diventare…» con tre barre, stato patrimoniale, conto economico, «Chiedi un prestito» e «Rimborsa»), pulsante «Scalata» nella barra degli strumenti, livello e avanzamento nella barra superiore (un clic apre il pannello), testi in `strings.csv`, schermata `17_scalata` nel pilota automatico;
|
||||
- test (`Economy/ClimbTests.cs`, 7, più il quadro via WebSocket in `ServerTests`): requisiti coerenti con `Tiers.Meets` e avanzamento, sblocchi dai dati, stato patrimoniale con industria, merce, prestito e scoperto che somma al patrimonio netto, notizia di promozione con gli sblocchi, rifiuti con il livello, salvataggio versione 6 e migrazione dalla 5, proiezione e round-trip di `ClimbReport`. 170 test (152 senza i lenti).
|
||||
- **Finanza completa (issue #39, ADR 0019)**:
|
||||
- analisi delle lacune nell'ADR: prestiti, fido per livello, rate, rating mensile e bancarotta ai giorni di `difficulty.json` c'erano già; mancavano stipendi delle compagnie, finestra di 12 mesi e leva su patrimonio nel rating, misure conservate, conto economico per voce mensile e annuale, voci separate per stazioni, dazi, magazzini e dividendi incassati, avvisi prima della bancarotta, quadro nel protocollo e pannello definitivo;
|
||||
- prestiti a tasso fisso (base della difficoltà + spread del rating all'accensione: niente spirale rating → rata → utile), rimborso anticipato parziale (stessa durata, rata più bassa) e totale senza penale, messaggi con tasso, rata, residuo e cassa disponibile;
|
||||
- rating ogni mese da margine = utile operativo / ricavi sugli ultimi 12 mesi chiusi e leva = (prestiti + scoperto) / patrimonio netto; punteggio, misure e mesi della finestra in `Company`; margine neutro finché la finestra non è piena e ha meno di `finance.ratingMinRevenueMonths` (3) mesi con ricavi, minimo senza ricavi e in perdita; `FinanceOutlook.Explain` dice componenti, soglie con il tasso per rating, gradino sopra, margine che basta, leva massima e debito da rimborsare (se la cassa basta), oppure che il punteggio vale già il gradino sopra;
|
||||
- voci nuove del registro: `StationUpkeep` (21), `Storage` (22), `Duties` (23), `DividendsReceived` (24, ora nell'utile); `LedgerEntries` fissa ordine e sezioni; stipendi giornalieri del personale presente nei depositi alle paghe delle industrie (`Wages`);
|
||||
- conto economico per voce: ultimi 12 mesi chiusi e 10 anni chiusi (`finance.incomeMonths`, `incomeYears`), ogni colonna con l'utile operativo e il flusso di cassa del motore;
|
||||
- avvisi di cassa negativa dopo `finance.negativeCashNoticeDays` (3) giorni di fila e a 30, 14, 7, 3, 1 giorni dal limite (`finance.bankruptcyWarningDaysLeft`, validati), notizia di rientro solo dopo il primo avviso, esito dell'ADR 0012 invariato; la quota dei trasporti dei nuovi concorrenti usa `Company.TransportRevenue` (tariffe, noli, contratti);
|
||||
- salvataggio: corpo versione 7 (`FinanceSerializer`) con mesi, anni e misure del rating nell'hash; le versioni 1–6 partono senza mesi chiusi, con l'ultimo anno dal registro;
|
||||
- protocollo: `DetailKind.Finance` (9) e `FinanceReport` (135); server: quadro su richiesta; `ClientWorld.Finance`;
|
||||
- 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).
|
||||
- **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: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, 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
|
||||
|
||||
- Godot non è eseguibile nell'ambiente cloud: il client potrà essere compilato con `Godot.NET.Sdk` ma non avviato né esportato qui.
|
||||
- Senza vettori il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004).
|
||||
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
|
||||
- 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 (F6, non ancora provato in Godot: qui manca l'editor); Industria, Scalata e la schermata di connessione vanno allineati in F6.
|
||||
- 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).
|
||||
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
|
||||
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
|
||||
|
||||
@@ -69,7 +69,8 @@ né come migrare i salvataggi con lo storico di un anno.
|
||||
(oggi il 2, «Compagnia regionale»). Se la compagnia ce l'ha è «sbloccata»; altrimenti l'avanzamento
|
||||
è il minimo tra le frazioni dei requisiti numerici (patrimonio netto / richiesto, città collegate /
|
||||
richieste, entrambe limitate a 1); il rating è soddisfatto o no e si mostra a parte, perché non ha
|
||||
una frazione sensata.
|
||||
una frazione sensata. *Sostituito dall'ADR 0018 §2: l'avanzamento è la media delle tre frazioni
|
||||
(patrimonio, città, rating), la stessa del pannello «La tua scalata».*
|
||||
|
||||
## Conseguenze
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# ADR 0018 — Scalata: livelli e sblocchi visibili, stato patrimoniale per voce (F6)
|
||||
|
||||
Stato: accettato (F6, issue #38).
|
||||
|
||||
## Contesto
|
||||
|
||||
Il motore ha i livelli dalla F5 (ADR 0011 §6: `tiers.json`, `Tiers`, promozione mensile dopo il rating,
|
||||
nessuna retrocessione), ma il giocatore li vedeva solo come distintivo nella barra e come rifiuti dei comandi
|
||||
con il nome del livello scritto a mano. La F6 chiede il pannello «La tua scalata» dell'immagine di
|
||||
riferimento 08: binario dei livelli con il treno che avanza, sblocchi di ogni livello, storico del
|
||||
patrimonio netto con i livelli raggiunti, requisiti del prossimo livello, stato patrimoniale, conto
|
||||
economico e prestiti. La guida non dice come scomporre il patrimonio netto, come misurare l'avanzamento,
|
||||
né come valutare le industrie possedute, che finora non entravano nel patrimonio.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Quadro come pura funzione del mondo.** `ClimbOutlook` (Core, `Economy/ClimbOutlook.cs`) legge il
|
||||
mondo e non scrive nulla, come `MarketOutlook` (ADR 0015). Il server lo proietta in `ClimbReport` (134)
|
||||
su richiesta (`RequestDetail` con `DetailKind.Climb` = 8); il client lo mostra com'è. Il pannello lo
|
||||
chiede all'apertura, a ogni nuovo giorno e dopo un comando di prestito; la barra superiore una volta
|
||||
al mese di gioco, per l'avanzamento accanto al livello.
|
||||
2. **Requisiti e avanzamento.** Per il prossimo livello: patrimonio netto, città collegate sopra la
|
||||
popolazione (lo stesso `Tiers.ConnectedTowns`) e rating, con valore attuale, soglia, soddisfatto o no
|
||||
(gli stessi confronti di `Tiers.Meets`) e frazione: patrimonio/soglia e città/città richieste limitate
|
||||
a 1; per il rating 1 − gradini mancanti / `ratingProgressSteps` di `tiers.json` (2,5), limitata tra 0
|
||||
e 1 (1 se soddisfatto: un gradino sotto vale il 60 %, tre o più lo 0 %). **L'avanzamento complessivo è
|
||||
la media delle tre frazioni**: con lo stato dell'immagine 08 (65 % di patrimonio, 1 città su 2, BBB
|
||||
verso A) le frazioni sono 0,65, 0,5 e 0,6 e l'avanzamento il 58 %, come nell'immagine. Misurare il
|
||||
rating dalla D (prima scelta) dava l'86 % per un solo gradino mancante e il 67 % complessivo, e gonfiava
|
||||
l'avanzamento fin dall'inizio. L'avanzamento vale 1 solo con tutti e tre i requisiti soddisfatti
|
||||
(altrimenti al massimo 0,999), e il client mostra queste percentuali per difetto, quindi il 100 %
|
||||
compare solo a requisito o livello raggiunto. Il quadro del Mercato globale usa la stessa funzione:
|
||||
l'ADR 0015 §12 (minimo dei requisiti numerici) è sostituito, così i due pannelli mostrano lo stesso numero.
|
||||
3. **Sblocchi dai dati.** `Tiers.NewUnlocks` elenca ciò che un livello aggiunge al precedente, nell'ordine
|
||||
di `UnlockKind`: fido massimo (fido iniziale × `maxLoanFactor`, se cresce), squadre di cantiere (se
|
||||
crescono), compravendita in proprio, acquisto di industrie, quotazione, scalate ostili, concessioni (le
|
||||
funzioni che passano da `false` a `true`); il livello 1 elenca la dotazione di partenza (fido e squadre).
|
||||
Le concessioni non si annunciano finché il comando non esiste (F7, `Tiers.ConcessionsAvailable`): il
|
||||
gioco non promette uno sblocco che non funziona. Il validatore pretende che gli sblocchi non diminuiscano
|
||||
salendo di livello (`maxLoanFactor` non decrescente, le funzioni non tornano `false`), come presumono
|
||||
notizie, rifiuti e pannello (ADR 0011: gli sblocchi restano acquisiti).
|
||||
Le squadre per livello stanno in due file (`construction.json`, usato dal cantiere, e `tiers.json`): il
|
||||
validatore ora pretende che coincidano. Nessun testo di regola è scritto a mano: il Core ha solo le
|
||||
etichette italiane degli sblocchi, il client le sue chiavi di traduzione.
|
||||
4. **Notizia di promozione.** Il passaggio di livello esisteva già; il testo ora elenca gli sblocchi
|
||||
ottenuti: «X diventa «Compagnia regionale» (livello 2): sblocca fido fino a …, 4 squadre di
|
||||
cantiere, compravendita in proprio» (il fido è quello della compagnia). Il livello non scende (ADR 0011): nessuna notizia di retrocessione.
|
||||
5. **Rifiuti con il livello.** I comandi bloccati dal livello dicono quale livello serve e come si chiama,
|
||||
dai dati (`Tiers.LockedText`): compravendita in proprio, acquisto di industrie, quotazione, scalate
|
||||
ostili e concessioni (che fino alla F7 sono «non ancora disponibili»: prima del livello il rifiuto è per
|
||||
il livello e dice che si sbloccheranno lì, dopo resta «non ancora disponibili»). Il fido insufficiente dice quanto resta su quanto e quale livello alza il
|
||||
fido e a quanto.
|
||||
6. **Stato patrimoniale per voce, una sola fonte.** `FinanceSystem.BookValues` calcola il valore contabile
|
||||
per compagnia e per voce (`AssetCategory`: binari e opere, stazioni e depositi, veicoli, industrie
|
||||
possedute, merce propria); `UpdateBookValues` (ogni mese, come prima) le scrive in `Company.BookValues`
|
||||
e `AssetBookValue` ne è la somma. Il patrimonio netto del motore resta cassa + attivi + partecipazioni −
|
||||
debiti; il pannello lo scompone in attivi per voce, partecipazioni, cassa positiva, prestiti (con il
|
||||
tasso medio pesato sul residuo) e scoperto di cassa (la cassa negativa), e la somma coincide al
|
||||
centesimo con `Company.NetWorth`.
|
||||
7. **Industrie possedute nel patrimonio.** Finora comprare un'industria toglieva il prezzo dalla cassa
|
||||
senza aggiungere nulla agli attivi. Ora entrano al valore contabile `IndustryMath.BookValue`: la parte
|
||||
del prezzo d'acquisto (ADR 0011 §5) senza l'avviamento, cioè impianti (`PlantValue`: costo
|
||||
d'ammodernamento × livello × quota, secondo le condizioni) più la cassa dell'impresa. Gli impianti
|
||||
contano al livello attuale: un'industria inattiva (livello 0), che non si può vendere, vale solo la sua
|
||||
cassa (il prezzo d'acquisto conta invece almeno un livello, come prima). Comprare costa
|
||||
quindi al patrimonio solo l'avviamento (il multiplo degli utili), e il rating e il prezzo dell'azione
|
||||
vedono gli impianti. Il prezzo di vendita (`Valuation`) non cambia.
|
||||
8. **Salvataggio versione 6.** Le voci non si possono ricostruire al caricamento (dipendono dal giorno del
|
||||
calcolo mensile e da attivi venduti o demoliti dopo), quindi il corpo versione 6
|
||||
(`BalanceSheetSerializer`, in coda allo stato dinamico e nell'hash) salva per ogni compagnia le voci e il
|
||||
giorno in cui ogni livello è stato raggiunto (`Company.TierReachedDay`, annotato da `Tiers.Evaluate`;
|
||||
il livello 1 vale dalla fondazione). Le versioni 1–5 salvano solo il totale: la migrazione lo ripartisce
|
||||
in proporzione alle voci calcolate al giorno del caricamento (resto dell'arrotondamento sulla voce più
|
||||
grande, tutto sui binari se non c'è nulla da ripartire), quindi il patrimonio netto non cambia fino al
|
||||
ricalcolo del mese; i giorni dei livelli si ricostruiscono dai fatti salienti («diventa «nome»») o, in
|
||||
mancanza, dalla prima fotografia dello storico con quel livello: quella dell'anno Y si scatta il primo
|
||||
giorno di Y+1, dopo la chiusura del mese che può aver promosso la compagnia, quindi si usa quel giorno
|
||||
(tra la fondazione e oggi).
|
||||
9. **Storico del patrimonio.** Nessuno stato nuovo: si riusa lo storico annuale della Cronaca
|
||||
(`Company.History`, fotografia di fine anno al primo giorno dell'anno dopo), preceduto dal capitale
|
||||
iniziale della difficoltà alla fondazione e seguito dal valore di oggi, che prende il posto della
|
||||
fotografia del primo giorno dell'anno in corso: un punto per anno di calendario, etichettato con il suo
|
||||
anno. I livelli raggiunti si segnano sul punto dell'anno della promozione, anche sull'ultimo (oggi).
|
||||
10. **Conto economico.** L'ultimo anno chiuso (o l'anno in corso fino a oggi, per una compagnia fondata
|
||||
quest'anno), con le voci del registro raggruppate in tariffe e noli, altri ricavi (commercio, contratti,
|
||||
industrie, controllate), costi operativi (esercizio, salari, penali), manutenzione (binari e flotta) e
|
||||
interessi: le righe sommano esattamente a `Company.OperatingProfit` («Utile netto» nel pannello).
|
||||
11. **Prestiti dal pannello.** «Chiedi un prestito» e «Rimborsa» mandano i comandi esistenti (`TakeLoan`,
|
||||
`RepayLoan`); il pannello rimborsa per primo il prestito con il tasso più alto (scelta dell'interfaccia:
|
||||
il server limita comunque l'importo al residuo e alla cassa).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le compagnie che possiedono industrie (giocatore dal livello 3, IA dal livello 3) hanno un patrimonio
|
||||
netto più alto di prima: salgono di livello un po' prima e il loro titolo vale di più. Le soglie restano
|
||||
provvisorie fino al bilanciamento della F6.
|
||||
- Il quadro della scalata costa poco (cinque livelli, una scansione di stazioni e treni per le città
|
||||
collegate) e si calcola solo su richiesta.
|
||||
- Il salvataggio cresce di 10 numeri per compagnia; l'hash giornaliero include le voci e i giorni dei
|
||||
livelli.
|
||||
@@ -0,0 +1,144 @@
|
||||
# ADR 0019 — Finanza completa: prestiti per rating, conto economico per voce, bancarotta (F6)
|
||||
|
||||
Stato: accettato (F6, issue #39).
|
||||
|
||||
## Contesto
|
||||
|
||||
La guida (§6.3) chiede cassa, prestiti con tasso = base + spread per rating, manutenzione, stipendi,
|
||||
interessi; rating da utile/ricavi e debito/patrimonio; bancarotta con la cassa sotto zero per i giorni
|
||||
previsti dalla difficoltà; patrimonio netto = attivo a valore di libro − debiti. Prima di scrivere codice
|
||||
si è confrontato il motore con la guida.
|
||||
|
||||
### Analisi delle lacune
|
||||
|
||||
C'era già, e resta com'era:
|
||||
|
||||
- `TakeLoan` / `RepayLoan`: tasso = `baseInterestRate` della difficoltà + `ratingSpreads[rating]`
|
||||
(`balance.json`), fissato all'accensione; fido = fido iniziale × `maxLoanFactor` del livello
|
||||
(`tiers.json`, ADR 0011 §6); rate mensili alla francese su `loanTermMonths` con interessi e quota
|
||||
capitale sul registro (`Interest`, `LoanRepaid`); rimborso parziale e totale limitato al residuo.
|
||||
- Rating ricalcolato ogni mese da un punteggio pesato (`profitMarginWeight`, `leverageWeight`) con le
|
||||
soglie `ratingByScore`; D in bancarotta.
|
||||
- Bancarotta dopo `Difficulty.BankruptcyDays` giorni di fila con la cassa negativa: il numero viene da
|
||||
`difficulty.json` (180 / 90 / 60 / 30) e si può sovrascrivere nelle impostazioni della partita; gli
|
||||
esiti per il giocatore e per le IA sono quelli dell'ADR 0012 (`StockMarketSystem.HandleBankruptcies`,
|
||||
`PlayerInsolvency`).
|
||||
- Patrimonio netto = attivo a valore di libro (ADR 0018) + partecipazioni + cassa − prestiti.
|
||||
- Manutenzione dei binari e della flotta sulle loro voci.
|
||||
|
||||
Mancava o era sbagliato:
|
||||
|
||||
1. il rating usava l'anno in corso (o l'anno chiuso nei primi mesi), non una finestra mobile, e la leva
|
||||
era debiti / attivo invece di debiti / patrimonio; le misure non restavano da nessuna parte, quindi il
|
||||
client non poteva spiegare il rating;
|
||||
2. le compagnie non pagavano stipendi: la voce `Wages` la usavano solo le industrie, e il personale dei
|
||||
depositi (tecnici e operai, ADR 0009) lavorava gratis;
|
||||
3. `RunningCosts` mescolava l'esercizio dei treni con quello di stazioni e depositi; giacenze dei
|
||||
magazzini e dazi degli hub erano dentro `Trading`; i dividendi incassati da un'altra compagnia finivano
|
||||
su `Dividends`, la voce dei dividendi pagati, fuori dall'utile;
|
||||
4. il conto economico esisteva solo come anno in corso e ultimo anno chiuso, senza mesi né storico;
|
||||
5. nessun avviso prima della bancarotta: solo la notizia finale;
|
||||
6. nessun quadro delle finanze nel protocollo; il pannello del client mostrava cassa, patrimonio, rating
|
||||
e un campo per chiedere un prestito;
|
||||
7. i messaggi dei prestiti erano asciutti («Cassa insufficiente») e la percentuale usava il punto.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Tasso fisso.** Il tasso di un prestito resta quello dell'accensione: base della difficoltà + spread
|
||||
del rating di quel giorno. Un tasso variabile renderebbe la rata imprevedibile e farebbe di ogni
|
||||
declassamento una spirale (rating giù → rate su → utile giù → rating giù) proprio quando la compagnia è
|
||||
in difficoltà; con il tasso fisso il rating decide il prezzo del debito *nuovo*, che è l'incentivo
|
||||
che la guida chiede, e la rata mostrata al momento della richiesta resta quella. Rimborsare in anticipo
|
||||
è sempre possibile e senza penale: chi ha migliorato il rating può estinguere e richiedere.
|
||||
Il rimborso parziale lascia la durata invariata e ricalcola la rata.
|
||||
2. **Rating spiegabile.** Ogni mese, dopo il pagamento delle rate e la chiusura del mese:
|
||||
- *margine* = utile operativo / ricavi sugli ultimi 12 mesi chiusi (`finance.incomeMonths`; meno se la
|
||||
compagnia è più giovane), con i ricavi = tariffe e noli più le altre voci di ricavo solo se positive.
|
||||
Finché la finestra non è piena e ha meno di `finance.ratingMinRevenueMonths` (3) mesi con ricavi il
|
||||
margine è neutro (0): senza questa soglia i mesi d'avvio con soli costi davano margine 0 e il primo
|
||||
incasso, piccolo rispetto a quei costi, faceva perdere tre o quattro gradini per un mese, proprio
|
||||
quando un prestito nuovo avrebbe fissato lo spread peggiore per dieci anni. Con la finestra piena (o
|
||||
con abbastanza mesi di ricavi) conta il margine vero; senza ricavi e in perdita il margine è il minimo
|
||||
(−100 %, componente nulla);
|
||||
- *leva* = debiti / patrimonio netto, con debiti = prestiti + scoperto di cassa; 0 senza debiti, infinita
|
||||
con patrimonio non positivo;
|
||||
- punteggio = `profitMarginWeight` × clamp(0,5 + margine, 0, 1) + `leverageWeight` × 1 / (1 + leva)
|
||||
(0 con leva infinita); rating = primo gradino di `ratingByScore` non superiore al punteggio, D sotto
|
||||
l'ultimo o in bancarotta.
|
||||
|
||||
Il motore conserva margine, leva, punteggio e mesi della finestra (`Company.RatingMargin`,
|
||||
`RatingLeverage`, `RatingScore`, `RatingMonths`). `FinanceOutlook.Explain` ne ricava, senza scrivere
|
||||
nulla, le componenti, le soglie con il tasso di un nuovo prestito per ogni rating, il gradino sopra, il
|
||||
margine che basterebbe da solo a raggiungerlo, la leva massima e il debito da rimborsare per arrivarci
|
||||
(a patrimonio invariato) con l'indicazione se quel rimborso è possibile oggi: si rimborsa con la cassa,
|
||||
quindi non oltre la cassa positiva né il residuo dei prestiti, e lo scoperto non si rimborsa. Se il
|
||||
punteggio raggiunge già il gradino sopra (rating iniziale dei dati, o D rimasto da una bancarotta
|
||||
risolta fino al calcolo successivo) la spiegazione lo dice («vale già A, si aggiorna a inizio mese»)
|
||||
senza obiettivi già raggiunti e senza leve infinite sul filo. Il client legge «BBB perché…, per il
|
||||
gradino A serve…» senza calcolare nulla.
|
||||
Prima del primo calcolo mensile (partita nuova o salvataggio migrato) il rating è quello iniziale dei
|
||||
dati e la spiegazione usa le misure del giorno.
|
||||
3. **Voci nuove del registro.** `StationUpkeep` (21, esercizio di binari di stazione e depositi, separato
|
||||
da `RunningCosts` che resta ai treni), `Storage` (22, giacenze dei magazzini), `Duties` (23, dazi degli
|
||||
hub: all'importazione la quota dazio del prezzo pagato, all'esportazione l'incasso al lordo e il dazio a
|
||||
parte, con lo stesso netto di prima), `DividendsReceived` (24, dividendi incassati da un'altra
|
||||
compagnia). `Ledger.Transfer` accetta voci diverse per chi paga e chi incassa. Il valore numerico delle
|
||||
voci esistenti non cambia, quindi i salvataggi restano leggibili.
|
||||
4. **Stipendi del personale dei depositi.** Ogni giorno la compagnia paga a tecnici e operai *presenti* nei
|
||||
suoi depositi le stesse paghe delle industrie (`industry.wagePerStaffPerMonth`, `wagePerWorkerPerMonth`)
|
||||
divise per i giorni del mese, sulla voce `Wages`. Nessun parametro nuovo: il mercato del lavoro è uno
|
||||
solo (ADR 0009). I posti scoperti non costano.
|
||||
5. **Utile operativo.** Ricavi: noli merci, biglietti, commercio in proprio, contratti, industrie
|
||||
possedute, controllate, dividendi incassati. Costi: esercizio dei treni, stazioni e depositi,
|
||||
manutenzione dei treni e dei binari, stipendi, interessi, dazi, magazzini, penali. Fuori dall'utile
|
||||
(investimenti e finanziamenti): costruzioni, acquisto e vendita di treni, acquisto di industrie,
|
||||
prestiti ricevuti e rimborsati, azioni, dividendi pagati, altro. I dividendi incassati ora entrano
|
||||
nell'utile (sono un reddito della compagnia), quelli pagati restano fuori. `LedgerEntries` (Core) fissa
|
||||
ordine e sezioni; `Company.OperatingProfit` ne è la somma, usata da rating, borsa, scalata e pannello.
|
||||
La quota dei trasporti che fa entrare un nuovo concorrente (12.1) usa invece `Company.TransportRevenue`
|
||||
(tariffe, noli e contratti): dividendi incassati, commercio in proprio, industrie e controllate non
|
||||
sono trasporto e non devono far sembrare una compagnia dominante.
|
||||
6. **Conto economico per voce.** A ogni chiusura di mese il registro del mese entra in
|
||||
`Company.IncomeMonths` (ultimi `finance.incomeMonths` = 12), a ogni chiusura d'anno quello dell'anno in
|
||||
`Company.IncomeYears` (ultimi `finance.incomeYears` = 10). Il quadro (`FinanceOutlook`) mostra il mese in
|
||||
corso, i mesi chiusi, l'anno in corso e gli anni chiusi, ogni colonna con l'utile operativo e il flusso
|
||||
di cassa del motore: le righe sommano al centesimo all'utile perché sono le stesse voci del registro.
|
||||
7. **Avvisi di bancarotta.** Dopo `finance.negativeCashNoticeDays` (3) giorni di fila di cassa negativa
|
||||
una notizia (avviso) dice lo scoperto e i giorni al limite della difficoltà; poi una notizia a 30, 14,
|
||||
7, 3 e 1 giorno dal limite (`finance.bankruptcyWarningDaysLeft`, l'ultima critica); se la cassa torna
|
||||
positiva dopo almeno quei giorni una notizia dice che il conto alla rovescia si azzera; al limite la
|
||||
notizia della bancarotta. Una cassa che oscilla intorno a zero (costi giornalieri contro incassi) azzera
|
||||
il conto ogni volta senza riempire le notizie. Il pannello mostra il conto alla rovescia solo con la
|
||||
cassa davvero negativa: dopo un prestito che la riporta sopra zero dice che il conto si azzera domani
|
||||
(il motore conta i giorni una volta al giorno). L'esito resta quello dell'ADR 0012.
|
||||
8. **Salvataggio versione 7.** `FinanceSerializer` in coda allo stato dinamico, nell'hash: mesi e anni
|
||||
chiusi (voci allungate a zero se in futuro se ne aggiungono) e misure del rating. Le versioni 1–6 si
|
||||
caricano con zero mesi chiusi (la finestra si riempie dal mese dopo), l'ultimo anno chiuso ricavato dal
|
||||
registro come primo anno dello storico e `RatingMonths` = 0; il rating salvato resta.
|
||||
9. **Protocollo e client.** `DetailKind.Finance` (9) e `FinanceReport` (135) su richiesta; il pannello
|
||||
«Finanze» diventa a tutto schermo: conto economico per voce con «Mesi» (mese in corso, cinque mesi
|
||||
chiusi, anno in corso) e «Anni» (anno in corso, cinque anni chiusi), rating con misure, componenti,
|
||||
soglie e «per salire…», prestiti con rata, interessi, scadenza, «Rimborsa» ed «Estingui», richiesta con
|
||||
il fido e il tasso, barra rossa dei giorni di cassa negativa sul limite.
|
||||
10. **Messaggi.** Accensione: «Prestito di X al 6,0% fisso (base … + rating BB …) per 10 anni: rata mensile
|
||||
Y»; rimborso: «Rimborsati X: restano R, nuova rata mensile P» o «… prestito estinto»; rifiuto: «Cassa
|
||||
insufficiente: per rimborsare X ci sono Y in cassa». Percentuali con la virgola.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le compagnie con depositi pagano gli stipendi e hanno utili un po' più bassi; il rating guarda fino a
|
||||
12 mesi e la leva sul patrimonio. Nei primi mesi il margine non conta finché non ci sono tre mesi con
|
||||
ricavi, quindi all'avvio il rating dipende dalla leva; da lì in poi la finestra cresce mese per mese e il
|
||||
rating si muove più dei mesi successivi, quando la finestra è piena. Le IA usano gli
|
||||
stessi prestiti e lo stesso rating (nessun cambiamento nel loro codice); le soglie restano provvisorie
|
||||
fino al bilanciamento della F6.
|
||||
- Il salvataggio cresce di circa 22 mesi × 25 voci per compagnia; l'hash giornaliero li include.
|
||||
- Il quadro delle finanze si calcola solo su richiesta.
|
||||
|
||||
## Limiti
|
||||
|
||||
- Niente ammortamento a conto economico: il valore di libro scende (ADR 0018) ma la perdita di valore non
|
||||
è una voce dell'utile. Niente imposte.
|
||||
- Il tasso non dipende dalla durata e la durata è una sola (`loanTermMonths`).
|
||||
- I mesi chiusi prima della versione 7 non si recuperano: dopo una migrazione il rating usa la finestra
|
||||
dal primo mese chiuso dopo il caricamento.
|
||||
@@ -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.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 239 KiB |
@@ -390,6 +390,25 @@ public sealed class FinanceBalance
|
||||
public required CreditRating StartingRating { get; init; }
|
||||
public required int DepreciationYearsTrack { get; init; }
|
||||
public required double BookValueFloor { get; init; }
|
||||
/// <summary>Mesi chiusi conservati per voce: conto economico mensile e finestra del rating (ADR 0019).</summary>
|
||||
public required int IncomeMonths { get; init; }
|
||||
/// <summary>Anni chiusi conservati per voce nel conto economico annuale (ADR 0019).</summary>
|
||||
public required int IncomeYears { get; init; }
|
||||
/// <summary>
|
||||
/// Giorni mancanti alla bancarotta in cui la compagnia riceve un avviso, in ordine decrescente
|
||||
/// (oltre al primo avviso dopo <see cref="NegativeCashNoticeDays"/> giorni, ADR 0019).
|
||||
/// </summary>
|
||||
public required int[] BankruptcyWarningDaysLeft { get; init; }
|
||||
/// <summary>
|
||||
/// Mesi chiusi con ricavi che servono, finché la finestra del rating non è piena, perché il margine
|
||||
/// conti: prima il margine è neutro (0), così i primi incassi non fanno crollare il rating (ADR 0019).
|
||||
/// </summary>
|
||||
public required int RatingMinRevenueMonths { get; init; }
|
||||
/// <summary>
|
||||
/// Giorni di cassa negativa di fila prima del primo avviso; il rientro si annuncia solo dopo almeno
|
||||
/// altrettanti giorni, così una cassa che oscilla intorno a zero non riempie le notizie (ADR 0019).
|
||||
/// </summary>
|
||||
public required int NegativeCashNoticeDays { get; init; }
|
||||
}
|
||||
|
||||
public sealed class StockMarketBalance
|
||||
|
||||
@@ -136,6 +136,22 @@ public static class DataValidator
|
||||
if (!levels.SequenceEqual(Enumerable.Range(1, levels.Count))) Err("tiers.json", "i livelli devono essere 1, 2, 3, 4, 5 in ordine");
|
||||
Increasing("tiers.json", "requirements.netWorth", d.Tiers.Tiers.Select(t => (double)t.Requirements.NetWorth), errors, strictFromSecond: true);
|
||||
if (!d.Tiers.RatingScale.SequenceEqual(Enum.GetValues<CreditRating>())) Err("tiers.json", "ratingScale deve elencare i rating da AAA a D");
|
||||
if (!(d.Tiers.RatingProgressSteps > 0)) Err("tiers.json", "ratingProgressSteps deve essere positivo");
|
||||
// gli sblocchi restano acquisiti salendo (ADR 0011): notizie, rifiuti e pannello lo presumono (ADR 0018)
|
||||
var unlocks = d.Tiers.Tiers.Select(t => t.Unlocks).ToList();
|
||||
for (int i = 1; i < unlocks.Count; i++)
|
||||
{
|
||||
var (prev, cur) = (unlocks[i - 1], unlocks[i]);
|
||||
if (cur.MaxLoanFactor < prev.MaxLoanFactor) Err("tiers.json", $"unlocks.maxLoanFactor non può scendere dal livello {i} al livello {i + 1}");
|
||||
foreach (var (name, had, has) in new[]
|
||||
{
|
||||
("trading", prev.Trading, cur.Trading), ("buyIndustry", prev.BuyIndustry, cur.BuyIndustry), ("ipo", prev.Ipo, cur.Ipo),
|
||||
("hostileTakeover", prev.HostileTakeover, cur.HostileTakeover), ("concessions", prev.Concessions, cur.Concessions),
|
||||
})
|
||||
{
|
||||
if (had && !has) Err("tiers.json", $"unlocks.{name} non può tornare falso dal livello {i} al livello {i + 1}");
|
||||
}
|
||||
}
|
||||
|
||||
// --- difficoltà
|
||||
Unique("difficulty.json", d.Difficulty.Presets.Select(p => p.Id), errors);
|
||||
@@ -174,6 +190,18 @@ public static class DataValidator
|
||||
RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames<CreditRating>(), errors);
|
||||
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
|
||||
Increasing("balance.json", "finance.ratingByScore (decrescente)", Enumerable.Reverse(b.Finance.RatingByScore), errors);
|
||||
if (b.Finance.IncomeMonths < 1 || b.Finance.IncomeMonths > 120) Err("balance.json", "finance.incomeMonths deve stare tra 1 e 120");
|
||||
if (b.Finance.IncomeYears < 1 || b.Finance.IncomeYears > 100) Err("balance.json", "finance.incomeYears deve stare tra 1 e 100");
|
||||
if (b.Finance.RatingMinRevenueMonths < 1 || b.Finance.RatingMinRevenueMonths > b.Finance.IncomeMonths)
|
||||
Err("balance.json", "finance.ratingMinRevenueMonths deve stare tra 1 e finance.incomeMonths");
|
||||
if (b.Finance.NegativeCashNoticeDays < 1) Err("balance.json", "finance.negativeCashNoticeDays deve essere almeno 1");
|
||||
if (b.Finance.ProfitMarginWeight <= 0 || b.Finance.LeverageWeight <= 0) Err("balance.json", "finance.profitMarginWeight e finance.leverageWeight devono essere positivi");
|
||||
for (int i = 0; i < b.Finance.BankruptcyWarningDaysLeft.Length; i++)
|
||||
{
|
||||
if (b.Finance.BankruptcyWarningDaysLeft[i] < 1) Err("balance.json", "finance.bankruptcyWarningDaysLeft: i giorni devono essere almeno 1");
|
||||
if (i > 0 && b.Finance.BankruptcyWarningDaysLeft[i] >= b.Finance.BankruptcyWarningDaysLeft[i - 1])
|
||||
Err("balance.json", "finance.bankruptcyWarningDaysLeft deve essere strettamente decrescente");
|
||||
}
|
||||
RequireKeys("balance.json", "industryMaintenance.budgets", b.IndustryMaintenance.Budgets.Keys, ["none", "base", "high"], errors);
|
||||
if (b.IndustryMaintenance.BreakdownDays.Length != 2) Err("balance.json", "industryMaintenance.breakdownDays deve essere [min, max]");
|
||||
if (b.Growth.MaxLevel > 5 || b.Growth.MaxLevel < 1) Err("balance.json", "growth.maxLevel deve stare tra 1 e 5");
|
||||
@@ -191,6 +219,10 @@ public static class DataValidator
|
||||
}
|
||||
RequireKeys("construction.json", "crews.metersPerDay", c.Crews.MetersPerDay.Keys, WorkKeys, errors);
|
||||
if (c.Crews.CrewsByTier.Length != 5) Err("construction.json", "crews.crewsByTier deve avere 5 valori");
|
||||
// le squadre per livello stanno in due file: il cantiere usa construction.json, il pannello della scalata
|
||||
// le mostra tra gli sblocchi; devono coincidere (ADR 0018)
|
||||
else if (!d.Tiers.Tiers.Select(t => t.Unlocks.Crews).SequenceEqual(c.Crews.CrewsByTier))
|
||||
Err("tiers.json", "unlocks.crews deve coincidere con crews.crewsByTier di construction.json");
|
||||
RequireKeys("construction.json", "costs.depotBySize", c.Costs.DepotBySize.Keys, SizeKeys, errors);
|
||||
foreach (string k in c.Costs.TerrainModifiers.Keys)
|
||||
{
|
||||
|
||||
@@ -8,6 +8,11 @@ public sealed class TiersFile
|
||||
[JsonPropertyName("$schema")] public string? Schema { get; init; }
|
||||
public required int Version { get; init; }
|
||||
public required List<CreditRating> RatingScale { get; init; }
|
||||
/// <summary>
|
||||
/// Gradini di rating sotto quello richiesto a cui l'avanzamento del requisito vale zero (ADR 0018):
|
||||
/// la frazione è 1 − gradini mancanti / questo valore, limitata tra 0 e 1.
|
||||
/// </summary>
|
||||
public required double RatingProgressSteps { get; init; }
|
||||
public required List<TierDef> Tiers { get; init; }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Requisiti di un livello per una compagnia: per ciascuno il valore attuale, la soglia, se è
|
||||
/// soddisfatto e la frazione raggiunta (0–1), più l'avanzamento complessivo (media delle tre frazioni).
|
||||
/// </summary>
|
||||
public sealed class RequirementProgress
|
||||
{
|
||||
public required int Level { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
public required Money NetWorthRequired { get; init; }
|
||||
public required double NetWorthFraction { get; init; }
|
||||
public required bool NetWorthMet { get; init; }
|
||||
public required int Towns { get; init; }
|
||||
public required int TownsRequired { get; init; }
|
||||
public required int TownPopulation { get; init; }
|
||||
public required double TownsFraction { get; init; }
|
||||
public required bool TownsMet { get; init; }
|
||||
public required CreditRating Rating { get; init; }
|
||||
public required CreditRating RatingRequired { get; init; }
|
||||
public required double RatingFraction { get; init; }
|
||||
public required bool RatingMet { get; init; }
|
||||
/// <summary>Media delle frazioni dei tre requisiti: 1 solo quando sono tutti soddisfatti.</summary>
|
||||
public required double Progress { get; init; }
|
||||
public bool AllMet => NetWorthMet && TownsMet && RatingMet;
|
||||
}
|
||||
|
||||
/// <summary>Un livello di tiers.json visto dalla compagnia: requisiti, se e quando è stato raggiunto, sblocchi.</summary>
|
||||
public sealed class TierOutlook
|
||||
{
|
||||
public required int Level { get; init; }
|
||||
public required string NameIt { get; init; }
|
||||
public required string NameEn { get; init; }
|
||||
public required TierRequirements Requirements { get; init; }
|
||||
public required bool Reached { get; init; }
|
||||
/// <summary>Giorno in cui è stato raggiunto (fondazione per il livello 1; −1 se non raggiunto o sconosciuto).</summary>
|
||||
public required long ReachedDay { get; init; }
|
||||
/// <summary>Sblocchi che il livello aggiunge al precedente (<see cref="Tiers.NewUnlocks"/>).</summary>
|
||||
public required List<TierUnlock> Unlocks { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Voce degli attivi non monetari dello stato patrimoniale.</summary>
|
||||
public readonly record struct AssetLine(AssetCategory Category, Money Value);
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale della compagnia: attivi per voce (dal valore contabile del motore),
|
||||
/// partecipazioni, cassa; debiti (prestiti e scoperto di cassa). Il patrimonio netto è quello del
|
||||
/// motore (<see cref="Company.NetWorth"/>): Totale attivo − Totale debiti.
|
||||
/// </summary>
|
||||
public sealed class BalanceSheet
|
||||
{
|
||||
public required List<AssetLine> Assets { get; init; }
|
||||
/// <summary>Azioni di altre compagnie al prezzo di mercato.</summary>
|
||||
public required Money Portfolio { get; init; }
|
||||
/// <summary>Cassa positiva (lo scoperto va tra i debiti).</summary>
|
||||
public required Money Cash { get; init; }
|
||||
public required Money TotalAssets { get; init; }
|
||||
public required Money Loans { get; init; }
|
||||
/// <summary>Tasso medio dei prestiti pesato sul residuo (0 senza prestiti).</summary>
|
||||
public required double LoansRate { get; init; }
|
||||
/// <summary>Scoperto di cassa (cassa negativa), tra gli altri debiti.</summary>
|
||||
public required Money Overdraft { get; init; }
|
||||
public required Money TotalLiabilities { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Righe del conto economico del pannello: raggruppano le voci del registro.</summary>
|
||||
public enum IncomeLineKind : byte
|
||||
{
|
||||
/// <summary>Tariffe passeggeri e noli merci.</summary>
|
||||
Fares = 0,
|
||||
/// <summary>Commercio in proprio, contratti, industrie possedute, controllate, dividendi incassati.</summary>
|
||||
OtherIncome = 1,
|
||||
/// <summary>Costi d'esercizio (treni, stazioni e depositi), salari, penali, dazi, magazzini.</summary>
|
||||
OperatingCosts = 2,
|
||||
/// <summary>Manutenzione dei binari e della flotta.</summary>
|
||||
Maintenance = 3,
|
||||
Interest = 4,
|
||||
}
|
||||
|
||||
public readonly record struct IncomeLine(IncomeLineKind Kind, Money Value);
|
||||
|
||||
/// <summary>Conto economico di un anno (le righe sommano esattamente all'utile operativo del motore).</summary>
|
||||
public sealed class IncomeStatement
|
||||
{
|
||||
public required int Year { get; init; }
|
||||
/// <summary>Anno in corso (fino a oggi) invece dell'ultimo anno chiuso.</summary>
|
||||
public required bool Partial { get; init; }
|
||||
public required List<IncomeLine> Lines { get; init; }
|
||||
public required Money Profit { get; init; }
|
||||
}
|
||||
|
||||
public readonly record struct LoanOutlook(LoanId Id, Money Remaining, double AnnualRate, int MonthsLeft);
|
||||
|
||||
/// <summary>Patrimonio netto a un giorno della partita.</summary>
|
||||
public readonly record struct NetWorthPoint(long Day, Money Value);
|
||||
|
||||
public sealed class ClimbOutlookReport
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
public required CompanyId Company { get; init; }
|
||||
public required long FoundedDay { get; init; }
|
||||
/// <summary>Capitale iniziale della difficoltà (quello del giocatore).</summary>
|
||||
public required Money InitialCapital { get; init; }
|
||||
public required int Tier { get; init; }
|
||||
/// <summary>Livello successivo (0 all'ultimo livello).</summary>
|
||||
public required int NextTier { get; init; }
|
||||
public required List<TierOutlook> Tiers { get; init; }
|
||||
/// <summary>Requisiti del livello successivo (null all'ultimo livello).</summary>
|
||||
public required RequirementProgress? Next { get; init; }
|
||||
public required BalanceSheet Balance { get; init; }
|
||||
public required IncomeStatement Income { get; init; }
|
||||
public required List<LoanOutlook> Loans { get; init; }
|
||||
public required Money MaxLoan { get; init; }
|
||||
public required Money LoanAvailable { get; init; }
|
||||
public required double NewLoanRate { get; init; }
|
||||
/// <summary>In bancarotta o in amministrazione controllata i prestiti non si possono chiedere (come in <see cref="FinanceOutlook"/>).</summary>
|
||||
public required bool LoansAllowed { get; init; }
|
||||
/// <summary>Patrimonio netto: fondazione, fine di ogni anno dello storico, oggi.</summary>
|
||||
public required List<NetWorthPoint> History { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro della scalata per il pannello «La tua scalata» (ADR 0018): pura funzione del mondo, come
|
||||
/// <see cref="MarketOutlook"/>. Livelli e sblocchi da tiers.json, requisiti del prossimo livello con
|
||||
/// l'avanzamento, stato patrimoniale dalle voci del valore contabile del motore, conto economico
|
||||
/// dell'ultimo anno, prestiti e storico del patrimonio netto (lo storico annuale della Cronaca).
|
||||
/// </summary>
|
||||
public static class ClimbOutlook
|
||||
{
|
||||
public static ClimbOutlookReport Build(World w, CompanyId company)
|
||||
{
|
||||
var c = w.Company(company);
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
var list = new List<TierOutlook>(tiers.Count);
|
||||
foreach (var t in tiers)
|
||||
{
|
||||
list.Add(new TierOutlook
|
||||
{
|
||||
Level = t.Level, NameIt = t.NameIt, NameEn = t.NameEn, Requirements = t.Requirements,
|
||||
Reached = c.Tier >= t.Level,
|
||||
ReachedDay = t.Level <= 1 ? c.FoundedDay : c.Tier >= t.Level ? c.TierReachedDay[Math.Min(t.Level, c.TierReachedDay.Length) - 1] : -1,
|
||||
Unlocks = Simulation.Systems.Tiers.NewUnlocks(w, c, t.Level),
|
||||
});
|
||||
}
|
||||
var max = FinanceSystem.MaxLoan(w, c);
|
||||
return new ClimbOutlookReport
|
||||
{
|
||||
Day = w.Clock.Day,
|
||||
Company = c.Id,
|
||||
FoundedDay = c.FoundedDay,
|
||||
InitialCapital = new Money(w.Difficulty.InitialCapital),
|
||||
Tier = c.Tier,
|
||||
NextTier = c.Tier < tiers.Count ? tiers[c.Tier].Level : 0,
|
||||
Tiers = list,
|
||||
Next = c.Tier < tiers.Count ? Requirements(w, c, tiers[c.Tier]) : null,
|
||||
Balance = Balance(c),
|
||||
Income = Income(w, c),
|
||||
Loans = c.Loans.Select(l => new LoanOutlook(l.Id, l.Remaining, l.AnnualRate, l.MonthsLeft)).ToList(),
|
||||
MaxLoan = max,
|
||||
LoanAvailable = Money.Max(Money.Zero, max - c.Debt),
|
||||
NewLoanRate = FinanceSystem.LoanRate(w, c),
|
||||
LoansAllowed = !c.Receivership && !c.Bankrupt,
|
||||
History = History(w, c),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requisiti di un livello per la compagnia, con gli stessi confronti di <see cref="Simulation.Systems.Tiers.Meets"/>.
|
||||
/// Frazioni: patrimonio / soglia e città / città richieste (limitate a 1; 1 se la soglia è zero); per il
|
||||
/// rating 1 − gradini mancanti / <see cref="TiersFile.RatingProgressSteps"/> (limitata tra 0 e 1).
|
||||
/// L'avanzamento è la loro media, sotto 1 finché un requisito manca (<see cref="ProgressCap"/>).
|
||||
/// </summary>
|
||||
public static RequirementProgress Requirements(World w, Company c, TierDef tier)
|
||||
{
|
||||
var req = tier.Requirements;
|
||||
int towns = Simulation.Systems.Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
|
||||
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
|
||||
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
|
||||
double rating = RatingFraction(w, c.Rating, req.CreditRating);
|
||||
bool worthMet = c.NetWorth.Cents >= req.NetWorth, townsMet = towns >= req.ConnectedTownsOver.Count, ratingMet = c.Rating <= req.CreditRating;
|
||||
double progress = (worth + townsFraction + rating) / 3;
|
||||
if (!(worthMet && townsMet && ratingMet)) progress = Math.Min(progress, ProgressCap);
|
||||
return new RequirementProgress
|
||||
{
|
||||
Level = tier.Level,
|
||||
NetWorth = c.NetWorth, NetWorthRequired = new Money(req.NetWorth), NetWorthFraction = worth, NetWorthMet = worthMet,
|
||||
Towns = towns, TownsRequired = req.ConnectedTownsOver.Count, TownPopulation = req.ConnectedTownsOver.Population,
|
||||
TownsFraction = townsFraction, TownsMet = townsMet,
|
||||
Rating = c.Rating, RatingRequired = req.CreditRating, RatingFraction = rating, RatingMet = ratingMet,
|
||||
Progress = progress,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tetto dell'avanzamento finché un requisito manca: una frazione arrotondata a 1 non basta, il pieno
|
||||
/// arriva solo con tutti i requisiti soddisfatti. Non è un parametro di gioco (non cambia la promozione,
|
||||
/// che segue <see cref="Simulation.Systems.Tiers.Meets"/>): il client mostra le percentuali per difetto,
|
||||
/// quindi sotto il tetto legge al massimo «99%».
|
||||
/// </summary>
|
||||
public const double ProgressCap = 0.999;
|
||||
|
||||
/// <summary>
|
||||
/// Frazione del requisito di rating: 1 se soddisfatto, altrimenti 1 − gradini mancanti /
|
||||
/// ratingProgressSteps di tiers.json, limitata tra 0 e 1 (immagine 08: un gradino sotto vale il 60 %).
|
||||
/// </summary>
|
||||
public static double RatingFraction(World w, CreditRating current, CreditRating required)
|
||||
{
|
||||
if (current <= required) return 1;
|
||||
int missing = (int)current - (int)required;
|
||||
return DMath.Clamp(1 - missing / w.Data.Tiers.RatingProgressSteps, 0, 1);
|
||||
}
|
||||
|
||||
/// <summary>Stato patrimoniale dalle voci del motore: somma esattamente al patrimonio netto.</summary>
|
||||
public static BalanceSheet Balance(Company c)
|
||||
{
|
||||
var assets = new List<AssetLine>(AssetCategories.Count);
|
||||
for (int k = 0; k < AssetCategories.Count; k++) assets.Add(new AssetLine((AssetCategory)k, new Money(c.BookValues[k])));
|
||||
var cash = Money.Max(Money.Zero, c.Cash);
|
||||
var overdraft = Money.Max(Money.Zero, -c.Cash);
|
||||
var total = c.AssetBookValue + c.PortfolioValue + cash;
|
||||
var loans = c.Debt;
|
||||
double rate = 0;
|
||||
if (loans.Cents > 0)
|
||||
{
|
||||
double weighted = 0;
|
||||
foreach (var l in c.Loans) weighted += (double)l.Remaining.Cents * l.AnnualRate;
|
||||
rate = weighted / loans.Cents;
|
||||
}
|
||||
return new BalanceSheet
|
||||
{
|
||||
Assets = assets, Portfolio = c.PortfolioValue, Cash = cash, TotalAssets = total,
|
||||
Loans = loans, LoansRate = rate, Overdraft = overdraft, TotalLiabilities = loans + overdraft,
|
||||
NetWorth = total - loans - overdraft,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Conto economico dell'ultimo anno chiuso (o dell'anno in corso, per una compagnia fondata
|
||||
/// quest'anno): righe raggruppate dalle voci del registro; l'utile è <see cref="Company.OperatingProfit"/>.
|
||||
/// </summary>
|
||||
public static IncomeStatement Income(World w, Company c)
|
||||
{
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
bool closed = w.Clock.Year > w.Calendar.StartYear && c.FoundedDay < yearStart;
|
||||
var e = closed ? c.LastYearEntries : c.YearEntries;
|
||||
long Sum(params LedgerEntry[] keys)
|
||||
{
|
||||
long s = 0;
|
||||
foreach (var k in keys) s += e[(int)k];
|
||||
return s;
|
||||
}
|
||||
var lines = new List<IncomeLine>
|
||||
{
|
||||
new(IncomeLineKind.Fares, new Money(Sum(LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue))),
|
||||
new(IncomeLineKind.OtherIncome, new Money(Sum(LedgerEntry.Trading, LedgerEntry.Contracts, LedgerEntry.Industries, LedgerEntry.Subsidiaries,
|
||||
LedgerEntry.DividendsReceived))),
|
||||
new(IncomeLineKind.OperatingCosts, new Money(Sum(LedgerEntry.RunningCosts, LedgerEntry.StationUpkeep, LedgerEntry.Wages, LedgerEntry.Penalties,
|
||||
LedgerEntry.Duties, LedgerEntry.Storage))),
|
||||
new(IncomeLineKind.Maintenance, new Money(Sum(LedgerEntry.TrackMaintenance, LedgerEntry.FleetMaintenance))),
|
||||
new(IncomeLineKind.Interest, new Money(Sum(LedgerEntry.Interest))),
|
||||
};
|
||||
return new IncomeStatement
|
||||
{
|
||||
Year = closed ? w.Clock.Year - 1 : w.Clock.Year,
|
||||
Partial = !closed,
|
||||
Lines = lines,
|
||||
Profit = new Money(Company.OperatingProfit(e)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Patrimonio netto nel tempo: il capitale iniziale alla fondazione, la fotografia di fine anno
|
||||
/// dello storico (al primo giorno dell'anno dopo) e il valore di oggi. La fotografia del primo giorno
|
||||
/// dell'anno in corso lascia il posto a oggi: un punto per anno di calendario, come l'immagine 08.
|
||||
/// </summary>
|
||||
public static List<NetWorthPoint> History(World w, Company c)
|
||||
{
|
||||
var points = new List<NetWorthPoint> { new(c.FoundedDay, new Money(w.Difficulty.InitialCapital)) };
|
||||
long today = w.Clock.Day;
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
foreach (var y in c.History)
|
||||
{
|
||||
long day = (long)(y.Year + 1 - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
if (day <= points[^1].Day || day >= yearStart) continue;
|
||||
points.Add(new NetWorthPoint(day, new Money(y.NetWorthCents)));
|
||||
}
|
||||
if (today > points[^1].Day) points.Add(new NetWorthPoint(today, c.NetWorth));
|
||||
else points[^1] = new NetWorthPoint(points[^1].Day, c.NetWorth);
|
||||
return points;
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,86 @@ public enum LedgerEntry : byte
|
||||
Industries = 19,
|
||||
/// <summary>Utili versati dalle compagnie controllate.</summary>
|
||||
Subsidiaries = 20,
|
||||
/// <summary>Esercizio dei binari di stazione e dei depositi (prima dentro <see cref="RunningCosts"/>, ADR 0019).</summary>
|
||||
StationUpkeep = 21,
|
||||
/// <summary>Giacenza della merce nei magazzini della compagnia (prima dentro <see cref="Trading"/>, ADR 0019).</summary>
|
||||
Storage = 22,
|
||||
/// <summary>Dazi sugli scambi in proprio con gli hub (prima dentro <see cref="Trading"/>, ADR 0019).</summary>
|
||||
Duties = 23,
|
||||
/// <summary>Dividendi incassati dalle azioni di altre compagnie (ADR 0019); <see cref="Dividends"/> resta per quelli pagati.</summary>
|
||||
DividendsReceived = 24,
|
||||
}
|
||||
|
||||
/// <summary>Sezione del conto economico di una voce del registro (ADR 0019).</summary>
|
||||
public enum IncomeSection : byte
|
||||
{
|
||||
/// <summary>Ricavi d'esercizio: entrano nell'utile operativo.</summary>
|
||||
Revenue = 0,
|
||||
/// <summary>Costi d'esercizio: entrano nell'utile operativo.</summary>
|
||||
Cost = 1,
|
||||
/// <summary>Investimenti e finanziamenti: muovono la cassa ma non l'utile operativo.</summary>
|
||||
Capital = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classificazione delle voci del registro (ADR 0019): unica fonte dell'utile operativo, dei ricavi del
|
||||
/// rating e delle righe del conto economico del pannello delle finanze.
|
||||
/// </summary>
|
||||
public static class LedgerEntries
|
||||
{
|
||||
/// <summary>Voci nell'ordine del conto economico: ricavi, costi, investimenti e finanziamenti.</summary>
|
||||
public static readonly LedgerEntry[] Ordered =
|
||||
[
|
||||
LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue, LedgerEntry.Trading, LedgerEntry.Contracts,
|
||||
LedgerEntry.Industries, LedgerEntry.Subsidiaries, LedgerEntry.DividendsReceived,
|
||||
LedgerEntry.RunningCosts, LedgerEntry.StationUpkeep, LedgerEntry.FleetMaintenance, LedgerEntry.TrackMaintenance,
|
||||
LedgerEntry.Wages, LedgerEntry.Interest, LedgerEntry.Duties, LedgerEntry.Storage, LedgerEntry.Penalties,
|
||||
LedgerEntry.Construction, LedgerEntry.VehiclePurchase, LedgerEntry.VehicleSale, LedgerEntry.IndustryPurchase,
|
||||
LedgerEntry.LoanTaken, LedgerEntry.LoanRepaid, LedgerEntry.Shares, LedgerEntry.Dividends, LedgerEntry.Other,
|
||||
];
|
||||
|
||||
public static IncomeSection Section(LedgerEntry e) => e switch
|
||||
{
|
||||
LedgerEntry.FreightRevenue or LedgerEntry.PassengerRevenue or LedgerEntry.Trading or LedgerEntry.Contracts
|
||||
or LedgerEntry.Industries or LedgerEntry.Subsidiaries or LedgerEntry.DividendsReceived => IncomeSection.Revenue,
|
||||
LedgerEntry.RunningCosts or LedgerEntry.StationUpkeep or LedgerEntry.FleetMaintenance or LedgerEntry.TrackMaintenance
|
||||
or LedgerEntry.Wages or LedgerEntry.Interest or LedgerEntry.Duties or LedgerEntry.Storage or LedgerEntry.Penalties => IncomeSection.Cost,
|
||||
_ => IncomeSection.Capital,
|
||||
};
|
||||
|
||||
/// <summary>Vero per le voci che entrano nell'utile operativo (ricavi e costi d'esercizio).</summary>
|
||||
public static bool Operating(LedgerEntry e) => Section(e) != IncomeSection.Capital;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Movimenti per voce di un mese o di un anno chiuso (ADR 0019): <see cref="Month"/> 1–12 per un mese,
|
||||
/// 0 per un anno intero.
|
||||
/// </summary>
|
||||
public sealed class IncomeRecord
|
||||
{
|
||||
public required int Year { get; init; }
|
||||
public required int Month { get; init; }
|
||||
public required long[] Entries { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Voci dello stato patrimoniale per gli attivi non monetari (ADR 0018).</summary>
|
||||
public enum AssetCategory : byte
|
||||
{
|
||||
/// <summary>Binari e opere (ponti, gallerie), ammortizzati.</summary>
|
||||
Track = 0,
|
||||
/// <summary>Stazioni e depositi, al costo.</summary>
|
||||
Stations = 1,
|
||||
/// <summary>Veicoli, ammortizzati.</summary>
|
||||
Vehicles = 2,
|
||||
/// <summary>Industrie possedute: impianti e cassa dell'impresa.</summary>
|
||||
Industries = 3,
|
||||
/// <summary>Merce propria in magazzino e in viaggio, al prezzo globale.</summary>
|
||||
Goods = 4,
|
||||
}
|
||||
|
||||
public static class AssetCategories
|
||||
{
|
||||
public const int Count = 5;
|
||||
}
|
||||
|
||||
/// <summary>Prestito con rata costante (ammortamento alla francese).</summary>
|
||||
@@ -45,7 +125,7 @@ public sealed class Loan
|
||||
/// <summary>Compagnia ferroviaria (giocatore o IA).</summary>
|
||||
public sealed class Company
|
||||
{
|
||||
public const int EntryCount = 21;
|
||||
public const int EntryCount = 25;
|
||||
|
||||
public required CompanyId Id { get; init; }
|
||||
public required string Name { get; set; }
|
||||
@@ -77,8 +157,44 @@ public sealed class Company
|
||||
/// <summary>Movimenti dell'anno precedente per voce (per rating e borsa).</summary>
|
||||
public long[] LastYearEntries { get; } = new long[EntryCount];
|
||||
|
||||
/// <summary>Valore contabile degli attivi non monetari (binari, stazioni, veicoli), aggiornato mensilmente.</summary>
|
||||
public Money AssetBookValue { get; set; }
|
||||
/// <summary>Mesi chiusi per voce, dal più vecchio (al massimo finance.incomeMonths, ADR 0019).</summary>
|
||||
public List<IncomeRecord> IncomeMonths { get; } = [];
|
||||
|
||||
/// <summary>Anni chiusi per voce, dal più vecchio (al massimo finance.incomeYears, ADR 0019).</summary>
|
||||
public List<IncomeRecord> IncomeYears { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Misure dell'ultimo calcolo del rating (ADR 0019): margine = utile operativo / ricavi dei mesi della
|
||||
/// finestra, leva = debiti / patrimonio netto (+∞ con patrimonio non positivo e debiti), punteggio
|
||||
/// pesato e numero di mesi della finestra (0 prima del primo calcolo).
|
||||
/// </summary>
|
||||
public double RatingMargin { get; set; }
|
||||
public double RatingLeverage { get; set; }
|
||||
public double RatingScore { get; set; }
|
||||
public int RatingMonths { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi non monetari per voce (<see cref="AssetCategory"/>, centesimi),
|
||||
/// aggiornato ogni mese da <c>FinanceSystem.UpdateBookValues</c> (ADR 0018).
|
||||
/// </summary>
|
||||
public long[] BookValues { get; } = new long[AssetCategories.Count];
|
||||
|
||||
/// <summary>Valore contabile degli attivi non monetari: somma delle voci di <see cref="BookValues"/>.</summary>
|
||||
public Money AssetBookValue
|
||||
{
|
||||
get
|
||||
{
|
||||
long sum = 0;
|
||||
foreach (long v in BookValues) sum += v;
|
||||
return new Money(sum);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giorno in cui la compagnia ha raggiunto ciascun livello (indice livello − 1; −1 se non
|
||||
/// raggiunto o sconosciuto). Il livello 1 non si annota: vale dalla fondazione (ADR 0018).
|
||||
/// </summary>
|
||||
public long[] TierReachedDay { get; } = [-1, -1, -1, -1, -1];
|
||||
|
||||
public Money Debt
|
||||
{
|
||||
@@ -164,20 +280,41 @@ public sealed class Company
|
||||
/// <summary>Capitalizzazione di borsa (centesimi).</summary>
|
||||
public double MarketCap => SharePrice * Shares.Outstanding;
|
||||
|
||||
/// <summary>Utile operativo dell'anno indicato (ricavi meno costi d'esercizio, esclusi prestiti e investimenti).</summary>
|
||||
/// <summary>
|
||||
/// Utile operativo dei movimenti indicati: somma delle voci di ricavo e di costo d'esercizio
|
||||
/// (<see cref="LedgerEntries.Operating"/>), esclusi prestiti, investimenti e capitale.
|
||||
/// </summary>
|
||||
public static long OperatingProfit(long[] entries)
|
||||
{
|
||||
long revenue = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
|
||||
+ entries[(int)LedgerEntry.Trading] + entries[(int)LedgerEntry.Contracts]
|
||||
+ entries[(int)LedgerEntry.Industries] + entries[(int)LedgerEntry.Subsidiaries];
|
||||
long costs = entries[(int)LedgerEntry.RunningCosts] + entries[(int)LedgerEntry.TrackMaintenance]
|
||||
+ entries[(int)LedgerEntry.FleetMaintenance] + entries[(int)LedgerEntry.Wages]
|
||||
+ entries[(int)LedgerEntry.Interest] + entries[(int)LedgerEntry.Penalties];
|
||||
return revenue + costs; // i costi sono già negativi
|
||||
long sum = 0;
|
||||
for (int i = 0; i < entries.Length && i < EntryCount; i++)
|
||||
{
|
||||
if (LedgerEntries.Operating((LedgerEntry)i)) sum += entries[i]; // i costi sono già negativi
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static long Revenue(long[] entries) =>
|
||||
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue]
|
||||
+ Math.Max(0, entries[(int)LedgerEntry.Trading]) + Math.Max(0, entries[(int)LedgerEntry.Contracts])
|
||||
+ Math.Max(0, entries[(int)LedgerEntry.Industries]) + Math.Max(0, entries[(int)LedgerEntry.Subsidiaries]);
|
||||
/// <summary>
|
||||
/// Ricavi dei trasporti: tariffe merci e passeggeri e contratti con le industrie (se positivi). Misura la
|
||||
/// quota dei trasporti dei nuovi concorrenti (12.1), senza commercio in proprio, industrie, controllate
|
||||
/// e dividendi incassati, che non sono trasporto.
|
||||
/// </summary>
|
||||
public static long TransportRevenue(long[] entries) =>
|
||||
entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue] + Math.Max(0, entries[(int)LedgerEntry.Contracts]);
|
||||
|
||||
/// <summary>
|
||||
/// Ricavi d'esercizio: tariffe merci e passeggeri come sono, le altre voci di ricavo solo se positive
|
||||
/// (commercio, contratti, industrie, controllate, dividendi incassati).
|
||||
/// </summary>
|
||||
public static long Revenue(long[] entries)
|
||||
{
|
||||
long sum = entries[(int)LedgerEntry.FreightRevenue] + entries[(int)LedgerEntry.PassengerRevenue];
|
||||
for (int i = 0; i < entries.Length && i < EntryCount; i++)
|
||||
{
|
||||
var e = (LedgerEntry)i;
|
||||
if (e is LedgerEntry.FreightRevenue or LedgerEntry.PassengerRevenue || LedgerEntries.Section(e) != IncomeSection.Revenue) continue;
|
||||
sum += Math.Max(0, entries[i]);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
using System.Globalization;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>Colonna del conto economico: mese in corso, mese chiuso, anno in corso o anno chiuso.</summary>
|
||||
public enum IncomeColumnKind : byte
|
||||
{
|
||||
CurrentMonth = 0,
|
||||
Month = 1,
|
||||
CurrentYear = 2,
|
||||
Year = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Movimenti per voce di un periodo (<see cref="Company.EntryCount"/> valori, indice = <see cref="LedgerEntry"/>),
|
||||
/// con l'utile operativo del motore e il flusso di cassa (somma di tutte le voci).
|
||||
/// </summary>
|
||||
public sealed class IncomeColumn
|
||||
{
|
||||
public required IncomeColumnKind Kind { get; init; }
|
||||
public required int Year { get; init; }
|
||||
/// <summary>Mese 1–12 per le colonne mensili, 0 per quelle annuali.</summary>
|
||||
public required int Month { get; init; }
|
||||
public required long[] Entries { get; init; }
|
||||
/// <summary>Utile operativo: <see cref="Company.OperatingProfit"/> sulle stesse voci.</summary>
|
||||
public required Money Profit { get; init; }
|
||||
/// <summary>Variazione della cassa nel periodo: somma di tutte le voci, investimenti e finanziamenti compresi.</summary>
|
||||
public required Money CashFlow { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Soglia di un rating: punteggio minimo e tasso di un nuovo prestito con quel rating.</summary>
|
||||
public readonly record struct RatingThreshold(CreditRating Rating, double MinScore, double LoanRate);
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione del rating (ADR 0019): le due misure conservate dal motore all'ultimo calcolo, le
|
||||
/// componenti e il punteggio, le soglie, e cosa servirebbe per il gradino sopra.
|
||||
/// </summary>
|
||||
public sealed class RatingExplanation
|
||||
{
|
||||
public required CreditRating Rating { get; init; }
|
||||
/// <summary>Vero prima del primo calcolo mensile: il rating è quello iniziale dei dati e le misure sono di oggi.</summary>
|
||||
public required bool Initial { get; init; }
|
||||
public required bool Bankrupt { get; init; }
|
||||
/// <summary>Mesi chiusi nella finestra del margine (fino a finance.incomeMonths).</summary>
|
||||
public required int Months { get; init; }
|
||||
/// <summary>Mesi della finestra con ricavi.</summary>
|
||||
public required int RevenueMonths { get; init; }
|
||||
/// <summary>
|
||||
/// Margine neutro (0) perché la finestra non è piena e ha meno di <see cref="MinRevenueMonths"/> mesi
|
||||
/// con ricavi (avvio della compagnia).
|
||||
/// </summary>
|
||||
public required bool MarginNeutral { get; init; }
|
||||
/// <summary>Mesi con ricavi che servono perché il margine conti prima che la finestra sia piena (finance.ratingMinRevenueMonths).</summary>
|
||||
public required int MinRevenueMonths { get; init; }
|
||||
public required double Margin { get; init; }
|
||||
/// <summary>Debiti / patrimonio netto (+∞ con patrimonio non positivo e debiti: <see cref="LeverageUnbounded"/>).</summary>
|
||||
public required double Leverage { get; init; }
|
||||
public bool LeverageUnbounded => double.IsPositiveInfinity(Leverage);
|
||||
public required double MarginWeight { get; init; }
|
||||
public required double LeverageWeight { get; init; }
|
||||
public required double MarginComponent { get; init; }
|
||||
public required double LeverageComponent { get; init; }
|
||||
public required double Score { get; init; }
|
||||
/// <summary>Soglie da AAA a C (sotto l'ultima è D).</summary>
|
||||
public required List<RatingThreshold> Thresholds { get; init; }
|
||||
/// <summary>Gradino sopra (null ad AAA) e punteggio che richiede.</summary>
|
||||
public required CreditRating? Next { get; init; }
|
||||
public required double NextThreshold { get; init; }
|
||||
/// <summary>Rating che corrisponde al punteggio (D in bancarotta).</summary>
|
||||
public required CreditRating ScoreRating { get; init; }
|
||||
/// <summary>
|
||||
/// Il punteggio raggiunge già il gradino sopra: il rating mostrato è quello iniziale o di un calcolo
|
||||
/// precedente e cambia al prossimo calcolo mensile. Margine e leva necessari non si calcolano.
|
||||
/// </summary>
|
||||
public required bool NextAlreadyMet { get; init; }
|
||||
/// <summary>Margine che basterebbe da solo, a leva invariata (se raggiungibile).</summary>
|
||||
public required double MarginNeeded { get; init; }
|
||||
public required bool MarginReachable { get; init; }
|
||||
/// <summary>Debiti/patrimonio massimo che basterebbe da solo, a margine invariato (se raggiungibile).</summary>
|
||||
public required double LeverageMax { get; init; }
|
||||
public required bool LeverageReachable { get; init; }
|
||||
/// <summary>Debiti da rimborsare oggi per scendere sotto <see cref="LeverageMax"/> (0 se già sotto o irraggiungibile).</summary>
|
||||
public required Money DebtToRepay { get; init; }
|
||||
/// <summary>
|
||||
/// Il rimborso di <see cref="DebtToRepay"/> si può fare oggi: non supera la cassa disponibile né il
|
||||
/// residuo dei prestiti (lo scoperto non si rimborsa, si copre solo riportando la cassa sopra zero).
|
||||
/// </summary>
|
||||
public required bool RepayAffordable { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Prestito in corso con rata e scadenza.</summary>
|
||||
public sealed class LoanDetail
|
||||
{
|
||||
public required LoanId Id { get; init; }
|
||||
public required Money Principal { get; init; }
|
||||
public required Money Remaining { get; init; }
|
||||
/// <summary>Tasso annuo fissato all'accensione.</summary>
|
||||
public required double AnnualRate { get; init; }
|
||||
public required int MonthsLeft { get; init; }
|
||||
/// <summary>Rata mensile costante sul residuo e i mesi restanti (alla francese).</summary>
|
||||
public required Money Payment { get; init; }
|
||||
/// <summary>Interessi della prossima rata.</summary>
|
||||
public required Money NextInterest { get; init; }
|
||||
/// <summary>Giorno dell'ultima rata (primo giorno del mese).</summary>
|
||||
public required long MaturityDay { get; init; }
|
||||
}
|
||||
|
||||
public sealed class FinanceOutlookReport
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
public required CompanyId Company { get; init; }
|
||||
public required Money Cash { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
/// <summary>Residuo dei prestiti.</summary>
|
||||
public required Money Loans { get; init; }
|
||||
/// <summary>Cassa negativa (scoperto), tra i debiti del rating.</summary>
|
||||
public required Money Overdraft { get; init; }
|
||||
/// <summary>Voci del conto economico nell'ordine di presentazione, con la loro sezione.</summary>
|
||||
public required List<(LedgerEntry Entry, IncomeSection Section)> Lines { get; init; }
|
||||
/// <summary>Mese in corso, mesi chiusi dal più recente, anno in corso, anni chiusi dal più recente.</summary>
|
||||
public required List<IncomeColumn> Columns { get; init; }
|
||||
public required RatingExplanation Rating { get; init; }
|
||||
public required List<LoanDetail> LoanList { get; init; }
|
||||
public required Money MaxLoan { get; init; }
|
||||
public required Money LoanAvailable { get; init; }
|
||||
/// <summary>Tasso di un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public required double NewLoanRate { get; init; }
|
||||
public required double BaseRate { get; init; }
|
||||
public required double Spread { get; init; }
|
||||
public required int LoanTermMonths { get; init; }
|
||||
public required Money LoanStep { get; init; }
|
||||
public required bool LoansAllowed { get; init; }
|
||||
public required int NegativeCashDays { get; init; }
|
||||
/// <summary>Giorni di cassa negativa che portano alla bancarotta (difficulty.json, bankruptcyDays).</summary>
|
||||
public required int BankruptcyDays { get; init; }
|
||||
public required bool Bankrupt { get; init; }
|
||||
public required bool Receivership { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro delle finanze per il pannello «Finanze» (ADR 0019): pura funzione del mondo, come
|
||||
/// <see cref="ClimbOutlook"/>. Conto economico per voce (mese in corso, mesi chiusi, anno in corso, anni
|
||||
/// chiusi) dalle stesse voci del registro che danno l'utile operativo, prestiti con rata e scadenza,
|
||||
/// spiegazione del rating dalle misure conservate dal motore, conto alla rovescia della bancarotta.
|
||||
/// </summary>
|
||||
public static class FinanceOutlook
|
||||
{
|
||||
public static FinanceOutlookReport Build(World w, CompanyId company)
|
||||
{
|
||||
var c = w.Company(company);
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var max = FinanceSystem.MaxLoan(w, c);
|
||||
return new FinanceOutlookReport
|
||||
{
|
||||
Day = w.Clock.Day,
|
||||
Company = c.Id,
|
||||
Cash = c.Cash,
|
||||
NetWorth = c.NetWorth,
|
||||
Loans = c.Debt,
|
||||
Overdraft = Money.Max(Money.Zero, -c.Cash),
|
||||
Lines = LedgerEntries.Ordered.Select(e => (e, LedgerEntries.Section(e))).ToList(),
|
||||
Columns = Columns(w, c),
|
||||
Rating = Explain(w, c),
|
||||
LoanList = c.Loans.Select(l => Detail(w, l)).ToList(),
|
||||
MaxLoan = max,
|
||||
LoanAvailable = Money.Max(Money.Zero, max - c.Debt),
|
||||
NewLoanRate = FinanceSystem.LoanRate(w, c),
|
||||
BaseRate = w.Difficulty.BaseInterestRate,
|
||||
Spread = fb.RatingSpreads[c.Rating.ToString()],
|
||||
LoanTermMonths = fb.LoanTermMonths,
|
||||
LoanStep = new Money(fb.LoanStep),
|
||||
LoansAllowed = !c.Receivership && !c.Bankrupt,
|
||||
NegativeCashDays = c.NegativeCashDays,
|
||||
BankruptcyDays = w.Difficulty.BankruptcyDays,
|
||||
Bankrupt = c.Bankrupt,
|
||||
Receivership = c.Receivership,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Colonne del conto economico: mese in corso, mesi chiusi (dal più recente), anno in corso, anni chiusi.</summary>
|
||||
public static List<IncomeColumn> Columns(World w, Company c)
|
||||
{
|
||||
var today = w.Calendar.DateOfDay(w.Clock.Day);
|
||||
var list = new List<IncomeColumn> { Column(IncomeColumnKind.CurrentMonth, today.Year, today.Month, c.MonthEntries) };
|
||||
for (int i = c.IncomeMonths.Count - 1; i >= 0; i--)
|
||||
list.Add(Column(IncomeColumnKind.Month, c.IncomeMonths[i].Year, c.IncomeMonths[i].Month, c.IncomeMonths[i].Entries));
|
||||
list.Add(Column(IncomeColumnKind.CurrentYear, today.Year, 0, c.YearEntries));
|
||||
for (int i = c.IncomeYears.Count - 1; i >= 0; i--)
|
||||
list.Add(Column(IncomeColumnKind.Year, c.IncomeYears[i].Year, 0, c.IncomeYears[i].Entries));
|
||||
return list;
|
||||
}
|
||||
|
||||
private static IncomeColumn Column(IncomeColumnKind kind, int year, int month, long[] source)
|
||||
{
|
||||
var entries = new long[Company.EntryCount];
|
||||
Array.Copy(source, entries, Math.Min(source.Length, entries.Length));
|
||||
long flow = 0;
|
||||
foreach (long v in entries) flow += v;
|
||||
return new IncomeColumn
|
||||
{
|
||||
Kind = kind, Year = year, Month = month, Entries = entries,
|
||||
Profit = new Money(Company.OperatingProfit(entries)), CashFlow = new Money(flow),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Prestito con la rata sul residuo e la scadenza al primo giorno del mese dell'ultima rata.</summary>
|
||||
public static LoanDetail Detail(World w, Loan l)
|
||||
{
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
long monthStart = w.Clock.Day / dpm * dpm;
|
||||
return new LoanDetail
|
||||
{
|
||||
Id = l.Id, Principal = l.Principal, Remaining = l.Remaining, AnnualRate = l.AnnualRate, MonthsLeft = l.MonthsLeft,
|
||||
Payment = FinanceSystem.MonthlyPayment(l.Remaining, l.AnnualRate, l.MonthsLeft),
|
||||
NextInterest = Money.FromCentsRounded(l.Remaining.Cents * l.AnnualRate / 12),
|
||||
MaturityDay = monthStart + (long)Math.Max(0, l.MonthsLeft) * dpm,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spiegazione del rating con le misure dell'ultimo calcolo mensile (prima del primo calcolo, quelle di
|
||||
/// oggi). Per il gradino sopra: il margine che basterebbe a leva invariata, il debiti/patrimonio massimo
|
||||
/// a margine invariato e quanto debito rimborsare oggi per arrivarci (a patrimonio invariato: il
|
||||
/// rimborso toglie lo stesso importo da cassa e debiti). Se il punteggio raggiunge già il gradino sopra
|
||||
/// (rating iniziale o rimasto da un calcolo precedente) lo dice e non calcola obiettivi già raggiunti.
|
||||
/// </summary>
|
||||
public static RatingExplanation Explain(World w, Company c)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
bool initial = c.RatingMonths == 0;
|
||||
var live = FinanceSystem.Measures(w, c);
|
||||
double margin = initial ? live.Margin : c.RatingMargin;
|
||||
double leverage = initial ? live.Leverage : c.RatingLeverage;
|
||||
double cm = FinanceSystem.MarginComponent(margin), cl = FinanceSystem.LeverageComponent(leverage);
|
||||
double score = fb.ProfitMarginWeight * cm + fb.LeverageWeight * cl;
|
||||
var thresholds = new List<RatingThreshold>(fb.RatingByScore.Length);
|
||||
for (int i = 0; i < fb.RatingByScore.Length; i++)
|
||||
thresholds.Add(new RatingThreshold((CreditRating)i, fb.RatingByScore[i], FinanceSystem.LoanRate(w, (CreditRating)i)));
|
||||
|
||||
CreditRating? next = c.Rating > CreditRating.AAA ? c.Rating - 1 : null;
|
||||
double target = next is { } n ? fb.RatingByScore[(int)n] : 0;
|
||||
var scoreRating = c.Bankrupt ? CreditRating.D : FinanceSystem.RatingOf(w, score);
|
||||
bool alreadyMet = next is not null && !c.Bankrupt && score >= target;
|
||||
double marginNeeded = 0, leverageMax = 0;
|
||||
bool marginOk = false, leverageOk = false, affordable = false;
|
||||
var repay = Money.Zero;
|
||||
if (next is not null && !c.Bankrupt && !alreadyMet)
|
||||
{
|
||||
// punteggio sotto la soglia: needCm > cm ≥ 0 e needCl > cl ≥ 0, quindi niente infiniti
|
||||
// pesoMargine·clamp(0,5 + m) + pesoLeva·cl = soglia → m
|
||||
double needCm = (target - fb.LeverageWeight * cl) / fb.ProfitMarginWeight;
|
||||
marginOk = needCm <= 1;
|
||||
marginNeeded = needCm - 0.5;
|
||||
// pesoMargine·cm + pesoLeva / (1 + ℓ) = soglia → ℓ
|
||||
double needCl = (target - fb.ProfitMarginWeight * cm) / fb.LeverageWeight;
|
||||
leverageOk = needCl <= 1;
|
||||
leverageMax = leverageOk ? 1 / needCl - 1 : 0;
|
||||
if (leverageOk && live.Equity > 0)
|
||||
{
|
||||
repay = new Money(Math.Max(0, live.Debt - (long)Math.Floor(leverageMax * live.Equity)));
|
||||
// si rimborsano i prestiti con la cassa: non oltre la cassa positiva né oltre il residuo
|
||||
long repayable = Math.Min(c.Debt.Cents, Math.Max(0, c.Cash.Cents));
|
||||
affordable = repay.Cents <= repayable;
|
||||
}
|
||||
}
|
||||
return new RatingExplanation
|
||||
{
|
||||
Rating = c.Rating, Initial = initial, Bankrupt = c.Bankrupt,
|
||||
Months = initial ? live.Months : c.RatingMonths,
|
||||
RevenueMonths = live.RevenueMonths, MarginNeutral = live.MarginNeutral, MinRevenueMonths = fb.RatingMinRevenueMonths,
|
||||
Margin = margin, Leverage = leverage,
|
||||
MarginWeight = fb.ProfitMarginWeight, LeverageWeight = fb.LeverageWeight,
|
||||
MarginComponent = cm, LeverageComponent = cl, Score = score,
|
||||
Thresholds = thresholds, Next = next, NextThreshold = target, ScoreRating = scoreRating, NextAlreadyMet = alreadyMet,
|
||||
MarginNeeded = marginNeeded, MarginReachable = marginOk,
|
||||
LeverageMax = leverageMax, LeverageReachable = leverageOk, DebtToRepay = repay, RepayAffordable = affordable,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Tasso in percentuale all'italiana con un decimale («6,5%»).</summary>
|
||||
public static string Percent(double rate) =>
|
||||
(rate * 100).ToString("0.0", CultureInfo.InvariantCulture).Replace('.', ',') + "%";
|
||||
}
|
||||
@@ -26,11 +26,17 @@ public sealed class MoneyLedger(Func<CompanyId, Company> companies, Func<Industr
|
||||
/// <summary>Totale trasferito dall'inizio (statistica).</summary>
|
||||
public long TransfersCount { get; internal set; }
|
||||
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry entry)
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry entry) => Transfer(from, to, amount, entry, entry);
|
||||
|
||||
/// <summary>
|
||||
/// Trasferimento registrato su voci diverse per chi paga e chi incassa (per esempio dividendi pagati
|
||||
/// e dividendi incassati, ADR 0019): la somma dei saldi resta zero.
|
||||
/// </summary>
|
||||
public void Transfer(Account from, Account to, Money amount, LedgerEntry fromEntry, LedgerEntry toEntry)
|
||||
{
|
||||
if (amount.Cents == 0 || from == to) return;
|
||||
Adjust(from, -amount, entry);
|
||||
Adjust(to, amount, entry);
|
||||
Adjust(from, -amount, fromEntry);
|
||||
Adjust(to, amount, toEntry);
|
||||
TransfersCount++;
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ public sealed class TradingProgress
|
||||
public required bool Unlocked { get; init; }
|
||||
/// <summary>Livello che sblocca il commercio (0 se nessuno).</summary>
|
||||
public required int Level { get; init; }
|
||||
/// <summary>Minimo tra le frazioni dei requisiti numerici (patrimonio, città collegate), in [0, 1].</summary>
|
||||
/// <summary>Avanzamento verso il livello (media delle frazioni dei tre requisiti, ADR 0018), in [0, 1].</summary>
|
||||
public required double Fraction { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
public required Money NetWorthRequired { get; init; }
|
||||
@@ -413,24 +413,22 @@ public static class MarketOutlook
|
||||
Rating = c?.Rating ?? CreditRating.D, RatingRequired = r?.CreditRating ?? CreditRating.D, RatingMet = false,
|
||||
};
|
||||
}
|
||||
var req = target.Requirements;
|
||||
int towns = Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
|
||||
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
|
||||
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
|
||||
// stessi requisiti e stesso avanzamento del pannello «La tua scalata» (ADR 0018)
|
||||
var progress = ClimbOutlook.Requirements(w, c, target);
|
||||
bool unlocked = Tiers.Unlocks(w, c).Trading;
|
||||
return new TradingProgress
|
||||
{
|
||||
Unlocked = unlocked,
|
||||
Level = target.Level,
|
||||
Fraction = unlocked ? 1 : Math.Min(worth, townsFraction),
|
||||
NetWorth = c.NetWorth,
|
||||
NetWorthRequired = new Money(req.NetWorth),
|
||||
TownsConnected = towns,
|
||||
TownsRequired = req.ConnectedTownsOver.Count,
|
||||
TownPopulation = req.ConnectedTownsOver.Population,
|
||||
Rating = c.Rating,
|
||||
RatingRequired = req.CreditRating,
|
||||
RatingMet = c.Rating <= req.CreditRating,
|
||||
Fraction = unlocked ? 1 : progress.Progress,
|
||||
NetWorth = progress.NetWorth,
|
||||
NetWorthRequired = progress.NetWorthRequired,
|
||||
TownsConnected = progress.Towns,
|
||||
TownsRequired = progress.TownsRequired,
|
||||
TownPopulation = progress.TownPopulation,
|
||||
Rating = progress.Rating,
|
||||
RatingRequired = progress.RatingRequired,
|
||||
RatingMet = progress.RatingMet,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale delle compagnie (corpo del salvataggio dalla versione 6, ADR 0018): valore
|
||||
/// contabile degli attivi per voce (<see cref="AssetCategory"/>) e giorno in cui ogni livello è stato
|
||||
/// raggiunto. Entra nell'hash giornaliero con lo stato dinamico. Le versioni precedenti salvano solo
|
||||
/// il totale degli attivi: <see cref="Migrate"/> lo ripartisce senza cambiarlo.
|
||||
/// </summary>
|
||||
public static class BalanceSheetSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
s.Write(w.Companies.Count);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
s.Write(c.BookValues);
|
||||
s.Write(c.TierReachedDay);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n != w.Companies.Count) throw new InvalidDataException($"Stato patrimoniale di {n} compagnie su {w.Companies.Count}");
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
CopyInto(r.ReadInt64Array(), c.BookValues);
|
||||
CopyInto(r.ReadInt64Array(), c.TierReachedDay);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Migrazione dalle versioni 1–5: il totale salvato (letto nella voce dei binari) si ripartisce in
|
||||
/// proporzione alla scomposizione calcolata al giorno del caricamento, con il resto dell'arrotondamento
|
||||
/// sulla voce più grande; il totale, e quindi il patrimonio netto, non cambia fino al ricalcolo del
|
||||
/// mese. I giorni dei livelli si ricostruiscono dai fatti salienti («diventa «nome»») e, in mancanza,
|
||||
/// dallo storico annuale (giorno della prima fotografia con il livello, tra fondazione e oggi).
|
||||
/// </summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
var live = FinanceSystem.BookValues(w);
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
var c = w.Companies[i];
|
||||
long total = c.AssetBookValue.Cents;
|
||||
Array.Clear(c.BookValues);
|
||||
long liveSum = 0;
|
||||
foreach (long v in live[i]) liveSum += v;
|
||||
if (total != 0 && liveSum > 0)
|
||||
{
|
||||
long assigned = 0;
|
||||
int largest = 0;
|
||||
for (int k = 0; k < AssetCategories.Count; k++)
|
||||
{
|
||||
c.BookValues[k] = (long)((Int128)total * live[i][k] / liveSum);
|
||||
assigned += c.BookValues[k];
|
||||
if (live[i][k] > live[i][largest]) largest = k;
|
||||
}
|
||||
c.BookValues[largest] += total - assigned;
|
||||
}
|
||||
else
|
||||
{
|
||||
c.BookValues[(int)AssetCategory.Track] = total;
|
||||
}
|
||||
RebuildTierDays(w, c);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RebuildTierDays(World w, Company c)
|
||||
{
|
||||
Array.Fill(c.TierReachedDay, -1L);
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
for (int level = 2; level <= Math.Min(c.Tier, c.TierReachedDay.Length); level++)
|
||||
{
|
||||
string text = $"diventa «{tiers[level - 1].NameIt}»";
|
||||
long day = c.Milestones.FirstOrDefault(m => m.Text == text, new CompanyMilestone(-1, "")).Day;
|
||||
if (day < 0)
|
||||
{
|
||||
// la fotografia dell'anno Y si scatta il primo giorno di Y+1, dopo la chiusura del mese che
|
||||
// può aver promosso la compagnia: il livello è certo solo da quel giorno (come ClimbOutlook.History)
|
||||
int year = c.History.FirstOrDefault(y => y.Tier >= level, new CompanyYear(int.MinValue, 0, 0, 0, 0, 0, 0, 0, 0)).Year;
|
||||
if (year != int.MinValue)
|
||||
day = Math.Clamp((long)(year + 1 - w.Calendar.StartYear) * w.Calendar.DaysPerYear, Math.Max(0, c.FoundedDay), Math.Max(c.FoundedDay, w.Clock.Day));
|
||||
}
|
||||
c.TierReachedDay[level - 1] = day;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyInto(long[] source, long[] target) =>
|
||||
Array.Copy(source, target, Math.Min(source.Length, target.Length));
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Conti delle compagnie (corpo del salvataggio dalla versione 7, ADR 0019): mesi e anni chiusi per voce
|
||||
/// del registro e misure dell'ultimo calcolo del rating. Entra nell'hash giornaliero con lo stato
|
||||
/// dinamico. Le versioni precedenti non hanno i mesi chiusi: <see cref="Migrate"/> parte da zero mesi
|
||||
/// e recupera l'ultimo anno chiuso.
|
||||
/// </summary>
|
||||
public static class FinanceSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
s.Write(w.Companies.Count);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
WriteRecords(c.IncomeMonths, s);
|
||||
WriteRecords(c.IncomeYears, s);
|
||||
s.Write(c.RatingMargin);
|
||||
s.Write(c.RatingLeverage);
|
||||
s.Write(c.RatingScore);
|
||||
s.Write(c.RatingMonths);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n != w.Companies.Count) throw new InvalidDataException($"Conti di {n} compagnie su {w.Companies.Count}");
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
ReadRecords(c.IncomeMonths, r);
|
||||
ReadRecords(c.IncomeYears, r);
|
||||
c.RatingMargin = r.ReadDouble();
|
||||
c.RatingLeverage = r.ReadDouble();
|
||||
c.RatingScore = r.ReadDouble();
|
||||
c.RatingMonths = r.ReadInt32();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Migrazione dalle versioni 1–6: nessun mese chiuso conservato (il conto economico mensile e la
|
||||
/// finestra del rating si riempiono dal mese dopo il caricamento); l'ultimo anno chiuso, se c'è, entra
|
||||
/// negli anni; il rating resta quello salvato e la sua spiegazione usa le misure del giorno fino al
|
||||
/// primo calcolo mensile (<see cref="Company.RatingMonths"/> = 0).
|
||||
/// </summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
c.IncomeMonths.Clear();
|
||||
c.IncomeYears.Clear();
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
bool closedYear = w.Clock.Year > w.Calendar.StartYear && c.FoundedDay < yearStart;
|
||||
if (closedYear && c.LastYearEntries.Any(v => v != 0))
|
||||
c.IncomeYears.Add(new IncomeRecord { Year = w.Clock.Year - 1, Month = 0, Entries = (long[])c.LastYearEntries.Clone() });
|
||||
c.RatingMargin = 0;
|
||||
c.RatingLeverage = 0;
|
||||
c.RatingScore = 0;
|
||||
c.RatingMonths = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteRecords(List<IncomeRecord> records, SaveWriter s)
|
||||
{
|
||||
s.Write(records.Count);
|
||||
foreach (var m in records)
|
||||
{
|
||||
s.Write(m.Year);
|
||||
s.Write(m.Month);
|
||||
s.Write(m.Entries);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReadRecords(List<IncomeRecord> into, SaveReader r)
|
||||
{
|
||||
into.Clear();
|
||||
int n = r.ReadInt32();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int year = r.ReadInt32();
|
||||
int month = r.ReadInt32();
|
||||
var source = r.ReadInt64Array();
|
||||
// le voci aggiunte dopo il salvataggio partono da zero
|
||||
var entries = new long[Company.EntryCount];
|
||||
Array.Copy(source, entries, Math.Min(source.Length, entries.Length));
|
||||
into.Add(new IncomeRecord { Year = year, Month = month, Entries = entries });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace RailEnterprise.Core.Persistence;
|
||||
public static class WorldSerializer
|
||||
{
|
||||
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
|
||||
public const int BodyVersion = 5;
|
||||
public const int BodyVersion = 7;
|
||||
|
||||
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
|
||||
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
|
||||
@@ -247,6 +247,8 @@ public static class WorldSerializer
|
||||
if (version >= 3) CorporateSerializer.Write(w, s);
|
||||
if (version >= 4) TradingSerializer.Write(w, s);
|
||||
if (version >= 5) EventSerializer.Write(w, s);
|
||||
if (version >= 6) BalanceSheetSerializer.Write(w, s);
|
||||
if (version >= 7) FinanceSerializer.Write(w, s);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -641,7 +643,8 @@ public static class WorldSerializer
|
||||
CopyInto(r.ReadInt64Array(), c.MonthEntries);
|
||||
CopyInto(r.ReadInt64Array(), c.YearEntries);
|
||||
CopyInto(r.ReadInt64Array(), c.LastYearEntries);
|
||||
c.AssetBookValue = new Money(r.ReadInt64());
|
||||
// totale degli attivi: dalla versione 6 lo sostituisce la scomposizione per voce (BalanceSheetSerializer)
|
||||
c.BookValues[(int)AssetCategory.Track] = r.ReadInt64();
|
||||
int loans = r.ReadInt32();
|
||||
for (int k = 0; k < loans; k++)
|
||||
{
|
||||
@@ -707,6 +710,12 @@ public static class WorldSerializer
|
||||
else TradingSerializer.Migrate(w);
|
||||
// versione 5 (F6): eventi del mondo in corso; prima nessun evento attivo
|
||||
if (version >= 5) EventSerializer.Read(w, r);
|
||||
// versione 6 (F6): stato patrimoniale per voce e giorni dei livelli raggiunti
|
||||
if (version >= 6) BalanceSheetSerializer.Read(w, r);
|
||||
else BalanceSheetSerializer.Migrate(w);
|
||||
// versione 7 (F6): conto economico per mese e per anno, misure del rating (ADR 0019)
|
||||
if (version >= 7) FinanceSerializer.Read(w, r);
|
||||
else FinanceSerializer.Migrate(w);
|
||||
}
|
||||
|
||||
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
|
||||
|
||||
@@ -62,6 +62,14 @@ public static class CommandProcessor
|
||||
BuyGoodsCommand c => TradingCommandHandlers.Buy(w, company, c, Reply),
|
||||
SellGoodsCommand c => TradingCommandHandlers.Sell(w, company, c, Reply),
|
||||
ShipGoodsCommand c => TradingCommandHandlers.Ship(w, company, c, ctx, Reply),
|
||||
// le concessioni (F7) si rifiutano prima per il livello, poi perché non ancora disponibili; il testo
|
||||
// non promette che il livello basti
|
||||
BuyConcessionCommand when !Tiers.Unlocks(w, company).Concessions =>
|
||||
Result(CommandError.TierLocked, Tiers.ConcessionsAvailable
|
||||
? Tiers.LockedText(w, "Le concessioni", u => u.Concessions, plural: true)
|
||||
: Tiers.ConcessionsUnavailableText(w)),
|
||||
BuyConcessionCommand when !Tiers.ConcessionsAvailable =>
|
||||
Result(CommandError.NotImplemented, "Le concessioni non sono ancora disponibili"),
|
||||
_ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"),
|
||||
};
|
||||
}
|
||||
@@ -72,7 +80,7 @@ public static class CommandProcessor
|
||||
if (company.Receivership) return result(CommandError.NotAllowed, "In amministrazione controllata non si possono chiedere prestiti");
|
||||
var max = FinanceSystem.MaxLoan(w, company);
|
||||
if (company.Debt + c.Amount > max)
|
||||
return result(CommandError.CreditLimit, $"Fido insufficiente: disponibili {(max - company.Debt).ToString()}");
|
||||
return result(CommandError.CreditLimit, LoanLimitText(w, company, max));
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var loan = new Loan
|
||||
{
|
||||
@@ -85,7 +93,22 @@ public static class CommandProcessor
|
||||
};
|
||||
company.Loans.Add(loan);
|
||||
w.Money.Transfer(Account.External, Account.Of(company.Id), c.Amount, LedgerEntry.LoanTaken);
|
||||
return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni");
|
||||
var payment = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||||
return result(CommandError.None,
|
||||
$"Prestito di {c.Amount} al {FinanceOutlook.Percent(loan.AnnualRate)} fisso (base {FinanceOutlook.Percent(w.Difficulty.BaseInterestRate)} + rating {company.Rating}) " +
|
||||
$"per {loan.TermMonths / 12} anni: rata mensile {payment}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rifiuto per fido insufficiente: quanto resta disponibile e, se un livello successivo alza il
|
||||
/// fattore del fido, quale livello serve e a quanto porta il fido (ADR 0018).
|
||||
/// </summary>
|
||||
public static string LoanLimitText(World w, Company company, Money max)
|
||||
{
|
||||
string text = $"Fido insufficiente: disponibili {Money.Max(Money.Zero, max - company.Debt)} su {max}";
|
||||
var current = Tiers.Def(w, company.Tier);
|
||||
var next = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Level > current.Level && t.Unlocks.MaxLoanFactor > current.Unlocks.MaxLoanFactor);
|
||||
return next is null ? text : $"{text}; il livello {next.Level}, «{next.NameIt}», porta il fido a {Tiers.LoanLimit(company, next)}";
|
||||
}
|
||||
|
||||
private static CommandResult RepayLoan(World w, Company company, RepayLoanCommand c, Func<CommandError, string, CommandResult> result)
|
||||
@@ -94,10 +117,17 @@ public static class CommandProcessor
|
||||
if (loan is null) return result(CommandError.NotFound, "Prestito inesistente");
|
||||
if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido");
|
||||
var amount = Money.Min(c.Amount, loan.Remaining);
|
||||
if (company.Cash < amount) return result(CommandError.InsufficientFunds, "Cassa insufficiente");
|
||||
if (company.Cash < amount)
|
||||
return result(CommandError.InsufficientFunds, $"Cassa insufficiente: per rimborsare {amount} ci sono {Money.Max(Money.Zero, company.Cash)} in cassa");
|
||||
w.Money.Transfer(Account.Of(company.Id), Account.External, amount, LedgerEntry.LoanRepaid);
|
||||
loan.Remaining -= amount;
|
||||
if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan);
|
||||
return result(CommandError.None, $"Rimborsati {amount}");
|
||||
if (loan.Remaining.Cents <= 0)
|
||||
{
|
||||
company.Loans.Remove(loan);
|
||||
return result(CommandError.None, $"Rimborsati {amount}: prestito estinto");
|
||||
}
|
||||
// rimborso parziale: stessa durata e stesso tasso, la rata scende con il residuo
|
||||
return result(CommandError.None,
|
||||
$"Rimborsati {amount}: restano {loan.Remaining}, nuova rata mensile {FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft)}");
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public static class CorporateCommandHandlers
|
||||
{
|
||||
var sm = w.Data.Balance.StockMarket;
|
||||
if (company.IsPlayer && !company.Listed && !Tiers.Unlocks(w, company).Ipo)
|
||||
return reply(CommandError.TierLocked, "La quotazione si sblocca al livello «Grande compagnia»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "La quotazione in borsa", u => u.Ipo));
|
||||
// prima quotazione fino a ipoMaxShare; per chi è già quotato un aumento di capitale fino al flottante massimo
|
||||
double limit = company.Listed ? sm.SecondaryMaxFloat - (double)company.Shares.Public / company.Shares.Total : sm.IpoMaxShare;
|
||||
if (!(c.FloatShare > 0) || c.FloatShare > limit + 1e-9)
|
||||
@@ -137,7 +137,7 @@ public static class CorporateCommandHandlers
|
||||
if (target.Defunct) return reply(CommandError.NotAllowed, $"{target.Name} non è più attiva");
|
||||
|
||||
if (company.IsPlayer && !Tiers.Unlocks(w, company).HostileTakeover)
|
||||
return reply(CommandError.TierLocked, "Le scalate ostili si sbloccano al livello «Impero ferroviario»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "Le scalate ostili", u => u.HostileTakeover, plural: true));
|
||||
if (!target.Listed) return reply(CommandError.NotAllowed, $"{target.Name} non è quotata");
|
||||
if (target.IsPlayer && w.Difficulty.PlayerTakeover == TakeoverRule.Disabled)
|
||||
return reply(CommandError.NotAllowed, "Con questa difficoltà la compagnia del giocatore non è scalabile");
|
||||
|
||||
@@ -11,7 +11,7 @@ public static class IndustryCommandHandlers
|
||||
public static CommandResult BuyIndustry(World w, Company company, BuyIndustryCommand c, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Tiers.Unlocks(w, company).BuyIndustry)
|
||||
return reply(CommandError.TierLocked, "L'acquisto di industrie si sblocca al livello «Compagnia nazionale»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "L'acquisto di industrie", u => u.BuyIndustry));
|
||||
if (!TryIndustry(w, c.Industry, out var ind) || ind.Closed) return reply(CommandError.NotFound, "Industria inesistente");
|
||||
if (ind.Owner == company.Id) return reply(CommandError.NotAllowed, $"{ind.Name} è già della compagnia");
|
||||
if (ind.Owner.IsValid) return reply(CommandError.NotAllowed, $"{ind.Name} appartiene a {w.Company(ind.Owner).Name}");
|
||||
|
||||
@@ -23,11 +23,7 @@ public sealed class ConstructionSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>Squadre disponibili per una compagnia secondo il livello.</summary>
|
||||
public static int Crews(World w, Company c)
|
||||
{
|
||||
var byTier = w.Data.Construction.Crews.CrewsByTier;
|
||||
return byTier[Math.Clamp(c.Tier, 1, byTier.Length) - 1];
|
||||
}
|
||||
public static int Crews(World w, Company c) => Tiers.Crews(w, c.Tier);
|
||||
|
||||
private static void Projects(WorldContext ctx, World w)
|
||||
{
|
||||
|
||||
@@ -5,62 +5,133 @@ using RailEnterprise.Core.Economy;
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Finanza delle compagnie: giorni di cassa negativa e bancarotta, rate mensili dei prestiti,
|
||||
/// rating di credito, chiusura dei conti mensili e annuali (guida 6.3).
|
||||
/// Finanza delle compagnie (guida 6.3, ADR 0019): costi d'esercizio e salari del personale dei depositi
|
||||
/// ogni giorno, giorni di cassa negativa con avvisi e bancarotta, rate mensili dei prestiti, chiusura dei
|
||||
/// conti mensili e annuali (conto economico per voce), rating di credito dagli ultimi mesi chiusi.
|
||||
/// </summary>
|
||||
public sealed class FinanceSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Finance";
|
||||
|
||||
private double[] _running = [];
|
||||
private double[] _upkeep = [];
|
||||
private double[] _wages = [];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
PayRunningCosts(w);
|
||||
PayDepotWages(w);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (c.Defunct) continue;
|
||||
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
|
||||
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
|
||||
{
|
||||
c.Bankrupt = true;
|
||||
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
|
||||
$"{c.Name}: dichiarata la bancarotta dopo {c.NegativeCashDays} giorni di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
UpdateNegativeCash(ctx, c);
|
||||
}
|
||||
if (ctx.IsNewMonth && ctx.Day > 0)
|
||||
{
|
||||
UpdateBookValues(w);
|
||||
var closed = w.Calendar.DateOfDay(ctx.Day - 1);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (c.Merged) continue;
|
||||
if (!c.Bankrupt) PayLoans(w, c);
|
||||
c.Rating = ComputeRating(w, c);
|
||||
CloseMonth(w, c, closed.Year, closed.Month);
|
||||
UpdateRating(w, c);
|
||||
if (!c.Bankrupt) Tiers.Evaluate(ctx, c);
|
||||
// utile del mese chiuso nell'anello dei 12 mesi (borsa, 12.2); il nuovo mese parte senza dividendi
|
||||
c.ProfitRing[c.ProfitRingIndex] = Company.OperatingProfit(c.MonthEntries);
|
||||
c.ProfitRingIndex = (c.ProfitRingIndex + 1) % c.ProfitRing.Length;
|
||||
c.DividendRing[c.ProfitRingIndex] = 0;
|
||||
Array.Clear(c.MonthEntries);
|
||||
}
|
||||
}
|
||||
if (ctx.IsNewYear && ctx.Day > 0)
|
||||
{
|
||||
int year = w.Calendar.DateOfDay(ctx.Day - 1).Year;
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
Push(c.IncomeYears, new IncomeRecord { Year = year, Month = 0, Entries = (long[])c.YearEntries.Clone() }, w.Data.Balance.Finance.IncomeYears);
|
||||
Array.Copy(c.YearEntries, c.LastYearEntries, c.YearEntries.Length);
|
||||
Array.Clear(c.YearEntries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Costi d'esercizio giornalieri: veicoli posseduti, binari di stazione, depositi.</summary>
|
||||
/// <summary>
|
||||
/// Chiusura del mese: utile nell'anello dei 12 mesi della borsa (12.2) e movimenti per voce nel conto
|
||||
/// economico mensile (ADR 0019); il nuovo mese parte senza movimenti né dividendi.
|
||||
/// </summary>
|
||||
private static void CloseMonth(World w, Company c, int year, int month)
|
||||
{
|
||||
c.ProfitRing[c.ProfitRingIndex] = Company.OperatingProfit(c.MonthEntries);
|
||||
c.ProfitRingIndex = (c.ProfitRingIndex + 1) % c.ProfitRing.Length;
|
||||
c.DividendRing[c.ProfitRingIndex] = 0;
|
||||
Push(c.IncomeMonths, new IncomeRecord { Year = year, Month = month, Entries = (long[])c.MonthEntries.Clone() }, w.Data.Balance.Finance.IncomeMonths);
|
||||
Array.Clear(c.MonthEntries);
|
||||
}
|
||||
|
||||
private static void Push(List<IncomeRecord> list, IncomeRecord record, int capacity)
|
||||
{
|
||||
list.Add(record);
|
||||
if (list.Count > capacity) list.RemoveRange(0, list.Count - capacity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giorni di cassa negativa (guida 6.3): primo avviso dopo finance.negativeCashNoticeDays giorni di
|
||||
/// fila, poi quando mancano i giorni di finance.bankruptcyWarningDaysLeft; bancarotta al limite della
|
||||
/// difficoltà (difficulty.json, bankruptcyDays). Se la cassa torna positiva il conto alla rovescia si
|
||||
/// azzera, con un avviso solo se era durato almeno i giorni del primo avviso: una cassa che oscilla
|
||||
/// intorno a zero non riempie le notizie.
|
||||
/// </summary>
|
||||
private static void UpdateNegativeCash(WorldContext ctx, Company c)
|
||||
{
|
||||
var w = ctx.World;
|
||||
int notice = w.Data.Balance.Finance.NegativeCashNoticeDays;
|
||||
if (!c.Cash.IsNegative)
|
||||
{
|
||||
if (c.NegativeCashDays >= notice)
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Info,
|
||||
$"{c.Name}: la cassa torna positiva dopo {Days(c.NegativeCashDays)} di scoperto, il conto alla rovescia della bancarotta si azzera",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
c.NegativeCashDays = 0;
|
||||
return;
|
||||
}
|
||||
c.NegativeCashDays++;
|
||||
int left = w.Difficulty.BankruptcyDays - c.NegativeCashDays;
|
||||
if (left <= 0)
|
||||
{
|
||||
c.Bankrupt = true;
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
|
||||
$"{c.Name}: dichiarata la bancarotta dopo {Days(c.NegativeCashDays)} di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
|
||||
return;
|
||||
}
|
||||
var warnings = w.Data.Balance.Finance.BankruptcyWarningDaysLeft;
|
||||
if (c.NegativeCashDays == notice)
|
||||
{
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Warning,
|
||||
$"{c.Name}: cassa negativa da {Days(c.NegativeCashDays)} ({c.Cash}); se non torna sopra zero la bancarotta arriva tra {Days(left)}",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
else if (Array.IndexOf(warnings, left) >= 0)
|
||||
{
|
||||
var severity = left == warnings[^1] ? EventSeverity.Critical : EventSeverity.Warning;
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Finance, severity,
|
||||
$"{c.Name}: cassa negativa da {Days(c.NegativeCashDays)} ({c.Cash}), bancarotta tra {Days(left)}",
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
}
|
||||
|
||||
private static string Days(int n) => n == 1 ? "1 giorno" : $"{n} giorni";
|
||||
|
||||
/// <summary>
|
||||
/// Costi d'esercizio giornalieri: veicoli posseduti (voce «Esercizio dei treni») e binari di stazione
|
||||
/// e depositi (voce «Stazioni e depositi», ADR 0019).
|
||||
/// </summary>
|
||||
private void PayRunningCosts(World w)
|
||||
{
|
||||
if (_running.Length < w.Companies.Count) _running = new double[w.Companies.Count];
|
||||
if (_running.Length < w.Companies.Count)
|
||||
{
|
||||
_running = new double[w.Companies.Count];
|
||||
_upkeep = new double[w.Companies.Count];
|
||||
}
|
||||
Array.Clear(_running);
|
||||
Array.Clear(_upkeep);
|
||||
double days = w.Calendar.DaysPerYear;
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
@@ -70,61 +141,106 @@ public sealed class FinanceSystem : ISimSystem
|
||||
var sp = w.Data.Construction.Stations;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _running[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _upkeep[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
|
||||
}
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _running[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _upkeep[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
if (_running[i] <= 0 || w.Companies[i].Defunct) continue;
|
||||
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
|
||||
if (w.Companies[i].Defunct) continue;
|
||||
var account = Account.Of(w.Companies[i].Id);
|
||||
if (_running[i] > 0) w.Money.Transfer(account, Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
|
||||
if (_upkeep[i] > 0) w.Money.Transfer(account, Account.External, Money.FromCentsRounded(_upkeep[i]), LedgerEntry.StationUpkeep);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Salari giornalieri del personale presente nei depositi (operai e tecnici, sezione 9), alle paghe
|
||||
/// delle industrie (balance.json, industry.wagePerWorkerPerMonth e wagePerStaffPerMonth): la voce
|
||||
/// «Stipendi» della guida 6.3 (ADR 0019).
|
||||
/// </summary>
|
||||
private void PayDepotWages(World w)
|
||||
{
|
||||
if (_wages.Length < w.Companies.Count) _wages = new double[w.Companies.Count];
|
||||
Array.Clear(_wages);
|
||||
var ib = w.Data.Balance.Industry;
|
||||
double daysPerMonth = w.Calendar.DaysPerMonth;
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (!d.Owner.IsValid || d.Owner.Value >= _wages.Length || !w.Network.IsAlive(d)) continue;
|
||||
_wages[d.Owner.Value] += (d.WorkersPresent * ib.WagePerWorkerPerMonth + d.StaffPresent * ib.WagePerStaffPerMonth) / daysPerMonth;
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
if (_wages[i] <= 0 || w.Companies[i].Defunct) continue;
|
||||
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_wages[i]), LedgerEntry.Wages);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo,
|
||||
/// merce della compagnia (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016).
|
||||
/// industrie possedute (impianti e cassa dell'impresa, ADR 0018), merce della compagnia
|
||||
/// (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016). Scrive le voci in
|
||||
/// <see cref="Company.BookValues"/>: il patrimonio netto le somma.
|
||||
/// </summary>
|
||||
public static void UpdateBookValues(World w)
|
||||
{
|
||||
var values = BookValues(w);
|
||||
for (int i = 0; i < w.Companies.Count; i++) Array.Copy(values[i], w.Companies[i].BookValues, AssetCategories.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale degli attivi non monetari di ogni compagnia, per voce
|
||||
/// (<see cref="AssetCategory"/>), calcolato al giorno corrente. Unica fonte del valore contabile.
|
||||
/// </summary>
|
||||
public static long[][] BookValues(World w)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var values = new long[w.Companies.Count];
|
||||
var values = new long[w.Companies.Count][];
|
||||
for (int i = 0; i < values.Length; i++) values[i] = new long[AssetCategories.Count];
|
||||
const int track = (int)AssetCategory.Track, stations = (int)AssetCategory.Stations, vehicles = (int)AssetCategory.Vehicles,
|
||||
industries = (int)AssetCategory.Industries, goods = (int)AssetCategory.Goods;
|
||||
double daysPerYear = w.Calendar.DaysPerYear;
|
||||
long today = w.Clock.Day;
|
||||
foreach (var e in w.Network.Edges)
|
||||
{
|
||||
if (e.State == Rail.EdgeState.Demolished) continue;
|
||||
double age = (today - e.BuiltDay) / daysPerYear;
|
||||
values[e.Owner.Value] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
|
||||
values[e.Owner.Value][track] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
|
||||
}
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value] += s.BuildCostCents;
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value][stations] += s.BuildCostCents;
|
||||
}
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value] += d.BuildCostCents;
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value][stations] += d.BuildCostCents;
|
||||
}
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
if (v.Sold) continue;
|
||||
double age = (today - v.BoughtDay) / daysPerYear;
|
||||
values[v.Owner.Value] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
|
||||
values[v.Owner.Value][vehicles] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
|
||||
}
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || !ind.Owner.IsValid || ind.Owner.Value >= values.Length) continue;
|
||||
values[ind.Owner.Value][industries] += IndustryMath.BookValue(w, ind).Cents;
|
||||
}
|
||||
var prices = w.Market.GlobalPrice;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (!s.Owner.IsValid || s.Owner.Value >= values.Length) continue;
|
||||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value] += (long)(s.Stock[g] * prices[g]);
|
||||
values[s.Owner.Value] += OwnedGoodsValue(s.Waiting, prices);
|
||||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value][goods] += (long)(s.Stock[g] * prices[g]);
|
||||
values[s.Owner.Value][goods] += OwnedGoodsValue(s.Waiting, prices);
|
||||
}
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value] += OwnedGoodsValue(t.Cargo, prices);
|
||||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value][goods] += OwnedGoodsValue(t.Cargo, prices);
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
|
||||
return values;
|
||||
}
|
||||
|
||||
private static long OwnedGoodsValue(List<Rail.Packet> packets, double[] prices)
|
||||
@@ -170,35 +286,104 @@ public sealed class FinanceSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rating da margine operativo e leva: punteggio = pesoMargine·clamp(0,5 + margine) +
|
||||
/// pesoLeva·clamp(1 − debito/attivi), confrontato con le soglie di balance.json.
|
||||
/// Misure del rating (ADR 0019): margine = utile operativo / ricavi dei mesi chiusi conservati
|
||||
/// (finance.incomeMonths, 12), leva = debiti (prestiti e scoperto di cassa) / patrimonio netto
|
||||
/// (+∞ con patrimonio non positivo e debiti).
|
||||
/// Il margine è neutro (0) finché la finestra non è piena e ha meno di finance.ratingMinRevenueMonths
|
||||
/// mesi con ricavi: i primi incassi, piccoli rispetto ai costi dei mesi d'avvio, non fanno crollare il
|
||||
/// rating per poi farlo risalire il mese dopo. Con la finestra piena (o con abbastanza mesi di ricavi)
|
||||
/// conta il margine vero; senza ricavi e in perdita è il minimo (−100 %, componente nulla).
|
||||
/// </summary>
|
||||
public static CreditRating ComputeRating(World w, Company c)
|
||||
public static RatingMeasures Measures(World w, Company c)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
long[] entries = w.Clock.Day % w.Calendar.DaysPerYear < 90 ? c.LastYearEntries : c.YearEntries;
|
||||
long revenue = Company.Revenue(entries);
|
||||
long profit = Company.OperatingProfit(entries);
|
||||
double margin = revenue > 0 ? (double)profit / revenue : 0;
|
||||
double assets = Math.Max(1, c.Cash.Cents + c.AssetBookValue.Cents);
|
||||
double leverage = c.Debt.Cents / assets;
|
||||
double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + margin, 0, 1) + fb.LeverageWeight * Math.Clamp(1 - leverage, 0, 1);
|
||||
if (c.Bankrupt) return CreditRating.D;
|
||||
for (int i = 0; i < fb.RatingByScore.Length; i++)
|
||||
long revenue = 0, profit = 0;
|
||||
int revenueMonths = 0;
|
||||
foreach (var m in c.IncomeMonths)
|
||||
{
|
||||
if (score >= fb.RatingByScore[i]) return (CreditRating)i;
|
||||
long r = Company.Revenue(m.Entries);
|
||||
revenue += r;
|
||||
profit += Company.OperatingProfit(m.Entries);
|
||||
if (r > 0) revenueMonths++;
|
||||
}
|
||||
bool neutral = revenueMonths < fb.RatingMinRevenueMonths && c.IncomeMonths.Count < fb.IncomeMonths;
|
||||
double margin = neutral ? 0 : revenue > 0 ? (double)profit / revenue : profit < 0 ? -1 : 0;
|
||||
long debt = c.Debt.Cents + Math.Max(0, -c.Cash.Cents);
|
||||
long equity = c.NetWorth.Cents;
|
||||
double leverage = debt <= 0 ? 0 : equity <= 0 ? double.PositiveInfinity : (double)debt / equity;
|
||||
return new RatingMeasures(c.IncomeMonths.Count, revenueMonths, neutral, revenue, profit, margin, debt, equity, leverage);
|
||||
}
|
||||
|
||||
/// <summary>Componente del margine nel punteggio: clamp(0,5 + margine, 0, 1).</summary>
|
||||
public static double MarginComponent(double margin) => DMath.Clamp(0.5 + margin, 0, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Componente della leva nel punteggio: 1 / (1 + debiti/patrimonio), cioè patrimonio / (debiti +
|
||||
/// patrimonio): 1 senza debiti, 0 con patrimonio non positivo e debiti.
|
||||
/// </summary>
|
||||
public static double LeverageComponent(double leverage) =>
|
||||
double.IsPositiveInfinity(leverage) ? 0 : DMath.Clamp(1 / (1 + Math.Max(0, leverage)), 0, 1);
|
||||
|
||||
/// <summary>Punteggio del rating (0–1): pesoMargine·componente del margine + pesoLeva·componente della leva.</summary>
|
||||
public static double Score(World w, double margin, double leverage)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
return fb.ProfitMarginWeight * MarginComponent(margin) + fb.LeverageWeight * LeverageComponent(leverage);
|
||||
}
|
||||
|
||||
/// <summary>Rating di un punteggio con le soglie di balance.json (finance.ratingByScore, da AAA a C; sotto è D).</summary>
|
||||
public static CreditRating RatingOf(World w, double score)
|
||||
{
|
||||
var thresholds = w.Data.Balance.Finance.RatingByScore;
|
||||
for (int i = 0; i < thresholds.Length; i++)
|
||||
{
|
||||
if (score >= thresholds[i]) return (CreditRating)i;
|
||||
}
|
||||
return CreditRating.D;
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(World w, Company c)
|
||||
/// <summary>
|
||||
/// Rating di credito (guida 6.3) dalle due misure di <see cref="Measures"/> confrontate con le soglie;
|
||||
/// D per una compagnia in bancarotta. Non scrive nulla.
|
||||
/// </summary>
|
||||
public static CreditRating ComputeRating(World w, Company c)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1];
|
||||
return c.BaseCredit * tier.Unlocks.MaxLoanFactor;
|
||||
var m = Measures(w, c);
|
||||
return c.Bankrupt ? CreditRating.D : RatingOf(w, Score(w, m.Margin, m.Leverage));
|
||||
}
|
||||
|
||||
/// <summary>Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public static double LoanRate(World w, Company c) =>
|
||||
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[c.Rating.ToString()];
|
||||
/// <summary>
|
||||
/// Rating mensile, dopo la chiusura del mese: calcola il rating e conserva nella compagnia le misure
|
||||
/// usate (margine, leva, punteggio, mesi della finestra), così il quadro delle finanze lo spiega.
|
||||
/// </summary>
|
||||
public static void UpdateRating(World w, Company c)
|
||||
{
|
||||
var m = Measures(w, c);
|
||||
c.RatingMargin = m.Margin;
|
||||
c.RatingLeverage = m.Leverage;
|
||||
c.RatingScore = Score(w, m.Margin, m.Leverage);
|
||||
c.RatingMonths = m.Months;
|
||||
c.Rating = c.Bankrupt ? CreditRating.D : RatingOf(w, c.RatingScore);
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(World w, Company c) => Tiers.LoanLimit(c, Tiers.Def(w, c.Tier));
|
||||
|
||||
/// <summary>
|
||||
/// Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating attuale. Il tasso resta
|
||||
/// fisso per tutta la durata del prestito (ADR 0019).
|
||||
/// </summary>
|
||||
public static double LoanRate(World w, Company c) => LoanRate(w, c.Rating);
|
||||
|
||||
/// <summary>Tasso annuo di un nuovo prestito con il rating indicato.</summary>
|
||||
public static double LoanRate(World w, CreditRating rating) =>
|
||||
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[rating.ToString()];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Misure del rating (ADR 0019): mesi della finestra e quanti con ricavi, margine neutro (avvio), ricavi e
|
||||
/// utile operativo dei mesi, margine, debiti (prestiti e scoperto) e patrimonio netto in centesimi,
|
||||
/// leva = debiti / patrimonio.
|
||||
/// </summary>
|
||||
public readonly record struct RatingMeasures(int Months, int RevenueMonths, bool MarginNeutral, long Revenue, long Profit, double Margin,
|
||||
long Debt, long Equity, double Leverage);
|
||||
@@ -92,8 +92,22 @@ public static class IndustryMath
|
||||
public static Common.Money Valuation(World w, Industry ind)
|
||||
{
|
||||
var p = w.Data.Balance.IndustryMaintenance.Purchase;
|
||||
double plant = ind.Def.UpgradeCost * Math.Max(1, ind.Level) * p.AssetShare * (1 - p.ConditionWeight + p.ConditionWeight * ind.Condition / 100);
|
||||
double earnings = Math.Max(0, AnnualProfit(w, ind)) * p.EarningsMultiple;
|
||||
return Common.Money.FromCentsRounded(plant + earnings + Math.Max(0, ind.Cash.Cents));
|
||||
return Common.Money.FromCentsRounded(PlantValue(w, ind, Math.Max(1, ind.Level)) + earnings + Math.Max(0, ind.Cash.Cents));
|
||||
}
|
||||
|
||||
/// <summary>Valore degli impianti: costo d'ammodernamento × livello × quota, secondo le condizioni.</summary>
|
||||
public static double PlantValue(World w, Industry ind, int level)
|
||||
{
|
||||
var p = w.Data.Balance.IndustryMaintenance.Purchase;
|
||||
return ind.Def.UpgradeCost * level * p.AssetShare * (1 - p.ConditionWeight + p.ConditionWeight * ind.Condition / 100);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile di un'industria per il proprietario (ADR 0018): il prezzo d'acquisto senza
|
||||
/// l'avviamento (multiplo degli utili), cioè impianti più cassa dell'impresa. Gli impianti contano
|
||||
/// al livello attuale: un'industria inattiva (livello 0), che non si può vendere, vale solo la sua cassa.
|
||||
/// </summary>
|
||||
public static Common.Money BookValue(World w, Industry ind) =>
|
||||
Common.Money.FromCentsRounded(PlantValue(w, ind, ind.Level) + Math.Max(0, ind.Cash.Cents));
|
||||
}
|
||||
@@ -362,8 +362,8 @@ public sealed class StockMarketSystem : ISimSystem
|
||||
Corporate.AddYear(w, c, Corporate.Snapshot(w, c, w.Clock.Year - 1, c.LastYearEntries));
|
||||
|
||||
/// <summary>
|
||||
/// Nuovi concorrenti (12.1): se una compagnia supera la soglia di concentrazione dei ricavi
|
||||
/// dell'anno, entra una nuova IA (al massimo una ogni pochi anni e fino al numero massimo).
|
||||
/// Nuovi concorrenti (12.1): se una compagnia supera la soglia di concentrazione dei ricavi dei
|
||||
/// trasporti dell'anno (<see cref="Company.TransportRevenue"/>), entra una nuova IA (al massimo una ogni pochi anni e fino al numero massimo).
|
||||
/// </summary>
|
||||
private static void NewCompetitors(WorldContext ctx)
|
||||
{
|
||||
@@ -377,7 +377,7 @@ public sealed class StockMarketSystem : ISimSystem
|
||||
{
|
||||
if (c.Defunct) continue;
|
||||
active++;
|
||||
long r = Company.Revenue(c.LastYearEntries);
|
||||
long r = Company.TransportRevenue(c.LastYearEntries);
|
||||
total += r;
|
||||
if (r > best)
|
||||
{
|
||||
@@ -414,7 +414,7 @@ public static class Dividends
|
||||
long held = shares.ByCompany[i];
|
||||
if (held <= 0 || i == payer.Id.Value) continue;
|
||||
var amount = Money.FromCentsRounded(held * perShare);
|
||||
w.Money.Transfer(Account.Of(payer.Id), Account.Of(new CompanyId(i)), amount, LedgerEntry.Dividends);
|
||||
w.Money.Transfer(Account.Of(payer.Id), Account.Of(new CompanyId(i)), amount, LedgerEntry.Dividends, LedgerEntry.DividendsReceived);
|
||||
paid += amount.Cents;
|
||||
}
|
||||
var rest = new Money(total.Cents - paid);
|
||||
|
||||
@@ -4,16 +4,36 @@ using RailEnterprise.Core.Economy;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Sblocco di un livello (ADR 0018): tipo e valore (fido in centesimi, numero di squadre).</summary>
|
||||
public enum UnlockKind : byte
|
||||
{
|
||||
/// <summary>Fido massimo (valore: centesimi per la compagnia).</summary>
|
||||
LoanLimit = 0,
|
||||
/// <summary>Squadre di cantiere (valore: numero).</summary>
|
||||
Crews = 1,
|
||||
Trading = 2,
|
||||
BuyIndustry = 3,
|
||||
Ipo = 4,
|
||||
HostileTakeover = 5,
|
||||
Concessions = 6,
|
||||
}
|
||||
|
||||
public readonly record struct TierUnlock(UnlockKind Kind, long Value);
|
||||
|
||||
/// <summary>
|
||||
/// Livelli della compagnia (tiers.json): ogni mese, dopo il rating, una compagnia che soddisfa i
|
||||
/// requisiti del livello successivo (patrimonio netto, città collegate sopra una popolazione,
|
||||
/// rating) sale di un livello. Il livello non scende: gli sblocchi restano acquisiti (ADR 0011).
|
||||
/// Al passaggio la notizia elenca gli sblocchi ottenuti (ADR 0018).
|
||||
/// </summary>
|
||||
public static class Tiers
|
||||
{
|
||||
/// <summary>Definizione del livello indicato (limitato tra 1 e l'ultimo).</summary>
|
||||
public static TierDef Def(World w, int level) =>
|
||||
w.Data.Tiers.Tiers[Math.Clamp(level, 1, w.Data.Tiers.Tiers.Count) - 1];
|
||||
|
||||
/// <summary>Sblocchi del livello attuale della compagnia.</summary>
|
||||
public static TierUnlocks Unlocks(World w, Company c) =>
|
||||
w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1].Unlocks;
|
||||
public static TierUnlocks Unlocks(World w, Company c) => Def(w, c.Tier).Unlocks;
|
||||
|
||||
/// <summary>Promuove la compagnia se soddisfa i requisiti del livello successivo.</summary>
|
||||
public static void Evaluate(WorldContext ctx, Company c)
|
||||
@@ -24,12 +44,102 @@ public static class Tiers
|
||||
{
|
||||
var next = tiers[c.Tier];
|
||||
c.Tier = next.Level;
|
||||
c.TierReachedDay[next.Level - 1] = ctx.Day;
|
||||
Corporate.Milestone(w, c, $"diventa «{next.NameIt}»");
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
|
||||
$"{c.Name} diventa «{next.NameIt}» (livello {next.Level})", EntityKind.Company, c.Id.Value, c.Id));
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity, PromotionText(w, c, next.Level),
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Testo della notizia di promozione con gli sblocchi ottenuti.</summary>
|
||||
public static string PromotionText(World w, Company c, int level)
|
||||
{
|
||||
var def = Def(w, level);
|
||||
var unlocks = NewUnlocks(w, c, level);
|
||||
string text = $"{c.Name} diventa «{def.NameIt}» (livello {def.Level})";
|
||||
return unlocks.Count == 0 ? text : $"{text}: sblocca {string.Join(", ", unlocks.Select(UnlockLabel))}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sblocchi che il livello aggiunge al precedente, nell'ordine di <see cref="UnlockKind"/>: per il
|
||||
/// primo livello la dotazione di partenza (fido e squadre). Tutto viene da tiers.json e dalle
|
||||
/// squadre di construction.json; il fido è quello della compagnia (fido iniziale × fattore).
|
||||
/// </summary>
|
||||
public static List<TierUnlock> NewUnlocks(World w, Company c, int level)
|
||||
{
|
||||
var def = Def(w, level);
|
||||
var u = def.Unlocks;
|
||||
var prev = def.Level > 1 ? Def(w, def.Level - 1) : null;
|
||||
var p = prev?.Unlocks;
|
||||
var list = new List<TierUnlock>();
|
||||
if (p is null || u.MaxLoanFactor > p.MaxLoanFactor) list.Add(new TierUnlock(UnlockKind.LoanLimit, LoanLimit(c, def).Cents));
|
||||
int crews = Crews(w, def.Level);
|
||||
if (prev is null || crews > Crews(w, prev.Level)) list.Add(new TierUnlock(UnlockKind.Crews, crews));
|
||||
if (u.Trading && p?.Trading != true) list.Add(new TierUnlock(UnlockKind.Trading, 0));
|
||||
if (u.BuyIndustry && p?.BuyIndustry != true) list.Add(new TierUnlock(UnlockKind.BuyIndustry, 0));
|
||||
if (u.Ipo && p?.Ipo != true) list.Add(new TierUnlock(UnlockKind.Ipo, 0));
|
||||
if (u.HostileTakeover && p?.HostileTakeover != true) list.Add(new TierUnlock(UnlockKind.HostileTakeover, 0));
|
||||
// le concessioni non si annunciano finché il comando non esiste (F7): il livello le sblocca, ma non funzionerebbero
|
||||
if (ConcessionsAvailable && u.Concessions && p?.Concessions != true) list.Add(new TierUnlock(UnlockKind.Concessions, 0));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Vero quando le concessioni (BuyConcession) saranno implementate: fino alla F7 il comando risponde
|
||||
/// «non ancora disponibili», quindi non compaiono tra gli sblocchi né nelle notizie.
|
||||
/// </summary>
|
||||
public static bool ConcessionsAvailable => false;
|
||||
|
||||
/// <summary>
|
||||
/// Rifiuto delle concessioni finché non sono implementate: prima del livello che le sblocca
|
||||
/// (TierLocked) dice anche quale livello servirà.
|
||||
/// </summary>
|
||||
public static string ConcessionsUnavailableText(World w)
|
||||
{
|
||||
const string text = "Le concessioni non sono ancora disponibili";
|
||||
var tier = FirstUnlocking(w, u => u.Concessions);
|
||||
return tier is null ? text : $"{text}: si sbloccheranno al livello {tier.Level}, «{tier.NameIt}»";
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia a un livello: fido iniziale × fattore del livello.</summary>
|
||||
public static Money LoanLimit(Company c, TierDef def) => c.BaseCredit * def.Unlocks.MaxLoanFactor;
|
||||
|
||||
/// <summary>Squadre di cantiere a un livello (construction.json, le stesse di ConstructionSystem).</summary>
|
||||
public static int Crews(World w, int level)
|
||||
{
|
||||
var byTier = w.Data.Construction.Crews.CrewsByTier;
|
||||
return byTier[Math.Clamp(level, 1, byTier.Length) - 1];
|
||||
}
|
||||
|
||||
/// <summary>Etichetta italiana di uno sblocco (per le notizie del motore).</summary>
|
||||
public static string UnlockLabel(TierUnlock u) => u.Kind switch
|
||||
{
|
||||
UnlockKind.LoanLimit => $"fido fino a {new Money(u.Value).ToString("short")}",
|
||||
UnlockKind.Crews => $"{u.Value} squadre di cantiere",
|
||||
UnlockKind.Trading => "compravendita in proprio",
|
||||
UnlockKind.BuyIndustry => "acquisto di industrie",
|
||||
UnlockKind.Ipo => "quotazione in borsa",
|
||||
UnlockKind.HostileTakeover => "scalate ostili",
|
||||
UnlockKind.Concessions => "concessioni",
|
||||
_ => u.Kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Primo livello di tiers.json che ha lo sblocco indicato (null se nessuno).</summary>
|
||||
public static TierDef? FirstUnlocking(World w, Func<TierUnlocks, bool> unlock) =>
|
||||
w.Data.Tiers.Tiers.FirstOrDefault(t => unlock(t.Unlocks));
|
||||
|
||||
/// <summary>
|
||||
/// Testo di rifiuto per una funzione bloccata dal livello: «{funzione} si sblocca al livello N,
|
||||
/// «nome»» dai dati, oppure «{funzione} non è disponibile» se nessun livello la sblocca.
|
||||
/// </summary>
|
||||
public static string LockedText(World w, string feature, Func<TierUnlocks, bool> unlock, bool plural = false)
|
||||
{
|
||||
var tier = FirstUnlocking(w, unlock);
|
||||
return tier is null
|
||||
? $"{feature} {(plural ? "non sono disponibili" : "non è disponibile")}"
|
||||
: $"{feature} {(plural ? "si sbloccano" : "si sblocca")} al livello {tier.Level}, «{tier.NameIt}»";
|
||||
}
|
||||
|
||||
/// <summary>Requisiti di un livello soddisfatti dalla compagnia.</summary>
|
||||
public static bool Meets(World w, Company c, TierRequirements req) =>
|
||||
c.NetWorth.Cents >= req.NetWorth
|
||||
|
||||
@@ -81,7 +81,10 @@ public static class TradingCommandHandlers
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ImportedThisMonth[good] += p.Units;
|
||||
w.Goods.Imported[good] += p.Units;
|
||||
w.Money.Transfer(from, Account.External, amount, LedgerEntry.Trading);
|
||||
// il prezzo d'importazione è Pg × (1 + dazio): il dazio va sulla sua voce (ADR 0019)
|
||||
var duty = Money.FromCentsRounded(p.Cents * hub.Duty / (1 + hub.Duty));
|
||||
w.Money.Transfer(from, Account.External, amount - duty, LedgerEntry.Trading);
|
||||
w.Money.Transfer(from, Account.External, duty, LedgerEntry.Duties);
|
||||
}
|
||||
}
|
||||
TradingMath.AddToWarehouse(s, good, bought, w.Data.GoodCount);
|
||||
@@ -143,7 +146,10 @@ public static class TradingCommandHandlers
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ExportedThisMonth[good] += p.Units;
|
||||
w.Goods.Exported[good] += p.Units;
|
||||
w.Money.Transfer(Account.External, to, amount, LedgerEntry.Trading);
|
||||
// il prezzo d'esportazione è Pg × (1 − dazio): si incassa il valore a Pg e si paga il dazio (ADR 0019)
|
||||
var duty = Money.FromCentsRounded(p.Cents * hub.Duty / (1 - hub.Duty));
|
||||
w.Money.Transfer(Account.External, to, amount + duty, LedgerEntry.Trading);
|
||||
w.Money.Transfer(to, Account.External, duty, LedgerEntry.Duties);
|
||||
}
|
||||
}
|
||||
s.Stock[good] -= sold;
|
||||
@@ -203,7 +209,7 @@ public static class TradingCommandHandlers
|
||||
|
||||
/// <summary>
|
||||
/// Costo di giacenza mensile (trading.storageCostPerUnitPerMonth) per ogni unità nei magazzini
|
||||
/// delle stazioni, addebitato alla compagnia proprietaria sulla voce «Commercio».
|
||||
/// delle stazioni, addebitato alla compagnia proprietaria sulla voce «Magazzini» (ADR 0019).
|
||||
/// </summary>
|
||||
public static void ChargeStorage(World w)
|
||||
{
|
||||
@@ -213,7 +219,7 @@ public static class TradingCommandHandlers
|
||||
{
|
||||
int units = s.StockTotal;
|
||||
if (units <= 0 || !s.Owner.IsValid || s.Owner.Value >= w.Companies.Count) continue;
|
||||
w.Money.Transfer(Account.Of(s.Owner), Account.External, new Money(perUnit * units), LedgerEntry.Trading);
|
||||
w.Money.Transfer(Account.Of(s.Owner), Account.External, new Money(perUnit * units), LedgerEntry.Storage);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,10 +236,7 @@ public static class TradingCommandHandlers
|
||||
s = null!;
|
||||
if (needsUnlock && !Tiers.Unlocks(w, company).Trading)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.Trading);
|
||||
error = (CommandError.TierLocked, tier is null
|
||||
? "La compravendita in proprio non è disponibile"
|
||||
: $"La compravendita in proprio si sblocca al livello «{tier.NameIt}»");
|
||||
error = (CommandError.TierLocked, Tiers.LockedText(w, "La compravendita in proprio", u => u.Trading));
|
||||
return false;
|
||||
}
|
||||
if (!TryOwnStation(w, company, station, out s, out error)) return false;
|
||||
|
||||
@@ -50,6 +50,12 @@ public sealed class ClientWorld(GameData data)
|
||||
/// <summary>Quadro del mercato globale (F6), su richiesta.</summary>
|
||||
public MarketReport? Market { get; private set; }
|
||||
|
||||
/// <summary>Quadro della scalata (F6), su richiesta: lo usano il pannello «La tua scalata» e la barra superiore.</summary>
|
||||
public ClimbReport? Climb { get; private set; }
|
||||
|
||||
/// <summary>Quadro delle finanze (F6), su richiesta: lo usa il pannello «Finanze».</summary>
|
||||
public FinanceReport? Finance { get; private set; }
|
||||
|
||||
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
|
||||
public int TapeVersion { get; private set; }
|
||||
|
||||
@@ -134,6 +140,14 @@ public sealed class ClientWorld(GameData data)
|
||||
Market = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case ClimbReport m:
|
||||
Climb = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case FinanceReport m:
|
||||
Finance = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case MaintenanceAlert m:
|
||||
Alerts.Insert(0, m);
|
||||
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
|
||||
@@ -154,6 +168,8 @@ public sealed class ClientWorld(GameData data)
|
||||
IndustryCards.Clear();
|
||||
Chronicle = null;
|
||||
Market = null;
|
||||
Climb = null;
|
||||
Finance = null;
|
||||
Alerts.Clear();
|
||||
Summary = m.Summary;
|
||||
SessionId = m.SessionId;
|
||||
|
||||
@@ -43,6 +43,10 @@ public enum MessageId : ushort
|
||||
Notification = 131,
|
||||
Newspaper = 132,
|
||||
SaveList = 133,
|
||||
/// <summary>Quadro della scalata: livelli, sblocchi, requisiti, stato patrimoniale (F6).</summary>
|
||||
ClimbReport = 134,
|
||||
/// <summary>Quadro delle finanze: conto economico per voce, rating spiegato, prestiti, bancarotta (F6).</summary>
|
||||
FinanceReport = 135,
|
||||
}
|
||||
|
||||
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
|
||||
|
||||
@@ -239,6 +239,10 @@ public enum DetailKind : byte
|
||||
Chronicle = 6,
|
||||
/// <summary>Quadro del mercato globale (risposta MarketReport, F6; Id ignorato).</summary>
|
||||
Market = 7,
|
||||
/// <summary>Quadro della scalata (risposta ClimbReport, F6; Id ignorato).</summary>
|
||||
Climb = 8,
|
||||
/// <summary>Quadro delle finanze (risposta FinanceReport, F6; Id ignorato).</summary>
|
||||
Finance = 9,
|
||||
}
|
||||
|
||||
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
|
||||
namespace RailEnterprise.Protocol.Messages;
|
||||
|
||||
// Messaggi della fase F6: pannello «La tua scalata» (immagine di riferimento 08). Il quadro arriva su
|
||||
// richiesta (RequestDetail con DetailKind.Climb) ed è calcolato dal server con ClimbOutlook (ADR 0018):
|
||||
// il client lo mostra com'è, senza logica di gioco.
|
||||
|
||||
/// <summary>Sblocco di un livello: Kind come UnlockKind del Core (0 fido, 1 squadre, 2 compravendita, 3 acquisto di industrie, 4 quotazione, 5 scalate ostili, 6 concessioni).</summary>
|
||||
public sealed class UnlockInfo
|
||||
{
|
||||
public const byte LoanLimit = 0, Crews = 1, Trading = 2, BuyIndustry = 3, Ipo = 4, HostileTakeover = 5, Concessions = 6;
|
||||
|
||||
public byte Kind { get; init; }
|
||||
/// <summary>Fido in centesimi (LoanLimit) o numero di squadre (Crews); 0 per gli altri.</summary>
|
||||
public long Value { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.I64(Value);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static UnlockInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new UnlockInfo { Kind = r.U8(), Value = r.I64() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Livello di tiers.json visto dalla compagnia: requisiti, raggiunto e quando, sblocchi che aggiunge.</summary>
|
||||
public sealed class TierInfo
|
||||
{
|
||||
public byte Level { get; init; }
|
||||
public string NameIt { get; init; } = "";
|
||||
public string NameEn { get; init; } = "";
|
||||
public Money NetWorthRequired { get; init; }
|
||||
public int TownsRequired { get; init; }
|
||||
public int TownPopulation { get; init; }
|
||||
public string RatingRequired { get; init; } = "";
|
||||
public bool Reached { get; init; }
|
||||
/// <summary>Giorno in cui è stato raggiunto (fondazione per il livello 1; −1 se non raggiunto o sconosciuto).</summary>
|
||||
public long ReachedDay { get; init; } = -1;
|
||||
public List<UnlockInfo> Unlocks { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Level); w.String(NameIt); w.String(NameEn); w.Money(NetWorthRequired); w.I32(TownsRequired); w.I32(TownPopulation);
|
||||
w.String(RatingRequired); w.Bool(Reached); w.I64(ReachedDay);
|
||||
w.Count(Unlocks.Count);
|
||||
foreach (var u in Unlocks) u.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static TierInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new TierInfo
|
||||
{
|
||||
Level = r.U8(), NameIt = r.String(), NameEn = r.String(), NetWorthRequired = r.Money(), TownsRequired = r.I32(), TownPopulation = r.I32(),
|
||||
RatingRequired = r.String(), Reached = r.Bool(), ReachedDay = r.I64(),
|
||||
};
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Unlocks.Add(UnlockInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Voce dello stato patrimoniale o del conto economico: Kind secondo la tabella del messaggio, valore con segno.</summary>
|
||||
public sealed class AmountInfo
|
||||
{
|
||||
public byte Kind { get; init; }
|
||||
public Money Value { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.Money(Value);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static AmountInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new AmountInfo { Kind = r.U8(), Value = r.Money() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prestito in corso: residuo, tasso annuo, mesi restanti.</summary>
|
||||
public sealed class LoanInfo
|
||||
{
|
||||
public int Loan { get; init; }
|
||||
public Money Remaining { get; init; }
|
||||
public float AnnualRate { get; init; }
|
||||
public int MonthsLeft { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Loan); w.Money(Remaining); w.F32(AnnualRate); w.I32(MonthsLeft);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static LoanInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new LoanInfo { Loan = r.I32(), Remaining = r.Money(), AnnualRate = r.F32(), MonthsLeft = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Patrimonio netto a un giorno della partita.</summary>
|
||||
public sealed class NetWorthPointInfo
|
||||
{
|
||||
public long Day { get; init; }
|
||||
public Money Value { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.Money(Value);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static NetWorthPointInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new NetWorthPointInfo { Day = r.I64(), Value = r.Money() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro della scalata per la compagnia della sessione (F6, ADR 0018): livelli con requisiti e
|
||||
/// sblocchi, requisiti del prossimo livello con l'avanzamento, stato patrimoniale per voce (somma al
|
||||
/// patrimonio netto del motore), conto economico, prestiti e storico del patrimonio netto.
|
||||
/// </summary>
|
||||
public sealed class ClimbReport : IMessage
|
||||
{
|
||||
/// <summary>Voci degli attivi (Assets[].Kind), come AssetCategory del Core.</summary>
|
||||
public const byte AssetTrack = 0, AssetStations = 1, AssetVehicles = 2, AssetIndustries = 3, AssetGoods = 4;
|
||||
/// <summary>Righe del conto economico (Income[].Kind), come IncomeLineKind del Core.</summary>
|
||||
public const byte IncomeFares = 0, IncomeOther = 1, IncomeOperating = 2, IncomeMaintenance = 3, IncomeInterest = 4;
|
||||
|
||||
public MessageId Id => MessageId.ClimbReport;
|
||||
public long Day { get; init; }
|
||||
public int Company { get; init; }
|
||||
public long FoundedDay { get; init; }
|
||||
public Money InitialCapital { get; init; }
|
||||
public byte Tier { get; init; }
|
||||
/// <summary>Livello successivo (0 all'ultimo livello: i requisiti che seguono sono vuoti).</summary>
|
||||
public byte NextTier { get; init; }
|
||||
public List<TierInfo> Tiers { get; init; } = [];
|
||||
|
||||
/// <summary>Requisiti del livello successivo: valore attuale, soglia, frazione (0–1) e se è soddisfatto.</summary>
|
||||
public Money NetWorth { get; init; }
|
||||
public Money NetWorthRequired { get; init; }
|
||||
public float NetWorthFraction { get; init; }
|
||||
public bool NetWorthMet { get; init; }
|
||||
public int Towns { get; init; }
|
||||
public int TownsRequired { get; init; }
|
||||
public int TownPopulation { get; init; }
|
||||
public float TownsFraction { get; init; }
|
||||
public bool TownsMet { get; init; }
|
||||
public string Rating { get; init; } = "";
|
||||
public string RatingRequired { get; init; } = "";
|
||||
public float RatingFraction { get; init; }
|
||||
public bool RatingMet { get; init; }
|
||||
/// <summary>Avanzamento complessivo verso il livello successivo (media delle tre frazioni).</summary>
|
||||
public float Progress { get; init; }
|
||||
|
||||
/// <summary>Stato patrimoniale: attivi per voce, partecipazioni, cassa; prestiti (tasso medio), scoperto.</summary>
|
||||
public List<AmountInfo> Assets { get; init; } = [];
|
||||
public Money Portfolio { get; init; }
|
||||
public Money Cash { get; init; }
|
||||
public Money TotalAssets { get; init; }
|
||||
public Money Loans { get; init; }
|
||||
public float LoansRate { get; init; }
|
||||
public Money Overdraft { get; init; }
|
||||
public Money TotalLiabilities { get; init; }
|
||||
public Money BalanceNetWorth { get; init; }
|
||||
|
||||
/// <summary>Conto economico dell'anno indicato (Partial se è l'anno in corso fino a oggi).</summary>
|
||||
public int IncomeYear { get; init; }
|
||||
public bool IncomePartial { get; init; }
|
||||
public List<AmountInfo> Income { get; init; } = [];
|
||||
public Money Profit { get; init; }
|
||||
|
||||
public List<LoanInfo> LoanList { get; init; } = [];
|
||||
public Money MaxLoan { get; init; }
|
||||
public Money LoanAvailable { get; init; }
|
||||
public float NewLoanRate { get; init; }
|
||||
public bool LoansAllowed { get; init; } = true;
|
||||
|
||||
public List<NetWorthPointInfo> History { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.I32(Company); w.I64(FoundedDay); w.Money(InitialCapital); w.U8(Tier); w.U8(NextTier);
|
||||
w.Count(Tiers.Count);
|
||||
foreach (var t in Tiers) t.Write(ref w);
|
||||
w.Money(NetWorth); w.Money(NetWorthRequired); w.F32(NetWorthFraction); w.Bool(NetWorthMet);
|
||||
w.I32(Towns); w.I32(TownsRequired); w.I32(TownPopulation); w.F32(TownsFraction); w.Bool(TownsMet);
|
||||
w.String(Rating); w.String(RatingRequired); w.F32(RatingFraction); w.Bool(RatingMet); w.F32(Progress);
|
||||
w.Count(Assets.Count);
|
||||
foreach (var a in Assets) a.Write(ref w);
|
||||
w.Money(Portfolio); w.Money(Cash); w.Money(TotalAssets); w.Money(Loans); w.F32(LoansRate); w.Money(Overdraft);
|
||||
w.Money(TotalLiabilities); w.Money(BalanceNetWorth);
|
||||
w.I32(IncomeYear); w.Bool(IncomePartial);
|
||||
w.Count(Income.Count);
|
||||
foreach (var i in Income) i.Write(ref w);
|
||||
w.Money(Profit);
|
||||
w.Count(LoanList.Count);
|
||||
foreach (var l in LoanList) l.Write(ref w);
|
||||
w.Money(MaxLoan); w.Money(LoanAvailable); w.F32(NewLoanRate); w.Bool(LoansAllowed);
|
||||
w.Count(History.Count);
|
||||
foreach (var p in History) p.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ClimbReport Read(ref SpanReader r)
|
||||
{
|
||||
long day = r.I64();
|
||||
int company = r.I32();
|
||||
long founded = r.I64();
|
||||
var capital = r.Money();
|
||||
byte tier = r.U8(), next = r.U8();
|
||||
var tiers = new List<TierInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) tiers.Add(TierInfo.Read(ref r));
|
||||
var worth = r.Money();
|
||||
var worthRequired = r.Money();
|
||||
float worthFraction = r.F32();
|
||||
bool worthMet = r.Bool();
|
||||
int towns = r.I32(), townsRequired = r.I32(), townPopulation = r.I32();
|
||||
float townsFraction = r.F32();
|
||||
bool townsMet = r.Bool();
|
||||
string rating = r.String(), ratingRequired = r.String();
|
||||
float ratingFraction = r.F32();
|
||||
bool ratingMet = r.Bool();
|
||||
float progress = r.F32();
|
||||
var assets = new List<AmountInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) assets.Add(AmountInfo.Read(ref r));
|
||||
var portfolio = r.Money();
|
||||
var cash = r.Money();
|
||||
var totalAssets = r.Money();
|
||||
var loans = r.Money();
|
||||
float loansRate = r.F32();
|
||||
var overdraft = r.Money();
|
||||
var totalLiabilities = r.Money();
|
||||
var balanceWorth = r.Money();
|
||||
int incomeYear = r.I32();
|
||||
bool partial = r.Bool();
|
||||
var income = new List<AmountInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) income.Add(AmountInfo.Read(ref r));
|
||||
var profit = r.Money();
|
||||
var loanList = new List<LoanInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) loanList.Add(LoanInfo.Read(ref r));
|
||||
var maxLoan = r.Money();
|
||||
var available = r.Money();
|
||||
float newRate = r.F32();
|
||||
bool allowed = r.Bool();
|
||||
var history = new List<NetWorthPointInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) history.Add(NetWorthPointInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return new ClimbReport
|
||||
{
|
||||
Day = day, Company = company, FoundedDay = founded, InitialCapital = capital, Tier = tier, NextTier = next, Tiers = tiers,
|
||||
NetWorth = worth, NetWorthRequired = worthRequired, NetWorthFraction = worthFraction, NetWorthMet = worthMet,
|
||||
Towns = towns, TownsRequired = townsRequired, TownPopulation = townPopulation, TownsFraction = townsFraction, TownsMet = townsMet,
|
||||
Rating = rating, RatingRequired = ratingRequired, RatingFraction = ratingFraction, RatingMet = ratingMet, Progress = progress,
|
||||
Assets = assets, Portfolio = portfolio, Cash = cash, TotalAssets = totalAssets, Loans = loans, LoansRate = loansRate,
|
||||
Overdraft = overdraft, TotalLiabilities = totalLiabilities, BalanceNetWorth = balanceWorth,
|
||||
IncomeYear = incomeYear, IncomePartial = partial, Income = income, Profit = profit,
|
||||
LoanList = loanList, MaxLoan = maxLoan, LoanAvailable = available, NewLoanRate = newRate, LoansAllowed = allowed,
|
||||
History = history,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
|
||||
namespace RailEnterprise.Protocol.Messages;
|
||||
|
||||
// Messaggi della fase F6: pannello «Finanze» definitivo. Il quadro arriva su richiesta (RequestDetail con
|
||||
// DetailKind.Finance) ed è calcolato dal server con FinanceOutlook (ADR 0019): il client lo mostra com'è,
|
||||
// senza calcolare utili, rating o rate.
|
||||
|
||||
/// <summary>Voce del conto economico in ordine di presentazione: Kind come LedgerEntry del Core, Section 0 ricavi, 1 costi, 2 investimenti e finanziamenti.</summary>
|
||||
public sealed class FinanceLineInfo
|
||||
{
|
||||
public const byte SectionRevenue = 0, SectionCost = 1, SectionCapital = 2;
|
||||
|
||||
public byte Kind { get; init; }
|
||||
public byte Section { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.U8(Section);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static FinanceLineInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new FinanceLineInfo { Kind = r.U8(), Section = r.U8() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Colonna del conto economico: Kind 0 mese in corso, 1 mese chiuso, 2 anno in corso, 3 anno chiuso;
|
||||
/// Month 1–12 (0 per gli anni); Values con le sole voci diverse da zero (Kind = LedgerEntry); utile
|
||||
/// operativo e flusso di cassa del motore.
|
||||
/// </summary>
|
||||
public sealed class IncomeColumnInfo
|
||||
{
|
||||
public const byte CurrentMonth = 0, ClosedMonth = 1, CurrentYear = 2, ClosedYear = 3;
|
||||
|
||||
public byte Kind { get; init; }
|
||||
public int Year { get; init; }
|
||||
public byte Month { get; init; }
|
||||
public List<AmountInfo> Values { get; init; } = [];
|
||||
public Money Profit { get; init; }
|
||||
public Money CashFlow { get; init; }
|
||||
|
||||
/// <summary>Valore di una voce (zero se assente).</summary>
|
||||
public Money Value(byte entry)
|
||||
{
|
||||
foreach (var v in Values)
|
||||
{
|
||||
if (v.Kind == entry) return v.Value;
|
||||
}
|
||||
return Money.Zero;
|
||||
}
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.I32(Year); w.U8(Month);
|
||||
w.Count(Values.Count);
|
||||
foreach (var v in Values) v.Write(ref w);
|
||||
w.Money(Profit); w.Money(CashFlow);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static IncomeColumnInfo Read(ref SpanReader r)
|
||||
{
|
||||
byte kind = r.U8();
|
||||
int year = r.I32();
|
||||
byte month = r.U8();
|
||||
var values = new List<AmountInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) values.Add(AmountInfo.Read(ref r));
|
||||
var m = new IncomeColumnInfo { Kind = kind, Year = year, Month = month, Values = values, Profit = r.Money(), CashFlow = r.Money() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Soglia di un rating: punteggio minimo e tasso di un nuovo prestito con quel rating.</summary>
|
||||
public sealed class RatingThresholdInfo
|
||||
{
|
||||
public string Rating { get; init; } = "";
|
||||
public float MinScore { get; init; }
|
||||
public float LoanRate { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.String(Rating); w.F32(MinScore); w.F32(LoanRate);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static RatingThresholdInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new RatingThresholdInfo { Rating = r.String(), MinScore = r.F32(), LoanRate = r.F32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prestito in corso: capitale, residuo, tasso fisso, mesi restanti, rata, interessi della prossima rata, scadenza.</summary>
|
||||
public sealed class FinanceLoanInfo
|
||||
{
|
||||
public int Loan { get; init; }
|
||||
public Money Principal { get; init; }
|
||||
public Money Remaining { get; init; }
|
||||
public float AnnualRate { get; init; }
|
||||
public int MonthsLeft { get; init; }
|
||||
public Money Payment { get; init; }
|
||||
public Money NextInterest { get; init; }
|
||||
public long MaturityDay { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Loan); w.Money(Principal); w.Money(Remaining); w.F32(AnnualRate); w.I32(MonthsLeft); w.Money(Payment); w.Money(NextInterest); w.I64(MaturityDay);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static FinanceLoanInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new FinanceLoanInfo
|
||||
{
|
||||
Loan = r.I32(), Principal = r.Money(), Remaining = r.Money(), AnnualRate = r.F32(), MonthsLeft = r.I32(),
|
||||
Payment = r.Money(), NextInterest = r.Money(), MaturityDay = r.I64(),
|
||||
};
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro delle finanze della compagnia della sessione (F6, ADR 0019): conto economico per voce (mese in
|
||||
/// corso, mesi chiusi, anno in corso, anni chiusi), spiegazione del rating, prestiti, fido e conto alla
|
||||
/// rovescia della bancarotta.
|
||||
/// </summary>
|
||||
public sealed class FinanceReport : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.FinanceReport;
|
||||
public long Day { get; init; }
|
||||
public int Company { get; init; }
|
||||
public Money Cash { get; init; }
|
||||
public Money NetWorth { get; init; }
|
||||
public Money Loans { get; init; }
|
||||
public Money Overdraft { get; init; }
|
||||
|
||||
/// <summary>Voci in ordine di presentazione e colonne del conto economico.</summary>
|
||||
public List<FinanceLineInfo> Lines { get; init; } = [];
|
||||
public List<IncomeColumnInfo> Columns { get; init; } = [];
|
||||
|
||||
/// <summary>Rating e sua spiegazione: misure dell'ultimo calcolo, componenti, punteggio.</summary>
|
||||
public string Rating { get; init; } = "";
|
||||
/// <summary>Prima del primo calcolo mensile: rating iniziale dei dati, misure di oggi.</summary>
|
||||
public bool RatingInitial { get; init; }
|
||||
public byte RatingMonths { get; init; }
|
||||
/// <summary>
|
||||
/// Mesi della finestra con ricavi; con <see cref="MarginNeutral"/> il margine vale 0 finché non ce ne
|
||||
/// sono <see cref="MinRevenueMonths"/> (o la finestra non è piena).
|
||||
/// </summary>
|
||||
public byte RevenueMonths { get; init; }
|
||||
public bool MarginNeutral { get; init; }
|
||||
public byte MinRevenueMonths { get; init; }
|
||||
public float Margin { get; init; }
|
||||
/// <summary>Debiti / patrimonio netto; con <see cref="LeverageUnbounded"/> il patrimonio non è positivo e la leva è infinita.</summary>
|
||||
public float Leverage { get; init; }
|
||||
public bool LeverageUnbounded { get; init; }
|
||||
public float MarginWeight { get; init; }
|
||||
public float LeverageWeight { get; init; }
|
||||
public float MarginComponent { get; init; }
|
||||
public float LeverageComponent { get; init; }
|
||||
public float Score { get; init; }
|
||||
public List<RatingThresholdInfo> Thresholds { get; init; } = [];
|
||||
/// <summary>
|
||||
/// Gradino sopra ("" ad AAA) con la soglia, il margine che basterebbe, la leva massima e il debito da
|
||||
/// rimborsare; con <see cref="NextAlreadyMet"/> il punteggio basta già (rating <see cref="ScoreRating"/>
|
||||
/// al prossimo calcolo mensile) e gli obiettivi non si calcolano.
|
||||
/// </summary>
|
||||
public string NextRating { get; init; } = "";
|
||||
public float NextThreshold { get; init; }
|
||||
public bool NextAlreadyMet { get; init; }
|
||||
public string ScoreRating { get; init; } = "";
|
||||
public float MarginNeeded { get; init; }
|
||||
public bool MarginReachable { get; init; }
|
||||
public float LeverageMax { get; init; }
|
||||
public bool LeverageReachable { get; init; }
|
||||
public Money DebtToRepay { get; init; }
|
||||
/// <summary>Il rimborso indicato non supera la cassa né il residuo dei prestiti (lo scoperto non si rimborsa).</summary>
|
||||
public bool RepayAffordable { get; init; }
|
||||
|
||||
/// <summary>Prestiti, fido e condizioni di un nuovo prestito (base della difficoltà + spread del rating).</summary>
|
||||
public List<FinanceLoanInfo> LoanList { get; init; } = [];
|
||||
public Money MaxLoan { get; init; }
|
||||
public Money LoanAvailable { get; init; }
|
||||
public float NewLoanRate { get; init; }
|
||||
public float BaseRate { get; init; }
|
||||
public float Spread { get; init; }
|
||||
public int LoanTermMonths { get; init; }
|
||||
public Money LoanStep { get; init; }
|
||||
public bool LoansAllowed { get; init; } = true;
|
||||
|
||||
/// <summary>Giorni di cassa negativa e limite della difficoltà prima della bancarotta.</summary>
|
||||
public int NegativeCashDays { get; init; }
|
||||
public int BankruptcyDays { get; init; }
|
||||
public bool Bankrupt { get; init; }
|
||||
public bool Receivership { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.I32(Company); w.Money(Cash); w.Money(NetWorth); w.Money(Loans); w.Money(Overdraft);
|
||||
w.Count(Lines.Count);
|
||||
foreach (var l in Lines) l.Write(ref w);
|
||||
w.Count(Columns.Count);
|
||||
foreach (var c in Columns) c.Write(ref w);
|
||||
w.String(Rating); w.Bool(RatingInitial); w.U8(RatingMonths); w.U8(RevenueMonths); w.Bool(MarginNeutral); w.U8(MinRevenueMonths); w.F32(Margin); w.F32(Leverage); w.Bool(LeverageUnbounded);
|
||||
w.F32(MarginWeight); w.F32(LeverageWeight); w.F32(MarginComponent); w.F32(LeverageComponent); w.F32(Score);
|
||||
w.Count(Thresholds.Count);
|
||||
foreach (var t in Thresholds) t.Write(ref w);
|
||||
w.String(NextRating); w.F32(NextThreshold); w.Bool(NextAlreadyMet); w.String(ScoreRating);
|
||||
w.F32(MarginNeeded); w.Bool(MarginReachable); w.F32(LeverageMax); w.Bool(LeverageReachable);
|
||||
w.Money(DebtToRepay); w.Bool(RepayAffordable);
|
||||
w.Count(LoanList.Count);
|
||||
foreach (var l in LoanList) l.Write(ref w);
|
||||
w.Money(MaxLoan); w.Money(LoanAvailable); w.F32(NewLoanRate); w.F32(BaseRate); w.F32(Spread); w.I32(LoanTermMonths); w.Money(LoanStep);
|
||||
w.Bool(LoansAllowed);
|
||||
w.I32(NegativeCashDays); w.I32(BankruptcyDays); w.Bool(Bankrupt); w.Bool(Receivership);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static FinanceReport Read(ref SpanReader r)
|
||||
{
|
||||
long day = r.I64();
|
||||
int company = r.I32();
|
||||
var cash = r.Money();
|
||||
var worth = r.Money();
|
||||
var loans = r.Money();
|
||||
var overdraft = r.Money();
|
||||
var lines = new List<FinanceLineInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) lines.Add(FinanceLineInfo.Read(ref r));
|
||||
var columns = new List<IncomeColumnInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) columns.Add(IncomeColumnInfo.Read(ref r));
|
||||
string rating = r.String();
|
||||
bool initial = r.Bool();
|
||||
byte months = r.U8(), revenueMonths = r.U8();
|
||||
bool neutral = r.Bool();
|
||||
byte minRevenueMonths = r.U8();
|
||||
float margin = r.F32(), leverage = r.F32();
|
||||
bool unbounded = r.Bool();
|
||||
float marginWeight = r.F32(), leverageWeight = r.F32(), marginComponent = r.F32(), leverageComponent = r.F32(), score = r.F32();
|
||||
var thresholds = new List<RatingThresholdInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) thresholds.Add(RatingThresholdInfo.Read(ref r));
|
||||
string next = r.String();
|
||||
float nextThreshold = r.F32();
|
||||
bool alreadyMet = r.Bool();
|
||||
string scoreRating = r.String();
|
||||
float marginNeeded = r.F32();
|
||||
bool marginReachable = r.Bool();
|
||||
float leverageMax = r.F32();
|
||||
bool leverageReachable = r.Bool();
|
||||
var repay = r.Money();
|
||||
bool affordable = r.Bool();
|
||||
var loanList = new List<FinanceLoanInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) loanList.Add(FinanceLoanInfo.Read(ref r));
|
||||
var maxLoan = r.Money();
|
||||
var available = r.Money();
|
||||
float newRate = r.F32(), baseRate = r.F32(), spread = r.F32();
|
||||
int term = r.I32();
|
||||
var step = r.Money();
|
||||
bool allowed = r.Bool();
|
||||
int negDays = r.I32(), limit = r.I32();
|
||||
bool bankrupt = r.Bool(), receivership = r.Bool();
|
||||
r.Flags();
|
||||
return new FinanceReport
|
||||
{
|
||||
Day = day, Company = company, Cash = cash, NetWorth = worth, Loans = loans, Overdraft = overdraft,
|
||||
Lines = lines, Columns = columns,
|
||||
Rating = rating, RatingInitial = initial, RatingMonths = months, RevenueMonths = revenueMonths, MarginNeutral = neutral,
|
||||
MinRevenueMonths = minRevenueMonths, Margin = margin, Leverage = leverage, LeverageUnbounded = unbounded,
|
||||
MarginWeight = marginWeight, LeverageWeight = leverageWeight, MarginComponent = marginComponent, LeverageComponent = leverageComponent,
|
||||
Score = score, Thresholds = thresholds,
|
||||
NextRating = next, NextThreshold = nextThreshold, NextAlreadyMet = alreadyMet, ScoreRating = scoreRating, MarginNeeded = marginNeeded, MarginReachable = marginReachable,
|
||||
LeverageMax = leverageMax, LeverageReachable = leverageReachable, DebtToRepay = repay, RepayAffordable = affordable,
|
||||
LoanList = loanList, MaxLoan = maxLoan, LoanAvailable = available, NewLoanRate = newRate, BaseRate = baseRate, Spread = spread,
|
||||
LoanTermMonths = term, LoanStep = step, LoansAllowed = allowed,
|
||||
NegativeCashDays = negDays, BankruptcyDays = limit, Bankrupt = bankrupt, Receivership = receivership,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ public static class MessageCodec
|
||||
MessageId.IndustryCard => IndustryCard.Read(ref r),
|
||||
MessageId.Chronicle => Chronicle.Read(ref r),
|
||||
MessageId.MarketReport => MarketReport.Read(ref r),
|
||||
MessageId.ClimbReport => ClimbReport.Read(ref r),
|
||||
MessageId.FinanceReport => FinanceReport.Read(ref r),
|
||||
MessageId.MarketTape => MarketTape.Read(ref r),
|
||||
MessageId.CommandResult => CommandResultMessage.Read(ref r),
|
||||
MessageId.Notification => Notification.Read(ref r),
|
||||
|
||||
@@ -661,6 +661,12 @@ public sealed class GameHost : IDisposable
|
||||
case DetailKind.Market:
|
||||
s.Send(Projection.Market(w, s.Company));
|
||||
break;
|
||||
case DetailKind.Climb:
|
||||
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Climb(w, s.Company));
|
||||
break;
|
||||
case DetailKind.Finance:
|
||||
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Finance(w, s.Company));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -553,6 +553,78 @@ public static class Projection
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Quadro della scalata per la compagnia della sessione (ClimbOutlook, ADR 0018).</summary>
|
||||
public static ClimbReport Climb(World w, CompanyId company)
|
||||
{
|
||||
var report = ClimbOutlook.Build(w, company);
|
||||
var next = report.Next;
|
||||
var balance = report.Balance;
|
||||
var income = report.Income;
|
||||
return new ClimbReport
|
||||
{
|
||||
Day = report.Day, Company = report.Company.Value, FoundedDay = report.FoundedDay, InitialCapital = report.InitialCapital,
|
||||
Tier = (byte)report.Tier, NextTier = (byte)report.NextTier,
|
||||
Tiers = report.Tiers.Select(t => new TierInfo
|
||||
{
|
||||
Level = (byte)t.Level, NameIt = t.NameIt, NameEn = t.NameEn, NetWorthRequired = new Money(t.Requirements.NetWorth),
|
||||
TownsRequired = t.Requirements.ConnectedTownsOver.Count, TownPopulation = t.Requirements.ConnectedTownsOver.Population,
|
||||
RatingRequired = t.Requirements.CreditRating.ToString(), Reached = t.Reached, ReachedDay = t.ReachedDay,
|
||||
Unlocks = t.Unlocks.Select(u => new UnlockInfo { Kind = (byte)u.Kind, Value = u.Value }).ToList(),
|
||||
}).ToList(),
|
||||
NetWorth = next?.NetWorth ?? w.Company(company).NetWorth, NetWorthRequired = next?.NetWorthRequired ?? Money.Zero,
|
||||
NetWorthFraction = (float)(next?.NetWorthFraction ?? 1), NetWorthMet = next?.NetWorthMet ?? true,
|
||||
Towns = next?.Towns ?? 0, TownsRequired = next?.TownsRequired ?? 0, TownPopulation = next?.TownPopulation ?? 0,
|
||||
TownsFraction = (float)(next?.TownsFraction ?? 1), TownsMet = next?.TownsMet ?? true,
|
||||
Rating = w.Company(company).Rating.ToString(), RatingRequired = next?.RatingRequired.ToString() ?? "",
|
||||
RatingFraction = (float)(next?.RatingFraction ?? 1), RatingMet = next?.RatingMet ?? true, Progress = (float)(next?.Progress ?? 1),
|
||||
Assets = balance.Assets.Select(a => new AmountInfo { Kind = (byte)a.Category, Value = a.Value }).ToList(),
|
||||
Portfolio = balance.Portfolio, Cash = balance.Cash, TotalAssets = balance.TotalAssets, Loans = balance.Loans,
|
||||
LoansRate = (float)balance.LoansRate, Overdraft = balance.Overdraft, TotalLiabilities = balance.TotalLiabilities,
|
||||
BalanceNetWorth = balance.NetWorth,
|
||||
IncomeYear = income.Year, IncomePartial = income.Partial,
|
||||
Income = income.Lines.Select(l => new AmountInfo { Kind = (byte)l.Kind, Value = l.Value }).ToList(), Profit = income.Profit,
|
||||
LoanList = report.Loans.Select(l => new LoanInfo { Loan = l.Id.Value, Remaining = l.Remaining, AnnualRate = (float)l.AnnualRate, MonthsLeft = l.MonthsLeft }).ToList(),
|
||||
MaxLoan = report.MaxLoan, LoanAvailable = report.LoanAvailable, NewLoanRate = (float)report.NewLoanRate, LoansAllowed = report.LoansAllowed,
|
||||
History = report.History.Select(p => new NetWorthPointInfo { Day = p.Day, Value = p.Value }).ToList(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Quadro delle finanze per la compagnia della sessione (FinanceOutlook, ADR 0019).</summary>
|
||||
public static FinanceReport Finance(World w, CompanyId company)
|
||||
{
|
||||
var report = FinanceOutlook.Build(w, company);
|
||||
var r = report.Rating;
|
||||
static float F(double v) => (float)Math.Clamp(v, float.MinValue, float.MaxValue);
|
||||
return new FinanceReport
|
||||
{
|
||||
Day = report.Day, Company = report.Company.Value, Cash = report.Cash, NetWorth = report.NetWorth, Loans = report.Loans, Overdraft = report.Overdraft,
|
||||
Lines = report.Lines.Select(l => new FinanceLineInfo { Kind = (byte)l.Entry, Section = (byte)l.Section }).ToList(),
|
||||
Columns = report.Columns.Select(c => new IncomeColumnInfo
|
||||
{
|
||||
Kind = (byte)c.Kind, Year = c.Year, Month = (byte)c.Month, Profit = c.Profit, CashFlow = c.CashFlow,
|
||||
Values = c.Entries.Select((v, i) => (v, i)).Where(x => x.v != 0).Select(x => new AmountInfo { Kind = (byte)x.i, Value = new Money(x.v) }).ToList(),
|
||||
}).ToList(),
|
||||
Rating = r.Rating.ToString(), RatingInitial = r.Initial, RatingMonths = (byte)Math.Clamp(r.Months, 0, 255),
|
||||
RevenueMonths = (byte)Math.Clamp(r.RevenueMonths, 0, 255), MarginNeutral = r.MarginNeutral, MinRevenueMonths = (byte)Math.Clamp(r.MinRevenueMonths, 0, 255),
|
||||
Margin = F(r.Margin), Leverage = r.LeverageUnbounded ? 0 : F(r.Leverage), LeverageUnbounded = r.LeverageUnbounded,
|
||||
MarginWeight = (float)r.MarginWeight, LeverageWeight = (float)r.LeverageWeight, MarginComponent = (float)r.MarginComponent,
|
||||
LeverageComponent = (float)r.LeverageComponent, Score = (float)r.Score,
|
||||
Thresholds = r.Thresholds.Select(t => new RatingThresholdInfo { Rating = t.Rating.ToString(), MinScore = (float)t.MinScore, LoanRate = (float)t.LoanRate }).ToList(),
|
||||
NextRating = r.Next?.ToString() ?? "", NextThreshold = (float)r.NextThreshold,
|
||||
NextAlreadyMet = r.NextAlreadyMet, ScoreRating = r.ScoreRating.ToString(), MarginNeeded = F(r.MarginNeeded), MarginReachable = r.MarginReachable,
|
||||
LeverageMax = F(r.LeverageMax), LeverageReachable = r.LeverageReachable, DebtToRepay = r.DebtToRepay,
|
||||
RepayAffordable = r.RepayAffordable,
|
||||
LoanList = report.LoanList.Select(l => new FinanceLoanInfo
|
||||
{
|
||||
Loan = l.Id.Value, Principal = l.Principal, Remaining = l.Remaining, AnnualRate = (float)l.AnnualRate, MonthsLeft = l.MonthsLeft,
|
||||
Payment = l.Payment, NextInterest = l.NextInterest, MaturityDay = l.MaturityDay,
|
||||
}).ToList(),
|
||||
MaxLoan = report.MaxLoan, LoanAvailable = report.LoanAvailable, NewLoanRate = (float)report.NewLoanRate, BaseRate = (float)report.BaseRate,
|
||||
Spread = (float)report.Spread, LoanTermMonths = report.LoanTermMonths, LoanStep = report.LoanStep, LoansAllowed = report.LoansAllowed,
|
||||
NegativeCashDays = report.NegativeCashDays, BankruptcyDays = report.BankruptcyDays, Bankrupt = report.Bankrupt, Receivership = report.Receivership,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
|
||||
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
|
||||
{
|
||||
|
||||
@@ -90,10 +90,10 @@ public sealed class SimulateCommand : IToolCommand
|
||||
csv.AppendLine(string.Join(';', year.ToString(It), "", def.Id, Dec(price), produced.ToString(It), consumed.ToString(It),
|
||||
population.ToString(It), Dec(efficiency), "", Dec(plant), "", "", "", note));
|
||||
}
|
||||
long totalCarrier = w.Companies.Sum(c => Company.Revenue(c.LastYearEntries));
|
||||
long totalCarrier = w.Companies.Sum(c => Company.TransportRevenue(c.LastYearEntries));
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
long revenue = Company.Revenue(c.LastYearEntries);
|
||||
long revenue = Company.TransportRevenue(c.LastYearEntries);
|
||||
double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0;
|
||||
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}{(c.Merged ? ", fusa" : "")}{AiNote(w, c)}";
|
||||
bool fleet = w.Trains.Any(t => !t.Removed && t.Owner == c.Id && t.Vehicles.Count > 0);
|
||||
|
||||
@@ -130,6 +130,20 @@ public static class DataTests
|
||||
Assert.True(errors.Any(e => e.Contains("failure.*Share", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[Test(Description = "Gli sblocchi non diminuiscono salendo di livello: fido e funzioni restano acquisiti (ADR 0011, 0018)")]
|
||||
public static void SemanticRejectsShrinkingUnlocks()
|
||||
{
|
||||
var errors = LoadErrors(files =>
|
||||
{
|
||||
var root = JsonNode.Parse(files["tiers.json"])!;
|
||||
root["tiers"]![4]!["unlocks"]!["ipo"] = false;
|
||||
root["tiers"]![2]!["unlocks"]!["maxLoanFactor"] = 1.0;
|
||||
files["tiers.json"] = root.ToJsonString();
|
||||
});
|
||||
Assert.True(errors.Any(e => e.Contains("unlocks.ipo", StringComparison.Ordinal)), string.Join("; ", errors));
|
||||
Assert.True(errors.Any(e => e.Contains("unlocks.maxLoanFactor", StringComparison.Ordinal)), string.Join("; ", errors));
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> LoadErrors(Action<Dictionary<string, string>> mutate)
|
||||
{
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using RailEnterprise.Server;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>Livelli, sblocchi e pannello «La tua scalata» (F6, ADR 0018).</summary>
|
||||
public static class ClimbTests
|
||||
{
|
||||
private static CommandResult Do(World w, GameCommand c)
|
||||
{
|
||||
w.Enqueue(c with { Issuer = w.Player.Id });
|
||||
w.RunTicks(1);
|
||||
return w.DrainResults().Last();
|
||||
}
|
||||
|
||||
/// <summary>Valdoria con la rete merci, un treno sulla linea e 40 giorni di servizio.</summary>
|
||||
private static RailFixture ServedValdoria()
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
|
||||
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
f.W.RunDays(40);
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Dati con il livello 2 raggiungibile subito (patrimonio di un centesimo, nessuna città, rating D).</summary>
|
||||
private static GameData EasyTierTwo()
|
||||
{
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
var tiers = JsonNode.Parse(files["tiers.json"])!;
|
||||
var req = tiers["tiers"]![1]!["requirements"]!;
|
||||
req["netWorth"] = 1;
|
||||
req["connectedTownsOver"]!["count"] = 0;
|
||||
req["creditRating"] = "D";
|
||||
files["tiers.json"] = tiers.ToJsonString();
|
||||
return GameData.Load(new MemoryDataSource(files));
|
||||
}
|
||||
|
||||
[Test(Description = "Requisiti e avanzamento coerenti con Tiers: soddisfatti esattamente quando Tiers.Meets, avanzamento = media delle frazioni")]
|
||||
public static void RequirementsAgreeWithTiers()
|
||||
{
|
||||
var f = ServedValdoria();
|
||||
var w = f.W;
|
||||
var c = w.Player;
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
var report = ClimbOutlook.Build(w, c.Id);
|
||||
Assert.Equal(hash, StateHasher.Compute(w), "il quadro non cambia il mondo");
|
||||
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
Assert.Equal(tiers.Count, report.Tiers.Count);
|
||||
Assert.Equal(c.Tier, report.Tier);
|
||||
Assert.Equal(tiers[c.Tier].Level, report.NextTier);
|
||||
Assert.Equal(c.FoundedDay, report.Tiers[0].ReachedDay, "il livello 1 vale dalla fondazione");
|
||||
for (int i = 0; i < tiers.Count; i++) Assert.Equal(c.Tier >= tiers[i].Level, report.Tiers[i].Reached, $"livello {i + 1}");
|
||||
|
||||
foreach (var tier in tiers)
|
||||
{
|
||||
var req = ClimbOutlook.Requirements(w, c, tier);
|
||||
Assert.Equal(Tiers.Meets(w, c, tier.Requirements), req.AllMet, $"livello {tier.Level}");
|
||||
Assert.Equal(Tiers.ConnectedTowns(w, c.Id, tier.Requirements.ConnectedTownsOver.Population), req.Towns);
|
||||
Assert.Equal(c.NetWorth, req.NetWorth);
|
||||
double average = (req.NetWorthFraction + req.TownsFraction + req.RatingFraction) / 3;
|
||||
Assert.Approx(req.AllMet ? average : Math.Min(average, ClimbOutlook.ProgressCap), req.Progress, 1e-12);
|
||||
Assert.InRange(req.Progress, 0, 1);
|
||||
Assert.Equal(req.AllMet, req.Progress >= 1, "avanzamento pieno solo con tutti i requisiti");
|
||||
double worth = tier.Requirements.NetWorth <= 0 ? 1 : Math.Clamp((double)c.NetWorth.Cents / tier.Requirements.NetWorth, 0, 1);
|
||||
Assert.Approx(worth, req.NetWorthFraction, 1e-12);
|
||||
}
|
||||
var next = report.Next!;
|
||||
Assert.Equal(tiers[c.Tier].Level, next.Level);
|
||||
Assert.True(report.Tiers.Skip(c.Tier).All(t => t.ReachedDay == -1), "livelli non raggiunti senza giorno");
|
||||
|
||||
// rating: 1 − gradini mancanti / ratingProgressSteps (2,5 nei dati)
|
||||
var bbb = tiers.First(t => t.Requirements.CreditRating == CreditRating.BBB);
|
||||
var saved = c.Rating;
|
||||
double steps = w.Data.Tiers.RatingProgressSteps;
|
||||
c.Rating = CreditRating.BB; // un gradino sotto BBB
|
||||
Assert.Approx(1 - 1 / steps, ClimbOutlook.Requirements(w, c, bbb).RatingFraction, 1e-12);
|
||||
c.Rating = CreditRating.D; // troppo lontano: zero
|
||||
Assert.Equal(0.0, ClimbOutlook.Requirements(w, c, bbb).RatingFraction);
|
||||
c.Rating = CreditRating.AA;
|
||||
Assert.Equal(1.0, ClimbOutlook.Requirements(w, c, bbb).RatingFraction);
|
||||
Assert.True(ClimbOutlook.Requirements(w, c, bbb).RatingMet);
|
||||
c.Rating = saved;
|
||||
|
||||
// all'ultimo livello non c'è un prossimo
|
||||
c.Tier = tiers.Count;
|
||||
var top = ClimbOutlook.Build(w, c.Id);
|
||||
Assert.Equal(0, top.NextTier);
|
||||
Assert.True(top.Next is null, "nessun requisito oltre l'ultimo livello");
|
||||
}
|
||||
|
||||
[Test(Description = "Gli sblocchi di ogni livello vengono da tiers.json e construction.json: ogni funzione compare una volta, al primo livello che la dà")]
|
||||
public static void UnlocksComeFromTheData()
|
||||
{
|
||||
var w = TestWorlds.NoAi(1801);
|
||||
var c = w.Player;
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
var first = Tiers.NewUnlocks(w, c, 1);
|
||||
Assert.Equal(new TierUnlock(UnlockKind.LoanLimit, (c.BaseCredit * tiers[0].Unlocks.MaxLoanFactor).Cents), first[0]);
|
||||
Assert.Equal(new TierUnlock(UnlockKind.Crews, w.Data.Construction.Crews.CrewsByTier[0]), first[1]);
|
||||
Assert.Equal(FinanceSystem.MaxLoan(w, c).Cents, first[0].Value, "il fido del livello 1 è quello del motore");
|
||||
|
||||
var features = new (UnlockKind Kind, Func<TierUnlocks, bool> Has)[]
|
||||
{
|
||||
(UnlockKind.Trading, u => u.Trading), (UnlockKind.BuyIndustry, u => u.BuyIndustry), (UnlockKind.Ipo, u => u.Ipo),
|
||||
(UnlockKind.HostileTakeover, u => u.HostileTakeover), (UnlockKind.Concessions, u => u.Concessions),
|
||||
};
|
||||
for (int level = 1; level <= tiers.Count; level++)
|
||||
{
|
||||
var unlocks = Tiers.NewUnlocks(w, c, level);
|
||||
var u = tiers[level - 1].Unlocks;
|
||||
var prev = level > 1 ? tiers[level - 2].Unlocks : null;
|
||||
foreach (var (kind, has) in features)
|
||||
{
|
||||
// le concessioni non si annunciano finché il comando non esiste (F7)
|
||||
bool available = kind != UnlockKind.Concessions || Tiers.ConcessionsAvailable;
|
||||
bool expected = available && has(u) && (prev is null || !has(prev));
|
||||
Assert.Equal(expected, unlocks.Any(x => x.Kind == kind), $"livello {level}, {kind}");
|
||||
}
|
||||
bool loanUp = prev is null || u.MaxLoanFactor > prev.MaxLoanFactor;
|
||||
Assert.Equal(loanUp, unlocks.Any(x => x.Kind == UnlockKind.LoanLimit && x.Value == (c.BaseCredit * u.MaxLoanFactor).Cents), $"fido al livello {level}");
|
||||
Assert.Equal(u.Crews, Tiers.Crews(w, level), "squadre uguali nei due file");
|
||||
Assert.True(unlocks.Select(x => x.Kind).SequenceEqual(unlocks.Select(x => x.Kind).Order()), "in ordine di tipo");
|
||||
}
|
||||
// le funzioni dell'ultimo livello compaiono ciascuna una volta sola
|
||||
var all = Enumerable.Range(1, tiers.Count).SelectMany(l => Tiers.NewUnlocks(w, c, l)).Where(x => x.Kind >= UnlockKind.Trading).ToList();
|
||||
Assert.Equal(all.Count, all.Select(x => x.Kind).Distinct().Count());
|
||||
Assert.Equal(features.Count(x => x.Has(tiers[^1].Unlocks) && (x.Kind != UnlockKind.Concessions || Tiers.ConcessionsAvailable)), all.Count);
|
||||
Assert.Equal("compravendita in proprio", Tiers.UnlockLabel(new TierUnlock(UnlockKind.Trading, 0)));
|
||||
}
|
||||
|
||||
[Test(Description = "Lo stato patrimoniale per voce (con industria, merce propria, prestito e scoperto) somma esattamente al patrimonio netto del motore")]
|
||||
public static void BalanceSheetSumsToTheEngineNetWorth()
|
||||
{
|
||||
var f = ServedValdoria();
|
||||
var w = f.W;
|
||||
var c = w.Player;
|
||||
// prestito, industria comprata al livello 3, merce propria in magazzino
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(20_000))).Ok);
|
||||
w.Money.Transfer(Account.External, Account.Of(c.Id), Money.FromLire(10_000_000), LedgerEntry.Other);
|
||||
c.Tier = 3;
|
||||
var mine = w.Industries.First(i => !i.Closed && i.Level > 0 && !i.Owner.IsValid);
|
||||
var bought = Do(w, new BuyIndustryCommand(mine.Id, IndustryMath.Valuation(w, mine) + Money.FromLire(100)));
|
||||
Assert.True(bought.Ok, bought.Message);
|
||||
var station = w.Network.Stations.First(s => s.Owner == c.Id && w.Network.IsAlive(s));
|
||||
int coal = w.Data.Goods.First(g => g.Id == "coal").Index;
|
||||
TradingMath.AddToWarehouse(station, coal, 50, w.Data.GoodCount);
|
||||
w.Goods.Produced[coal] += 50;
|
||||
w.RunDays(w.Calendar.DaysPerMonth); // il valore contabile si aggiorna a inizio mese
|
||||
|
||||
// le voci scritte ogni mese sono la scomposizione calcolata dal motore
|
||||
var parts = FinanceSystem.BookValues(w)[c.Id.Value];
|
||||
Assert.True(parts[(int)AssetCategory.Industries] > 0, "l'industria posseduta è tra gli attivi");
|
||||
Assert.Equal(IndustryMath.BookValue(w, mine).Cents, parts[(int)AssetCategory.Industries], "impianti più cassa dell'impresa");
|
||||
Assert.True(parts[(int)AssetCategory.Goods] > 0, "merce propria");
|
||||
Assert.True(parts[(int)AssetCategory.Track] > 0 && parts[(int)AssetCategory.Stations] > 0 && parts[(int)AssetCategory.Vehicles] > 0, "rete e flotta");
|
||||
|
||||
void Check(string when)
|
||||
{
|
||||
var b = ClimbOutlook.Balance(c);
|
||||
Assert.Equal(c.AssetBookValue.Cents, b.Assets.Sum(a => a.Value.Cents), $"voci = valore contabile ({when})");
|
||||
Assert.Equal(b.TotalAssets.Cents, b.Assets.Sum(a => a.Value.Cents) + b.Portfolio.Cents + b.Cash.Cents, $"totale attivo ({when})");
|
||||
Assert.Equal(b.TotalLiabilities, b.Loans + b.Overdraft, $"totale debiti ({when})");
|
||||
Assert.Equal(c.NetWorth, b.NetWorth, $"patrimonio netto del motore ({when})");
|
||||
Assert.Equal(c.NetWorth, b.TotalAssets - b.TotalLiabilities, $"attivo − debiti ({when})");
|
||||
Assert.Equal(c.Debt, b.Loans);
|
||||
}
|
||||
Check("con cassa positiva");
|
||||
var balance = ClimbOutlook.Balance(c);
|
||||
Assert.Approx(c.Loans.Sum(l => (double)l.Remaining.Cents * l.AnnualRate) / c.Debt.Cents, balance.LoansRate, 1e-12);
|
||||
|
||||
// scoperto: la cassa negativa passa tra i debiti, il patrimonio resta quello del motore
|
||||
var cash = c.Cash;
|
||||
w.Money.Transfer(Account.Of(c.Id), Account.External, cash + Money.FromLire(1_000), LedgerEntry.Other);
|
||||
Assert.True(c.Cash.IsNegative);
|
||||
Check("con lo scoperto");
|
||||
Assert.Equal(Money.FromLire(1_000), ClimbOutlook.Balance(c).Overdraft);
|
||||
Assert.Equal(Money.Zero, ClimbOutlook.Balance(c).Cash);
|
||||
|
||||
// conto economico: le righe sommano all'utile operativo
|
||||
var income = ClimbOutlook.Income(w, c);
|
||||
Assert.Equal(income.Profit.Cents, income.Lines.Sum(l => l.Value.Cents));
|
||||
Assert.Equal(w.Clock.Year, income.Year);
|
||||
Assert.True(income.Partial, "primo anno: anno in corso");
|
||||
Assert.Equal(Company.OperatingProfit(c.YearEntries), income.Profit.Cents);
|
||||
|
||||
// un'industria posseduta inattiva (livello 0) non si vende: a libro vale solo la sua cassa
|
||||
int level = mine.Level;
|
||||
mine.Level = 0;
|
||||
Assert.Equal(Money.Max(Money.Zero, mine.Cash), IndustryMath.BookValue(w, mine), "impianti a livello 0");
|
||||
mine.Level = level;
|
||||
Assert.True(IndustryMath.BookValue(w, mine) > Money.Max(Money.Zero, mine.Cash), "impianti al livello attuale");
|
||||
}
|
||||
|
||||
[Test(Description = "Al passaggio di livello la notizia elenca gli sblocchi ottenuti; il giorno resta annotato")]
|
||||
public static void PromotionNewsListsTheUnlocks()
|
||||
{
|
||||
var data = EasyTierTwo();
|
||||
var w = WorldFactory.Create(data, new NewGameSettings
|
||||
{
|
||||
Seed = 1802, SizeKm = 64, DifficultyId = "imprenditore",
|
||||
DifficultyOverride = DifficultyOverrides.Apply(data.DifficultyPreset("imprenditore"), new[] { ("aiCompetitors", 0.0) }),
|
||||
});
|
||||
Assert.Equal(1, w.Player.Tier);
|
||||
w.RunDays(w.Calendar.DaysPerMonth + 1);
|
||||
Assert.Equal(2, w.Player.Tier);
|
||||
long day = w.Player.TierReachedDay[1];
|
||||
Assert.Equal((long)w.Calendar.DaysPerMonth, day, "promosso alla chiusura del primo mese");
|
||||
var tier = data.Tiers.Tiers[1];
|
||||
var news = w.Events.Recent.Single(e => e.Kind == EventKind.Company && e.Text.Contains($"«{tier.NameIt}»"));
|
||||
Assert.Equal(EventSeverity.Opportunity, news.Severity);
|
||||
Assert.Equal(Tiers.PromotionText(w, w.Player, 2), news.Text);
|
||||
Assert.True(news.Text.Contains("(livello 2): sblocca"), news.Text);
|
||||
Assert.True(news.Text.Contains("compravendita in proprio"), news.Text);
|
||||
Assert.True(news.Text.Contains($"fido fino a {FinanceSystem.MaxLoan(w, w.Player).ToString("short")}"), news.Text);
|
||||
Assert.True(news.Text.Contains($"{data.Construction.Crews.CrewsByTier[1]} squadre di cantiere"), news.Text);
|
||||
var report = ClimbOutlook.Build(w, w.Player.Id);
|
||||
Assert.Equal(day, report.Tiers[1].ReachedDay);
|
||||
Assert.True(w.Player.Milestones.Any(m => m.Day == day && m.Text == $"diventa «{tier.NameIt}»"), "fatto saliente");
|
||||
}
|
||||
|
||||
[Test(Description = "I comandi bloccati dal livello dicono quale livello serve e come si chiama, dai dati")]
|
||||
public static void LockedCommandsNameTheTier()
|
||||
{
|
||||
var w = TestWorlds.Small(1803);
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
string Named(Func<TierUnlocks, bool> unlock)
|
||||
{
|
||||
var t = tiers.First(x => unlock(x.Unlocks));
|
||||
return $"livello {t.Level}, «{t.NameIt}»";
|
||||
}
|
||||
w.RunDays(2);
|
||||
var ind = w.Industries.First(i => !i.Closed && i.Level > 0 && !i.Owner.IsValid);
|
||||
var buy = Do(w, new BuyIndustryCommand(ind.Id, Money.FromLire(1)));
|
||||
Assert.Equal(CommandError.TierLocked, buy.Error);
|
||||
Assert.True(buy.Message.Contains(Named(u => u.BuyIndustry)), buy.Message);
|
||||
|
||||
var ipo = Do(w, new IpoCommand(0.2));
|
||||
Assert.Equal(CommandError.TierLocked, ipo.Error);
|
||||
Assert.True(ipo.Message.Contains(Named(u => u.Ipo)), ipo.Message);
|
||||
|
||||
var rival = w.Companies.First(x => !x.IsPlayer && !x.Defunct);
|
||||
var bid = Do(w, new LaunchBidCommand(rival.Id, Money.FromLire(1), 0.51));
|
||||
Assert.Equal(CommandError.TierLocked, bid.Error);
|
||||
Assert.True(bid.Message.Contains(Named(u => u.HostileTakeover)), bid.Message);
|
||||
|
||||
// il livello si controlla prima della stazione
|
||||
var goods = Do(w, new BuyGoodsCommand(new StationId(0), "coal", 1, Money.FromLire(1000)));
|
||||
Assert.Equal(CommandError.TierLocked, goods.Error);
|
||||
Assert.True(goods.Message.Contains(Named(u => u.Trading)), goods.Message);
|
||||
|
||||
// concessioni (F7): prima del livello il rifiuto dice che non ci sono ancora e dove si sbloccheranno,
|
||||
// dopo restano «non ancora disponibili»; nessuna notizia o pannello le annuncia
|
||||
var concession = Do(w, new BuyConcessionCommand(new RegionId(0)));
|
||||
Assert.Equal(CommandError.TierLocked, concession.Error);
|
||||
Assert.True(concession.Message.Contains("non sono ancora disponibili") && concession.Message.Contains(Named(u => u.Concessions)), concession.Message);
|
||||
int saved = w.Player.Tier;
|
||||
w.Player.Tier = tiers.First(t => t.Unlocks.Concessions).Level;
|
||||
var later = Do(w, new BuyConcessionCommand(new RegionId(0)));
|
||||
Assert.Equal(CommandError.NotImplemented, later.Error);
|
||||
Assert.True(later.Message.Contains("non sono ancora disponibili"), later.Message);
|
||||
Assert.False(Tiers.PromotionText(w, w.Player, w.Player.Tier).Contains("concessioni"), "la notizia non promette le concessioni");
|
||||
w.Player.Tier = saved;
|
||||
|
||||
// fido: quanto resta e quale livello lo alza
|
||||
var max = FinanceSystem.MaxLoan(w, w.Player);
|
||||
var loan = Do(w, new TakeLoanCommand(max + Money.FromLire(1)));
|
||||
Assert.Equal(CommandError.CreditLimit, loan.Error);
|
||||
var next = tiers[1];
|
||||
Assert.True(loan.Message.Contains($"livello {next.Level}, «{next.NameIt}», porta il fido a {Tiers.LoanLimit(w.Player, next)}"), loan.Message);
|
||||
w.Player.Tier = tiers.Count;
|
||||
var top = CommandProcessor.LoanLimitText(w, w.Player, FinanceSystem.MaxLoan(w, w.Player));
|
||||
Assert.False(top.Contains("livello"), "all'ultimo livello nessun livello successivo");
|
||||
}
|
||||
|
||||
[Test(Description = "Voci del patrimonio e giorni dei livelli nel salvataggio (versione 6) e nell'hash; la versione 5 si migra con lo stesso totale")]
|
||||
public static void BalanceSheetSurvivesSavesAndMigrates()
|
||||
{
|
||||
var f = ServedValdoria();
|
||||
var w = f.W;
|
||||
var c = w.Player;
|
||||
w.RunDays(w.Calendar.DaysPerMonth);
|
||||
c.TierReachedDay[1] = 17;
|
||||
c.Tier = 2;
|
||||
Corporate.Milestone(w, c, $"diventa «{w.Data.Tiers.Tiers[1].NameIt}»");
|
||||
Assert.True(c.AssetBookValue.Cents > 0, "attivi a valore di libro");
|
||||
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
var lc = loaded.Player;
|
||||
Assert.True(c.BookValues.SequenceEqual(lc.BookValues), "voci identiche");
|
||||
Assert.True(c.TierReachedDay.SequenceEqual(lc.TierReachedDay), "giorni dei livelli identici");
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
|
||||
|
||||
// le voci entrano nell'hash
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
c.BookValues[(int)AssetCategory.Track]--;
|
||||
c.BookValues[(int)AssetCategory.Vehicles]++;
|
||||
Assert.NotEqual(hash, StateHasher.Compute(w), "spostare valore tra le voci cambia l'hash");
|
||||
c.BookValues[(int)AssetCategory.Track]++;
|
||||
c.BookValues[(int)AssetCategory.Vehicles]--;
|
||||
|
||||
// versione 5: solo il totale; la migrazione lo ripartisce senza cambiarlo
|
||||
var v5 = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, v5, 5);
|
||||
var migrated = WorldSerializer.Read(TestData.Data, new SaveReader(v5.WrittenSpan.ToArray()));
|
||||
var mc = migrated.Player;
|
||||
Assert.Equal(c.AssetBookValue, mc.AssetBookValue, "stesso totale");
|
||||
Assert.Equal(c.NetWorth, mc.NetWorth, "stesso patrimonio netto");
|
||||
Assert.True(mc.BookValues.All(v => v >= 0), "voci non negative");
|
||||
Assert.True(mc.BookValues.Count(v => v > 0) >= 3, "ripartito tra rete, stazioni e veicoli");
|
||||
Assert.Equal(17L, c.TierReachedDay[1]);
|
||||
Assert.Equal(w.Clock.Day, mc.TierReachedDay[1], "giorno ricostruito dal fatto saliente");
|
||||
Assert.Equal(-1L, mc.TierReachedDay[2]);
|
||||
foreach (var other in migrated.Companies) Assert.Equal(w.Company(other.Id).AssetBookValue, other.AssetBookValue, other.Name);
|
||||
migrated.RunDays(3);
|
||||
Assert.Equal(0L, migrated.MoneyBalanceSum(), "la partita migrata prosegue");
|
||||
}
|
||||
|
||||
[Test(Description = "Proiezione del quadro della scalata: stessi numeri del Core e round-trip del messaggio ClimbReport")]
|
||||
public static void ClimbReportProjectionRoundTrips()
|
||||
{
|
||||
var f = ServedValdoria();
|
||||
var w = f.W;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(10_000))).Ok);
|
||||
var core = ClimbOutlook.Build(w, w.Player.Id);
|
||||
var message = Projection.Climb(w, w.Player.Id);
|
||||
var decoded = (ClimbReport)Frame.Decode(Frame.Encode(message));
|
||||
Assert.True(Frame.Encode(message).AsSpan().SequenceEqual(Frame.Encode(decoded)), "byte identici");
|
||||
Assert.Equal(w.Clock.Day, decoded.Day);
|
||||
Assert.Equal((byte)core.Tier, decoded.Tier);
|
||||
Assert.Equal((byte)core.NextTier, decoded.NextTier);
|
||||
Assert.Equal(core.Tiers.Count, decoded.Tiers.Count);
|
||||
Assert.Equal(core.Tiers[0].Unlocks.Count, decoded.Tiers[0].Unlocks.Count);
|
||||
Assert.Equal(w.Player.NetWorth, decoded.BalanceNetWorth);
|
||||
Assert.Equal(decoded.BalanceNetWorth, decoded.TotalAssets - decoded.TotalLiabilities);
|
||||
Assert.Equal(AssetCategories.Count, decoded.Assets.Count);
|
||||
Assert.Equal(core.Next!.NetWorthRequired, decoded.NetWorthRequired);
|
||||
Assert.Approx(core.Next.Progress, decoded.Progress, 1e-6);
|
||||
Assert.Equal(1, decoded.LoanList.Count);
|
||||
Assert.Equal(w.Player.Debt, decoded.Loans);
|
||||
Assert.Equal(decoded.Profit.Cents, decoded.Income.Sum(i => i.Value.Cents));
|
||||
Assert.True(decoded.History.Count >= 2, "fondazione e oggi");
|
||||
Assert.Equal(w.Player.NetWorth, decoded.History[^1].Value);
|
||||
Assert.Equal(new Money(w.Difficulty.InitialCapital), decoded.History[0].Value);
|
||||
}
|
||||
|
||||
[Test(Description = "L'avanzamento resta sotto il pieno (e sotto il 100 % per difetto) finché un requisito manca; il rating dell'immagine 08")]
|
||||
public static void ProgressIsFullOnlyWhenAllRequirementsAreMet()
|
||||
{
|
||||
var data = EasyTierTwo();
|
||||
var w = WorldFactory.Create(data, new NewGameSettings
|
||||
{
|
||||
Seed = 1804, SizeKm = 64, DifficultyId = "imprenditore",
|
||||
DifficultyOverride = DifficultyOverrides.Apply(data.DifficultyPreset("imprenditore"), new[] { ("aiCompetitors", 0.0) }),
|
||||
});
|
||||
var c = w.Player;
|
||||
var tier = data.Tiers.Tiers[1];
|
||||
// soglia del patrimonio a 1000 volte il patrimonio attuale, poi il 99,7 % della soglia
|
||||
var req = new TierRequirements
|
||||
{
|
||||
NetWorth = Math.Max(1_000_000, c.NetWorth.Cents) * 1000,
|
||||
ConnectedTownsOver = tier.Requirements.ConnectedTownsOver,
|
||||
CreditRating = tier.Requirements.CreditRating,
|
||||
};
|
||||
var def = new TierDef { Level = tier.Level, NameIt = tier.NameIt, NameEn = tier.NameEn, Requirements = req, Unlocks = tier.Unlocks };
|
||||
void SetNetWorth(long cents)
|
||||
{
|
||||
long delta = cents - c.NetWorth.Cents;
|
||||
if (delta > 0) w.Money.Transfer(Account.External, Account.Of(c.Id), new Money(delta), LedgerEntry.Other);
|
||||
else if (delta < 0) w.Money.Transfer(Account.Of(c.Id), Account.External, new Money(-delta), LedgerEntry.Other);
|
||||
Assert.Equal(cents, c.NetWorth.Cents);
|
||||
}
|
||||
SetNetWorth(req.NetWorth * 997 / 1000);
|
||||
var near = ClimbOutlook.Requirements(w, c, def);
|
||||
Assert.True(near.TownsMet && near.RatingMet && !near.NetWorthMet, "manca solo il patrimonio");
|
||||
Assert.False(Tiers.Meets(w, c, req));
|
||||
Assert.True(near.Progress < 1 && near.Progress <= ClimbOutlook.ProgressCap, $"avanzamento {near.Progress}");
|
||||
Assert.Equal(99.0, Math.Floor(near.Progress * 100), "per difetto si legge 99 %");
|
||||
Assert.Equal(99.0, Math.Floor(near.NetWorthFraction * 100), "patrimonio al 99 %");
|
||||
|
||||
SetNetWorth(req.NetWorth);
|
||||
var met = ClimbOutlook.Requirements(w, c, def);
|
||||
Assert.True(met.AllMet && Tiers.Meets(w, c, req));
|
||||
Assert.Equal(1.0, met.Progress);
|
||||
|
||||
// immagine 08: 65 % del patrimonio, 1 città su 2, BBB verso A danno il 58 %
|
||||
double rating = ClimbOutlook.RatingFraction(w, CreditRating.BBB, CreditRating.A);
|
||||
Assert.Approx(0.6, rating, 1e-12);
|
||||
Assert.Equal(58.0, Math.Floor((0.65 + 0.5 + rating) / 3 * 100));
|
||||
Assert.Equal(1.0, ClimbOutlook.RatingFraction(w, CreditRating.A, CreditRating.A));
|
||||
}
|
||||
|
||||
[Test(Description = "Lo storico del patrimonio ha un punto per anno di calendario: oggi sostituisce la fotografia del primo giorno dell'anno")]
|
||||
public static void HistoryHasOnePointPerCalendarYear()
|
||||
{
|
||||
var w = TestWorlds.NoAi(1805);
|
||||
var c = w.Player;
|
||||
int dpy = w.Calendar.DaysPerYear, start = w.Calendar.StartYear;
|
||||
Assert.Equal(0L, c.FoundedDay);
|
||||
w.Clock.Restore((3L * dpy + 100) * w.Calendar.TicksPerDay);
|
||||
for (int y = 0; y < 3; y++) c.History.Add(new CompanyYear(start + y, 1_000 * (y + 1), 0, 0, 0, 1, 0, 0, 0));
|
||||
var points = ClimbOutlook.History(w, c);
|
||||
Assert.True(points.Select(p => p.Day).SequenceEqual(new[] { 0L, dpy, 2L * dpy, w.Clock.Day }), string.Join(",", points.Select(p => p.Day)));
|
||||
var years = points.Select(p => w.Calendar.DateOfDay(p.Day).Year).ToList();
|
||||
Assert.Equal(years.Count, years.Distinct().Count(), "anni distinti");
|
||||
Assert.Equal(new Money(2_000), points[2].Value, "fine anno dal secondo anno dello storico");
|
||||
Assert.Equal(c.NetWorth, points[^1].Value);
|
||||
}
|
||||
|
||||
[Test(Description = "Migrazione senza fatto saliente: il giorno del livello è quello della prima fotografia annuale che lo mostra (primo giorno dell'anno dopo)")]
|
||||
public static void MigratedTierDayComesFromTheSnapshotDay()
|
||||
{
|
||||
var w = TestWorlds.NoAi(1806);
|
||||
var c = w.Player;
|
||||
int dpy = w.Calendar.DaysPerYear, start = w.Calendar.StartYear;
|
||||
w.Clock.Restore((3L * dpy + 100) * w.Calendar.TicksPerDay);
|
||||
c.Tier = 3;
|
||||
c.History.Add(new CompanyYear(start, 0, 0, 0, 0, 1, 0, 0, 0));
|
||||
c.History.Add(new CompanyYear(start + 1, 0, 0, 0, 0, 2, 0, 0, 0));
|
||||
c.History.Add(new CompanyYear(start + 2, 0, 0, 0, 0, 3, 0, 0, 0));
|
||||
Assert.False(c.Milestones.Any(m => m.Text.StartsWith("diventa", StringComparison.Ordinal)), "nessun fatto saliente dei livelli");
|
||||
var v5 = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, v5, 5);
|
||||
var mc = WorldSerializer.Read(TestData.Data, new SaveReader(v5.WrittenSpan.ToArray())).Player;
|
||||
// livello 2 nella fotografia del secondo anno, scattata il primo giorno del terzo
|
||||
Assert.Equal(2L * dpy, mc.TierReachedDay[1]);
|
||||
Assert.Equal(3L * dpy, mc.TierReachedDay[2]);
|
||||
Assert.Equal(-1L, mc.TierReachedDay[3]);
|
||||
}
|
||||
}
|
||||
@@ -186,9 +186,20 @@ public static class EconomyTests
|
||||
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
|
||||
w.Pipeline.Get<CommandSystem>().Step(w.Context);
|
||||
var results = w.DrainResults();
|
||||
Assert.Equal(CommandError.NotImplemented, results[0].Error);
|
||||
// al livello 1 le concessioni si rifiutano per il livello (ADR 0018), con il livello che le sblocca
|
||||
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Concessions);
|
||||
Assert.Equal(CommandError.TierLocked, results[0].Error);
|
||||
Assert.True(results[0].Message.Contains($"livello {tier.Level}, «{tier.NameIt}»"), results[0].Message);
|
||||
Assert.Equal(CommandError.UnknownCompany, results[1].Error);
|
||||
Assert.Equal(before, RailEnterprise.Core.Persistence.StateHasher.Compute(w));
|
||||
|
||||
// sbloccate dal livello, restano un comando non ancora disponibile (F7)
|
||||
w.Player.Tier = tier.Level;
|
||||
before = RailEnterprise.Core.Persistence.StateHasher.Compute(w);
|
||||
w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 11 });
|
||||
w.Pipeline.Get<CommandSystem>().Step(w.Context);
|
||||
Assert.Equal(CommandError.NotImplemented, w.DrainResults()[0].Error);
|
||||
Assert.Equal(before, RailEnterprise.Core.Persistence.StateHasher.Compute(w));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -0,0 +1,654 @@
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
using RailEnterprise.Server;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>Finanza completa: prestiti per rating, conto economico per voce, rating spiegato, bancarotta (F6, ADR 0019).</summary>
|
||||
public static class FinanceTests
|
||||
{
|
||||
private static CommandResult Do(World w, GameCommand c)
|
||||
{
|
||||
w.Enqueue(c with { Issuer = w.Player.Id });
|
||||
w.RunTicks(1);
|
||||
return w.DrainResults().Last();
|
||||
}
|
||||
|
||||
private static void SetCash(World w, Company c, Money target)
|
||||
{
|
||||
var delta = target - c.Cash;
|
||||
if (delta.IsPositive) w.Money.Transfer(Account.External, Account.Of(c.Id), delta, LedgerEntry.Other);
|
||||
else if (delta.IsNegative) w.Money.Transfer(Account.Of(c.Id), Account.External, -delta, LedgerEntry.Other);
|
||||
}
|
||||
|
||||
/// <summary>Valdoria con la rete merci, un treno sulla linea e i giorni di servizio indicati.</summary>
|
||||
private static RailFixture ServedValdoria(int days)
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
|
||||
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
f.W.RunDays(days);
|
||||
return f;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ prestiti
|
||||
|
||||
[Test(Description = "Il tasso di un prestito è base della difficoltà + spread del rating, fissato all'accensione")]
|
||||
public static void LoanRateIsBasePlusRatingSpreadAndFixed()
|
||||
{
|
||||
var w = TestWorlds.NoAi(901);
|
||||
var c = w.Player;
|
||||
var fb = w.Data.Balance.Finance;
|
||||
foreach (var rating in new[] { CreditRating.AAA, CreditRating.BBB, CreditRating.CCC })
|
||||
{
|
||||
c.Rating = rating;
|
||||
var r = Do(w, new TakeLoanCommand(Money.FromLire(10_000)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
var loan = c.Loans[^1];
|
||||
double expected = w.Difficulty.BaseInterestRate + fb.RatingSpreads[rating.ToString()];
|
||||
Assert.Approx(expected, loan.AnnualRate, 1e-12, $"tasso con {rating}");
|
||||
Assert.Approx(expected, FinanceSystem.LoanRate(w, c), 1e-12);
|
||||
Assert.True(r.Message.Contains(FinanceOutlook.Percent(expected)) && r.Message.Contains("rata mensile"), r.Message);
|
||||
}
|
||||
// il rating cambia, i tassi dei prestiti già accesi no
|
||||
var rates = c.Loans.Select(l => l.AnnualRate).ToList();
|
||||
c.Rating = CreditRating.D;
|
||||
w.RunDays(w.Calendar.DaysPerMonth + 1);
|
||||
Assert.SequenceEqual(rates, c.Loans.Select(l => l.AnnualRate).ToList(), "tassi fissi");
|
||||
Assert.True(FinanceSystem.LoanRate(w, w.Player) > rates.Min(), "un nuovo prestito costa secondo il rating nuovo");
|
||||
// tassi crescenti al peggiorare del rating
|
||||
for (int i = 1; i <= (int)CreditRating.D; i++)
|
||||
Assert.True(FinanceSystem.LoanRate(w, (CreditRating)i) >= FinanceSystem.LoanRate(w, (CreditRating)(i - 1)), $"spread di {(CreditRating)i}");
|
||||
}
|
||||
|
||||
[Test(Description = "Il fido è il fido iniziale per il fattore del livello; oltre si rifiuta con un messaggio chiaro e senza effetti")]
|
||||
public static void CreditLimitComesFromTheTierFactor()
|
||||
{
|
||||
var w = TestWorlds.NoAi(902);
|
||||
var c = w.Player;
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
Assert.Equal(c.BaseCredit * tiers[0].Unlocks.MaxLoanFactor, FinanceSystem.MaxLoan(w, c));
|
||||
Assert.True(Do(w, new TakeLoanCommand(FinanceSystem.MaxLoan(w, c))).Ok, "tutto il fido");
|
||||
var (loans, debt, cashBefore) = (c.Loans.Count, c.Debt, c.Cash);
|
||||
var refused = Do(w, new TakeLoanCommand(Money.FromLire(1)));
|
||||
Assert.Equal(CommandError.CreditLimit, refused.Error);
|
||||
Assert.True(refused.Message.StartsWith("Fido insufficiente: disponibili ₤ 0"), refused.Message);
|
||||
Assert.Equal(CommandError.InvalidArgument, Do(w, new TakeLoanCommand(Money.Zero)).Error);
|
||||
Assert.Equal((loans, debt), (c.Loans.Count, c.Debt), "i rifiuti non cambiano i prestiti");
|
||||
Assert.True(c.Cash <= cashBefore, "nessun incasso dai rifiuti");
|
||||
|
||||
var higher = tiers.First(t => t.Unlocks.MaxLoanFactor > tiers[0].Unlocks.MaxLoanFactor);
|
||||
c.Tier = higher.Level;
|
||||
Assert.Equal(c.BaseCredit * higher.Unlocks.MaxLoanFactor, FinanceSystem.MaxLoan(w, c));
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(1))).Ok, "il livello alza il fido");
|
||||
|
||||
// in amministrazione controllata niente prestiti nuovi
|
||||
c.Receivership = true;
|
||||
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1))).Error);
|
||||
Assert.False(FinanceOutlook.Build(w, c.Id).LoansAllowed, "il quadro lo dice");
|
||||
}
|
||||
|
||||
[Test(Description = "Interessi e quota capitale si pagano ogni mese sul registro, alla francese, con il denaro che torna a zero")]
|
||||
public static void MonthlyInterestIsBookedOnTheLedger()
|
||||
{
|
||||
var w = TestWorlds.NoAi(903);
|
||||
var c = w.Player;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(120_000))).Ok);
|
||||
var loan = c.Loans[0];
|
||||
var interest = Money.FromCentsRounded(loan.Remaining.Cents * loan.AnnualRate / 12);
|
||||
var payment = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||||
var remaining = loan.Remaining;
|
||||
long interestBefore = c.MonthEntries[(int)LedgerEntry.Interest], repaidBefore = c.MonthEntries[(int)LedgerEntry.LoanRepaid];
|
||||
// la rata si paga il primo giorno del mese e finisce nel mese che si chiude
|
||||
w.RunDays(w.Calendar.DaysPerMonth - (int)(w.Clock.Day % w.Calendar.DaysPerMonth));
|
||||
var closed = c.IncomeMonths[^1].Entries;
|
||||
Assert.Equal(-interest.Cents, closed[(int)LedgerEntry.Interest] - interestBefore, "interessi del mese");
|
||||
Assert.Equal(-(payment - interest).Cents, closed[(int)LedgerEntry.LoanRepaid] - repaidBefore, "quota capitale");
|
||||
Assert.Equal(remaining - (payment - interest), loan.Remaining);
|
||||
Assert.Equal(c.Loans[0].MonthsLeft, w.Data.Balance.Finance.LoanTermMonths - 1);
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
// il quadro mostra rata e scadenza coerenti
|
||||
var detail = FinanceOutlook.Build(w, c.Id).LoanList[0];
|
||||
Assert.Equal(FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft), detail.Payment);
|
||||
Assert.Equal(w.Clock.Day / w.Calendar.DaysPerMonth * w.Calendar.DaysPerMonth + (long)loan.MonthsLeft * w.Calendar.DaysPerMonth, detail.MaturityDay);
|
||||
}
|
||||
|
||||
[Test(Description = "Rimborso anticipato parziale (rata più bassa, stessa durata) e totale; cassa insufficiente e prestito inesistente rifiutati")]
|
||||
public static void EarlyRepaymentPartialAndTotal()
|
||||
{
|
||||
var w = TestWorlds.NoAi(904);
|
||||
var c = w.Player;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(100_000))).Ok);
|
||||
var loan = c.Loans[0];
|
||||
var payment = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||||
int months = loan.MonthsLeft;
|
||||
|
||||
var partial = Do(w, new RepayLoanCommand(loan.Id, Money.FromLire(40_000)));
|
||||
Assert.True(partial.Ok, partial.Message);
|
||||
Assert.Equal(Money.FromLire(60_000), loan.Remaining);
|
||||
Assert.Equal(months, loan.MonthsLeft, "la durata non cambia");
|
||||
var lower = FinanceSystem.MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||||
Assert.True(lower < payment, "la rata scende");
|
||||
Assert.True(partial.Message.Contains($"nuova rata mensile {lower}"), partial.Message);
|
||||
|
||||
// cassa insufficiente: rifiuto con gli importi, nulla cambia
|
||||
var cash = c.Cash;
|
||||
SetCash(w, c, Money.FromLire(1_000));
|
||||
var owed = loan.Remaining;
|
||||
var poor = Do(w, new RepayLoanCommand(loan.Id, loan.Remaining));
|
||||
Assert.Equal(CommandError.InsufficientFunds, poor.Error);
|
||||
Assert.True(poor.Message.Contains("Cassa insufficiente") && poor.Message.Contains(loan.Remaining.ToString()), poor.Message);
|
||||
Assert.Equal(owed, loan.Remaining, "il rifiuto non rimborsa nulla");
|
||||
SetCash(w, c, cash);
|
||||
|
||||
Assert.Equal(CommandError.NotFound, Do(w, new RepayLoanCommand(new LoanId(999), Money.FromLire(1))).Error);
|
||||
var total = Do(w, new RepayLoanCommand(loan.Id, Money.FromLire(1_000_000)));
|
||||
Assert.True(total.Ok && total.Message.Contains("prestito estinto"), total.Message);
|
||||
Assert.Equal(0, c.Loans.Count);
|
||||
Assert.Equal(Money.Zero, c.Debt);
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ rating
|
||||
|
||||
/// <summary>Mese chiuso con i ricavi e i costi indicati (centesimi), per costruire la finestra del rating.</summary>
|
||||
private static IncomeRecord Month(int year, int month, long revenue, long cost)
|
||||
{
|
||||
var e = new long[Company.EntryCount];
|
||||
e[(int)LedgerEntry.FreightRevenue] = revenue;
|
||||
e[(int)LedgerEntry.RunningCosts] = -cost;
|
||||
return new IncomeRecord { Year = year, Month = month, Entries = e };
|
||||
}
|
||||
|
||||
[Test(Description = "Il rating è funzione documentata di utile/ricavi (12 mesi) e debiti/patrimonio; le misure restano per spiegarlo")]
|
||||
public static void RatingComesFromMarginAndLeverage()
|
||||
{
|
||||
var w = TestWorlds.NoAi(905);
|
||||
var c = w.Player;
|
||||
var fb = w.Data.Balance.Finance;
|
||||
c.IncomeMonths.Clear();
|
||||
for (int m = 1; m <= 12; m++) c.IncomeMonths.Add(Month(1850, m, 100_000_00, 80_000_00)); // margine 20 %
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
Assert.Approx(0.2, c.RatingMargin, 1e-12, "margine");
|
||||
Assert.Equal(12, c.RatingMonths);
|
||||
long debt = c.Debt.Cents + Math.Max(0, -c.Cash.Cents);
|
||||
Assert.Approx(debt == 0 ? 0 : (double)debt / c.NetWorth.Cents, c.RatingLeverage, 1e-12, "leva");
|
||||
double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + 0.2, 0, 1) + fb.LeverageWeight * (1 / (1 + c.RatingLeverage));
|
||||
Assert.Approx(score, c.RatingScore, 1e-12, "punteggio");
|
||||
Assert.Equal(FinanceSystem.RatingOf(w, score), c.Rating);
|
||||
var noDebt = c.Rating;
|
||||
|
||||
// più debito (stesso patrimonio): leva più alta, rating non migliore
|
||||
Assert.True(Do(w, new TakeLoanCommand(FinanceSystem.MaxLoan(w, c))).Ok);
|
||||
FinanceSystem.UpdateBookValues(w);
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
Assert.Approx((double)c.Debt.Cents / c.NetWorth.Cents, c.RatingLeverage, 1e-12, "debiti/patrimonio");
|
||||
Assert.True(c.Rating >= noDebt, $"con debito {c.Rating}, senza {noDebt}");
|
||||
|
||||
// margine negativo: rating non migliore; margine alto: non peggiore
|
||||
var leveraged = c.Rating;
|
||||
for (int i = 0; i < 12; i++) c.IncomeMonths[i] = Month(1850, i + 1, 100_000_00, 150_000_00);
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
Assert.Approx(-0.5, c.RatingMargin, 1e-12);
|
||||
Assert.True(c.Rating >= leveraged, "in perdita il rating non sale");
|
||||
for (int i = 0; i < 12; i++) c.IncomeMonths[i] = Month(1850, i + 1, 100_000_00, 10_000_00);
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
Assert.True(c.Rating <= leveraged, "con il 90 % di margine il rating non scende");
|
||||
|
||||
// patrimonio negativo con debiti: leva infinita, componente nulla
|
||||
SetCash(w, c, Money.FromLire(-10_000_000));
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
Assert.True(double.IsPositiveInfinity(c.RatingLeverage), "leva infinita");
|
||||
Assert.Approx(fb.ProfitMarginWeight * 1.0, c.RatingScore, 1e-12);
|
||||
c.Bankrupt = true;
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
Assert.Equal(CreditRating.D, c.Rating, "in bancarotta è D");
|
||||
}
|
||||
|
||||
[Test(Description = "La spiegazione del rating dice cosa serve per salire: il margine o la leva indicati portano al gradino sopra")]
|
||||
public static void RatingExplanationReachesTheNextNotch()
|
||||
{
|
||||
var w = TestWorlds.NoAi(906);
|
||||
var c = w.Player;
|
||||
var fb = w.Data.Balance.Finance;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(200_000))).Ok);
|
||||
c.IncomeMonths.Clear();
|
||||
for (int m = 1; m <= 12; m++) c.IncomeMonths.Add(Month(1850, m, 100_000_00, 95_000_00)); // margine 5 %
|
||||
FinanceSystem.UpdateBookValues(w);
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
var e = FinanceOutlook.Explain(w, c);
|
||||
Assert.False(e.Initial, "misure dell'ultimo calcolo");
|
||||
Assert.Equal(c.Rating, e.Rating);
|
||||
Assert.Approx(c.RatingScore, e.Score, 1e-12);
|
||||
Assert.Equal(fb.RatingByScore.Length, e.Thresholds.Count);
|
||||
Assert.True(e.Next is not null, "c'è un gradino sopra");
|
||||
Assert.Approx(fb.RatingByScore[(int)e.Next!.Value], e.NextThreshold, 1e-12);
|
||||
Assert.True(e.Score < e.NextThreshold && e.Score >= (c.Rating == CreditRating.D ? 0 : fb.RatingByScore[(int)c.Rating]), "punteggio tra le due soglie");
|
||||
if (e.MarginReachable)
|
||||
Assert.Equal(e.Next.Value, FinanceSystem.RatingOf(w, FinanceSystem.Score(w, e.MarginNeeded + 1e-9, c.RatingLeverage)), "con il margine indicato si sale");
|
||||
if (e.LeverageReachable)
|
||||
{
|
||||
Assert.Equal(e.Next.Value, FinanceSystem.RatingOf(w, FinanceSystem.Score(w, c.RatingMargin, e.LeverageMax - 1e-9)), "con la leva indicata si sale");
|
||||
// rimborsando il debito indicato la leva scende sotto il massimo (il patrimonio non cambia)
|
||||
var live = FinanceSystem.Measures(w, c);
|
||||
Assert.True((double)(live.Debt - e.DebtToRepay.Cents) / live.Equity <= e.LeverageMax + 1e-9, "debito da rimborsare");
|
||||
Assert.True(e.RepayAffordable == (e.DebtToRepay <= Money.Min(c.Debt, Money.Max(Money.Zero, c.Cash))), "rimborso possibile con la cassa");
|
||||
}
|
||||
Assert.True(e.MarginReachable || e.LeverageReachable, "almeno una via per salire");
|
||||
Assert.False(e.NextAlreadyMet, "il punteggio non basta ancora");
|
||||
|
||||
// pochi contanti e molti attivi non monetari: il rimborso che servirebbe supera la cassa, quindi oggi
|
||||
// non è percorribile (si rimborsa con la cassa; lo scoperto non si rimborsa)
|
||||
SetCash(w, c, Money.FromLire(10_000));
|
||||
c.BookValues[(int)AssetCategory.Vehicles] += Money.FromLire(400_000).Cents;
|
||||
var poor = FinanceOutlook.Explain(w, c);
|
||||
Assert.True(poor.LeverageReachable && poor.DebtToRepay > c.Cash && !poor.RepayAffordable, $"rimborso {poor.DebtToRepay} con cassa {c.Cash}");
|
||||
SetCash(w, c, Money.FromLire(-1));
|
||||
Assert.False(FinanceOutlook.Explain(w, c).RepayAffordable, "con la cassa negativa nessun rimborso");
|
||||
}
|
||||
|
||||
[Test(Description = "Se il punteggio basta già per il gradino sopra (rating iniziale o rimasto indietro) la spiegazione lo dice senza obiettivi né infiniti")]
|
||||
public static void RatingExplanationWhenTheScoreAlreadyMeetsTheNextNotch()
|
||||
{
|
||||
var fb = TestData.Data.Balance.Finance;
|
||||
// partita nuova: rating iniziale dei dati, misure di oggi (margine neutro, nessun debito)
|
||||
var fresh = TestWorlds.NoAi(907);
|
||||
var first = FinanceOutlook.Explain(fresh, fresh.Player);
|
||||
Assert.True(first.Initial);
|
||||
Assert.Equal(fb.StartingRating, first.Rating);
|
||||
Assert.True(first.MarginNeutral, "nessun mese chiuso: margine neutro");
|
||||
Assert.True(first.Score >= first.NextThreshold, $"con i dati attuali il punteggio iniziale {first.Score} supera la soglia {first.NextThreshold}");
|
||||
Assert.True(first.NextAlreadyMet, "il punteggio basta già");
|
||||
Assert.Equal(FinanceSystem.RatingOf(fresh, first.Score), first.ScoreRating);
|
||||
Assert.False(first.MarginReachable || first.LeverageReachable, "nessun obiettivo da raggiungere");
|
||||
Assert.Approx(0, first.MarginNeeded, 1e-12);
|
||||
Assert.Approx(0, first.LeverageMax, 1e-12);
|
||||
var message = Projection.Finance(fresh, fresh.Player.Id);
|
||||
Assert.True(message.NextAlreadyMet && message.ScoreRating == first.ScoreRating.ToString(), "nel protocollo");
|
||||
|
||||
// rating rimasto a D dopo una bancarotta risolta, con un punteggio normale: niente leva infinita
|
||||
var w = TestWorlds.NoAi(908);
|
||||
var c = w.Player;
|
||||
for (int m = 1; m <= 12; m++) c.IncomeMonths.Add(Month(1850, m, 100_000_00, 95_000_00));
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
c.Rating = CreditRating.D;
|
||||
var e = FinanceOutlook.Explain(w, c);
|
||||
Assert.True(e.NextAlreadyMet && e.Next == CreditRating.C, "il punteggio vale già più di C");
|
||||
Assert.True(double.IsFinite(e.LeverageMax) && double.IsFinite(e.MarginNeeded), "nessun infinito");
|
||||
var wire = Projection.Finance(w, c.Id);
|
||||
Assert.True(wire.LeverageMax < 1e6 && wire.MarginNeeded > -0.5 - 1e-6, $"leva {wire.LeverageMax}, margine {wire.MarginNeeded}");
|
||||
}
|
||||
|
||||
[Test(Description = "I primi incassi non fanno crollare il rating: il margine resta neutro finché la finestra non ha abbastanza mesi con ricavi")]
|
||||
public static void FirstRevenueDoesNotSinkTheRating()
|
||||
{
|
||||
var w = TestWorlds.NoAi(909);
|
||||
var c = w.Player;
|
||||
var fb = w.Data.Balance.Finance;
|
||||
Assert.True(fb.RatingMinRevenueMonths > 1 && fb.RatingMinRevenueMonths + 3 < fb.IncomeMonths, "parametri del test");
|
||||
// tre mesi d'avvio con soli costi, poi il primo incasso piccolo (margine vero −90 %)
|
||||
c.IncomeMonths.Clear();
|
||||
for (int m = 1; m <= 3; m++) c.IncomeMonths.Add(Month(1850, m, 0, 50_000_00));
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
var start = c.Rating;
|
||||
Assert.Approx(0, c.RatingMargin, 1e-12, "solo costi nell'avvio: margine neutro");
|
||||
c.IncomeMonths.Add(Month(1850, 4, 10_000_00, 50_000_00));
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
var m4 = FinanceSystem.Measures(w, c);
|
||||
Assert.True(m4.MarginNeutral && m4.RevenueMonths == 1, "un solo mese con ricavi");
|
||||
Assert.Approx(0, c.RatingMargin, 1e-12, "margine ancora neutro");
|
||||
Assert.True((int)c.Rating - (int)start <= 1, $"primo incasso: da {start} a {c.Rating}");
|
||||
Assert.True(FinanceOutlook.Explain(w, c).MarginNeutral, "la spiegazione lo dice");
|
||||
|
||||
// con abbastanza mesi di ricavi il margine conta
|
||||
for (int m = 5; c.IncomeMonths.Count(x => Company.Revenue(x.Entries) > 0) < fb.RatingMinRevenueMonths; m++)
|
||||
c.IncomeMonths.Add(Month(1850, m, 40_000_00, 50_000_00));
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
var counted = FinanceSystem.Measures(w, c);
|
||||
Assert.False(counted.MarginNeutral, "margine vero");
|
||||
Assert.Approx((double)counted.Profit / counted.Revenue, c.RatingMargin, 1e-12);
|
||||
Assert.True(c.RatingMargin < 0, "in perdita");
|
||||
|
||||
// finestra piena senza ricavi e in perdita: margine minimo, componente nulla
|
||||
c.IncomeMonths.Clear();
|
||||
for (int m = 1; m <= fb.IncomeMonths; m++) c.IncomeMonths.Add(Month(1850, m, 0, 50_000_00));
|
||||
FinanceSystem.UpdateRating(w, c);
|
||||
Assert.Approx(-1, c.RatingMargin, 1e-12, "margine minimo");
|
||||
Assert.Approx(0, FinanceSystem.MarginComponent(c.RatingMargin), 1e-12);
|
||||
}
|
||||
|
||||
[Test(Description = "Il rating si aggiorna ogni mese sulla finestra degli ultimi 12 mesi chiusi")]
|
||||
public static void RatingUsesTheLastTwelveClosedMonths()
|
||||
{
|
||||
var f = ServedValdoria(0);
|
||||
var w = f.W;
|
||||
var c = w.Player;
|
||||
int months = w.Data.Balance.Finance.IncomeMonths;
|
||||
w.RunDays((months + 2) * w.Calendar.DaysPerMonth);
|
||||
Assert.Equal(months, c.IncomeMonths.Count, "finestra piena e non oltre");
|
||||
Assert.Equal(months, c.RatingMonths);
|
||||
// i mesi sono consecutivi e finiscono col mese appena chiuso
|
||||
var last = w.Calendar.DateOfDay(w.Clock.Day / w.Calendar.DaysPerMonth * w.Calendar.DaysPerMonth - 1);
|
||||
Assert.Equal((last.Year, last.Month), (c.IncomeMonths[^1].Year, c.IncomeMonths[^1].Month));
|
||||
// le misure conservate sono quelle della finestra (il rating si ricalcola solo a inizio mese)
|
||||
long revenue = c.IncomeMonths.Sum(m => Company.Revenue(m.Entries));
|
||||
long profit = c.IncomeMonths.Sum(m => Company.OperatingProfit(m.Entries));
|
||||
Assert.Approx(revenue > 0 ? (double)profit / revenue : 0, c.RatingMargin, 1e-12);
|
||||
Assert.True(revenue > 0, "la linea incassa");
|
||||
// l'anello dell'utile della borsa e i mesi del conto economico hanno la stessa fonte
|
||||
long ring = c.AnnualProfit;
|
||||
Assert.Equal(c.IncomeMonths.Skip(months - 12).Sum(m => Company.OperatingProfit(m.Entries)), ring);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ conto economico
|
||||
|
||||
[Test(Description = "Il conto economico per voce somma esattamente all'utile operativo del motore in ogni colonna")]
|
||||
public static void IncomeStatementSumsToOperatingProfit()
|
||||
{
|
||||
var f = ServedValdoria(0);
|
||||
var w = f.W;
|
||||
var c = w.Player;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(50_000))).Ok);
|
||||
w.RunDays(w.Calendar.DaysPerYear + 3 * w.Calendar.DaysPerMonth);
|
||||
var report = FinanceOutlook.Build(w, c.Id);
|
||||
Assert.Equal(Company.EntryCount, report.Lines.Count);
|
||||
Assert.Equal(Company.EntryCount, report.Lines.Select(l => l.Entry).Distinct().Count(), "ogni voce una volta");
|
||||
Assert.True(report.Columns.Count >= 3, "mese, mesi chiusi, anno");
|
||||
Assert.Equal(IncomeColumnKind.CurrentMonth, report.Columns[0].Kind);
|
||||
Assert.True(report.Columns.Any(x => x.Kind == IncomeColumnKind.Year), "un anno chiuso");
|
||||
foreach (var col in report.Columns)
|
||||
{
|
||||
long operating = report.Lines.Where(l => l.Section != IncomeSection.Capital).Sum(l => col.Entries[(int)l.Entry]);
|
||||
long all = col.Entries.Sum();
|
||||
Assert.Equal(col.Profit.Cents, operating, $"utile {col.Kind} {col.Month}/{col.Year}");
|
||||
Assert.Equal(Company.OperatingProfit(col.Entries), col.Profit.Cents);
|
||||
Assert.Equal(col.CashFlow.Cents, all, "flusso di cassa");
|
||||
}
|
||||
Assert.Equal(Company.OperatingProfit(c.MonthEntries), report.Columns[0].Profit.Cents, "mese in corso dal registro");
|
||||
var year = report.Columns.First(x => x.Kind == IncomeColumnKind.Year);
|
||||
Assert.SequenceEqual(c.LastYearEntries, year.Entries, "anno chiuso = registro dell'anno precedente");
|
||||
// la scalata mostra lo stesso utile dell'ultimo anno chiuso
|
||||
Assert.Equal(ClimbOutlook.Income(w, c).Profit, year.Profit);
|
||||
// voci vive: tariffe, esercizio dei treni, stazioni e depositi, interessi
|
||||
Assert.True(year.Entries[(int)LedgerEntry.FreightRevenue] > 0, "noli");
|
||||
Assert.True(year.Entries[(int)LedgerEntry.RunningCosts] < 0, "esercizio dei treni");
|
||||
Assert.True(year.Entries[(int)LedgerEntry.StationUpkeep] < 0, "stazioni e depositi");
|
||||
Assert.True(year.Entries[(int)LedgerEntry.Interest] < 0, "interessi");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "Il personale presente nei depositi riceve gli stipendi alle paghe delle industrie, sulla voce «Stipendi»")]
|
||||
public static void DepotStaffIsPaidWages()
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 0);
|
||||
var w = f.W;
|
||||
var depot = w.Network.Depots[net.Officina];
|
||||
w.RunDays(w.Calendar.DaysPerMonth + 1);
|
||||
Assert.True(depot.StaffPresent > 0 && depot.WorkersPresent > 0, $"personale presente: {depot.StaffPresent} tecnici, {depot.WorkersPresent} operai");
|
||||
long before = w.Player.YearEntries[(int)LedgerEntry.Wages];
|
||||
w.RunDays(1);
|
||||
var ib = w.Data.Balance.Industry;
|
||||
double expected = 0;
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (d.Owner == w.Player.Id && w.Network.IsAlive(d))
|
||||
expected += (d.WorkersPresent * ib.WagePerWorkerPerMonth + d.StaffPresent * ib.WagePerStaffPerMonth) / w.Calendar.DaysPerMonth;
|
||||
}
|
||||
Assert.Equal(-Money.FromCentsRounded(expected).Cents, w.Player.YearEntries[(int)LedgerEntry.Wages] - before, "stipendi del giorno");
|
||||
Assert.True(Company.OperatingProfit(w.Player.YearEntries) < Company.OperatingProfit(w.Player.YearEntries) - w.Player.YearEntries[(int)LedgerEntry.Wages],
|
||||
"gli stipendi riducono l'utile operativo");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "Dazi degli hub e giacenze dei magazzini sulle loro voci, con lo stesso netto per la cassa")]
|
||||
public static void DutiesAndStorageHaveTheirOwnEntries()
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var w = f.W;
|
||||
w.Player.Tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading).Level;
|
||||
int port = f.Ok(new BuildStationCommand(RailFixture.K(14.5, 6.3), 2, "Porto di Levante"));
|
||||
var hub = w.Hubs[0];
|
||||
int coal = w.Data.Goods.First(g => g.Id == "coal").Index;
|
||||
double price = hub.SellPrice(w.Market.GlobalPrice[coal]);
|
||||
var cash = w.Player.Cash;
|
||||
long trading = w.Player.YearEntries[(int)LedgerEntry.Trading], duties = w.Player.YearEntries[(int)LedgerEntry.Duties];
|
||||
var r = f.Do(new BuyGoodsCommand(new StationId(port), "coal", 60, Money.FromCentsRounded(price + 1)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
long paid = (cash - w.Player.Cash).Cents;
|
||||
long duty = -(w.Player.YearEntries[(int)LedgerEntry.Duties] - duties);
|
||||
Assert.Approx(60 * price * hub.Duty / (1 + hub.Duty), duty, 1, "dazio d'importazione");
|
||||
Assert.Equal(-(paid - duty), w.Player.YearEntries[(int)LedgerEntry.Trading] - trading, "il resto è commercio");
|
||||
|
||||
// vendita all'hub: incasso a Pg e dazio a parte, netto = prezzo d'esportazione
|
||||
cash = w.Player.Cash;
|
||||
duties = w.Player.YearEntries[(int)LedgerEntry.Duties];
|
||||
double sell = hub.BuyPrice(w.Market.GlobalPrice[coal]);
|
||||
var s = f.Do(new SellGoodsCommand(new StationId(port), "coal", 20, Money.Zero));
|
||||
Assert.True(s.Ok, s.Message);
|
||||
Assert.Approx(20 * sell, (w.Player.Cash - cash).Cents, 1, "incasso netto");
|
||||
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Duties] < duties, "dazio d'esportazione");
|
||||
|
||||
// giacenza mensile sulla voce «Magazzini»
|
||||
long storage = w.Player.YearEntries[(int)LedgerEntry.Storage];
|
||||
f.W.RunDays(w.Calendar.DaysPerMonth + 1);
|
||||
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Storage] < storage || w.Player.LastYearEntries[(int)LedgerEntry.Storage] < 0, "giacenza addebitata");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bancarotta
|
||||
|
||||
[Test(Slow = true, Description = "Cassa negativa: avviso subito e alle scadenze fisse, bancarotta esattamente ai giorni di difficulty.json per ogni preset")]
|
||||
public static void BankruptcyFollowsTheDifficultyDays()
|
||||
{
|
||||
var fb = TestData.Data.Balance.Finance;
|
||||
foreach (var preset in TestData.Data.Difficulty.Presets)
|
||||
{
|
||||
var w = TestWorlds.NoAi(910, preset.Id);
|
||||
var c = w.Player;
|
||||
Assert.Equal(preset.BankruptcyDays, w.Difficulty.BankruptcyDays, preset.Id);
|
||||
SetCash(w, c, Money.FromLire(-1_000_000));
|
||||
w.Events.Drain();
|
||||
var warnings = new List<(int Day, GameEvent Event)>();
|
||||
int days = 0;
|
||||
while (!c.Bankrupt && days < preset.BankruptcyDays + 5)
|
||||
{
|
||||
w.RunDays(1);
|
||||
days++;
|
||||
foreach (var e in w.Events.Drain())
|
||||
{
|
||||
if (e.Kind == EventKind.Finance && e.Company == c.Id) warnings.Add((c.NegativeCashDays, e));
|
||||
}
|
||||
}
|
||||
Assert.True(c.Bankrupt, $"{preset.Id}: bancarotta");
|
||||
Assert.Equal(preset.BankruptcyDays, c.NegativeCashDays, $"{preset.Id}: giorni di cassa negativa");
|
||||
Assert.Equal(preset.BankruptcyDays, days, $"{preset.Id}: giorni trascorsi");
|
||||
int notice = fb.NegativeCashNoticeDays;
|
||||
Assert.True(warnings[0].Day == notice && warnings[0].Event.Text.Contains($"bancarotta arriva tra {preset.BankruptcyDays - notice} giorni"),
|
||||
$"{preset.Id}: {warnings[0].Event.Text}");
|
||||
foreach (int left in fb.BankruptcyWarningDaysLeft.Where(l => l < preset.BankruptcyDays - notice))
|
||||
{
|
||||
Assert.True(warnings.Any(x => x.Day == preset.BankruptcyDays - left && x.Event.Text.Contains($"bancarotta tra {(left == 1 ? "1 giorno" : $"{left} giorni")}")),
|
||||
$"{preset.Id}: avviso a {left} giorni");
|
||||
}
|
||||
var last = warnings[^1].Event;
|
||||
Assert.True(last.Severity == EventSeverity.Critical && last.Text.Contains("dichiarata la bancarotta"), last.Text);
|
||||
// l'esito segue la regola della difficoltà (ADR 0012): senza IA che la rilevino la partita finisce
|
||||
w.RunDays(1);
|
||||
Assert.True(w.GameOver is not null, $"{preset.Id}: fine partita");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
}
|
||||
|
||||
[Test(Description = "Se la cassa torna positiva il conto alla rovescia si azzera con un avviso; una cassa che oscilla intorno a zero non genera notizie")]
|
||||
public static void PositiveCashResetsTheCountdown()
|
||||
{
|
||||
var w = TestWorlds.NoAi(911);
|
||||
var c = w.Player;
|
||||
var cash = c.Cash;
|
||||
int notice = w.Data.Balance.Finance.NegativeCashNoticeDays;
|
||||
Assert.True(notice > 1 && notice < 5, "parametri del test");
|
||||
// oscillazioni più brevi del primo avviso: il contatore riparte, nessuna notizia
|
||||
w.Events.Drain();
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
SetCash(w, c, Money.FromLire(-50));
|
||||
w.RunDays(notice - 1);
|
||||
Assert.Equal(notice - 1, c.NegativeCashDays);
|
||||
SetCash(w, c, cash);
|
||||
w.RunDays(1);
|
||||
Assert.Equal(0, c.NegativeCashDays, "il conto alla rovescia si azzera");
|
||||
}
|
||||
Assert.False(w.Events.Drain().Any(e => e.Company == c.Id && e.Kind == EventKind.Finance), "nessun avviso per le oscillazioni");
|
||||
|
||||
SetCash(w, c, Money.FromLire(-1_000));
|
||||
w.RunDays(5);
|
||||
Assert.Equal(5, c.NegativeCashDays);
|
||||
var report = FinanceOutlook.Build(w, c.Id);
|
||||
Assert.Equal(5, report.NegativeCashDays);
|
||||
Assert.Equal(w.Difficulty.BankruptcyDays, report.BankruptcyDays);
|
||||
Assert.Equal(Money.FromLire(1_000), report.Overdraft);
|
||||
w.Events.Drain();
|
||||
SetCash(w, c, cash);
|
||||
w.RunDays(1);
|
||||
Assert.Equal(0, c.NegativeCashDays);
|
||||
Assert.True(w.Events.Drain().Any(e => e.Company == c.Id && e.Kind == EventKind.Finance && e.Text.Contains("torna positiva")), "avviso di rientro");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ salvataggi e determinismo
|
||||
|
||||
[Test(Description = "Mesi e anni chiusi e misure del rating nel salvataggio (versione 7) e nell'hash; la versione 6 si migra")]
|
||||
public static void FinanceStateSurvivesSavesAndMigrates()
|
||||
{
|
||||
var f = ServedValdoria(0);
|
||||
var w = f.W;
|
||||
var c = w.Player;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(30_000))).Ok);
|
||||
w.RunDays(w.Calendar.DaysPerYear + 2 * w.Calendar.DaysPerMonth);
|
||||
Assert.True(c.IncomeMonths.Count > 0 && c.IncomeYears.Count > 0 && c.RatingMonths > 0, "stato da salvare");
|
||||
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
var lc = loaded.Player;
|
||||
Assert.Equal(c.IncomeMonths.Count, lc.IncomeMonths.Count);
|
||||
for (int i = 0; i < c.IncomeMonths.Count; i++)
|
||||
{
|
||||
Assert.Equal((c.IncomeMonths[i].Year, c.IncomeMonths[i].Month), (lc.IncomeMonths[i].Year, lc.IncomeMonths[i].Month));
|
||||
Assert.SequenceEqual(c.IncomeMonths[i].Entries, lc.IncomeMonths[i].Entries);
|
||||
}
|
||||
Assert.SequenceEqual(c.IncomeYears[0].Entries, lc.IncomeYears[0].Entries);
|
||||
Assert.Equal(c.RatingScore, lc.RatingScore);
|
||||
Assert.Equal(c.RatingMargin, lc.RatingMargin);
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
|
||||
|
||||
// i mesi entrano nell'hash
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
c.IncomeMonths[0].Entries[(int)LedgerEntry.Wages]--;
|
||||
Assert.NotEqual(hash, StateHasher.Compute(w), "un mese chiuso cambia l'hash");
|
||||
c.IncomeMonths[0].Entries[(int)LedgerEntry.Wages]++;
|
||||
|
||||
// stesso futuro dopo il caricamento
|
||||
w.RunDays(40);
|
||||
loaded.RunDays(40);
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso futuro");
|
||||
|
||||
// versione 6: nessun mese conservato, l'anno chiuso dal registro, il rating resta
|
||||
var v6 = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, v6, 6);
|
||||
var migrated = WorldSerializer.Read(TestData.Data, new SaveReader(v6.WrittenSpan.ToArray()));
|
||||
var mc = migrated.Player;
|
||||
Assert.Equal(0, mc.IncomeMonths.Count);
|
||||
Assert.Equal(0, mc.RatingMonths);
|
||||
Assert.Equal(c.Rating, mc.Rating);
|
||||
Assert.Equal(1, mc.IncomeYears.Count);
|
||||
Assert.SequenceEqual(c.LastYearEntries, mc.IncomeYears[0].Entries);
|
||||
Assert.True(FinanceOutlook.Explain(migrated, mc).Initial, "spiegazione con le misure di oggi fino al primo calcolo");
|
||||
migrated.RunDays(w.Calendar.DaysPerMonth);
|
||||
Assert.Equal(1, mc.IncomeMonths.Count);
|
||||
Assert.Equal(1, mc.RatingMonths);
|
||||
Assert.Equal(0L, migrated.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "Stesso seme e stessi comandi finanziari danno lo stesso hash; denaro e merci restano in equilibrio")]
|
||||
public static void FinanceIsDeterministicAndKeepsInvariants()
|
||||
{
|
||||
ulong Run()
|
||||
{
|
||||
var f = ServedValdoria(0);
|
||||
var w = f.W;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(40_000))).Ok);
|
||||
w.RunDays(200);
|
||||
Assert.True(Do(w, new RepayLoanCommand(w.Player.Loans[0].Id, Money.FromLire(10_000))).Ok);
|
||||
w.RunDays(200);
|
||||
Assert.Equal(0L, w.MoneyBalanceSum(), "denaro");
|
||||
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
|
||||
return StateHasher.Compute(w);
|
||||
}
|
||||
Assert.Equal(Run(), Run());
|
||||
}
|
||||
|
||||
[Test(Description = "Il quadro delle finanze si proietta nel protocollo con le stesse somme del motore")]
|
||||
public static void ProjectionMatchesTheEngine()
|
||||
{
|
||||
var f = ServedValdoria(2 * 30);
|
||||
var w = f.W;
|
||||
Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(20_000))).Ok);
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
var report = FinanceOutlook.Build(w, w.Player.Id);
|
||||
var message = Projection.Finance(w, w.Player.Id);
|
||||
Assert.Equal(hash, StateHasher.Compute(w), "il quadro non cambia il mondo");
|
||||
Assert.Equal(report.Columns.Count, message.Columns.Count);
|
||||
for (int i = 0; i < report.Columns.Count; i++)
|
||||
{
|
||||
Assert.Equal(report.Columns[i].Profit, message.Columns[i].Profit);
|
||||
foreach (var line in message.Lines) Assert.Equal(report.Columns[i].Entries[line.Kind], message.Columns[i].Value(line.Kind).Cents);
|
||||
}
|
||||
Assert.Equal(w.Player.Rating.ToString(), message.Rating);
|
||||
Assert.Equal(1, message.LoanList.Count);
|
||||
Assert.Equal(report.LoanList[0].Payment, message.LoanList[0].Payment);
|
||||
Assert.Equal(w.Difficulty.BankruptcyDays, message.BankruptcyDays);
|
||||
}
|
||||
|
||||
[Test(Description = "I dividendi tra compagnie escono come dividendi pagati (fuori dall'utile) ed entrano come dividendi incassati (nell'utile)")]
|
||||
public static void DividendsReceivedCountInOperatingProfit()
|
||||
{
|
||||
var w = TestWorlds.Small(912);
|
||||
var payer = w.Companies.First(c => !c.Id.Equals(w.Player.Id));
|
||||
var me = w.Player;
|
||||
long profitBefore = Company.OperatingProfit(me.YearEntries), payerProfit = Company.OperatingProfit(payer.YearEntries);
|
||||
var amount = Money.FromLire(2_500);
|
||||
w.Money.Transfer(Account.Of(payer.Id), Account.Of(me.Id), amount, LedgerEntry.Dividends, LedgerEntry.DividendsReceived);
|
||||
Assert.Equal(amount.Cents, me.YearEntries[(int)LedgerEntry.DividendsReceived], "incassati");
|
||||
Assert.Equal(-amount.Cents, payer.YearEntries[(int)LedgerEntry.Dividends], "pagati");
|
||||
Assert.Equal(profitBefore + amount.Cents, Company.OperatingProfit(me.YearEntries), "nell'utile di chi incassa");
|
||||
Assert.Equal(payerProfit, Company.OperatingProfit(payer.YearEntries), "fuori dall'utile di chi paga");
|
||||
Assert.Equal(IncomeSection.Revenue, LedgerEntries.Section(LedgerEntry.DividendsReceived));
|
||||
Assert.Equal(IncomeSection.Capital, LedgerEntries.Section(LedgerEntry.Dividends));
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "La quota dei trasporti dei nuovi concorrenti conta solo tariffe, noli e contratti, non dividendi né commercio")]
|
||||
public static void TransportShareIgnoresDividendsAndTrading()
|
||||
{
|
||||
var e = new long[Company.EntryCount];
|
||||
e[(int)LedgerEntry.FreightRevenue] = 1_000;
|
||||
e[(int)LedgerEntry.PassengerRevenue] = 500;
|
||||
e[(int)LedgerEntry.Contracts] = 200;
|
||||
long transport = Company.TransportRevenue(e);
|
||||
Assert.Equal(1_700L, transport);
|
||||
e[(int)LedgerEntry.DividendsReceived] = 1_000_000;
|
||||
e[(int)LedgerEntry.Trading] = 50_000;
|
||||
e[(int)LedgerEntry.Subsidiaries] = 7_000;
|
||||
Assert.Equal(transport, Company.TransportRevenue(e), "dividendi, commercio e controllate fuori dalla quota");
|
||||
Assert.True(Company.Revenue(e) > transport, "restano nei ricavi del rating");
|
||||
}
|
||||
}
|
||||
@@ -226,9 +226,10 @@ public static class MarketOutlookTests
|
||||
Assert.False(trading.Unlocked);
|
||||
Assert.Equal(tier.Requirements.CreditRating, trading.RatingRequired);
|
||||
Assert.InRange(trading.Fraction, 0, 1);
|
||||
double worth = Math.Clamp((double)w.Player.NetWorth.Cents / tier.Requirements.NetWorth, 0, 1);
|
||||
double towns = Math.Clamp((double)trading.TownsConnected / tier.Requirements.ConnectedTownsOver.Count, 0, 1);
|
||||
Assert.Approx(Math.Min(worth, towns), trading.Fraction, 1e-12);
|
||||
// stesso avanzamento del pannello «La tua scalata» (ADR 0018): media dei tre requisiti
|
||||
var climb = ClimbOutlook.Requirements(w, w.Player, tier);
|
||||
Assert.Approx(climb.Progress, trading.Fraction, 1e-12);
|
||||
Assert.Approx((climb.NetWorthFraction + climb.TownsFraction + climb.RatingFraction) / 3, trading.Fraction, 1e-12);
|
||||
w.Player.Tier = tier.Level;
|
||||
Assert.True(MarketOutlook.Trading(w, f.Me).Unlocked);
|
||||
Assert.Equal(1.0, MarketOutlook.Trading(w, f.Me).Fraction);
|
||||
|
||||
@@ -158,6 +158,59 @@ public static class ProtocolTests
|
||||
new WarehouseInfo { Station = 5, Capacity = 500 },
|
||||
],
|
||||
};
|
||||
yield return new ClimbReport
|
||||
{
|
||||
Day = 2600, Company = 0, FoundedDay = 0, InitialCapital = new Money(25_000_000), Tier = 2, NextTier = 3,
|
||||
Tiers =
|
||||
[
|
||||
new TierInfo
|
||||
{
|
||||
Level = 1, NameIt = "Compagnia locale", NameEn = "Local company", RatingRequired = "D", Reached = true, ReachedDay = 0,
|
||||
Unlocks = [new UnlockInfo { Kind = UnlockInfo.LoanLimit, Value = 50_000_000 }, new UnlockInfo { Kind = UnlockInfo.Crews, Value = 2 }],
|
||||
},
|
||||
new TierInfo
|
||||
{
|
||||
Level = 3, NameIt = "Compagnia nazionale", NameEn = "National company", NetWorthRequired = new Money(100_000_000), TownsRequired = 3,
|
||||
TownPopulation = 1000, RatingRequired = "BBB", Reached = false, ReachedDay = -1,
|
||||
Unlocks = [new UnlockInfo { Kind = UnlockInfo.BuyIndustry }, new UnlockInfo { Kind = UnlockInfo.Concessions }],
|
||||
},
|
||||
],
|
||||
NetWorth = new Money(65_000_000), NetWorthRequired = new Money(100_000_000), NetWorthFraction = 0.65f, NetWorthMet = false,
|
||||
Towns = 1, TownsRequired = 3, TownPopulation = 1000, TownsFraction = 0.333f, TownsMet = false,
|
||||
Rating = "BBB", RatingRequired = "BBB", RatingFraction = 1, RatingMet = true, Progress = 0.661f,
|
||||
Assets = [new AmountInfo { Kind = ClimbReport.AssetTrack, Value = new Money(24_500_000) }, new AmountInfo { Kind = ClimbReport.AssetGoods, Value = new Money(-3) }],
|
||||
Portfolio = new Money(1_000), Cash = new Money(12_845_000), TotalAssets = new Money(51_145_000), Loans = new Money(12_000_000), LoansRate = 0.055f,
|
||||
Overdraft = new Money(7), TotalLiabilities = new Money(12_000_007), BalanceNetWorth = new Money(39_144_993),
|
||||
IncomeYear = 1871, IncomePartial = true,
|
||||
Income = [new AmountInfo { Kind = ClimbReport.IncomeFares, Value = new Money(19_600_000) }, new AmountInfo { Kind = ClimbReport.IncomeInterest, Value = new Money(-660_000) }],
|
||||
Profit = new Money(5_440_000),
|
||||
LoanList = [new LoanInfo { Loan = 4, Remaining = new Money(12_000_000), AnnualRate = 0.055f, MonthsLeft = 97 }],
|
||||
MaxLoan = new Money(100_000_000), LoanAvailable = new Money(88_000_000), NewLoanRate = 0.061f, LoansAllowed = false,
|
||||
History = [new NetWorthPointInfo { Day = 0, Value = new Money(25_000_000) }, new NetWorthPointInfo { Day = 2600, Value = new Money(39_144_993) }],
|
||||
};
|
||||
yield return new FinanceReport
|
||||
{
|
||||
Day = 2610, Company = 0, Cash = new Money(-120_000), NetWorth = new Money(39_000_000), Loans = new Money(12_000_000), Overdraft = new Money(120_000),
|
||||
Lines = [new FinanceLineInfo { Kind = 0, Section = FinanceLineInfo.SectionRevenue }, new FinanceLineInfo { Kind = 9, Section = FinanceLineInfo.SectionCost },
|
||||
new FinanceLineInfo { Kind = 2, Section = FinanceLineInfo.SectionCapital }],
|
||||
Columns =
|
||||
[
|
||||
new IncomeColumnInfo { Kind = IncomeColumnInfo.CurrentMonth, Year = 1872, Month = 3, Values = [new AmountInfo { Kind = 0, Value = new Money(150_000) }],
|
||||
Profit = new Money(150_000), CashFlow = new Money(150_000) },
|
||||
new IncomeColumnInfo { Kind = IncomeColumnInfo.ClosedYear, Year = 1871, Values = [new AmountInfo { Kind = 9, Value = new Money(-66_000) }, new AmountInfo { Kind = 2, Value = new Money(-1_000) }],
|
||||
Profit = new Money(-66_000), CashFlow = new Money(-67_000) },
|
||||
],
|
||||
Rating = "BBB", RatingInitial = false, RatingMonths = 12, RevenueMonths = 9, MarginNeutral = true, MinRevenueMonths = 3, Margin = 0.28f, Leverage = 0.31f, LeverageUnbounded = false,
|
||||
MarginWeight = 0.6f, LeverageWeight = 0.4f, MarginComponent = 0.78f, LeverageComponent = 0.76f, Score = 0.772f,
|
||||
Thresholds = [new RatingThresholdInfo { Rating = "AAA", MinScore = 0.85f, LoanRate = 0.055f }, new RatingThresholdInfo { Rating = "C", MinScore = 0.05f, LoanRate = 0.17f }],
|
||||
NextRating = "A", NextThreshold = 0.65f, NextAlreadyMet = true, ScoreRating = "AA", MarginNeeded = 0.31f, MarginReachable = true, LeverageMax = 0.12f, LeverageReachable = false,
|
||||
DebtToRepay = new Money(7_000_000), RepayAffordable = true,
|
||||
LoanList = [new FinanceLoanInfo { Loan = 4, Principal = new Money(15_000_000), Remaining = new Money(12_000_000), AnnualRate = 0.075f, MonthsLeft = 97,
|
||||
Payment = new Money(171_234), NextInterest = new Money(75_000), MaturityDay = 5520 }],
|
||||
MaxLoan = new Money(60_000_000), LoanAvailable = new Money(48_000_000), NewLoanRate = 0.075f, BaseRate = 0.05f, Spread = 0.025f,
|
||||
LoanTermMonths = 120, LoanStep = new Money(5_000_000), LoansAllowed = false,
|
||||
NegativeCashDays = 12, BankruptcyDays = 90, Bankrupt = false, Receivership = true,
|
||||
};
|
||||
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
|
||||
yield return new Notification { Event = SampleEvent() };
|
||||
yield return new Newspaper { Day = 30, Title = "La Cronaca di Valdoria", Articles = [("Nuova linea", "Inaugurata la linea per il valico."), ("Prezzi", "Il carbone sale.")] };
|
||||
|
||||
@@ -102,8 +102,9 @@ public sealed class TestClient : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
public Task<bool> WaitUntil(Func<bool> condition, string what, int timeoutMs = 60_000) =>
|
||||
WaitFor(() => condition() ? (object)true : null, what, timeoutMs).ContinueWith(_ => true);
|
||||
/// <summary>Come WaitFor; il tempo scaduto fa fallire il test (prima veniva ingoiato, #24).</summary>
|
||||
public async Task WaitUntil(Func<bool> condition, string what, int timeoutMs = 60_000) =>
|
||||
await WaitFor(() => condition() ? (object)true : null, what, timeoutMs);
|
||||
|
||||
/// <summary>Invia un comando e ne attende l'esito.</summary>
|
||||
public async Task<CommandResultMessage> Do(GameCommand command)
|
||||
@@ -185,19 +186,31 @@ public static class ServerTests
|
||||
await client.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Speed > 5, "treno in moto", 120_000);
|
||||
|
||||
// in pausa: la posizione disegnata dal client coincide con quella del server
|
||||
await client.Connection.SendAsync(new SetSpeed { Speed = 0 });
|
||||
// la pausa vale da quando il ciclo di gioco ha elaborato SetSpeed (sotto carico può tardare)
|
||||
for (int i = 0; i < 500 && server.Host.Speed != 0; i++) await Task.Delay(10);
|
||||
Assert.Equal((byte)0, server.Host.Speed);
|
||||
long tick;
|
||||
Vec2? head;
|
||||
while (true)
|
||||
// in pausa: la posizione disegnata dal client coincide con quella del server. La pausa
|
||||
// deve cogliere il treno in marcia: fermo (in stazione, a un segnale) il server non
|
||||
// rimanda il moto e il client ne tiene uno di un tick precedente (#24)
|
||||
long tick = 0;
|
||||
Vec2? head = null;
|
||||
for (int attempt = 0; ; attempt++)
|
||||
{
|
||||
(tick, head) = await server.Host.InvokeAsync(world => (world.Clock.Tick, Projection.HeadPoint(world, world.Trains[train])));
|
||||
await Task.Delay(60);
|
||||
long again = await server.Host.InvokeAsync(world => world.Clock.Tick);
|
||||
if (again == tick) break;
|
||||
await client.Connection.SendAsync(new SetSpeed { Speed = 0 });
|
||||
// la pausa vale da quando il ciclo di gioco ha elaborato SetSpeed (sotto carico può tardare)
|
||||
for (int i = 0; i < 500 && server.Host.Speed != 0; i++) await Task.Delay(10);
|
||||
Assert.Equal((byte)0, server.Host.Speed);
|
||||
float speed;
|
||||
while (true)
|
||||
{
|
||||
(tick, head, speed) = await server.Host.InvokeAsync(world =>
|
||||
(world.Clock.Tick, Projection.HeadPoint(world, world.Trains[train]), Projection.Motion(world, world.Trains[train])?.Speed ?? 0f));
|
||||
await Task.Delay(60);
|
||||
long again = await server.Host.InvokeAsync(world => world.Clock.Tick);
|
||||
if (again == tick) break;
|
||||
}
|
||||
if (speed > 0) break;
|
||||
Assert.True(attempt < 20, "in 20 pause il treno non era mai in marcia");
|
||||
await client.Connection.SendAsync(new SetSpeed { Speed = 8 });
|
||||
long paused = tick;
|
||||
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Tick > paused && m.Speed > 0, "treno di nuovo in moto", 120_000);
|
||||
}
|
||||
// in pausa il server rimanda i moti dei treni in marcia ogni 100 ms
|
||||
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Tick == tick, "moto all'ultimo tick", 10_000);
|
||||
@@ -296,6 +309,101 @@ public static class ServerTests
|
||||
Assert.True(report.TradingProgress is >= 0 and < 1, $"avanzamento {report.TradingProgress}");
|
||||
}
|
||||
|
||||
[Test(Description = "F6 in rete: il quadro della scalata arriva su richiesta con livelli, sblocchi, requisiti e stato patrimoniale")]
|
||||
public static void ClimbReportOnRequest() => RunClimb().GetAwaiter().GetResult();
|
||||
|
||||
private static async Task RunClimb()
|
||||
{
|
||||
var scenario = ScenarioHelper.Load("valdoria");
|
||||
await using var server = ServerFixture.Start(scenario.World);
|
||||
await using var client = await TestClient.ConnectAsync(server);
|
||||
var w = client.World;
|
||||
var data = TestData.Data;
|
||||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||||
|
||||
// il server non manda il quadro da solo: si aspetta la risposta a questa richiesta
|
||||
Assert.True(w.Climb is null, "nessun quadro prima della richiesta");
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
var report = await client.WaitFor(() => w.Climb, "quadro della scalata");
|
||||
Assert.True(report.Day >= 2, $"giorno {report.Day}");
|
||||
Assert.Equal(w.Summary!.CompanyId, report.Company);
|
||||
Assert.Equal((byte)1, report.Tier);
|
||||
Assert.Equal((byte)2, report.NextTier);
|
||||
Assert.Equal(data.Tiers.Tiers.Count, report.Tiers.Count);
|
||||
var tier = data.Tiers.Tiers[1];
|
||||
Assert.Equal(tier.NameIt, report.Tiers[1].NameIt);
|
||||
Assert.Equal(new Money(tier.Requirements.NetWorth), report.NetWorthRequired);
|
||||
Assert.Equal(tier.Requirements.CreditRating.ToString(), report.RatingRequired);
|
||||
Assert.True(report.Tiers[0].Reached && !report.Tiers[1].Reached, "solo il livello 1 raggiunto");
|
||||
Assert.True(report.Tiers[1].Unlocks.Any(u => u.Kind == UnlockInfo.Trading), "il livello 2 sblocca il commercio");
|
||||
Assert.True(report.Progress is >= 0 and < 1, $"avanzamento {report.Progress}");
|
||||
Assert.Equal(report.BalanceNetWorth, report.TotalAssets - report.TotalLiabilities);
|
||||
Assert.Equal(5, report.Assets.Count);
|
||||
Assert.True(report.History.Count >= 1, "storico del patrimonio");
|
||||
|
||||
// dopo un prestito una nuova richiesta riporta il debito: si aspetta la risposta nuova, non quella vecchia
|
||||
var result = await client.Do(new TakeLoanCommand(Money.FromLire(5_000)));
|
||||
Assert.True(result.Error == 0, result.Message);
|
||||
var stale = w.Climb;
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
var after = await client.WaitFor(() => ReferenceEquals(w.Climb, stale) ? null : w.Climb, "quadro aggiornato");
|
||||
Assert.Equal(1, after.LoanList.Count);
|
||||
Assert.Equal(Money.FromLire(5_000), after.Loans);
|
||||
}
|
||||
|
||||
[Test(Description = "Il quadro delle finanze arriva su richiesta e dopo un prestito riporta il prestito nuovo (ADR 0019)")]
|
||||
public static void FinanceReportOnRequest() => RunFinance().GetAwaiter().GetResult();
|
||||
|
||||
private static async Task RunFinance()
|
||||
{
|
||||
var scenario = ScenarioHelper.Load("valdoria");
|
||||
int limit = scenario.World.Difficulty.BankruptcyDays;
|
||||
await using var server = ServerFixture.Start(scenario.World);
|
||||
await using var client = await TestClient.ConnectAsync(server);
|
||||
var w = client.World;
|
||||
var data = TestData.Data;
|
||||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||||
|
||||
// il server non manda il quadro da solo: si aspetta la risposta a questa richiesta
|
||||
Assert.True(w.Finance is null, "nessun quadro prima della richiesta");
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||||
var report = await client.WaitFor(() => w.Finance, "quadro delle finanze");
|
||||
Assert.True(report.Day >= 2, $"giorno {report.Day}");
|
||||
Assert.Equal(w.Summary!.CompanyId, report.Company);
|
||||
Assert.Equal(global::RailEnterprise.Core.Economy.Company.EntryCount, report.Lines.Count);
|
||||
Assert.Equal(IncomeColumnInfo.CurrentMonth, report.Columns[0].Kind);
|
||||
Assert.True(report.Columns.Any(c => c.Kind == IncomeColumnInfo.CurrentYear), "colonna dell'anno in corso");
|
||||
foreach (var col in report.Columns)
|
||||
{
|
||||
long operating = report.Lines.Where(l => l.Section != FinanceLineInfo.SectionCapital).Sum(l => col.Value(l.Kind).Cents);
|
||||
Assert.Equal(col.Profit.Cents, operating, $"le voci d'esercizio sommano all'utile ({col.Kind} {col.Month}/{col.Year})");
|
||||
}
|
||||
Assert.Equal(data.Balance.Finance.RatingByScore.Length, report.Thresholds.Count);
|
||||
// con TickMs = 1 il primo mese può già essere passato su una macchina lenta: il rating iniziale vale solo prima
|
||||
int dpm = scenario.World.Calendar.DaysPerMonth;
|
||||
if (report.Day < dpm) Assert.True(report.RatingInitial, "prima del primo mese il rating è quello iniziale");
|
||||
Assert.Equal(limit, report.BankruptcyDays);
|
||||
Assert.Equal(0, report.LoanList.Count);
|
||||
|
||||
// dopo un prestito una nuova richiesta riporta il prestito: si aspetta la risposta nuova, non quella vecchia
|
||||
var result = await client.Do(new TakeLoanCommand(Money.FromLire(5_000)));
|
||||
Assert.True(result.Error == 0, result.Message);
|
||||
var stale = w.Finance;
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Finance, Target = 0 });
|
||||
var after = await client.WaitFor(() => ReferenceEquals(w.Finance, stale) ? null : w.Finance, "quadro aggiornato");
|
||||
Assert.Equal(1, after.LoanList.Count);
|
||||
var loan = after.LoanList[0];
|
||||
Assert.Equal(Money.FromLire(5_000), loan.Principal);
|
||||
// il tasso del prestito è quello di un rating (base + spread all'accensione); se il quadro è dello stesso
|
||||
// mese del prestito il rating non è cambiato e coincide con il tasso di un prestito nuovo
|
||||
double baseRate = scenario.World.Difficulty.BaseInterestRate;
|
||||
var rates = data.Balance.Finance.RatingSpreads.Values.Select(s => (float)(baseRate + s)).ToList();
|
||||
Assert.True(rates.Any(r => Math.Abs(r - loan.AnnualRate) < 1e-6), $"tasso {loan.AnnualRate} = base + spread di un rating");
|
||||
if (after.Day / dpm == report.Day / dpm) Assert.Approx(after.NewLoanRate, loan.AnnualRate, 1e-6, "tasso fissato all'accensione");
|
||||
Assert.True(loan.Payment.Cents > 0 && loan.MaturityDay > after.Day, "rata e scadenza");
|
||||
Assert.Equal(Money.FromLire(5_000), after.Loans);
|
||||
}
|
||||
|
||||
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
|
||||
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();
|
||||
|
||||
|
||||
Reference in new issue
Block a user