Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e5215c570 | ||
|
|
d473e21708 | ||
|
|
a61bf1dc27 | ||
|
|
640d4423d7 | ||
|
|
208faf625f | ||
|
|
d6b631405b | ||
|
|
357a743e91 | ||
|
|
5abf3645bb | ||
|
|
dafe9f6d11 | ||
|
|
5a4a156d52 | ||
|
|
1f8da87e51 | ||
|
|
b258e0858a | ||
|
|
596ce2c376 | ||
|
|
e157dd77bc | ||
|
|
3f00acb994 | ||
|
|
b2de314d7c | ||
|
|
2992e7cc36 | ||
|
|
bfbdb6297e |
No files matched your search
@@ -2,7 +2,7 @@
|
||||
<!-- Impostazioni comuni a tutti i progetti .NET di Rail Enterprise (il client Godot ha il proprio). -->
|
||||
<PropertyGroup>
|
||||
<!-- Unica fonte della versione: letta anche da scripts/publish-image.sh e dal protocollo. -->
|
||||
<Version>0.5.2</Version>
|
||||
<Version>0.6.0</Version>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
|
||||
@@ -442,3 +442,165 @@ ultimi,,last
|
||||
vincitore,,winner
|
||||
"volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.",,"times annual profit, divided by the shares and multiplied by market sentiment."
|
||||
⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto.,,⚠ Out of spare parts: plant recovery is halved. Bring them by train from a machinery factory or a port.
|
||||
30 giorni,,30 days
|
||||
Avanzamento verso,,Progress towards
|
||||
Capacità,,Capacity
|
||||
Capacità usata questo mese,,Capacity used this month
|
||||
Città collegate oltre,,Connected towns over
|
||||
Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello,,Buy goods at the source and resell them where the price is highest. Unlocked at level
|
||||
Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello,,Buy goods at the source and resell them where the price is highest. Unlocks at level
|
||||
Compravendita in proprio,,Own-account trading
|
||||
Consumi della mappa,,Map consumption
|
||||
Dazio,,Duty
|
||||
Disponibile dal,,Available from
|
||||
Domanda globale,,Global demand
|
||||
Dove conviene vendere,,Where to sell
|
||||
Evento in corso,,Current event
|
||||
Hub verso il mercato mondiale via mare,,Hub to the world market by sea
|
||||
Hub verso il mercato mondiale via terra,,Hub to the world market by land
|
||||
"I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse.",,"World prices follow their multi-year cycle, with no shocks."
|
||||
Il prezzo mondiale di,,The world price of
|
||||
In attesa dei prezzi dal server…,,Waiting for prices from the server…
|
||||
Indice materie prime,,Commodity index
|
||||
Lo storico si forma giorno dopo giorno,,The history builds up day by day
|
||||
"Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni.",,"Average of the global prices of the available goods relative to their base price (100 = base prices), with the change over the last 30 days."
|
||||
Mercato globale,,Global market
|
||||
Merce,,Goods
|
||||
Nessun evento in corso,,No current event
|
||||
Nessuna industria consuma questa merce e nessun hub la compra.,,No industry consumes these goods and no hub buys them.
|
||||
Non ancora disponibili,,Not yet available
|
||||
Offerta,,Supply
|
||||
Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub.,,Supply and demand add the map's production and consumption to the share of the world market traded through the hubs.
|
||||
Offerta globale,,Global supply
|
||||
Offerta · domanda,,Supply · demand
|
||||
Pianifica la linea,,Plan the line
|
||||
Porta i binari fino al confine per comprare e vendere via terra.,,Lay track to the border to buy and sell by land.
|
||||
Porta i binari fino al porto per comprare e vendere via mare.,,Lay track to the port to buy and sell by sea.
|
||||
"Prezzo locale della compravendita in proprio: più alto dove il magazzino è vuoto; gli hub comprano al prezzo mondiale meno il dazio. Le consegne del vettore restano pagate al prezzo globale. Il trasporto è a parte.",,"Local price for own trading: higher where storage is empty; hubs buy at the world price minus duty. Carrier deliveries are still paid at the global price. Transport is extra."
|
||||
Prezzi mondiali al,,World prices as of
|
||||
Prezzo,,Price
|
||||
"Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza.",,"Global price at the end of each month; the dashed line is the forecast from the world component (cycle and fading shocks), the blue band its uncertainty."
|
||||
Produzione della mappa,,Map production
|
||||
Scegli una merce a sinistra,,Pick goods on the left
|
||||
Servito da,,Served by
|
||||
Torna alla mappa,,Back to the map
|
||||
aggiornati ogni giorno di gioco,,updated every game day
|
||||
ago,,Aug
|
||||
apr,,Apr
|
||||
collegato,,connected
|
||||
dic,,Dec
|
||||
domanda,,demand
|
||||
esportazione,,export
|
||||
feb,,Feb
|
||||
gen,,Jan
|
||||
giu,,Jun
|
||||
in 30 giorni,,in 30 days
|
||||
lug,,Jul
|
||||
mag,,May
|
||||
mar,,Mar
|
||||
mese,,month
|
||||
mesi e previsione a,,months and forecast for
|
||||
"nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa",,"in industry storage and at stations, divided by the map's monthly demand"
|
||||
nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino,,none of your stations served by a line with trains has this destination in its catchment
|
||||
non collegato,,not connected
|
||||
nov,,Nov
|
||||
oggi,,today
|
||||
ott,,Oct
|
||||
prev.,,fcst.
|
||||
prezzo mondiale in calo,,world price falling
|
||||
prezzo mondiale in rialzo,,world price rising
|
||||
quota mondiale dagli hub,,world share through the hubs
|
||||
rispetto al ciclo per circa,,compared with the cycle for about
|
||||
serve,,needs
|
||||
servita dalla tua linea,,served by your line
|
||||
set,,Sep
|
||||
unità/mese,,units/month
|
||||
è più alto del,,is higher by
|
||||
è più basso del,,is lower by
|
||||
Spedisci a,,Ship to
|
||||
Quantità,,Quantity
|
||||
"Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato.",,"Buys from producers and hubs in the station's catchment, cheapest first, up to 10% above the quoted price."
|
||||
"Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato.",,"Sells from the warehouse to consumers and hubs in the catchment, highest price first, down to 10% below the quoted price."
|
||||
"Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa.",,"Ships the goods on your lines to the warehouse of another of your stations, with no fare."
|
||||
In magazzino,,In the warehouse
|
||||
Costruisci una stazione per avere un magazzino dove comprare e vendere.,,Build a station to get a warehouse where you can buy and sell.
|
||||
in magazzino,,in the warehouse
|
||||
Si compra a,,Buy at
|
||||
disponibili,,available
|
||||
Nessun produttore né hub nel bacino la vende,,No producer or hub in the catchment sells it
|
||||
si vende a,,sell at
|
||||
richieste,,wanted
|
||||
nessun consumatore né hub nel bacino la compra,,no consumer or hub in the catchment buys it
|
||||
Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.,,Local price: it rises as the seller runs low and falls as the buyer fills up.
|
||||
Magazzino,,Warehouse
|
||||
unità,,units
|
||||
di cui,,of which
|
||||
Vuoto,,Empty
|
||||
Scegli una stazione di arrivo diversa da quella di partenza,,Choose a destination station different from the departure one
|
||||
"Hai merce nei magazzini: puoi venderla o spedirla, ma non comprarne altra.",,"You have goods in your warehouses: you can sell or ship them, but not buy more."
|
||||
Eventi in corso,,Current events
|
||||
altri,,more
|
||||
Capacità produttiva,,Production capacity
|
||||
Consumi della città,,Town consumption
|
||||
Domanda di,,Demand for
|
||||
Presenze al lavoro,,Attendance at work
|
||||
Velocità dei treni,,Train speed
|
||||
Usura dei binari,,Track wear
|
||||
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
|
||||
|
@@ -235,6 +235,16 @@ public partial class AutoPilot : Node
|
||||
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
|
||||
await Shot("14_compagnia_giocatore", 40);
|
||||
|
||||
// Mercato globale (immagine 06): storico, previsione, hub ed evento in corso
|
||||
_game.OpenMarket();
|
||||
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);
|
||||
|
||||
// Cronaca provvisoria
|
||||
_game.OpenChronicle();
|
||||
await Until(() => _game.ChronicleVisible, "cronaca", 30);
|
||||
|
||||
@@ -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,6 +1,8 @@
|
||||
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;
|
||||
@@ -11,6 +13,12 @@ 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();
|
||||
@@ -83,7 +105,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");
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Panels;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
|
||||
/// <summary>
|
||||
/// Riquadro «Eventi in corso» del pannello destro, sopra la minimappa (ADR 0017): gli eventi del
|
||||
/// mondo attivi dal resoconto giornaliero, con luogo, effetti e scadenza. Nascosto se non ce ne sono.
|
||||
/// </summary>
|
||||
public partial class WorldEventsBox : PanelContainer
|
||||
{
|
||||
private readonly VBoxContainer _list = new();
|
||||
private readonly Label _title = UiTheme.Text("", 13, Palette.AmberLight, bold: true);
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 8, 10));
|
||||
var col = new VBoxContainer();
|
||||
col.AddThemeConstantOverride("separation", 6);
|
||||
AddChild(col);
|
||||
col.AddChild(_title);
|
||||
_list.AddThemeConstantOverride("separation", 8);
|
||||
col.AddChild(_list);
|
||||
Visible = false;
|
||||
}
|
||||
|
||||
/// <summary>Ridisegna l'elenco (a ogni resoconto giornaliero).</summary>
|
||||
public void Update(ClientWorld w)
|
||||
{
|
||||
var events = w.LastDigest?.WorldEvents ?? [];
|
||||
Visible = events.Count > 0;
|
||||
foreach (var c in _list.GetChildren()) c.QueueFree();
|
||||
_title.Text = $"{T("Eventi in corso")} ({events.Count})";
|
||||
// al massimo quattro righe: il riquadro non deve schiacciare la minimappa
|
||||
foreach (var e in events.OrderBy(e => e.EndDay).Take(4)) _list.AddChild(WorldEventText.Row(w, e));
|
||||
if (events.Count > 4) _list.AddChild(UiTheme.Text($"+ {events.Count - 4} {T("altri")}", 12, Palette.TextSecondary));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
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;
|
||||
_borrow.TooltipText = report is null ? "" : report.LoansAllowed
|
||||
? $"{T("Fido disponibile")} {report.LoanAvailable} {T("su")} {report.MaxLoan}, {T("al")} {Fmt.Pct(report.NewLoanRate, 1)}"
|
||||
: 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -142,6 +142,7 @@ public partial class InfoPanel : VBoxContainer
|
||||
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
|
||||
}
|
||||
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
|
||||
WorldEventText.AddNotices(w, this, WorldEventText.Industry, ind.Id);
|
||||
// pannello del proprietario (sezione 11): manutenzione degli impianti o acquisto
|
||||
int me = w.Summary?.CompanyId ?? 0;
|
||||
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
|
||||
@@ -180,6 +181,7 @@ public partial class InfoPanel : VBoxContainer
|
||||
AddChild(PanelKit.Pair(T("Abitanti"), PanelKit.Value(Money.GroupThousands((ulong)town.Population))));
|
||||
AddChild(PanelKit.Pair(T("Soddisfazione"), PanelKit.Value($"{town.Satisfaction * 100:0}%")));
|
||||
AddChild(PanelKit.Pair(T("Servizi"), PanelKit.Value($"{town.Services}")));
|
||||
WorldEventText.AddNotices(w, this, WorldEventText.Town, town.Id);
|
||||
// dove lavorano gli abitanti (posti serviti dai tuoi treni)
|
||||
if (w.Employment is { } report)
|
||||
{
|
||||
|
||||
@@ -279,6 +279,8 @@ public partial class MaintenancePanel : VBoxContainer
|
||||
stats.AddChild(PanelKit.Stat(T("Ricambi"), PanelKit.Value($"{d.SpareParts}")));
|
||||
_workshop.AddChild(stats);
|
||||
if (d.WaitingParts) _workshop.AddChild(UiTheme.Notice(T("Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.")));
|
||||
// sciopero del personale del deposito (ADR 0017)
|
||||
WorldEventText.AddNotices(w, _workshop, WorldEventText.Depot, _depot);
|
||||
if (reg is not null)
|
||||
{
|
||||
if (reg.WorkRate < 0.999f)
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// «Mercato globale» a tutto schermo (immagine di riferimento 06): a sinistra i beni con prezzo,
|
||||
/// variazione a 30 giorni e barre di offerta e domanda; al centro il bene scelto con lo storico a
|
||||
/// 24 mesi, la previsione, offerta, domanda, scorte e «Dove conviene vendere»; a destra gli hub,
|
||||
/// l'evento di mercato in corso e l'avanzamento verso la compravendita in proprio. Tutti i numeri
|
||||
/// arrivano dal server (MarketReport, ADR 0015): il pannello li chiede all'apertura e a ogni nuovo
|
||||
/// giorno e li mostra com'è.
|
||||
/// </summary>
|
||||
public partial class MarketPanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _index = UiTheme.Text("", 22, bold: true);
|
||||
private readonly Label _indexChange = UiTheme.Text("", 16, bold: true);
|
||||
private readonly VBoxContainer _rows = PanelKit.Column(2);
|
||||
private readonly Label _later = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private readonly Label _goodTitle = UiTheme.TitleLabel("", 40);
|
||||
private readonly Label _goodCaption = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _goodPrice = UiTheme.Text("", 26, bold: true);
|
||||
private readonly Label _goodChange = UiTheme.Text("", 14, bold: true);
|
||||
private readonly SeriesChart _chart = new(250);
|
||||
private readonly HBoxContainer _stats = PanelKit.Row(10);
|
||||
private readonly VBoxContainer _sell = PanelKit.Column(4);
|
||||
private readonly VBoxContainer _right = PanelKit.Column(14);
|
||||
private readonly Dictionary<int, GoodRow> _rowByGood = [];
|
||||
private readonly TradeBox _trade;
|
||||
private MarketReport? _shown;
|
||||
private string _rowsKey = "";
|
||||
private int _selected = -1;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action? CloseRequested;
|
||||
/// <summary>Chiesto di pianificare una linea verso un hub (strumento binari centrato sull'hub).</summary>
|
||||
public event Action<int>? PlanLineRequested;
|
||||
|
||||
public MarketPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
_trade = new TradeBox(session);
|
||||
// dopo un comando di compravendita si chiede subito il quadro aggiornato (giacenze e prezzi)
|
||||
_trade.Traded += () => _requestedDay = long.MinValue;
|
||||
AddThemeConstantOverride("separation", 14);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
var header = PanelKit.Row(16);
|
||||
var titles = PanelKit.Column(0);
|
||||
titles.AddChild(UiTheme.TitleLabel(T("Mercato globale"), 40));
|
||||
titles.AddChild(_subtitle);
|
||||
header.AddChild(titles);
|
||||
var index = PanelKit.Column(0);
|
||||
index.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
|
||||
index.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var indexCaption = UiTheme.Text(T("Indice materie prime"), 13, Palette.TextSecondary);
|
||||
indexCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
index.AddChild(indexCaption);
|
||||
var indexRow = new HBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
|
||||
indexRow.AddThemeConstantOverride("separation", 8);
|
||||
indexRow.AddChild(_index);
|
||||
indexRow.AddChild(_indexChange);
|
||||
index.AddChild(indexRow);
|
||||
index.TooltipText = T("Media dei prezzi globali dei beni disponibili rispetto al loro prezzo base (100 = prezzi base), con la variazione degli ultimi 30 giorni.");
|
||||
index.MouseFilter = MouseFilterEnum.Pass;
|
||||
header.AddChild(index);
|
||||
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(150, 44) };
|
||||
close.Pressed += () => CloseRequested?.Invoke();
|
||||
header.AddChild(close);
|
||||
AddChild(header);
|
||||
|
||||
var body = PanelKit.Row(16);
|
||||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
AddChild(body);
|
||||
|
||||
var left = Column(body, 1.05f);
|
||||
left.AddChild(TableHeader());
|
||||
left.AddChild(PanelKit.Separator());
|
||||
left.AddChild(_rows);
|
||||
_later.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
left.AddChild(_later);
|
||||
left.AddChild(Wrapped(T("Offerta e domanda sommano produzione e consumi della mappa con la quota del mercato mondiale scambiata dagli hub."), 12, Palette.TextSecondary));
|
||||
|
||||
var center = Column(body, 1.35f);
|
||||
var top = PanelKit.Row(12);
|
||||
var names = PanelKit.Column(0);
|
||||
names.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
names.AddChild(_goodTitle);
|
||||
names.AddChild(_goodCaption);
|
||||
top.AddChild(names);
|
||||
var price = PanelKit.Column(0);
|
||||
price.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
|
||||
_goodPrice.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_goodChange.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
price.AddChild(_goodPrice);
|
||||
price.AddChild(_goodChange);
|
||||
top.AddChild(price);
|
||||
center.AddChild(top);
|
||||
center.AddChild(_chart);
|
||||
center.AddChild(_stats);
|
||||
center.AddChild(UiTheme.Text(T("Dove conviene vendere"), 16, bold: true));
|
||||
center.AddChild(_sell);
|
||||
|
||||
var right = Column(body, 0.8f);
|
||||
right.AddChild(_right);
|
||||
|
||||
_subtitle.Text = T("In attesa dei prezzi dal server…");
|
||||
}
|
||||
|
||||
public override void _Notification(int what)
|
||||
{
|
||||
// il riquadro della compravendita fuori dall'albero (commercio non sbloccato) va liberato a mano
|
||||
if (what == NotificationPredelete && IsInstanceValid(_trade) && _trade.GetParent() is null) _trade.Free();
|
||||
}
|
||||
|
||||
/// <summary>Bene mostrato al centro (−1 se nessuno).</summary>
|
||||
public int Selected => _selected;
|
||||
|
||||
public void Select(int good)
|
||||
{
|
||||
_selected = good;
|
||||
foreach (var (id, row) in _rowByGood) row.SetSelected(id == good);
|
||||
if (_session.World.Market is { } report)
|
||||
{
|
||||
ShowGood(_session.World, report);
|
||||
_trade.Update(report, good, report.TradingUnlocked);
|
||||
}
|
||||
}
|
||||
|
||||
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, 10, 18));
|
||||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
frame.AddChild(scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
scroll.AddChild(margin);
|
||||
var col = PanelKit.Column(12);
|
||||
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.Market is null && _sinceRequest > 5))
|
||||
{
|
||||
_requestedDay = today;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Market, Target = 0 });
|
||||
}
|
||||
if (w.Market is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||
}
|
||||
|
||||
private void Refresh(ClientWorld w, MarketReport report)
|
||||
{
|
||||
_shown = report;
|
||||
_subtitle.Text = $"{T("Prezzi mondiali al")} {Fmt.Date(w, report.Day)}, {T("aggiornati ogni giorno di gioco")}";
|
||||
_index.Text = Fmt.Number(report.Index, 1);
|
||||
SetChange(_indexChange, report.IndexChange, "");
|
||||
RefreshRows(w, report);
|
||||
if (_selected < 0 || report.Goods.All(g => g.Good != _selected))
|
||||
_selected = report.Goods.Where(g => g.Available).Select(g => g.Good).DefaultIfEmpty(0).First();
|
||||
foreach (var (id, row) in _rowByGood) row.SetSelected(id == _selected);
|
||||
ShowGood(w, report);
|
||||
RefreshRight(w, report);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ dati di comodo (solo lettura)
|
||||
|
||||
private static string GoodName(ClientWorld w, int good)
|
||||
{
|
||||
var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)];
|
||||
return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
|
||||
}
|
||||
|
||||
private static string Unit(ClientWorld w, int good) => w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)].Unit;
|
||||
|
||||
private static string Price(double cents) => Money.FromCentsRounded(cents).ToString();
|
||||
|
||||
private static string PerUnit(ClientWorld w, int good, double cents) => $"{Price(cents)} / {Unit(w, good)}";
|
||||
|
||||
/// <summary>Quantità intera con il punto delle migliaia («41.200»).</summary>
|
||||
private static string Quantity(double units) => Fmt.Number(Math.Round(units), 0);
|
||||
|
||||
private static string LineName(ClientWorld w, int line) =>
|
||||
w.Lines.TryGetValue(line, out var l) ? l.Name : $"{T("Linea")} {line + 1}";
|
||||
|
||||
/// <summary>Variazione con la freccia: ambra in salita, azzurro in discesa (immagine 06).</summary>
|
||||
private static void SetChange(Label label, double change, string suffix)
|
||||
{
|
||||
bool up = change > 0.0005, down = change < -0.0005;
|
||||
string arrow = up ? "▲ " : down ? "▼ " : "= ";
|
||||
label.Text = arrow + Fmt.Pct(Math.Abs(change)) + suffix;
|
||||
label.AddThemeColorOverride("font_color", up ? Palette.AmberLight : down ? Palette.Staff : Palette.TextSecondary);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ elenco dei beni
|
||||
|
||||
private const float WPrice = 96, WChange = 86, WBars = 110;
|
||||
|
||||
private static Control TableHeader()
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
var name = UiTheme.Text(T("Merce"), 13, Palette.TextSecondary);
|
||||
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
row.AddChild(new Control { CustomMinimumSize = new Vector2(4, 0) });
|
||||
row.AddChild(name);
|
||||
foreach (var (text, width) in new[] { (T("Prezzo"), WPrice), (T("30 giorni"), WChange), (T("Offerta · domanda"), WBars) })
|
||||
{
|
||||
var l = UiTheme.Text(text, 13, Palette.TextSecondary);
|
||||
l.CustomMinimumSize = new Vector2(width, 0);
|
||||
row.AddChild(l);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private void RefreshRows(ClientWorld w, MarketReport report)
|
||||
{
|
||||
var available = report.Goods.Where(g => g.Available).ToList();
|
||||
string key = string.Join(",", available.Select(g => g.Good));
|
||||
if (key != _rowsKey)
|
||||
{
|
||||
_rowsKey = key;
|
||||
foreach (var c in _rows.GetChildren()) c.QueueFree();
|
||||
_rowByGood.Clear();
|
||||
foreach (var g in available)
|
||||
{
|
||||
int id = g.Good;
|
||||
var row = new GoodRow();
|
||||
row.Pressed += () => Select(id);
|
||||
_rowByGood[id] = row;
|
||||
_rows.AddChild(row);
|
||||
}
|
||||
}
|
||||
foreach (var g in available)
|
||||
{
|
||||
double supply = g.SupplyMonth + g.WorldSupplyMonth, demand = g.DemandMonth + g.WorldDemandMonth;
|
||||
_rowByGood[g.Good].Update(GoodName(w, g.Good), PerUnit(w, g.Good, g.Price), g.Change, supply, demand,
|
||||
$"{GoodName(w, g.Good)}\n{T("Offerta")} {Quantity(supply)} {Unit(w, g.Good)}/{T("mese")} · {T("domanda")} {Quantity(demand)} {Unit(w, g.Good)}/{T("mese")}");
|
||||
}
|
||||
var later = report.Goods.Where(g => !g.Available).Select(g => $"{GoodName(w, g.Good)} ({w.Data.Goods[g.Good].Era})").ToList();
|
||||
_later.Text = later.Count > 0 ? $"{T("Non ancora disponibili")}: {string.Join(", ", later)}" : "";
|
||||
_later.Visible = later.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>Riga di un bene: pulsante piatto con nome, prezzo, variazione e barre di offerta e domanda.</summary>
|
||||
private sealed partial class GoodRow : Button
|
||||
{
|
||||
private readonly Label _name = UiTheme.Text("", 16, bold: true);
|
||||
private readonly Label _price = UiTheme.Text("", 15);
|
||||
private readonly Label _change = UiTheme.Text("", 14, bold: true);
|
||||
private readonly SupplyDemandBars _bars = new();
|
||||
|
||||
public GoodRow()
|
||||
{
|
||||
CustomMinimumSize = new Vector2(0, 58);
|
||||
FocusMode = FocusModeEnum.None;
|
||||
AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.Border, 8, 8));
|
||||
AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8));
|
||||
SetSelected(false);
|
||||
var row = new HBoxContainer { MouseFilter = MouseFilterEnum.Ignore };
|
||||
row.AddThemeConstantOverride("separation", 8);
|
||||
row.SetAnchorsPreset(LayoutPreset.FullRect);
|
||||
row.OffsetLeft = 12;
|
||||
row.OffsetRight = -8;
|
||||
AddChild(row);
|
||||
_name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_name.ClipText = true;
|
||||
_name.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||||
_name.CustomMinimumSize = new Vector2(24, 0);
|
||||
foreach (var (l, width) in new[] { (_name, 0f), (_price, WPrice), (_change, WChange) })
|
||||
{
|
||||
if (width > 0) l.CustomMinimumSize = new Vector2(width, 0);
|
||||
l.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
l.MouseFilter = MouseFilterEnum.Ignore;
|
||||
row.AddChild(l);
|
||||
}
|
||||
_bars.CustomMinimumSize = new Vector2(WBars, 22);
|
||||
_bars.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
row.AddChild(_bars);
|
||||
}
|
||||
|
||||
public void SetSelected(bool on) =>
|
||||
AddThemeStyleboxOverride("normal", on ? UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8) : UiTheme.Box(Palette.Panel, Palette.Panel, 8, 8));
|
||||
|
||||
public void Update(string name, string price, double change, double supply, double demand, string tooltip)
|
||||
{
|
||||
_name.Text = name;
|
||||
_price.Text = price;
|
||||
SetChange(_change, change, "");
|
||||
_bars.Set(supply, demand);
|
||||
TooltipText = tooltip;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Due barre sovrapposte: offerta in azzurro, domanda in ambra, riferite alla maggiore delle due.</summary>
|
||||
private sealed partial class SupplyDemandBars : Control
|
||||
{
|
||||
private double _supply, _demand;
|
||||
|
||||
public SupplyDemandBars() => MouseFilter = MouseFilterEnum.Ignore;
|
||||
|
||||
public void Set(double supply, double demand)
|
||||
{
|
||||
_supply = supply;
|
||||
_demand = demand;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
double top = Math.Max(1e-9, Math.Max(_supply, _demand) * 1.2);
|
||||
float h = 6, gap = 5;
|
||||
float y0 = (Size.Y - 2 * h - gap) / 2;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
var y = y0 + i * (h + gap);
|
||||
double v = i == 0 ? _supply : _demand;
|
||||
DrawRect(new Rect2(0, y, Size.X, h), Palette.Inner);
|
||||
DrawRect(new Rect2(0, y, (float)(Size.X * Math.Clamp(v / top, 0, 1)), h), i == 0 ? Palette.Staff : Palette.Amber);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bene scelto
|
||||
|
||||
private void ShowGood(ClientWorld w, MarketReport report)
|
||||
{
|
||||
var g = report.Goods.FirstOrDefault(x => x.Good == _selected);
|
||||
foreach (var c in _stats.GetChildren()) c.QueueFree();
|
||||
foreach (var c in _sell.GetChildren()) c.QueueFree();
|
||||
if (g is null)
|
||||
{
|
||||
_goodTitle.Text = "";
|
||||
_goodCaption.Text = "";
|
||||
_goodPrice.Text = "";
|
||||
_goodChange.Text = "";
|
||||
_chart.Show([], [], Price, SeriesChart.Style.Line, Palette.Amber, T("Scegli una merce a sinistra"));
|
||||
return;
|
||||
}
|
||||
_goodTitle.Text = GoodName(w, g.Good);
|
||||
int months = g.History.Count;
|
||||
_goodCaption.Text = g.Forecast.Count > 0
|
||||
? $"{T("Storico")} {months} {T("mesi e previsione a")} {g.Forecast.Count} {T("mesi")}"
|
||||
: $"{T("Storico")} {months} {T("mesi")}";
|
||||
_goodPrice.Text = PerUnit(w, g.Good, g.Price);
|
||||
SetChange(_goodChange, g.Change, " " + T("in 30 giorni"));
|
||||
|
||||
var labels = g.History.Select((p, i) => i == g.History.Count - 1 ? "" : MonthLabel(w, p.Day)).ToList();
|
||||
_chart.ShowWithForecast(g.History.Select(p => p.Price).ToList(), labels,
|
||||
g.Forecast.Select(f => f.Price).ToList(), g.Forecast.Select(f => f.Low).ToList(), g.Forecast.Select(f => f.High).ToList(),
|
||||
Price, Palette.Amber, T("Lo storico si forma giorno dopo giorno"), T("oggi"), g.Forecast.Count > 0 ? T("prev.") : "");
|
||||
_chart.TooltipText = T("Prezzo globale a fine mese; la linea tratteggiata è la previsione dalla componente mondiale (ciclo e shock che si attenuano), la fascia azzurra l'incertezza.");
|
||||
_chart.MouseFilter = MouseFilterEnum.Pass;
|
||||
|
||||
string unit = Unit(w, g.Good);
|
||||
double supply = g.SupplyMonth + g.WorldSupplyMonth, demand = g.DemandMonth + g.WorldDemandMonth;
|
||||
AddStat(T("Offerta globale"), $"{Quantity(supply)} {unit}/{T("mese")}",
|
||||
$"{T("Produzione della mappa")} {Quantity(g.SupplyMonth)} {unit} + {T("quota mondiale dagli hub")} {Quantity(g.WorldSupplyMonth)} {unit}");
|
||||
AddStat(T("Domanda globale"), $"{Quantity(demand)} {unit}/{T("mese")}",
|
||||
$"{T("Consumi della mappa")} {Quantity(g.DemandMonth)} {unit} + {T("quota mondiale dagli hub")} {Quantity(g.WorldDemandMonth)} {unit}");
|
||||
AddStat(T("Scorte"), g.StockMonths < 0 ? "—" : $"{Fmt.Number(g.StockMonths, 1)} {T("mesi")}",
|
||||
$"{Quantity(g.StockUnits)} {unit} {T("nei magazzini delle industrie e nelle stazioni, divise per la domanda mensile della mappa")}");
|
||||
|
||||
if (!g.Available)
|
||||
{
|
||||
_sell.AddChild(Wrapped($"{T("Disponibile dal")} {w.Data.Goods[g.Good].Era}.", 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
if (g.SellPlaces.Count == 0)
|
||||
{
|
||||
_sell.AddChild(Wrapped(T("Nessuna industria consuma questa merce e nessun hub la compra."), 13, Palette.TextSecondary));
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < g.SellPlaces.Count; i++) _sell.AddChild(SellRow(w, g, g.SellPlaces[i], i == 0));
|
||||
_sell.AddChild(Wrapped(T("Prezzo locale della compravendita in proprio: più alto dove il magazzino è vuoto; gli hub comprano al prezzo mondiale meno il dazio. Le consegne del vettore restano pagate al prezzo globale. Il trasporto è a parte."), 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
private static string MonthLabel(ClientWorld w, long day)
|
||||
{
|
||||
if (w.Calendar is not { } c) return "";
|
||||
var date = c.DateOfDay(Math.Max(0, day));
|
||||
string[] months = [T("gen"), T("feb"), T("mar"), T("apr"), T("mag"), T("giu"), T("lug"), T("ago"), T("set"), T("ott"), T("nov"), T("dic")];
|
||||
return $"{months[Math.Clamp(date.Month, 1, 12) - 1]} {date.Year}";
|
||||
}
|
||||
|
||||
private void AddStat(string caption, string value, string tooltip)
|
||||
{
|
||||
var stat = PanelKit.Stat(caption, PanelKit.Value(value));
|
||||
stat.TooltipText = tooltip;
|
||||
stat.MouseFilter = MouseFilterEnum.Pass;
|
||||
_stats.AddChild(stat);
|
||||
}
|
||||
|
||||
private static Control SellRow(ClientWorld w, GoodMarketInfo g, SellPlaceInfo p, bool best)
|
||||
{
|
||||
var box = new PanelContainer();
|
||||
box.AddThemeStyleboxOverride("panel", best ? UiTheme.Box(Palette.Inner, Palette.Inner, 6, 12) : UiTheme.Box(Palette.Panel, Palette.Panel, 6, 12));
|
||||
var row = PanelKit.Row(10);
|
||||
box.AddChild(row);
|
||||
string name = p.Kind == SellPlaceInfo.Hub
|
||||
? $"{(w.Hubs.TryGetValue(p.Target, out var hub) ? hub.Name : "#" + p.Target)}, {T("esportazione")}"
|
||||
: w.Industries.TryGetValue(p.Target, out var ind) ? ind.Name : "#" + p.Target;
|
||||
var label = UiTheme.Text(name, 14);
|
||||
label.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
label.ClipText = true;
|
||||
label.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||||
label.CustomMinimumSize = new Vector2(24, 0);
|
||||
row.AddChild(label);
|
||||
var price = UiTheme.Text(PerUnit(w, g.Good, p.Price), 14, bold: true);
|
||||
price.CustomMinimumSize = new Vector2(110, 0);
|
||||
row.AddChild(price);
|
||||
var line = UiTheme.Text(p.Line >= 0 ? LineName(w, p.Line) : T("non collegato"), 14, p.Line >= 0 ? Palette.TextSecondary : Palette.Amber);
|
||||
line.CustomMinimumSize = new Vector2(130, 0);
|
||||
line.ClipText = true;
|
||||
line.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
|
||||
row.AddChild(line);
|
||||
box.TooltipText = p.Line >= 0
|
||||
? $"{name}: {T("servita dalla tua linea")} {LineName(w, p.Line)}"
|
||||
: $"{name}: {T("nessuna tua stazione servita da una linea con treni ha questa destinazione nel bacino")}";
|
||||
return box;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ colonna destra
|
||||
|
||||
private void RefreshRight(ClientWorld w, MarketReport report)
|
||||
{
|
||||
// il riquadro della compravendita resta lo stesso nodo tra un quadro e l'altro
|
||||
_trade.GetParent()?.RemoveChild(_trade);
|
||||
foreach (var c in _right.GetChildren()) c.QueueFree();
|
||||
foreach (var h in report.Hubs) _right.AddChild(HubCard(w, h));
|
||||
_right.AddChild(EventCard(w, report));
|
||||
_right.AddChild(TradingCard(w, report));
|
||||
}
|
||||
|
||||
private Control HubCard(ClientWorld w, HubMarketInfo h)
|
||||
{
|
||||
var card = Card(Palette.Inner, Palette.Border);
|
||||
var col = (VBoxContainer)card.GetChild(0);
|
||||
var title = PanelKit.Row(8);
|
||||
var name = UiTheme.Text(w.Hubs.TryGetValue(h.Hub, out var info) ? info.Name : $"Hub {h.Hub}", 17, bold: true);
|
||||
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
name.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
title.AddChild(name);
|
||||
bool connected = h.Line >= 0;
|
||||
title.AddChild(UiTheme.Text(connected ? T("collegato") : T("non collegato"), 13, connected ? Palette.Ok : Palette.Amber));
|
||||
col.AddChild(title);
|
||||
bool port = h.Kind == 0;
|
||||
col.AddChild(Wrapped(port ? T("Hub verso il mercato mondiale via mare") : T("Hub verso il mercato mondiale via terra"), 13, Palette.TextSecondary));
|
||||
col.AddChild(PanelKit.Pair(T("Capacità"), PanelKit.Value($"{Fmt.Number(h.MonthlyCapacity, 0)} {T("unità/mese")}")));
|
||||
col.AddChild(PanelKit.Pair(T("Dazio"), PanelKit.Value(Fmt.Pct(h.Duty, 0))));
|
||||
double used = h.MonthlyCapacity > 0 ? Math.Clamp((double)h.UsedThisMonth / h.MonthlyCapacity, 0, 1) : 0;
|
||||
col.AddChild(Bar(used, Palette.Workers));
|
||||
col.AddChild(UiTheme.Text($"{T("Capacità usata questo mese")}: {Fmt.Pct(used, 0)}", 12, Palette.TextSecondary));
|
||||
if (connected)
|
||||
{
|
||||
col.AddChild(UiTheme.Text($"{T("Servito da")} {LineName(w, h.Line)}", 12, Palette.TextSecondary));
|
||||
}
|
||||
else
|
||||
{
|
||||
col.AddChild(Wrapped(port ? T("Porta i binari fino al porto per comprare e vendere via mare.") : T("Porta i binari fino al confine per comprare e vendere via terra."), 13, Palette.TextSecondary));
|
||||
var plan = new Button { Text = T("Pianifica la linea"), CustomMinimumSize = new Vector2(0, 40) };
|
||||
int hub = h.Hub;
|
||||
plan.Pressed += () => PlanLineRequested?.Invoke(hub);
|
||||
col.AddChild(plan);
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
private static Control EventCard(ClientWorld w, MarketReport report)
|
||||
{
|
||||
var card = Card(Palette.Inner, Palette.Inner);
|
||||
var col = (VBoxContainer)card.GetChild(0);
|
||||
if (report.EventGood < 0 && report.GoodEvents.Count == 0)
|
||||
{
|
||||
col.AddChild(UiTheme.Text(T("Nessun evento in corso"), 13, Palette.TextSecondary, bold: true));
|
||||
col.AddChild(Wrapped(T("I prezzi mondiali seguono il loro ciclo pluriennale, senza scosse."), 13, Palette.TextSecondary));
|
||||
return card;
|
||||
}
|
||||
col.AddChild(UiTheme.Text(T("Evento in corso"), 13, Palette.AmberLight, bold: true));
|
||||
// eventi del mondo sulla domanda di un bene in una zona (ADR 0017)
|
||||
foreach (var e in report.GoodEvents)
|
||||
{
|
||||
col.AddChild(Wrapped($"{GoodName(w, e.Good)}: {WorldEventText.Name(w, e).ToLowerInvariant()} {WorldEventText.Where(w, e)}", 17, Palette.Text, bold: true));
|
||||
col.AddChild(Wrapped($"{WorldEventText.Effects(w, e)}, {WorldEventText.Until(w, e)}.", 13, Palette.Text));
|
||||
}
|
||||
if (report.EventGood < 0) return card;
|
||||
bool up = report.EventShock > 0;
|
||||
string good = GoodName(w, report.EventGood);
|
||||
col.AddChild(Wrapped(up ? $"{good}: {T("prezzo mondiale in rialzo")}" : $"{good}: {T("prezzo mondiale in calo")}", 17, Palette.Text, bold: true));
|
||||
int months = Math.Max(1, (int)Math.Ceiling(report.EventMonths));
|
||||
col.AddChild(Wrapped($"{T("Il prezzo mondiale di")} {good.ToLowerInvariant()} {(up ? T("è più alto del") : T("è più basso del"))} {Fmt.Pct(Math.Abs(report.EventShock), 0)} " +
|
||||
$"{T("rispetto al ciclo per circa")} {months} {(months == 1 ? T("mese") : T("mesi"))}.", 13, Palette.Text));
|
||||
return card;
|
||||
}
|
||||
|
||||
private Control TradingCard(ClientWorld w, MarketReport report)
|
||||
{
|
||||
var card = Card(Palette.Panel, Palette.Border);
|
||||
var col = (VBoxContainer)card.GetChild(0);
|
||||
col.AddChild(UiTheme.Text(T("Compravendita in proprio"), 17, bold: true));
|
||||
string tier = report.TradingTier > 0 ? Fmt.Tier(w, report.TradingTier) : "—";
|
||||
if (report.TradingUnlocked)
|
||||
{
|
||||
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello")} {tier}.", 13, Palette.Text));
|
||||
col.AddChild(_trade);
|
||||
_trade.Update(report, _selected);
|
||||
return card;
|
||||
}
|
||||
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.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)))
|
||||
{
|
||||
col.AddChild(Wrapped(T("Hai merce nei magazzini: puoi venderla o spedirla, ma non comprarne altra."), 13, Palette.Text));
|
||||
col.AddChild(_trade);
|
||||
_trade.Update(report, _selected, buyAllowed: false);
|
||||
}
|
||||
col.AddChild(Requirement($"{T("Patrimonio netto")} {report.NetWorth.ToString("short")} / {report.NetWorthRequired.ToString("short")}",
|
||||
report.NetWorth.Cents >= report.NetWorthRequired.Cents));
|
||||
col.AddChild(Requirement($"{T("Città collegate oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}: {report.TownsConnected} / {report.TownsRequired}",
|
||||
report.TownsConnected >= report.TownsRequired));
|
||||
col.AddChild(Requirement($"{T("Rating")} {report.Rating} ({T("serve")} {report.RatingRequired})", report.RatingMet));
|
||||
return card;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ mattoni
|
||||
|
||||
private static PanelContainer Card(Color background, Color border)
|
||||
{
|
||||
var card = new PanelContainer();
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(background, border, 10, 18));
|
||||
card.AddChild(PanelKit.Column(8));
|
||||
return card;
|
||||
}
|
||||
|
||||
private static ProgressBar Bar(double fraction, Color color)
|
||||
{
|
||||
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));
|
||||
return bar;
|
||||
}
|
||||
|
||||
private static Label Requirement(string text, bool met)
|
||||
{
|
||||
var l = UiTheme.Text((met ? "✓ " : "· ") + text, 12, met ? Palette.Ok : Palette.TextSecondary);
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
return l;
|
||||
}
|
||||
|
||||
private static Label Wrapped(string text, int size, Color? color, bool bold = false)
|
||||
{
|
||||
var l = UiTheme.Text(text, size, color, bold);
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
return l;
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,9 @@ using static RailEnterprise.Client.App.Localization;
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni,
|
||||
/// barre per il patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
|
||||
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni e
|
||||
/// delle merci (con la previsione tratteggiata e la sua banda, immagine 06), barre per il
|
||||
/// patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
|
||||
/// </summary>
|
||||
public partial class SeriesChart : Control
|
||||
{
|
||||
@@ -18,6 +19,9 @@ public partial class SeriesChart : Control
|
||||
private Style _style;
|
||||
private Color _color = Palette.Amber;
|
||||
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)
|
||||
{
|
||||
@@ -34,9 +38,38 @@ public partial class SeriesChart : Control
|
||||
_style = style;
|
||||
_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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serie a linea seguita dalla previsione (prezzi, banda bassa e alta), un punto per passo
|
||||
/// dopo l'ultimo valore; una riga verticale segna «oggi».
|
||||
/// </summary>
|
||||
public void ShowWithForecast(IReadOnlyList<double> values, IReadOnlyList<string> labels, IReadOnlyList<double> forecast,
|
||||
IReadOnlyList<double> low, IReadOnlyList<double> high, Func<double, string> format, Color color, string empty,
|
||||
string todayLabel, string forecastLabel)
|
||||
{
|
||||
Show(values, labels, format, Style.Line, color, empty);
|
||||
bool consistent = forecast.Count == low.Count && forecast.Count == high.Count;
|
||||
_forecast = consistent ? forecast : [];
|
||||
_low = consistent ? low : [];
|
||||
_high = consistent ? high : [];
|
||||
_todayLabel = todayLabel;
|
||||
_forecastLabel = forecastLabel;
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
|
||||
@@ -50,6 +83,11 @@ public partial class SeriesChart : Control
|
||||
return;
|
||||
}
|
||||
double min = _values.Min(), max = _values.Max();
|
||||
if (_style == Style.Line && _forecast.Count > 0)
|
||||
{
|
||||
min = Math.Min(min, _low.Min());
|
||||
max = Math.Max(max, _high.Max());
|
||||
}
|
||||
if (_style == Style.Bars) min = Math.Min(0, min);
|
||||
if (max - min < 1e-9)
|
||||
{
|
||||
@@ -84,12 +122,27 @@ public partial class SeriesChart : Control
|
||||
return;
|
||||
}
|
||||
|
||||
float step = area.Size.X / (n - 1);
|
||||
int f = _forecast.Count;
|
||||
float step = area.Size.X / (n - 1 + f);
|
||||
var points = new Vector2[n];
|
||||
for (int i = 0; i < n; i++) points[i] = new Vector2(area.Position.X + step * i, Y(_values[i]));
|
||||
var fill = new List<Vector2>(points) { new(area.End.X, area.End.Y), new(area.Position.X, area.End.Y) };
|
||||
var fill = new List<Vector2>(points) { new(points[^1].X, area.End.Y), new(area.Position.X, area.End.Y) };
|
||||
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);
|
||||
@@ -99,6 +152,37 @@ public partial class SeriesChart : Control
|
||||
DrawLabels(area, n, step, font, fontSize, centered: false);
|
||||
}
|
||||
|
||||
/// <summary>Previsione: banda chiara, linea tratteggiata e riga verticale di «oggi».</summary>
|
||||
private void DrawForecast(Rect2 area, Vector2 today, float step, Func<double, float> y, Font font, int fontSize)
|
||||
{
|
||||
int f = _forecast.Count;
|
||||
var band = new List<Vector2> { today };
|
||||
for (int i = 0; i < f; i++) band.Add(new Vector2(today.X + step * (i + 1), y(_high[i])));
|
||||
for (int i = f - 1; i >= 0; i--) band.Add(new Vector2(today.X + step * (i + 1), y(_low[i])));
|
||||
DrawColoredPolygon(band.ToArray(), Palette.WithAlpha(Palette.Workers, 0.22f));
|
||||
var previous = today;
|
||||
for (int i = 0; i < f; i++)
|
||||
{
|
||||
var next = new Vector2(today.X + step * (i + 1), y(_forecast[i]));
|
||||
DrawDashedLine(previous, next, Palette.Staff, 2f, 6f);
|
||||
previous = next;
|
||||
}
|
||||
DrawDashedLine(new Vector2(today.X, area.Position.Y), new Vector2(today.X, area.End.Y), Palette.TextSecondary, 1f, 4f);
|
||||
if (_todayLabel.Length > 0)
|
||||
{
|
||||
// in cima alla riga verticale: in basso si sovrapporrebbe alle etichette dei mesi
|
||||
var dims = font.GetStringSize(_todayLabel, HorizontalAlignment.Left, -1, fontSize);
|
||||
float x = Math.Min(today.X + 4, Size.X - dims.X - 4);
|
||||
DrawString(font, new Vector2(x, area.Position.Y + fontSize), _todayLabel, HorizontalAlignment.Left, -1, fontSize, Palette.Text);
|
||||
}
|
||||
if (_forecastLabel.Length > 0)
|
||||
{
|
||||
var dims = font.GetStringSize(_forecastLabel, HorizontalAlignment.Left, -1, fontSize);
|
||||
DrawString(font, new Vector2(Math.Min(area.End.X - dims.X / 2, Size.X - dims.X - 4), area.End.Y + 16), _forecastLabel,
|
||||
HorizontalAlignment.Left, -1, fontSize, Palette.Staff);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Etichette dell'asse orizzontale, diradate per non sovrapporsi.</summary>
|
||||
private void DrawLabels(Rect2 area, int n, float step, Font font, int fontSize, bool centered)
|
||||
{
|
||||
|
||||
@@ -78,39 +78,6 @@ public partial class HelpPanel : VBoxContainer
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prezzi globali del giorno (resoconto giornaliero).</summary>
|
||||
public partial class MarketPanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly VBoxContainer _rows = PanelKit.Column(4);
|
||||
private long _day = -1;
|
||||
|
||||
public MarketPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 10);
|
||||
AddChild(UiTheme.TitleLabel(T("Mercato"), 34));
|
||||
AddChild(UiTheme.Text(T("Prezzi globali di oggi (la borsa arriva in seguito)."), 13, Palette.TextSecondary));
|
||||
AddChild(_rows);
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var digest = _session.World.LastDigest;
|
||||
if (digest is null || digest.Day == _day) return;
|
||||
_day = digest.Day;
|
||||
foreach (var c in _rows.GetChildren()) c.QueueFree();
|
||||
var goods = _session.World.Data.Goods;
|
||||
for (int g = 0; g < Math.Min(goods.Count, digest.Prices.Count); g++)
|
||||
{
|
||||
var ratio = digest.Prices[g].Cents / (double)Math.Max(1, goods[g].BasePrice);
|
||||
var value = PanelKit.Value($"{digest.Prices[g]} / {goods[g].Unit}");
|
||||
value.AddThemeColorOverride("font_color", ratio > 1.15 ? Palette.AmberLight : ratio < 0.85 ? Palette.Staff : Palette.Text);
|
||||
_rows.AddChild(PanelKit.Pair(goods[g].NameIt, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Conti della compagnia e prestiti.</summary>
|
||||
public partial class FinancePanel : VBoxContainer
|
||||
{
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
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>
|
||||
/// Riquadro «Compravendita in proprio» del Mercato globale, quando il livello lo sblocca (ADR 0016):
|
||||
/// scelta della stazione propria, quantità, Compra, Vendi e Spedisci a un'altra stazione per la
|
||||
/// merce scelta nel pannello; giacenze del magazzino. Prezzi, disponibilità e giacenze arrivano dal
|
||||
/// server nel MarketReport: i comandi li ricalcola il server. I controlli restano gli stessi tra un
|
||||
/// quadro e l'altro, così le scelte non si perdono a ogni nuovo giorno.
|
||||
/// </summary>
|
||||
public sealed partial class TradeBox : VBoxContainer
|
||||
{
|
||||
/// <summary>Margine sul prezzo mostrato: si compra fino al 10 % sopra e si vende fino al 10 % sotto.</summary>
|
||||
private const double PriceTolerance = 0.10;
|
||||
|
||||
private readonly GameSession _session;
|
||||
private readonly OptionButton _station = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
|
||||
private readonly OptionButton _destination = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
|
||||
private readonly SpinBox _quantity = new() { MinValue = 1, MaxValue = 100_000, Step = 1, Rounded = true, Value = 50, SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _good = UiTheme.Text("", 14, bold: true);
|
||||
private readonly Label _quote = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private readonly Label _capacity = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private readonly VBoxContainer _stock = PanelKit.Column(2);
|
||||
private readonly Label _status = UiTheme.Text("", 12);
|
||||
private readonly Button _buy = UiTheme.Primary(T("Compra"));
|
||||
private readonly Button _sell = new() { Text = T("Vendi") };
|
||||
private readonly Button _ship = new() { Text = T("Spedisci a") };
|
||||
private readonly List<int> _stationIds = [];
|
||||
private readonly List<int> _destinationIds = [];
|
||||
private MarketReport? _report;
|
||||
private int _goodId = -1;
|
||||
private bool _buyAllowed = true;
|
||||
|
||||
/// <summary>Esito di un comando: il pannello chiede subito un quadro aggiornato.</summary>
|
||||
public event Action? Traded;
|
||||
|
||||
public TradeBox(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 8);
|
||||
foreach (var l in new[] { _quote, _capacity, _status }) l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
|
||||
var station = PanelKit.Row(6);
|
||||
station.AddChild(UiTheme.Text(T("Stazione"), 13, Palette.TextSecondary));
|
||||
station.AddChild(_station);
|
||||
AddChild(station);
|
||||
_station.ItemSelected += _ =>
|
||||
{
|
||||
PickDestination(SelectedDestination);
|
||||
Render();
|
||||
};
|
||||
AddChild(_good);
|
||||
AddChild(_quote);
|
||||
|
||||
var qty = PanelKit.Row(6);
|
||||
qty.AddChild(UiTheme.Text(T("Quantità"), 13, Palette.TextSecondary));
|
||||
qty.AddChild(_quantity);
|
||||
AddChild(qty);
|
||||
|
||||
var trade = PanelKit.Row(6);
|
||||
_buy.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_sell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_buy.TooltipText = T("Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato.");
|
||||
_sell.TooltipText = T("Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato.");
|
||||
_buy.Pressed += Buy;
|
||||
_sell.Pressed += Sell;
|
||||
trade.AddChild(_buy);
|
||||
trade.AddChild(_sell);
|
||||
AddChild(trade);
|
||||
|
||||
var ship = PanelKit.Row(6);
|
||||
_ship.TooltipText = T("Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa.");
|
||||
_ship.Pressed += Ship;
|
||||
ship.AddChild(_ship);
|
||||
ship.AddChild(_destination);
|
||||
AddChild(ship);
|
||||
|
||||
AddChild(_capacity);
|
||||
AddChild(UiTheme.Text(T("In magazzino"), 13, Palette.TextSecondary, bold: true));
|
||||
AddChild(_stock);
|
||||
AddChild(_status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aggiorna stazioni, quotazioni e giacenze dal quadro ricevuto, per la merce scelta. Senza lo
|
||||
/// sblocco del livello (<paramref name="buyAllowed"/> falso) si vende e si spedisce solo la merce
|
||||
/// già in magazzino, per esempio quella ereditata da una fusione.
|
||||
/// </summary>
|
||||
public void Update(MarketReport report, int good, bool buyAllowed = true)
|
||||
{
|
||||
_report = report;
|
||||
_goodId = good;
|
||||
_buyAllowed = buyAllowed;
|
||||
var w = _session.World;
|
||||
int keep = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1;
|
||||
int keepTo = SelectedDestination;
|
||||
_stationIds.Clear();
|
||||
_station.Clear();
|
||||
foreach (var h in report.Warehouses)
|
||||
{
|
||||
_stationIds.Add(h.Station);
|
||||
_station.AddItem(StationName(w, h.Station));
|
||||
}
|
||||
int index = _stationIds.IndexOf(keep);
|
||||
if (_stationIds.Count > 0) _station.Select(index >= 0 ? index : 0);
|
||||
_destinationIds.Clear();
|
||||
_destination.Clear();
|
||||
foreach (var h in report.Warehouses)
|
||||
{
|
||||
_destinationIds.Add(h.Station);
|
||||
_destination.AddItem(StationName(w, h.Station));
|
||||
}
|
||||
PickDestination(keepTo);
|
||||
Render();
|
||||
}
|
||||
|
||||
private int SelectedDestination =>
|
||||
_destination.Selected >= 0 && _destination.Selected < _destinationIds.Count ? _destinationIds[_destination.Selected] : -1;
|
||||
|
||||
/// <summary>
|
||||
/// Mantiene la stazione di arrivo scelta se è ancora nell'elenco e diversa da quella di partenza,
|
||||
/// altrimenti sceglie la prima diversa dalla partenza.
|
||||
/// </summary>
|
||||
private void PickDestination(int keep)
|
||||
{
|
||||
if (_destinationIds.Count == 0) return;
|
||||
int from = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1;
|
||||
int to = _destinationIds.IndexOf(keep);
|
||||
if (to < 0 || _destinationIds[to] == from) to = _destinationIds.FindIndex(id => id != from);
|
||||
_destination.Select(to >= 0 ? to : 0);
|
||||
}
|
||||
|
||||
private WarehouseInfo? Current =>
|
||||
_report is null || _station.Selected < 0 || _station.Selected >= _stationIds.Count
|
||||
? null
|
||||
: _report.Warehouses.FirstOrDefault(h => h.Station == _stationIds[_station.Selected]);
|
||||
|
||||
private WarehouseGoodInfo? CurrentGood => Current?.Goods.FirstOrDefault(g => g.Good == _goodId);
|
||||
|
||||
private void Render()
|
||||
{
|
||||
var w = _session.World;
|
||||
foreach (var c in _stock.GetChildren()) c.QueueFree();
|
||||
var house = Current;
|
||||
bool any = house is not null && _goodId >= 0 && _goodId < w.Data.Goods.Count;
|
||||
_buy.Disabled = _sell.Disabled = _ship.Disabled = !any;
|
||||
if (!any)
|
||||
{
|
||||
_good.Text = "";
|
||||
_quote.Text = T("Costruisci una stazione per avere un magazzino dove comprare e vendere.");
|
||||
_capacity.Text = "";
|
||||
return;
|
||||
}
|
||||
string unit = w.Data.Goods[_goodId].Unit;
|
||||
var g = CurrentGood;
|
||||
_good.Text = $"{T("Merce")}: {GoodName(w, _goodId)} · {T("in magazzino")} {g?.Units ?? 0} {unit}";
|
||||
string buy = g is { BuyPrice: >= 0 }
|
||||
? $"{T("Si compra a")} {Price(g.BuyPrice)}/{unit} ({Fmt.Number(g.BuyUnits, 0)} {unit} {T("disponibili")})"
|
||||
: T("Nessun produttore né hub nel bacino la vende");
|
||||
string sell = g is { SellPrice: >= 0 }
|
||||
? $"{T("si vende a")} {Price(g.SellPrice)}/{unit} ({Fmt.Number(g.SellUnits, 0)} {unit} {T("richieste")})"
|
||||
: T("nessun consumatore né hub nel bacino la compra");
|
||||
_quote.Text = $"{buy}; {sell}. {T("Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.")}";
|
||||
_buy.Disabled = !_buyAllowed || g is not { BuyPrice: >= 0 };
|
||||
_sell.Disabled = g is not { SellPrice: >= 0 } || g.Units <= 0;
|
||||
_ship.Disabled = (g?.Units ?? 0) <= 0 || _destinationIds.Count < 2;
|
||||
int used = house!.Goods.Sum(x => x.Units) + house.Incoming;
|
||||
_capacity.Text = $"{T("Magazzino")}: {Fmt.Number(used, 0)} / {Fmt.Number(house.Capacity, 0)} {T("unità")}"
|
||||
+ (house.Incoming > 0 ? $" ({T("di cui")} {Fmt.Number(house.Incoming, 0)} {T("in arrivo")})" : "");
|
||||
var held = house.Goods.Where(x => x.Units > 0).ToList();
|
||||
if (held.Count == 0) _stock.AddChild(UiTheme.Text(T("Vuoto"), 12, Palette.TextSecondary));
|
||||
foreach (var x in held)
|
||||
_stock.AddChild(PanelKit.Pair(GoodName(w, x.Good), PanelKit.Value($"{Fmt.Number(x.Units, 0)} {w.Data.Goods[x.Good].Unit}")));
|
||||
}
|
||||
|
||||
private void Buy()
|
||||
{
|
||||
if (Current is not { } house || CurrentGood is not { BuyPrice: >= 0 } g) return;
|
||||
var max = Money.FromCentsRounded(g.BuyPrice * (1 + PriceTolerance));
|
||||
_session.Command(new BuyGoodsCommand(new StationId(house.Station), GoodId(), Units(), max), Result);
|
||||
}
|
||||
|
||||
private void Sell()
|
||||
{
|
||||
if (Current is not { } house || CurrentGood is not { SellPrice: >= 0 } g) return;
|
||||
var min = Money.FromCentsRounded(g.SellPrice * (1 - PriceTolerance));
|
||||
_session.Command(new SellGoodsCommand(new StationId(house.Station), GoodId(), Units(), min), Result);
|
||||
}
|
||||
|
||||
private void Ship()
|
||||
{
|
||||
if (Current is not { } house || _destination.Selected < 0 || _destination.Selected >= _destinationIds.Count) return;
|
||||
int to = _destinationIds[_destination.Selected];
|
||||
if (to == house.Station)
|
||||
{
|
||||
ShowStatus(T("Scegli una stazione di arrivo diversa da quella di partenza"), false);
|
||||
return;
|
||||
}
|
||||
_session.Command(new ShipGoodsCommand(new StationId(house.Station), new StationId(to), GoodId(), Units()), Result);
|
||||
}
|
||||
|
||||
private string GoodId() => _session.World.Data.Goods[_goodId].Id;
|
||||
|
||||
private int Units() => (int)Math.Max(1, Math.Round(_quantity.Value));
|
||||
|
||||
private void Result(CommandResultMessage r)
|
||||
{
|
||||
ShowStatus(r.Message, r.Ok);
|
||||
Traded?.Invoke();
|
||||
}
|
||||
|
||||
private void ShowStatus(string text, bool ok)
|
||||
{
|
||||
_status.Text = text;
|
||||
_status.AddThemeColorOverride("font_color", ok ? Palette.Ok : Palette.Danger);
|
||||
}
|
||||
|
||||
private static string StationName(ClientWorld w, int station) =>
|
||||
w.Stations.TryGetValue(station, out var s) ? s.Name : $"{T("Stazione")} {station}";
|
||||
|
||||
private static string GoodName(ClientWorld w, int good)
|
||||
{
|
||||
var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)];
|
||||
return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
|
||||
}
|
||||
|
||||
private static string Price(double cents) => Money.FromCentsRounded(cents).ToString();
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// Testi degli eventi del mondo in corso (ADR 0017) per l'elenco «Eventi in corso», le schede delle
|
||||
/// entità e il Mercato globale. Solo presentazione: i valori dei moltiplicatori arrivano dal server.
|
||||
/// </summary>
|
||||
public static class WorldEventText
|
||||
{
|
||||
// codici di EntityKind del protocollo
|
||||
private const byte TownEntity = 1, IndustryEntity = 2, DepotEntity = 7;
|
||||
|
||||
private static bool English => TranslationServer.GetLocale().StartsWith("en");
|
||||
|
||||
public static WorldEventDef? Def(ClientWorld w, WorldEventInfo e) => w.Data.Events.Events.FirstOrDefault(d => d.Id == e.Type);
|
||||
|
||||
/// <summary>Nome del tipo di evento nella lingua dell'interfaccia.</summary>
|
||||
public static string Name(ClientWorld w, WorldEventInfo e) =>
|
||||
Def(w, e) is { } d ? (English ? d.NameEn : d.NameIt) : e.Type;
|
||||
|
||||
/// <summary>Nome dell'entità coinvolta (città, industria, deposito).</summary>
|
||||
public static string Target(ClientWorld w, WorldEventInfo e) => e.Entity switch
|
||||
{
|
||||
TownEntity => w.Towns.TryGetValue(e.EntityIndex, out var t) ? t.Name : "?",
|
||||
IndustryEntity => w.Industries.TryGetValue(e.EntityIndex, out var i) ? i.Name : "?",
|
||||
DepotEntity => w.Depots.TryGetValue(e.EntityIndex, out var d) ? d.Name : "?",
|
||||
_ => "?",
|
||||
};
|
||||
|
||||
public static string GoodName(ClientWorld w, int good)
|
||||
{
|
||||
if (good < 0 || good >= w.Data.Goods.Count) return "";
|
||||
var def = w.Data.Goods[good];
|
||||
return English ? def.NameEn : def.NameIt;
|
||||
}
|
||||
|
||||
/// <summary>Effetti con il loro valore («Produzione 25%», «Velocità dei treni 80%»).</summary>
|
||||
public static string Effects(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
var def = Def(w, e);
|
||||
if (def is null) return "";
|
||||
var parts = new List<string>();
|
||||
for (int i = 0; i < def.Effects.Count && i < e.Effects.Length; i++)
|
||||
{
|
||||
string label = def.Effects[i].Kind switch
|
||||
{
|
||||
EventEffectKind.IndustryCapacity => T("Capacità produttiva"),
|
||||
EventEffectKind.TownDemand => T("Consumi della città"),
|
||||
EventEffectKind.GoodDemand => $"{T("Domanda di")} {GoodName(w, e.Good).ToLowerInvariant()}",
|
||||
EventEffectKind.Attendance => T("Presenze al lavoro"),
|
||||
EventEffectKind.TrainSpeed => T("Velocità dei treni"),
|
||||
EventEffectKind.TrackWear => T("Usura dei binari"),
|
||||
_ => "",
|
||||
};
|
||||
parts.Add($"{label} {Fmt.Pct(e.Effects[i], 0)}");
|
||||
}
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
|
||||
/// <summary>Zona dell'evento («entro 12 km da Valdoria») per area e domanda di un bene.</summary>
|
||||
public static string Where(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
var def = Def(w, e);
|
||||
string target = Target(w, e);
|
||||
return def?.RadiusKm is { } km ? $"{T("entro")} {Fmt.Number(km, 0)} km {T("da")} {target}" : target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scadenza: ultimo giorno dell'evento (EndDay − 1) e giorni che restano, oggi compreso. Il server
|
||||
/// toglie l'evento il mattino di EndDay, quindi il conto va dalla durata estratta a 1. Un evento
|
||||
/// estratto oggi inizia domani: si dice da quando, con la sua durata.
|
||||
/// </summary>
|
||||
public static string Until(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
long today = Fmt.Today(w);
|
||||
string until = $"{T("fino al")} {Fmt.Date(w, e.EndDay - 1)}";
|
||||
if (e.StartDay > today)
|
||||
{
|
||||
string from = e.StartDay == today + 1 ? T("da domani") : $"{T("dal")} {Fmt.Date(w, e.StartDay)}";
|
||||
return $"{from} {until} ({Days(e.EndDay - e.StartDay)})";
|
||||
}
|
||||
return $"{until} ({Days(Math.Max(1, e.EndDay - today))})";
|
||||
}
|
||||
|
||||
private static string Days(long n) => $"{n} {(n == 1 ? T("giorno") : T("giorni"))}";
|
||||
|
||||
/// <summary>Colore della gravità: opportunità in verde, avvisi in ambra, critici in rosso.</summary>
|
||||
public static Color Color(WorldEventInfo e) => e.Severity switch
|
||||
{
|
||||
1 => Palette.Ok,
|
||||
2 => Palette.AmberLight,
|
||||
3 => Palette.Danger,
|
||||
_ => Palette.Text,
|
||||
};
|
||||
|
||||
/// <summary>Riga compatta: titolo, luogo, effetti e scadenza.</summary>
|
||||
public static Control Row(ClientWorld w, WorldEventInfo e)
|
||||
{
|
||||
var col = PanelKit.Column(2);
|
||||
col.AddChild(UiTheme.Text($"{Name(w, e)} · {Where(w, e)}", 14, Color(e), bold: true));
|
||||
var effects = UiTheme.Text(Effects(w, e), 12, Palette.Text);
|
||||
effects.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(effects);
|
||||
col.AddChild(UiTheme.Text(Until(w, e), 12, Palette.TextSecondary));
|
||||
return col;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Eventi che riguardano un'entità: bersaglio diretto oppure, per una città, zona (maltempo,
|
||||
/// domanda di un bene) che la contiene. Come sul server, una città è nella zona se dista dalla città
|
||||
/// centro al più il raggio del catalogo.
|
||||
/// </summary>
|
||||
public static IEnumerable<WorldEventInfo> For(ClientWorld w, byte entity, int index) =>
|
||||
(w.LastDigest?.WorldEvents ?? []).Where(e => (e.Entity == entity && e.EntityIndex == index) || (entity == TownEntity && InZone(w, e, index)));
|
||||
|
||||
private static bool InZone(ClientWorld w, WorldEventInfo e, int town)
|
||||
{
|
||||
if (e.Entity != TownEntity || Def(w, e)?.RadiusKm is not { } km) return false;
|
||||
if (!w.Towns.TryGetValue(town, out var t) || !w.Towns.TryGetValue(e.EntityIndex, out var center)) return false;
|
||||
double r = km * 1000;
|
||||
return (t.Position - center.Position).LengthSquared <= r * r;
|
||||
}
|
||||
|
||||
/// <summary>Avvisi «Evento in corso» per la scheda dell'entità.</summary>
|
||||
public static void AddNotices(ClientWorld w, Control into, byte entity, int index)
|
||||
{
|
||||
foreach (var e in For(w, entity, index))
|
||||
into.AddChild(UiTheme.Notice($"{T("Evento in corso")}: {Name(w, e)} · {Effects(w, e)} · {Until(w, e)}"));
|
||||
}
|
||||
|
||||
public const byte Town = TownEntity, Industry = IndustryEntity, Depot = DepotEntity;
|
||||
}
|
||||
@@ -28,6 +28,7 @@ public partial class GameScreen : Node
|
||||
private readonly Toolbar _toolbar = new();
|
||||
private readonly Ticker _ticker = new();
|
||||
private readonly Minimap _minimap = new();
|
||||
private readonly WorldEventsBox _worldEvents = new();
|
||||
private readonly ScrollContainer _scroll = new() { SizeFlagsVertical = Control.SizeFlags.ExpandFill, HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
|
||||
private readonly VBoxContainer _content = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
|
||||
private readonly VBoxContainer _toasts = new();
|
||||
@@ -41,7 +42,9 @@ public partial class GameScreen : Node
|
||||
private MaintenancePanel? _maintenance;
|
||||
private IndustryPanel? _industryPanel;
|
||||
private CompaniesPanel? _companies;
|
||||
// pannelli a tutto schermo (Compagnie e borsa): coprono mappa e pannello destro, la barra resta
|
||||
private MarketPanel? _market;
|
||||
private ClimbPanel? _climb;
|
||||
// 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;
|
||||
private Control? _side;
|
||||
@@ -108,6 +111,30 @@ public partial class GameScreen : Node
|
||||
_companies?.Select(company);
|
||||
}
|
||||
|
||||
/// <summary>Apre il «Mercato globale» a tutto schermo, facoltativamente su un bene.</summary>
|
||||
public void OpenMarket(int good = -1)
|
||||
{
|
||||
if (_tool != Tool.Market) _toolbar.Select(Tool.Market);
|
||||
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>Dal Mercato globale: strumento binari con la mappa centrata sull'hub da collegare.</summary>
|
||||
private void PlanLineToHub(int hub)
|
||||
{
|
||||
_toolbar.Select(Tool.Track);
|
||||
if (_session.World.Hubs.TryGetValue(hub, out var h))
|
||||
{
|
||||
_map.CenterOn(MapScale.V(h.Position));
|
||||
_map.SetZoom(0.3f);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
|
||||
public void OpenChronicle()
|
||||
{
|
||||
@@ -187,6 +214,7 @@ public partial class GameScreen : Node
|
||||
miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
|
||||
miniHeader.AddChild(miniTitle);
|
||||
miniHeader.AddChild(UiTheme.Text(_session.World.Summary?.RegionId is { Length: > 0 } r ? $"{T("Regione di")} {char.ToUpperInvariant(r[0])}{r[1..]}" : "", 13, Palette.TextSecondary));
|
||||
sideCol.AddChild(_worldEvents);
|
||||
sideCol.AddChild(miniHeader);
|
||||
sideCol.AddChild(_minimap);
|
||||
root.AddChild(_ticker);
|
||||
@@ -197,6 +225,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;
|
||||
@@ -212,6 +241,9 @@ public partial class GameScreen : Node
|
||||
|
||||
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
|
||||
|
||||
/// <summary>Codice di EventKind.World nel protocollo (notizie degli eventi del mondo, ADR 0017).</summary>
|
||||
private const byte WorldEventKind = 10;
|
||||
|
||||
/// <summary>Avviso permanente dopo la fine della partita: si guarda il mondo, la Cronaca resta a portata.</summary>
|
||||
private void BuildObserverBanner(Control mapArea)
|
||||
{
|
||||
@@ -285,7 +317,10 @@ public partial class GameScreen : Node
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
|
||||
break;
|
||||
case DailyDigest d:
|
||||
foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e);
|
||||
// le notizie non informative arrivano già una per una come Notification (GameHost); dal
|
||||
// resoconto si aggiungono solo le fini degli eventi del mondo, informative (ADR 0017 §7)
|
||||
foreach (var e in d.Events.Where(e => e.Kind == WorldEventKind && e.Severity == 0)) _ticker.Add(e);
|
||||
_worldEvents.Update(_session.World);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -365,8 +400,10 @@ public partial class GameScreen : Node
|
||||
_maintenance = null;
|
||||
_industryPanel = null;
|
||||
_companies = null;
|
||||
_market = null;
|
||||
_climb = null;
|
||||
foreach (var c in _full.GetChildren()) c.QueueFree();
|
||||
bool full = tool == Tool.Companies;
|
||||
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb;
|
||||
_full.Visible = full;
|
||||
if (_mapArea is not null) _mapArea.Visible = !full;
|
||||
if (_side is not null) _side.Visible = !full;
|
||||
@@ -430,7 +467,17 @@ public partial class GameScreen : Node
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Market:
|
||||
panel = new MarketPanel(_session);
|
||||
_market = new MarketPanel(_session);
|
||||
_market.CloseRequested += () => _toolbar.Select(Tool.None);
|
||||
_market.PlanLineRequested += PlanLineToHub;
|
||||
_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);
|
||||
|
||||
+3
-1
@@ -49,9 +49,11 @@
|
||||
"ratioMax": 5.0,
|
||||
"world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 0.5, "baselinePerDay": 4.0, "elasticity": 1.0,
|
||||
"shockChancePerYear": 0.25, "shockMin": 0.08, "shockMax": 0.30, "shockDecayDays": 150, "priceFloor": 0.05 },
|
||||
"historyDays": 360
|
||||
"historyDays": 720,
|
||||
"outlook": { "historyMonths": 24, "changeDays": 30, "forecastMonths": 4, "forecastBandPerMonth": 0.03, "sellPlaces": 3, "eventThreshold": 0.05 }
|
||||
},
|
||||
"localPrice": { "lambda": 0.35, "maxDeviation": 0.40, "epsilon": 1.0 },
|
||||
"trading": { "warehouseCapacity": 500, "storageCostPerUnitPerMonth": 25 },
|
||||
"industry": {
|
||||
"coverageWindowDays": 30,
|
||||
"profitFactorSlope": 0.5,
|
||||
|
||||
@@ -6,25 +6,25 @@
|
||||
"presets": [
|
||||
{ "id": "apprendista", "name_it": "Apprendista", "name_en": "Apprentice",
|
||||
"initialCapital": 50000000, "initialCredit": 50000000, "baseInterestRate": 0.03,
|
||||
"constructionCostMultiplier": 0.8, "tariffMultiplier": 1.15, "wearMultiplier": 0.7, "marketVolatilityMultiplier": 0.6,
|
||||
"constructionCostMultiplier": 0.8, "tariffMultiplier": 1.15, "wearMultiplier": 0.7, "marketVolatilityMultiplier": 0.6, "eventFrequencyMultiplier": 0.7,
|
||||
"aiCompetitors": 1, "aiCapitalMultiplier": 0.7, "aiCostDiscount": 0.0,
|
||||
"playerTakeover": "disabled", "takeoverRansomYears": 0, "bankruptcyDays": 180,
|
||||
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "no", "depletion": "slow" },
|
||||
{ "id": "imprenditore", "name_it": "Imprenditore", "name_en": "Entrepreneur",
|
||||
"initialCapital": 25000000, "initialCredit": 30000000, "baseInterestRate": 0.05,
|
||||
"constructionCostMultiplier": 1.0, "tariffMultiplier": 1.0, "wearMultiplier": 1.0, "marketVolatilityMultiplier": 1.0,
|
||||
"constructionCostMultiplier": 1.0, "tariffMultiplier": 1.0, "wearMultiplier": 1.0, "marketVolatilityMultiplier": 1.0, "eventFrequencyMultiplier": 1.0,
|
||||
"aiCompetitors": 2, "aiCapitalMultiplier": 1.0, "aiCostDiscount": 0.0,
|
||||
"playerTakeover": "ransom", "takeoverRansomYears": 3, "bankruptcyDays": 90,
|
||||
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "normal" },
|
||||
{ "id": "magnate", "name_it": "Magnate", "name_en": "Tycoon",
|
||||
"initialCapital": 15000000, "initialCredit": 15000000, "baseInterestRate": 0.07,
|
||||
"constructionCostMultiplier": 1.25, "tariffMultiplier": 0.9, "wearMultiplier": 1.3, "marketVolatilityMultiplier": 1.3,
|
||||
"constructionCostMultiplier": 1.25, "tariffMultiplier": 0.9, "wearMultiplier": 1.3, "marketVolatilityMultiplier": 1.3, "eventFrequencyMultiplier": 1.2,
|
||||
"aiCompetitors": 3, "aiCapitalMultiplier": 1.5, "aiCostDiscount": 0.10,
|
||||
"playerTakeover": "ransom", "takeoverRansomYears": 1, "bankruptcyDays": 60,
|
||||
"publicFromStart": false, "playerShareAtStart": 1.0, "ironman": "optional", "depletion": "fast" },
|
||||
{ "id": "ferro_e_sangue", "name_it": "Ferro e sangue", "name_en": "Iron and blood",
|
||||
"initialCapital": 10000000, "initialCredit": 10000000, "baseInterestRate": 0.09,
|
||||
"constructionCostMultiplier": 1.5, "tariffMultiplier": 0.8, "wearMultiplier": 1.6, "marketVolatilityMultiplier": 1.6,
|
||||
"constructionCostMultiplier": 1.5, "tariffMultiplier": 0.8, "wearMultiplier": 1.6, "marketVolatilityMultiplier": 1.6, "eventFrequencyMultiplier": 1.4,
|
||||
"aiCompetitors": 5, "aiCapitalMultiplier": 2.0, "aiCostDiscount": 0.20,
|
||||
"playerTakeover": "immediate", "takeoverRansomYears": 0, "bankruptcyDays": 30,
|
||||
"publicFromStart": true, "playerShareAtStart": 0.6, "ironman": "yes", "depletion": "fast" }
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"$schema": "schema/events.schema.json",
|
||||
"version": 1,
|
||||
"maxActive": 6,
|
||||
"events": [
|
||||
{ "id": "industry_accident", "name_it": "Incidente in un impianto", "name_en": "Plant accident",
|
||||
"target": "industry", "chancePerYear": 1.2, "durationDays": [ 10, 45 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "industryCapacity", "min": 0.0, "max": 0.5 } ],
|
||||
"news_it": "Incidente a {target}: produzione al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: la produzione riprende dopo l'incidente" },
|
||||
{ "id": "industry_boom", "name_it": "Boom di produzione", "name_en": "Production boom",
|
||||
"target": "industry", "chancePerYear": 1.0, "durationDays": [ 30, 120 ], "minYear": 1850, "severity": "opportunity",
|
||||
"effects": [ { "kind": "industryCapacity", "min": 1.2, "max": 1.5 } ],
|
||||
"news_it": "Boom di produzione a {target}: capacità al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: finito il boom di produzione" },
|
||||
{ "id": "town_fair", "name_it": "Fiera cittadina", "name_en": "Town fair",
|
||||
"target": "town", "chancePerYear": 1.0, "durationDays": [ 7, 20 ], "minYear": 1850, "minPopulation": 1500, "severity": "opportunity",
|
||||
"effects": [ { "kind": "townDemand", "min": 1.3, "max": 1.8 } ],
|
||||
"news_it": "Fiera a {target}: consumi della città al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: chiusa la fiera, i consumi tornano normali" },
|
||||
{ "id": "epidemic", "name_it": "Epidemia", "name_en": "Epidemic",
|
||||
"target": "town", "chancePerYear": 0.4, "durationDays": [ 30, 90 ], "minYear": 1850, "minPopulation": 2000, "severity": "warning",
|
||||
"effects": [ { "kind": "townDemand", "min": 0.7, "max": 0.9 }, { "kind": "attendance", "min": 0.5, "max": 0.8 } ],
|
||||
"news_it": "Epidemia a {target}: consumi al {pct} e lavoratori assenti per {days} giorni",
|
||||
"newsEnd_it": "{target}: l'epidemia è finita" },
|
||||
{ "id": "good_demand_boom", "name_it": "Domanda in crescita", "name_en": "Demand boom",
|
||||
"target": "townGood", "radiusKm": 15, "chancePerYear": 0.8, "durationDays": [ 60, 180 ], "minYear": 1850, "severity": "opportunity",
|
||||
"effects": [ { "kind": "goodDemand", "min": 1.4, "max": 2.0 } ],
|
||||
"news_it": "Domanda di {good} in forte crescita intorno a {target}: consumi al {pct} per {days} giorni",
|
||||
"newsEnd_it": "Intorno a {target} la domanda di {good} torna normale" },
|
||||
{ "id": "good_demand_slump", "name_it": "Crollo della domanda", "name_en": "Demand slump",
|
||||
"target": "townGood", "radiusKm": 15, "chancePerYear": 0.8, "durationDays": [ 60, 180 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "goodDemand", "min": 0.3, "max": 0.7 } ],
|
||||
"news_it": "Crolla la domanda di {good} intorno a {target}: consumi al {pct} per {days} giorni",
|
||||
"newsEnd_it": "Intorno a {target} la domanda di {good} torna normale" },
|
||||
{ "id": "storm", "name_it": "Maltempo", "name_en": "Storm",
|
||||
"target": "area", "radiusKm": 12, "chancePerYear": 1.5, "durationDays": [ 3, 12 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "trainSpeed", "min": 0.5, "max": 0.8 }, { "kind": "trackWear", "min": 2.0, "max": 4.0 } ],
|
||||
"news_it": "Maltempo intorno a {target}: treni al {pct} della velocità e binari che si consumano di più per {days} giorni",
|
||||
"newsEnd_it": "Torna il sereno intorno a {target}" },
|
||||
{ "id": "strike_town", "name_it": "Sciopero dei lavoratori", "name_en": "Workers' strike",
|
||||
"target": "town", "chancePerYear": 0.5, "durationDays": [ 5, 20 ], "minYear": 1850, "minPopulation": 1000, "severity": "warning",
|
||||
"effects": [ { "kind": "attendance", "min": 0.2, "max": 0.6 } ],
|
||||
"news_it": "Sciopero dei lavoratori di {target}: presenze al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: finito lo sciopero, i lavoratori tornano al lavoro" },
|
||||
{ "id": "strike_depot", "name_it": "Sciopero in deposito", "name_en": "Depot strike",
|
||||
"target": "depot", "chancePerYear": 0.5, "durationDays": [ 5, 20 ], "minYear": 1850, "severity": "warning",
|
||||
"effects": [ { "kind": "attendance", "min": 0.0, "max": 0.5 } ],
|
||||
"news_it": "Sciopero del personale a {target}: presenze al {pct} per {days} giorni",
|
||||
"newsEnd_it": "{target}: finito lo sciopero del personale" }
|
||||
]
|
||||
}
|
||||
@@ -256,6 +256,48 @@
|
||||
"historyDays": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"outlook": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"historyMonths": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"changeDays": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"forecastMonths": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 24
|
||||
},
|
||||
"forecastBandPerMonth": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"sellPlaces": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 20
|
||||
},
|
||||
"eventThreshold": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"historyMonths",
|
||||
"changeDays",
|
||||
"forecastMonths",
|
||||
"forecastBandPerMonth",
|
||||
"sellPlaces",
|
||||
"eventThreshold"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -267,7 +309,8 @@
|
||||
"ratioMin",
|
||||
"ratioMax",
|
||||
"world",
|
||||
"historyDays"
|
||||
"historyDays",
|
||||
"outlook"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
@@ -296,6 +339,24 @@
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"trading": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"warehouseCapacity": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"storageCostPerUnitPerMonth": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"warehouseCapacity",
|
||||
"storageCostPerUnitPerMonth"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"industry": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -446,6 +507,7 @@
|
||||
"map",
|
||||
"market",
|
||||
"localPrice",
|
||||
"trading",
|
||||
"industry",
|
||||
"growth",
|
||||
"town",
|
||||
|
||||
@@ -87,6 +87,11 @@
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"eventFrequencyMultiplier": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"aiCompetitors": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
@@ -156,6 +161,7 @@
|
||||
"tariffMultiplier",
|
||||
"wearMultiplier",
|
||||
"marketVolatilityMultiplier",
|
||||
"eventFrequencyMultiplier",
|
||||
"aiCompetitors",
|
||||
"aiCapitalMultiplier",
|
||||
"aiCostDiscount",
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "Eventi del mondo (events.json)",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"maxActive": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 64
|
||||
},
|
||||
"events": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]*$"
|
||||
},
|
||||
"name_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"name_en": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"target": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"industry",
|
||||
"town",
|
||||
"townGood",
|
||||
"area",
|
||||
"depot"
|
||||
]
|
||||
},
|
||||
"radiusKm": {
|
||||
"type": "number",
|
||||
"minimum": 0.5,
|
||||
"maximum": 200
|
||||
},
|
||||
"chancePerYear": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 100
|
||||
},
|
||||
"durationDays": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 3600
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"minYear": {
|
||||
"type": "integer",
|
||||
"minimum": 1800,
|
||||
"maximum": 2200
|
||||
},
|
||||
"minPopulation": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"goods": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]*$"
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"industryKinds": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"primary",
|
||||
"processing",
|
||||
"manufacturing"
|
||||
]
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"severity": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"info",
|
||||
"opportunity",
|
||||
"warning",
|
||||
"critical"
|
||||
]
|
||||
},
|
||||
"effects": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"industryCapacity",
|
||||
"townDemand",
|
||||
"goodDemand",
|
||||
"attendance",
|
||||
"trainSpeed",
|
||||
"trackWear"
|
||||
]
|
||||
},
|
||||
"min": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"max": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"kind",
|
||||
"min",
|
||||
"max"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"news_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"newsEnd_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name_it",
|
||||
"name_en",
|
||||
"target",
|
||||
"chancePerYear",
|
||||
"durationDays",
|
||||
"minYear",
|
||||
"severity",
|
||||
"effects",
|
||||
"news_it",
|
||||
"newsEnd_it"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"version",
|
||||
"maxActive",
|
||||
"events"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -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" },
|
||||
|
||||
+13
-6
@@ -30,7 +30,7 @@ Regole:
|
||||
| `RailEnterprise.Core.Economy` | Città, industrie, hub, mercato, compagnie, registro contabile a partita doppia, finanza. |
|
||||
| `RailEnterprise.Core.Rail` | `TrackGeometry` (raccordi), `TrackPlanner` (profilo a 25 m, opere, costi, tempi, vincoli per era), `RailNetwork` (nodi, archi campionati, stazioni, depositi, cantieri, indice spaziale), `Pathfinder` (A* sugli archi orientati), veicoli, treni, linee, pacchetti, `LineGraph` con maschere dei carichi (ADR 0007, 0008). |
|
||||
| `RailEnterprise.Core.Commands` | Comandi di gioco (record immutabili) ed esiti. Sono l'unico modo di cambiare il mondo dall'esterno, anche per le IA. |
|
||||
| `RailEnterprise.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor` e gestori dei comandi, `Corporate` (fusioni, liquidazioni, fine partita), `Estimators` (stime condivise da IA e tooltip), `ChronicleReport`, `Ai/` (agenti delle compagnie IA, ricerca del percorso sulle celle), eventi in uscita. |
|
||||
| `RailEnterprise.Core.Simulation` | `World`, `WorldContext`, `SystemPipeline` e `Systems/`, `WorldFactory`, `IndustryPlacer`, `CommandProcessor` e gestori dei comandi, `Corporate` (fusioni, liquidazioni, fine partita), `Estimators` (stime condivise da IA e tooltip), `ChronicleReport`, `Ai/` (agenti delle compagnie IA, ricerca del percorso sulle celle), eventi in uscita, `WorldEvents` (eventi del mondo attivi e loro moltiplicatori, ADR 0017). |
|
||||
| `RailEnterprise.Core.Persistence` | `SaveWriter`/`SaveReader`, `SaveFile` (Brotli), `StateHasher`. |
|
||||
|
||||
## 3. Il tick
|
||||
@@ -60,9 +60,10 @@ 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 di veicoli, stazioni e depositi, valori di libro per voce (`BookValues`, ADR 0018), cassa negativa e bancarotta, rate dei prestiti, rating, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
|
||||
| `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») |
|
||||
| `HashSystem` | giorno | hash dello stato dinamico |
|
||||
|
||||
- Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick: nei 239 tick su 240 lavora solo `TrainSystem`.
|
||||
@@ -86,13 +87,16 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
|
||||
- File in `data/*.json`, schema in `data/schema/*.schema.json` (sottoinsieme di JSON Schema validato da Core senza librerie esterne), deserializzazione rigorosa (proprietà sconosciute vietate, proprietà `required`), validazione semantica (id univoci, riferimenti risolti, limiti) in `DataValidator` (ADR 0002).
|
||||
- Caricamento con `System.Text.Json` e source generator (`DataJsonContext`), nessuna reflection.
|
||||
- `events.json` (F6, ADR 0017) è il catalogo degli eventi del mondo: bersaglio, zona, probabilità annua per mappa, durata, effetti come moltiplicatori con ampiezza min/max e testi delle notizie; `DataValidator` controlla anche che ogni effetto sia compatibile con il bersaglio.
|
||||
- `GameData.Hash` (XxHash64 dei file normalizzati) viaggia nel `Welcome`: client e server devono avere gli stessi dati.
|
||||
|
||||
## 6. Economia e contabilità
|
||||
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`.
|
||||
- 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.
|
||||
- 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.
|
||||
- Ogni unità di merce sta in un magazzino tracciato (industrie, città, 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».
|
||||
- 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.
|
||||
- Interpretazioni delle formule della guida: ADR 0004.
|
||||
|
||||
## 7. Salvataggi
|
||||
@@ -102,13 +106,16 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- `StateHasher` = XxHash64 di `WorldSerializer.WriteDynamic` (stato senza terreno, impostazioni ed eventi; il terreno entra con il suo hash). Dettagli: ADR 0006.
|
||||
- Corpo versione 2 (F4): `MaintenanceSerializer` aggiunge in coda allo stato dinamico manutenzione di veicoli e treni, officine, politiche, convenzioni e motivi dei posti scoperti; i salvataggi della versione 1 si migrano (ADR 0010).
|
||||
- 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).
|
||||
|
||||
## 8. Server
|
||||
|
||||
- `ServerProgram`: Kestrel minimale, log JSON su stdout, configurazione da ambiente (`ServerConfig`: `RE_PORT`, `RE_TOKEN`, `RE_DATA_DIR`, `RE_TICK_MS`, `RE_AUTOSAVE_MIN`, `RE_SEED`, `RE_MAP_SIZE`, `RE_DIFFICULTY`, `RE_LOG_LEVEL`) e argomenti `--local` (127.0.0.1 su porta casuale, stampa `LISTENING porta`), `--healthcheck`, `--token`, `--port`, `--data`.
|
||||
- `GameHost`: possiede il mondo su un thread dedicato. Ogni giro drena la coda delle azioni (messaggi delle sessioni, richieste HTTP), esegue i tick dovuti con un accumulatore (velocità 0/1/2/4/8, budget `RE_TICK_MS`), adegua la velocità effettiva se i tick costano troppo (`slow`), pubblica e fa l'autosave a rotazione.
|
||||
- `Session` / `SessionEndpoint`: WebSocket su `/ws`, primo frame `Hello`, coda d'invio a due classi (affidabili e moti scartabili), ripresa con `sessionId` entro 120 s.
|
||||
- `Projection`: mondo → record del protocollo (entità, archi, chunk, moto dei treni, resoconti, cartelle di manutenzione, registri officina, Registro degli impieghi); i delta per sessione si calcolano con gli hash dei record; i dettagli F4 si mandano su `RequestDetail`, gli avvisi di manutenzione (`World.Alerts`) come `MaintenanceAlert`.
|
||||
- `Projection`: mondo → record del protocollo (entità, archi, chunk, moto dei treni, resoconti con gli eventi del mondo in corso, cartelle di manutenzione, registri officina, Registro degli impieghi); i delta per sessione si calcolano con gli hash dei record; i dettagli F4 si mandano su `RequestDetail`, gli avvisi di manutenzione (`World.Alerts`) come `MaintenanceAlert`.
|
||||
- `SaveStore`: salvataggi `.vfsave` in `$RE_DATA_DIR/saves`, ultimi cinque automatici; all'avvio si riprende il più recente.
|
||||
- HTTP: `/health`, `/metrics` (Prometheus), `GET/POST /api/saves`, `GET /api/saves/{id}`.
|
||||
- Docker: `docker/Dockerfile` (build in due stadi, utente non root, healthcheck), `docker-compose.yml`, `unraid-template.xml`; `scripts/publish-image.sh` per il registry Gitea.
|
||||
@@ -119,7 +126,7 @@ 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).
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze; a tutto schermo «Compagnie e borsa», «Mercato globale» (`MarketPanel`, immagine 06) e «La tua scalata» (`ClimbPanel`, immagine 08: binario dei livelli, storico del patrimonio con `SeriesChart` e i livelli segnati, requisiti, stato patrimoniale, conto economico, prestiti), che si apre anche dal livello nella `TopBar`; scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
|
||||
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
|
||||
|
||||
## 10. Prestazioni
|
||||
|
||||
+20
-6
@@ -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), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3 e 6). 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), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6, 7 e 8). Aggiunto in F4 |
|
||||
|
||||
### Comandi (`Command.type`, payload in ordine)
|
||||
|
||||
@@ -122,14 +122,17 @@ costMultiplier: f64 }`
|
||||
| 37 | FundResearch | `project: string`, `amount: Money` |
|
||||
| 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` |
|
||||
| 39 | MergeCompany | `subsidiary: i32` — fusione di una controllata dopo 360 giorni di controllo (aggiunto in F5) |
|
||||
| 40 | ShipGoods | `from: i32`, `to: i32`, `good: string`, `units: i32` — spedizione di merce propria tra due magazzini della compagnia (aggiunto in F6, ADR 0016) |
|
||||
|
||||
`LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`.
|
||||
I codici coincidono con l'enum `CommandType` di Core. Dalla F4 i comandi 15–18 e 21–22 sono attivi
|
||||
(`policy`: `economy`, `standard`, `thorough`, oppure `inherit` per togliere l'eccezione di linea o
|
||||
treno; `intervention`: `inspection`, `service`, `overhaul`; `OrderParts` fissa la scorta desiderata
|
||||
del deposito). Dalla F5 sono attivi anche 25–34 e 39 (industrie, borsa, offerte, fusioni; `LaunchBid` su
|
||||
una compagnia fallita è un'offerta all'asta degli attivi: prezzo per azione × azioni). Fino alla loro fase i
|
||||
comandi 23–24 e 35–38 rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
|
||||
una compagnia fallita è un'offerta all'asta degli attivi: prezzo per azione × azioni). Dalla F6 sono attivi
|
||||
23–24 e 40 (compravendita in proprio dal livello che sblocca `trading`: si compra dal più economico e si vende
|
||||
al più caro nel bacino della stazione, entro `maxUnitPrice`/`minUnitPrice` per unità; ADR 0016). Fino alla
|
||||
loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
|
||||
|
||||
## 5. Messaggi Server → Client
|
||||
|
||||
@@ -143,7 +146,7 @@ comandi 23–24 e 35–38 rispondono `NotImplemented`. Il server imposta l'emitt
|
||||
| 112 | EntityDelta | `tick: i64`, `EntityLists` (nuovi o cambiati), `removed: [(type: u8, id: i32)]` |
|
||||
| 113 | TrackWorks | `edges: [EdgeInfo]`, `removed: [i32]` (lotti sotto 1 MB) |
|
||||
| 114 | TrainMotion | `trainId: i32`, `tick: i64`, `state: u8`, `condition: f32`, `speed: f32` (m/s), `lengthM: f32`, `headDistance: f64`, `segments: [(edge: i32, forward: bool, fromS: f64, toS: f64)]` |
|
||||
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32` |
|
||||
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32`; blocco 1 (F6): `worldEvents: [WorldEventInfo]` (eventi del mondo in corso su tutta la mappa, solo se ce ne sono; ADR 0017) |
|
||||
| 121 | MaintenanceAlert | `train: i32`, `depot: i32`, `component: string`, `condition: f32`, `dueDays: i32`, `text: string` |
|
||||
| 122 | EmploymentReport | `day: i64`, `rows: [EmploymentRow]`; blocco 1: `agreements: [AgreementInfo]` (mensile, su richiesta e dopo Accept/RejectAgreement) |
|
||||
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
|
||||
@@ -152,10 +155,12 @@ comandi 23–24 e 35–38 rispondono `NotImplemented`. Il server imposta l'emitt
|
||||
| 126 | CompanyCard | `company, totalShares: i64, treasury: i64, holdings: [HoldingInfo], priceHistory: [f64] (centesimi, mensile), history: [CompanyYearInfo], annualProfit, dividendsYear, debt, marketCap: Money, controlDays: i64, auctionMin, auctionBest: Money, auctionBestBidder, auctionEndDay: i64` (su richiesta, F5) |
|
||||
| 127 | IndustryCard | `industry, margin, conditionMultiplier, wearPerDay, recoveryPerDay: f32, maintenanceCostPerDay, maintenanceSpentYear: Money, partsTarget, partsPerMonth, partsOrdered, machineryRequired, upgradeCost, valuation, cash: Money, breakdownChancePerYear: f32, stops: [IndustryStopInfo]` (su richiesta, F5) |
|
||||
| 128 | Chronicle | `gameOver: bool, reason: u8 (1 fallimento, 2 scalata, 3 riscatto scaduto), text, winner, day: i64, company, foundedYear, prestige: i64, history: [CompanyYearInfo], records: [RecordInfo], highlights: [string]` (alla fine della partita e su richiesta, F5) |
|
||||
| 129 | MarketReport | `day: i64, index: f32 (100 = prezzi base), indexChange: f32, goods: [GoodMarketInfo], hubs: [HubMarketInfo], eventGood: i32 (−1 nessuno), eventShock: f32 (con segno, frazione del prezzo base), eventMonths: f32, tradingUnlocked: bool, tradingTier: u8, tradingProgress: f32, netWorth, netWorthRequired: Money, townsConnected, townsRequired, townPopulation: i32, rating, ratingRequired: string, ratingMet: bool`; blocco 1: `warehouses: [WarehouseInfo]` (magazzini della compagnia, solo se ne ha; ADR 0016); blocco 2: `goodEvents: [WorldEventInfo]` (eventi del mondo sulla domanda di un bene, mostrati come «evento in corso»; ADR 0017). I due blocchi sono indipendenti: `flags` bit 0 e bit 1, in quest'ordine (su richiesta, F6; ADR 0015) |
|
||||
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
|
||||
| 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) |
|
||||
|
||||
Record (ognuno chiude con `flags`):
|
||||
|
||||
@@ -176,7 +181,8 @@ Record (ognuno chiude con `flags`):
|
||||
3 guasto lieve, 4 fermo in linea, 5 rimorchiato), `reserve: bool`, `policy: u8` (255 = ereditata), `nextIntervention: string`,
|
||||
`nextDueDays: i32`, `maintenanceDepot: i32`
|
||||
- `EdgeInfo { id, owner, a, b, trackClass: u8, doubleTrack, electrified, state: u8, condition: f32, structureCondition: f32, progress: f32, samples: [(s, x, y, h, ground: f64, kind: u8, speedLimitKmh: f64)], signals: [f64] }`
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`; `kind` 10 = evento del mondo (inizio e fine, F6)
|
||||
- `WorldEventInfo { id: i32, type: string (id di events.json), entity: u8 (1 città, 2 industria, 7 deposito), entityIndex: i32, good: i32 (−1 se nessuno), startDay: i64 (dopo `day` per un evento estratto oggi, che inizia domani), endDay: i64 (primo giorno senza l'evento: il server lo toglie quel mattino), severity: u8, effects: [f32] }`: `effects` sono i moltiplicatori nell'ordine degli effetti del tipo nel catalogo (ADR 0017)
|
||||
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`;
|
||||
blocco 1: `kind: u8` (0 industria, 1 deposito: `industry` è allora l'id del deposito), `workersReason: u8`, `staffReason: u8`
|
||||
(0 nessuno, 1 nessuna stazione, 2 nessuna città entro il tempo massimo, 3 nessun lavoratore libero, 4 città senza servizi
|
||||
@@ -190,6 +196,12 @@ Record (ognuno chiude con `flags`):
|
||||
- `HoldingInfo { holder: i32 (−1 fondatore, −2 mercato, altrimenti compagnia), shares: i64 }`, `CompanyYearInfo { year, netWorth, cash, revenue, profit: Money, tier: u8, trains, trackKm: f32, sharePrice: Money }`
|
||||
- `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 }`
|
||||
- `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)
|
||||
|
||||
## 6. Flusso e interest management
|
||||
|
||||
@@ -208,7 +220,9 @@ Record (ognuno chiude con `flags`):
|
||||
inesistenti non hanno risposta). Il client li richiede mentre il pannello è aperto (una volta al
|
||||
secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità. Dalla F5 anche
|
||||
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
|
||||
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce.
|
||||
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. 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.
|
||||
- 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.
|
||||
+45
-6
@@ -89,30 +89,69 @@ 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). 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
|
||||
|
||||
- Nessun lavoro a metà: F5 chiusa.
|
||||
### F6 — Economia completa, eventi, rifinitura
|
||||
- **Mercato globale (issue #29, ADR 0015)**:
|
||||
- storico dei prezzi a 24 mesi (`market.historyDays` 720); i salvataggi con lo storico di 360 giorni si migrano al caricamento con `RollingWindow.Extended`, senza cambiare formato;
|
||||
- `MarketOutlook` (Core, sola lettura): storico mensile (un campione per mese di calendario), variazione a 30 giorni, offerta e domanda mensili con la quota mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi dalla componente mondiale con banda, «Dove conviene vendere» (industrie al prezzo locale dell'ADR 0004 e hub) con la linea che collega, hub, evento in corso, avanzamento verso la compravendita in proprio; parametri in `balance.json` (`market.outlook`);
|
||||
- protocollo: `DetailKind.Market` (7) e `MarketReport` (129); server: quadro su richiesta;
|
||||
- client: pannello «Mercato globale» a tutto schermo come l'immagine 06 (beni, storico e previsione nel grafico, offerta, domanda, scorte, vendite, hub con «Pianifica la linea», evento, compravendita in proprio); schermata `16_mercato` nel pilota automatico;
|
||||
- test: finestra allungata, migrazione di un salvataggio a 360 giorni, storico mensile, previsione deterministica ed entro i limiti, evento, analisi su Valdoria (linea che collega, ordine delle vendite, indice, commercio, nessun effetto sull'hash), round-trip di `MarketReport`, quadro via WebSocket. 126 test (120 senza i lenti).
|
||||
- **Compravendita in proprio (issue #31, ADR 0016)**:
|
||||
- magazzino della compagnia in ogni sua stazione (`Station.Stock`), capacità e giacenza mensile in `balance.json` (`trading`: 500 unità, 25 centesimi per unità al mese sulla voce «Commercio»); la merce in magazzino entra nell'invariante «merci» e nelle scorte del Mercato globale; una stazione con merce in magazzino non si demolisce, con la liquidazione la merce si perde;
|
||||
- `BuyGoods` (23): dai produttori del bacino al prezzo locale marginale (ADR 0004 §3, unità per unità, dal più economico) e dagli hub al prezzo d'importazione entro la capacità; `SellGoods` (24): ai consumatori del bacino (dal prezzo più alto, entro lo spazio dell'input e la loro cassa) e agli hub al prezzo d'esportazione; denaro sul registro, rifiuti in italiano per livello, stazione, merce, era, prezzo, cassa, magazzino pieno;
|
||||
- `ShipGoods` (40): pacchetti di merce propria (`Packet.Owned`) senza tariffa né consumatore, instradati sulle linee come gli altri ed entrati nel magazzino di destinazione; lo spazio di destinazione si riserva alla partenza (rifiuto se pieno), senza percorso il comando si rifiuta; i pacchetti esistenti non cambiano (accettazione F4 invariata: 35 / 20 guasti senza la linea, 75 / 2 con la linea);
|
||||
- salvataggio: corpo versione 4 (`TradingSerializer`), migrazione delle versioni 1–3 con i magazzini vuoti, magazzini e merce propria nell'hash;
|
||||
- protocollo: comando 40, blocco 1 di `MarketReport` con i magazzini e le quotazioni della prossima unità; client: riquadro «Compravendita in proprio» del Mercato globale (stazione, quantità, Compra, Vendi, Spedisci a, giacenze; tetto e minimo al 10 % dal prezzo mostrato), testi in `strings.csv`;
|
||||
- le IA non commerciano ancora (ADR 0016 §9);
|
||||
- correzioni della revisione: la merce propria segue i flag carico/scarico delle fermate (`LineGraph` con `stopFlags`), la scadenza riparte al trasbordo, ricalcolo giornaliero del tratto in attesa, scarico della merce a bordo dei treni che lasciano la linea o il cui tratto non è più sulla linea, niente demolizione con merce propria in partenza o in arrivo, merce propria nel valore contabile al prezzo globale, vendita e spedizione senza lo sblocco del livello (solo l'acquisto lo richiede), stazione di arrivo predefinita diversa dalla partenza nel riquadro;
|
||||
- test (`Economy/TradingTests.cs`, 17): acquisto dal produttore e dall'hub, vendita al consumatore e all'hub, rifiuti senza effetti, spedizione senza tariffa, un anno di commercio con gli invarianti, determinismo e salvataggio con merce in magazzino e in viaggio, migrazione dalla versione 3, magazzini nel quadro del mercato, round-trip del comando 40, flag delle fermate, treno tolto dalla linea, linea modificata con la merce a bordo, scadenza al trasbordo, demolizione bloccata, valore contabile. 143 test (126 senza i lenti).
|
||||
- **Eventi del mondo (issue #33, ADR 0017)**:
|
||||
- catalogo `data/events.json` con schema e validazione (effetti compatibili con il bersaglio): incidente e boom di un'industria, fiera ed epidemia in una città, boom e crollo della domanda di un bene nella zona di una città, maltempo su un'area (treni più lenti, usura del binario più rapida), sciopero dei lavoratori di una città o del personale di un deposito; probabilità annua per mappa × `eventFrequencyMultiplier` della difficoltà (0,7 / 1,0 / 1,2 / 1,4; 0 li disattiva), al massimo 6 eventi insieme, nessun doppione dello stesso tipo sullo stesso bersaglio;
|
||||
- effetti come moltiplicatori letti da un'unica sorgente (`World.WorldEvents`): capacità delle industrie (produzione e domanda di input), consumi delle città, presenze dei pendolari, velocità dei treni e usura del binario; a evento finito tutto torna come prima;
|
||||
- `EventSystem` tra le IA e l'hash, flusso pseudo-casuale dedicato «events», bersaglio in ordine di id, notizie d'inizio e di fine in italiano (`EventKind.World` = 10); `EventSystem.Force` per test e scenari;
|
||||
- salvataggio: corpo versione 5 (`EventSerializer`) con gli eventi attivi nell'hash e la frequenza nelle impostazioni; le versioni 1–4 si caricano senza eventi e con la frequenza del preset;
|
||||
- protocollo: blocco 1 di `DailyDigest` con gli eventi in corso (`WorldEventInfo`), blocco 2 di `MarketReport` con quelli sulla domanda di un bene; client: riquadro «Eventi in corso» sopra la minimappa, avvisi nelle schede di industria e città e nel Registro officina, «evento in corso» nel Mercato globale, notizie degli eventi sempre nel notiziario, testi in `strings.csv` (corretta anche una chiave con la virgola non tra virgolette);
|
||||
- scenari: campo facoltativo `eventFrequencyMultiplier`; `valdoria.json` lo mette a 0, così l'accettazione F2 e F4 resta invariata (35 / 20 guasti senza la linea, 75 / 2 con la linea). Con gli eventi a frequenza «Imprenditore» la rete senza linea si fermava a 41 con 10 guasti e il criterio «sotto 40 entro 3 anni» non valeva più (ADR 0017 §8);
|
||||
- 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).
|
||||
- **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).
|
||||
- Restano della F6: finanza completa, ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F6: hub e commercio (`BuyGoods`/`SellGoods`), eventi, storico dei prezzi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 06–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`, esportazione Windows con il server.
|
||||
- F6: finanza completa, ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, 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): i pannelli Mercato, Industria e 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).
|
||||
- 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).
|
||||
- Comandi ancora `NotImplemented`: commercio, concessioni, contratti, ricerca, regioni (fasi F6–F7).
|
||||
- Comandi ancora `NotImplemented`: concessioni, contratti, ricerca, regioni (fasi F6–F7).
|
||||
- Manutenzione (ADR 0010): il viaggio verso l'officina si stima in linea d'aria; un treno rimorchiato completa il tratto in corso prima di dirigersi all'officina; con un solo treno su una linea di pendolari e un deposito senza personale la copertura cala durante gli interventi (servono riserve e personale); la mappa dei flussi dei pendolari (frecce blu, opzionale nella guida) non è ancora disegnata.
|
||||
- Una rete a binario semplice con pochi binari di stazione può ancora bloccarsi se tutti i binari alle due estremità sono occupati da treni che devono incrociarsi (stallo di capacità segnalato al giocatore come «possibile stallo»): la rete dell'accettazione F4 è dimensionata di conseguenza.
|
||||
- IA (ADR 0013): su mappe da 128 km in «Magnate» di solito una o due IA crescono (livello 2–3 in 15 anni) mentre le altre restano piccole o falliscono quando la regione non offre candidati con ROI sopra soglia; nel 1850 i grandi fiumi dividono la mappa in regioni fino ai ponti in ferro. Le IA non comprano ancora industrie se non dal livello 3 e non usano il commercio (F6).
|
||||
- IA (ADR 0013): su mappe da 128 km in «Magnate» di solito una o due IA crescono (livello 2–3 in 15 anni) mentre le altre restano piccole o falliscono quando la regione non offre candidati con ROI sopra soglia; nel 1850 i grandi fiumi dividono la mappa in regioni fino ai ponti in ferro. Le IA non comprano ancora industrie se non dal livello 3 e non usano la compravendita in proprio (ADR 0016: da aggiungere ai candidati degli agenti con il bilanciamento della F6).
|
||||
- Borsa (ADR 0012): per le compagnie piccole il prezzo per azione è di pochi centesimi e il premio di un'offerta ha la granularità di un centesimo; antitrust e finanziamenti statali arrivano in F7.
|
||||
- Prezzi, soglie dei livelli e taratura economica restano provvisori fino al bilanciamento della F6.
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# ADR 0015 — Mercato globale: storico a 24 mesi, analisi e previsione (F6)
|
||||
|
||||
Stato: accettato (F6, issue #29).
|
||||
|
||||
## Contesto
|
||||
|
||||
La F6 chiede lo storico dei prezzi e il pannello «Mercato globale» dell'immagine di riferimento 06:
|
||||
elenco dei beni con prezzo, variazione a 30 giorni e barre di offerta e domanda; storico a 24 mesi con
|
||||
la previsione a qualche mese; offerta, domanda e scorte; «Dove conviene vendere»; hub con capacità e
|
||||
dazio; evento di mercato in corso; avanzamento verso la compravendita in proprio. La guida (6.3) fissa
|
||||
le formule del prezzo globale e locale ma non dice come leggere storico, scorte, previsione ed eventi,
|
||||
né come migrare i salvataggi con lo storico di un anno.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Storico a 24 mesi.** `market.historyDays` passa da 360 a 720: `Market.PriceHistory` resta una
|
||||
finestra mobile giornaliera per bene, salvata con la sua lunghezza. Al caricamento, se la finestra
|
||||
salvata è più corta di quella dei dati, `RollingWindow.Extended` ne crea una più lunga riaggiungendo
|
||||
i valori dal più vecchio: stessi prezzi, stesso ordine, nessun cambio di formato del salvataggio.
|
||||
Una finestra salvata più lunga dei dati resta com'è. Il KPI annuale di `simulate` usa la media degli
|
||||
ultimi 360 giorni (`AverageOfLast`), non dell'intera finestra.
|
||||
2. **Analisi come pura funzione del mondo.** `MarketOutlook` (Core, `Economy/MarketOutlook.cs`) legge
|
||||
il mondo e non scrive nulla: nessuno stato nuovo, nessun numero casuale, nessuna iterazione di
|
||||
dizionari; matematica da `DMath`. Il server la proietta in `MarketReport` (129) su richiesta
|
||||
(`RequestDetail` con `DetailKind.Market` = 7); il client la mostra com'è. I parametri stanno in
|
||||
`balance.json`, `market.outlook` (validati: lo storico mensile deve stare nella finestra).
|
||||
3. **Storico mensile.** Un campione per mese di calendario: il prezzo dell'ultimo giorno di ogni mese
|
||||
concluso più quello del giorno corrente, fino a `historyMonths` (24) campioni. Il «giorno corrente» è
|
||||
l'ultimo registrato dal sistema del mercato, che gira al primo tick del giorno: al tick 0 è ancora
|
||||
ieri.
|
||||
4. **Variazione a 30 giorni** = Pg(oggi)/Pg(oggi − 30) − 1; con meno storico si usa il più vecchio
|
||||
disponibile (0 senza storico).
|
||||
5. **Offerta e domanda mensili.** Le finestre `Supply` e `Demand` (30 giorni) riportate ai giorni del
|
||||
mese. Accanto si dà la quota mondiale con la stessa formula di `MarketSystem` (ADR 0004 §1):
|
||||
V = max(baseline·giorni, quota·(D + S)/2) al prezzo mondiale Pw, domanda V·(Pw/Pg)^ε e offerta
|
||||
V·(Pg/Pw)^ε. Il pannello mostra «offerta globale» e «domanda globale» come somma delle due, che è
|
||||
proprio il rapporto che muove il prezzo; il suggerimento separa mappa e mondo. Il quadro usa il
|
||||
prezzo e l'istante correnti, mentre `MarketSystem` ha usato quelli di inizio giornata: la differenza
|
||||
è minima e si accetta.
|
||||
6. **Scorte in mesi** = giacenze del bene (input e output nei magazzini delle industrie aperte più le
|
||||
merci in attesa nelle stazioni vive; esclusi i carichi in viaggio) divise per la domanda mensile
|
||||
della mappa; −1 se la domanda è nulla.
|
||||
7. **Indice materie prime** = media di Pg/Pb × 100 sui beni disponibili nell'anno corrente (era), con
|
||||
la variazione a 30 giorni calcolata sugli stessi beni. Tutti i beni disponibili, non solo le materie
|
||||
grezze: è l'indice del mercato che il giocatore vede nell'elenco.
|
||||
8. **Previsione** a `forecastMonths` (4) mesi dalla sola componente mondiale, che è l'unica parte del
|
||||
prezzo con una dinamica nota in anticipo: Pf(Δ) = Pg·(1 + W(t + Δ))/(1 + W(t)), con il ciclo
|
||||
A·sin(2πt/T) e lo shock che decade come in `MarketSystem` (shock·exp(−Δ/shockDecayDays)), (1 + W)
|
||||
non sotto `priceFloor`, Pf entro 0,3·Pb e 3·Pb. La banda è ±`forecastBandPerMonth` (3 %) per mese di
|
||||
distanza, anch'essa entro i limiti. Domanda e offerta della mappa non si prevedono: dipendono dalle
|
||||
scelte dei giocatori. Un bene non ancora disponibile ha previsione piatta.
|
||||
9. **Dove conviene vendere.** Candidati: le industrie aperte di livello > 0 che consumano il bene, al
|
||||
prezzo locale dell'ADR 0004 §3 con Dl = consumo giornaliero a piena capacità × giorni di magazzino
|
||||
(`IndustryMath.InputCapacity`, cioè `storageDays` come scorta desiderata) e Sl = giacenza dell'input;
|
||||
e gli hub, al prezzo d'esportazione Pg·(1 − dazio). Ordine per prezzo decrescente (a parità prima le
|
||||
industrie, poi l'id), i primi `sellPlaces` (3). Il prezzo è quello alla destinazione: il trasporto
|
||||
dipende dall'origine e si stima a parte. È il prezzo locale della compravendita in proprio (ADR 0004 §3):
|
||||
le consegne del vettore restano pagate al prezzo globale, e il pannello lo dice. Gli hub che hanno
|
||||
esaurito la capacità del mese non compaiono.
|
||||
10. **Collegato o no.** Una destinazione è collegata se una stazione viva della compagnia la ha nel
|
||||
bacino ed è fermata di una linea della compagnia con almeno un treno (lo stesso criterio di
|
||||
`Tiers.ServedStations`); si indica la linea con l'id più basso, altrimenti −1 («non collegato»).
|
||||
Vale anche per gli hub, con la capacità usata nel mese corrente.
|
||||
11. **Evento in corso.** Lo shock mondiale più forte in valore assoluto tra i beni disponibili, se supera
|
||||
`eventThreshold` (5 % del prezzo base), con il segno e i mesi stimati prima che il decadimento lo
|
||||
porti sotto la soglia: shockDecayDays·ln(|shock|/soglia)/giorni del mese. È lo stesso shock che
|
||||
`MarketSystem` annuncia con una notizia quando nasce.
|
||||
12. **Compravendita in proprio.** Il primo livello di `tiers.json` con `trading` sblocca il commercio
|
||||
(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. *Sostituito dall'ADR 0018 §2: l'avanzamento è la media delle tre frazioni
|
||||
(patrimonio, città, rating), la stessa del pannello «La tua scalata».*
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il quadro del mercato costa poco (16 beni, 24 campioni, una scansione di industrie e stazioni) e si
|
||||
calcola solo su richiesta: il pannello lo chiede all'apertura e a ogni nuovo giorno.
|
||||
- Lo storico doppio raddoppia la sezione dei prezzi nel salvataggio e nell'hash giornaliero
|
||||
(16 × 720 numeri).
|
||||
- I comandi `BuyGoods` e `SellGoods` restano da fare (seconda parte della F6): l'analisi dà già i prezzi
|
||||
e le destinazioni che useranno, e lo sblocco del livello che li abilita.
|
||||
@@ -0,0 +1,110 @@
|
||||
# ADR 0016 — Compravendita in proprio e spedizione della merce tra stazioni (F6)
|
||||
|
||||
Stato: accettato (F6, issue #31).
|
||||
|
||||
## Contesto
|
||||
|
||||
La guida (6.3) e l'ADR 0004 §3 prevedono che una compagnia, dal livello che sblocca `trading` in
|
||||
`tiers.json` (oggi il 2, «Compagnia regionale»), compri e venda merci in proprio al prezzo locale.
|
||||
L'ADR 0015 ha già dato i prezzi e le destinazioni nel pannello «Mercato globale». Restavano aperti:
|
||||
dove sta la merce della compagnia, come si fissa il prezzo di ogni unità, da chi si compra e a chi si
|
||||
vende, come la merce viaggia sulle linee senza essere confusa con quella dei clienti, cosa succede se
|
||||
la destinazione è piena o il percorso sparisce, e come tutto questo entra in salvataggi, hash e
|
||||
invarianti.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Magazzino della compagnia.** Ogni stazione ha un magazzino (`Station.Stock`, unità per bene)
|
||||
della compagnia proprietaria, con capacità complessiva `trading.warehouseCapacity` (500 unità,
|
||||
tutti i beni insieme) in `balance.json`. Le unità di merce propria in viaggio verso una stazione
|
||||
(pacchetti propri in stazione e a bordo) occupano già il suo magazzino: lo spazio libero è
|
||||
capacità − giacenza − in arrivo. Il magazzino segue la stazione se cambia proprietario (fusioni,
|
||||
aste); con la liquidazione la merce va persa (deperita). Una stazione con merce in magazzino, o
|
||||
con merce propria in attesa di partire o in arrivo, non si demolisce. Ogni mese la compagnia paga `trading.storageCostPerUnitPerMonth` (25 centesimi) per
|
||||
unità in magazzino, sulla voce «Commercio». La merce in magazzino non deperisce. È contata da
|
||||
`World.TotalStock` (invariante «merci») e nelle scorte del Mercato globale. La merce propria, in
|
||||
magazzino e in viaggio, entra nel valore contabile degli attivi (`AssetBookValue`, quindi nel
|
||||
patrimonio netto per livelli, rating e borsa) al prezzo globale del mese: comprare costa al
|
||||
patrimonio solo la differenza dal prezzo globale e la giacenza.
|
||||
Lo sblocco del livello serve solo per comprare: la merce già in magazzino, per esempio quella
|
||||
ereditata con una fusione da una controllata di livello più alto, si vende e si spedisce sempre,
|
||||
e il riquadro del pannello compare anche senza lo sblocco quando c'è merce nei magazzini.
|
||||
2. **Prezzo locale marginale.** Ogni unità si paga al prezzo locale (ADR 0004 §3) calcolato con la
|
||||
giacenza che il venditore o il compratore ha in quel momento, unità dopo unità. Per un produttore:
|
||||
Dl = spazio libero del magazzino dell'output (capienza − giacenza), Sl = giacenza: pieno vale
|
||||
(1 − λ)·Pg = 0,65·Pg, a metà Pg, quasi vuoto fino a 1,35·Pg. Per un consumatore, come «Dove
|
||||
conviene vendere»: Dl = capienza dell'input, Sl = giacenza. Il prezzo quindi sale man mano che si
|
||||
svuota il venditore e scende man mano che si riempie il compratore: comprare tanto in un posto solo
|
||||
costa di più. Gli hub vendono a Pg·(1 + dazio) e comprano a Pg·(1 − dazio), a prezzo fisso entro
|
||||
la capacità mensile residua (comune a import ed export, come per il trasporto locale).
|
||||
3. **Compra (`BuyGoods`).** Venditori: produttori aperti nel bacino della stazione con il bene in
|
||||
magazzino e hub del bacino. Si compra un'unità alla volta dal venditore con la prossima unità più
|
||||
economica (a parità prima le industrie, poi gli hub, poi l'id), finché si raggiunge la quantità,
|
||||
lo spazio libero, il tetto `MaxUnitPrice`, la merce in vendita o la cassa. Se già la prima unità
|
||||
supera il tetto il comando è rifiutato (`InvalidArgument`); se la cassa non basta per un'unità,
|
||||
`InsufficientFunds`. Il denaro va dalla compagnia all'industria (o al conto Esterno per gli hub,
|
||||
che contano come importazione e usano la capacità del mese) sulla voce «Commercio»; il produttore
|
||||
registra la vendita come per il ritiro del vettore e diventa «servito» (ADR 0008 §5: la merce
|
||||
lascia l'industria dalla stazione della compagnia). Un bene non ancora disponibile nell'era si
|
||||
rifiuta (`EraLocked`).
|
||||
4. **Vendi (`SellGoods`).** Compratori: industrie aperte di livello > 0 nel bacino che hanno il bene
|
||||
in ricetta, fino allo spazio libero dell'input, e hub del bacino entro la capacità (esportazione).
|
||||
Si vende un'unità alla volta al compratore che paga di più la prossima unità (a parità prima le
|
||||
industrie, poi l'id) finché la quantità, la giacenza o il minimo `MinUnitPrice` lo consentono.
|
||||
Le industrie pagano con la loro cassa come per gli altri input, ma non vanno in rosso: un'industria
|
||||
che non può pagare la prossima unità si salta (le consegne del vettore restano come prima). Ricambi
|
||||
e macchinari si vendono solo alle industrie che li hanno in ricetta: la scorta di manutenzione
|
||||
degli impianti resta rifornita come nell'ADR 0011. Le città non comprano dalla compagnia.
|
||||
5. **Spedisci (`ShipGoods`, comando 40).** `ShipGoods(from, to, good, units)` toglie fino a `units`
|
||||
dal magazzino di `from` e crea un pacchetto merci con `Owned = true` diretto alla stazione `to`
|
||||
della compagnia, instradato sul grafo delle linee come gli altri (ADR 0008: carico per linea e
|
||||
bene, trasbordi, sosta proporzionale alle unità) e con la scadenza in stazione del bene
|
||||
(`decayDaysAtStation`), come ogni merce in attesa; la scadenza riparte a ogni trasbordo, così
|
||||
conta solo il tempo passato ad aspettare in una stazione e non quello del viaggio. A differenza dei
|
||||
pacchetti dei clienti, il percorso della merce propria rispetta i flag delle fermate: si sale su
|
||||
una linea solo dove una sua fermata carica e, ai cambi, si scende solo dove una fermata della linea
|
||||
lasciata scarica (`LineGraph.From(…, stopFlags: true)`); se un percorso esiste solo ignorando i
|
||||
flag il comando si rifiuta con `Blocked`. Senza tariffa (la merce è della compagnia) e
|
||||
senza consumatore: all'arrivo entra nel magazzino di `to`. Non tocca `Incoming` (che misura il
|
||||
bisogno dei consumatori nella scelta delle destinazioni), quindi la scelta delle destinazioni e i
|
||||
pacchetti esistenti non cambiano. Si rifiuta se non c'è un percorso per quel bene, se le stazioni
|
||||
coincidono, non sono della compagnia o sono demolite.
|
||||
6. **Destinazione piena: rifiuto a priori.** La spedizione si limita allo spazio libero di `to`
|
||||
calcolato con la merce già in arrivo, e si rifiuta (`Blocked`) se è zero. Così all'arrivo la merce
|
||||
entra sempre nel magazzino, senza un secondo stato «in attesa del magazzino» con scadenze proprie;
|
||||
il prezzo è che una spedizione lunga tiene occupato lo spazio di destinazione per tutto il viaggio.
|
||||
Se il percorso sparisce durante il viaggio (linea cancellata o modificata), la merce entra nel
|
||||
magazzino della stazione dove si trova, anche oltre la capacità: comprare e ricevere altre
|
||||
spedizioni lì resta bloccato finché non si vende o si rispedisce. Per questo la merce propria in
|
||||
attesa ricalcola il tratto ogni giorno sulle linee di quel giorno (senza percorso torna in
|
||||
magazzino); quella a bordo scende alla prima stazione in cui il treno si ferma se il suo tratto
|
||||
non è più sulla linea del treno (o la fine del tratto non scarica più) e da lì riparte o entra in
|
||||
magazzino; un treno che lascia la linea (riassegnato, mandato al deposito, messo in riserva, fine
|
||||
della copertura di una riserva) la lascia subito alla stazione dove si trova o, se è in viaggio,
|
||||
alla prossima fermata della linea. Così la merce non resta mai a bordo senza un tratto e lo spazio
|
||||
prenotato a destinazione si libera. Un deragliamento la perde come il resto del carico.
|
||||
7. **Salvataggio, versione 4.** `TradingSerializer` aggiunge in coda allo stato dinamico i magazzini
|
||||
(beni per id testuale, solo quelli non vuoti) e gli id dei pacchetti propri in ogni stazione e
|
||||
treno: il formato dei pacchetti di `RailSerializer` non cambia. Entra nell'hash giornaliero. I
|
||||
salvataggi delle versioni 1–3 si caricano con i magazzini vuoti. `WorldSerializer.Write(w, s,
|
||||
versione)` scrive un corpo di una versione precedente per provare le migrazioni.
|
||||
8. **Protocollo e client.** `MarketReport` (129) porta nel blocco 1 i magazzini della compagnia nelle
|
||||
sue stazioni vive: capacità, merce in arrivo e, per ogni bene in magazzino o scambiabile nel bacino,
|
||||
giacenza e quotazione della prossima unità (prezzo e unità di venditori e compratori, −1 senza
|
||||
controparti; la cassa delle industrie non è considerata nella quotazione). Il riquadro
|
||||
«Compravendita in proprio» del pannello, quando sbloccato, sceglie stazione, quantità e
|
||||
destinazione per la merce selezionata e manda i comandi con un tetto del 10 % sopra (o un minimo
|
||||
del 10 % sotto) il prezzo mostrato: è una scelta d'interfaccia, il server ricalcola tutto.
|
||||
9. **IA.** Le compagnie IA non commerciano ancora: i loro candidati restano linee e treni (ADR 0013).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il commercio rende soprattutto dove il vettore non arriva: un produttore con il magazzino pieno
|
||||
vende a 0,65·Pg e un consumatore a secco paga fino a 1,35·Pg, quindi comprare all'origine, spedire
|
||||
gratis sulle proprie linee e vendere al consumatore vuoto vale fino a 0,7·Pg per unità meno la
|
||||
giacenza. Dove il vettore già consegna, i consumatori hanno l'input pieno e non comprano.
|
||||
- Le quantità sono piccole rispetto alle consegne del vettore (500 unità per stazione): il commercio
|
||||
è uno strumento di arbitraggio, non sostituisce il trasporto.
|
||||
- Il prezzo marginale costa un calcolo per unità e controparte: con le quantità del magazzino è
|
||||
trascurabile e lo si fa solo all'esecuzione di un comando o del quadro del mercato.
|
||||
- L'accettazione F4 dà gli stessi numeri di prima (i pacchetti senza `Owned` seguono lo stesso codice).
|
||||
@@ -0,0 +1,137 @@
|
||||
# ADR 0017 — Eventi del mondo con effetti temporanei e notizie (F6)
|
||||
|
||||
Stato: accettato (F6, issue #33).
|
||||
|
||||
## Contesto
|
||||
|
||||
La roadmap F6 (guida, sezione 16) chiede gli «eventi»: fatti del mondo che cambiano per un po' il
|
||||
gioco e che il giocatore legge nel notiziario. Fino alla F5 esistevano solo gli shock mondiali dei
|
||||
prezzi di `MarketSystem` (ADR 0004 e 0015), che fanno parte del modello dei prezzi. La guida non dice
|
||||
quali eventi, con che frequenza, come agiscono sui sistemi, come si salvano né come arrivano al
|
||||
client. Servono effetti leggibili (si sa cosa succede, dove e fino a quando), reversibili (a evento
|
||||
finito tutto torna come prima) e deterministici.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Catalogo in `data/events.json`** (schema `data/schema/events.schema.json`, caricato in
|
||||
`GameData.Events`, validato da `DataValidator`). Ogni tipo ha id, nomi it/en, bersaglio
|
||||
(`industry`, `town`, `townGood`, `area`, `depot`), raggio della zona in km (solo `area` e
|
||||
`townGood`), probabilità annua, durata min/max in giorni, anno minimo, popolazione minima della
|
||||
città, beni o tipi di industria ammessi (facoltativi), gravità, effetti con ampiezza min/max e le
|
||||
notizie d'inizio e di fine con i segnaposti `{target}`, `{good}`, `{pct}` (effetto principale),
|
||||
`{days}`, `{until}`. Il validatore controlla id univoci, intervalli non invertiti, beni esistenti e
|
||||
di consumo delle città, raggio presente solo dove serve ed effetti compatibili con il bersaglio.
|
||||
`maxActive` (6) limita gli eventi attivi insieme su tutta la mappa: il notiziario resta leggibile.
|
||||
2. **Tipi.** Nove tipi, adattati a ciò che il motore permette senza riscritture:
|
||||
- industria: *incidente* (capacità × 0–0,5 per 10–45 giorni) e *boom di produzione* (× 1,2–1,5
|
||||
per 30–120 giorni);
|
||||
- città: *fiera* (consumi della città × 1,3–1,8 per 7–20 giorni, città da 1.500 abitanti) ed
|
||||
*epidemia* (consumi × 0,7–0,9 e presenze dei suoi lavoratori × 0,5–0,8 per 30–90 giorni, da 2.000
|
||||
abitanti). Il motore non ha passeggeri occasionali, solo pendolari: la «domanda di passeggeri»
|
||||
della richiesta diventa la domanda di beni della città (fiera) e le presenze al lavoro
|
||||
(epidemia);
|
||||
- bene: *boom* (× 1,4–2,0) e *crollo* (× 0,3–0,7) della domanda di un bene di consumo nelle città
|
||||
entro 15 km da una città, per 60–180 giorni;
|
||||
- maltempo: velocità dei treni × 0,5–0,8 e usura del binario dovuta al traffico × 2–4 (8.3) sugli
|
||||
archi il cui punto medio cade entro 12 km da una città, per 3–12 giorni;
|
||||
- sciopero: dei lavoratori di una città (presenze × 0,2–0,6, città da 1.000 abitanti) o del
|
||||
personale di un deposito (presenze × 0–0,5, sezione 9: l'officina rallenta come senza
|
||||
personale), per 5–20 giorni.
|
||||
Gli shock mondiali dei prezzi restano in `MarketSystem` con i loro parametri in `balance.json`
|
||||
(`market.world`): sono parte della formula del prezzo (6.3), non un moltiplicatore temporaneo su
|
||||
un'entità, e spostarli avrebbe cambiato i numeri. Non hanno quindi una voce nel catalogo.
|
||||
3. **Una sola sorgente degli effetti.** Lo stato è `World.WorldEvents` (`WorldEventState`): elenco
|
||||
degli eventi attivi (`ActiveWorldEvent`: tipo, bersaglio, bene, giorno d'inizio e di fine,
|
||||
intensità in [0, 1]) con le interrogazioni per entità che restituiscono il prodotto degli effetti
|
||||
attivi, 1 senza eventi: `IndustryCapacity` (letta da `IndustrySystem` per produzione, capacità
|
||||
installata ed efficienza, e da `DemandSystem` per la domanda di input), `TownDemand`
|
||||
(`DemandSystem.TownDemand`, quindi anche stime e IA), `Attendance` (presenze dei pendolari in
|
||||
`EmploymentSystem`: città d'origine e deposito di destinazione; contratti e coperture del
|
||||
trasporto non cambiano), `EdgeSpeed` (fattore di condizione del binario in `TrainSystem`, anche
|
||||
nell'anticipo dei limiti) ed `EdgeWear` (`ConstructionSystem`). Nessun sistema modifica uno stato
|
||||
«di base»: a evento scaduto il moltiplicatore torna 1 e tutto torna come prima. Le medie mobili
|
||||
esistenti (coperture a 30 giorni, margini) si riprendono con i loro tempi, come dopo ogni altro
|
||||
cambiamento. Un valore per ogni effetto = min + intensità·(max − min); l'intensità è una sola per
|
||||
evento, così gli effetti di uno stesso evento sono coerenti.
|
||||
4. **Frequenza per mappa, non per bersaglio.** `chancePerYear` è il numero atteso di eventi di quel
|
||||
tipo all'anno sull'intera mappa, moltiplicato per `eventFrequencyMultiplier` della difficoltà
|
||||
(nuovo campo di `difficulty.json`: 0,7 / 1,0 / 1,2 / 1,4, ritoccabile come «Personalizzata»;
|
||||
0 disattiva gli eventi). Il bersaglio si sceglie poi a caso tra quelli ammessi. Così il flusso di
|
||||
notizie non cresce con la dimensione della mappa (con «Imprenditore» circa 7,7 eventi l'anno
|
||||
prima del tetto) e ogni giorno costa una estrazione per tipo, non una per entità.
|
||||
5. **Sistema `EventSystem`**, tra le IA e l'hash, al posto di «Events» nell'ordine della guida
|
||||
(… → AiAgents → Events → Contracts → Hash). Ogni giorno chiude gli eventi giunti all'ultimo giorno
|
||||
o con il bersaglio sparito (industria chiusa o a livello 0, deposito demolito: senza notizia di
|
||||
fine), poi per ogni tipo, in ordine di catalogo, dall'anno minimo: un'estrazione `Chance` con il
|
||||
flusso dedicato `World.Stream("events")` (derivato con `Rng.Fork`, salvato con gli altri); se il
|
||||
tetto non è raggiunto, i candidati in ordine di id (industrie aperte di livello > 0, depositi vivi,
|
||||
città sopra la popolazione minima; per `townGood` le coppie città–bene con domanda nell'anno) senza
|
||||
quelli che hanno già un evento dello stesso tipo e, per le zone, quelli la cui zona si
|
||||
sovrappone a quella di un evento con lo stesso bersaglio di zona (due maltempi; due eventi sulla
|
||||
domanda dello stesso bene, quindi né due boom né boom e crollo insieme): i centri devono distare
|
||||
più della somma dei raggi, così nessuna città e nessun arco ricevono due volte lo stesso effetto.
|
||||
Poi bersaglio, durata e intensità dallo stesso flusso. Tipi diversi sullo stesso bersaglio si
|
||||
sommano (prodotto dei moltiplicatori), per esempio epidemia e sciopero sulle presenze.
|
||||
Posizione e date: girando dopo i sistemi giornalieri, un evento estratto il giorno S inizia il
|
||||
giorno S + 1 ed è in vigore nei giorni [inizio, fine), cioè esattamente per la durata estratta.
|
||||
L'evento resta nell'elenco dall'estrazione al mattino del primo giorno libero (fine), quando
|
||||
esce con la notizia di fine; le interrogazioni di `WorldEventState` contano solo gli eventi in
|
||||
vigore nel giorno dell'orologio, così valgono gli stessi giorni per i sistemi giornalieri, per i
|
||||
treni che si muovono a ogni tick (niente rallentamento il giorno dell'estrazione, rallentamento
|
||||
per intero l'ultimo giorno) e per l'usura, che `ConstructionSystem` applica al mattino al traffico
|
||||
del giorno prima e che quindi conta il maltempo in vigore ieri. Inizio e fine danno un
|
||||
`GameEvent` di tipo nuovo `EventKind.World` (10), in italiano, con l'entità coinvolta, per
|
||||
notiziario e Cronaca. `EventSystem.Force` fa iniziare un evento scelto (test, scenari, strumenti),
|
||||
senza numeri casuali.
|
||||
6. **Salvataggio, versione 5.** `EventSerializer` aggiunge in coda allo stato dinamico il prossimo id
|
||||
e gli eventi attivi (tipo e bene per id testuale, bersaglio, giorni, intensità); la zona si
|
||||
ricalcola dal catalogo al caricamento. Entra nell'hash giornaliero. Le impostazioni salvano anche
|
||||
`eventFrequencyMultiplier`. I salvataggi delle versioni 1–4 si caricano senza eventi attivi e con la
|
||||
frequenza del preset con lo stesso id nei dati correnti (1 se l'id non esiste): una partita salvata
|
||||
prima della F6 riceve gli eventi da quel momento. Un tipo o un bene tolti dai dati fanno finire
|
||||
l'evento al caricamento.
|
||||
7. **Protocollo e client.** `DailyDigest` (120) porta nel blocco 1 l'elenco compatto degli eventi in
|
||||
corso (`WorldEventInfo`: id, tipo, entità, bene, giorni, gravità e valori dei moltiplicatori),
|
||||
compresi quelli estratti oggi che iniziano domani;
|
||||
`MarketReport` (129) porta nel blocco 2 quelli sulla domanda di un bene, che il pannello «Mercato
|
||||
globale» mostra come «evento in corso» insieme allo shock mondiale (`MarketOutlook.GoodEvents`).
|
||||
Il client mostra il riquadro «Eventi in corso» sopra la minimappa (fino a quattro righe, i più
|
||||
vicini alla fine) con l'ultimo giorno (fine − 1) e i giorni che restano, oggi compreso (dalla
|
||||
durata a 1), oppure «da domani» per quelli non ancora iniziati. Mostra l'avviso dell'evento nelle
|
||||
schede dell'industria, della città (bersaglio diretto o città entro il raggio del catalogo dalla
|
||||
città centro di una zona, come sul server) e nel Registro officina del deposito in sciopero. Le
|
||||
notizie non informative arrivano già una per una come `Notification`; dal `DailyDigest` il
|
||||
notiziario aggiunge solo quelle informative di `EventKind.World` (le notizie di fine), così
|
||||
nessuna compare due volte. Il segnaposto `{until}` è l'ultimo giorno dell'evento, come nel
|
||||
client. Testi con `T()` e chiavi in `strings.csv`; i nomi dei tipi vengono dal catalogo nella
|
||||
lingua dell'interfaccia.
|
||||
8. **Accettazione con gli eventi disattivati.** Lo scenario di riferimento `valdoria.json` mette
|
||||
`eventFrequencyMultiplier` a 0 (nuovo campo facoltativo degli scenari, che sostituisce quello della
|
||||
difficoltà): l'accettazione F2 e F4 e tutti i test sulla rete di Valdoria misurano il sistema che
|
||||
provano, non la fortuna. Con gli eventi attivi alla frequenza di «Imprenditore» la rete F4 senza
|
||||
linea dei ricambi resta a 41 di condizione minima con 10 guasti (19,7 per milione di km) invece di
|
||||
35 con 20 guasti: scioperi e maltempo riducono i km di servizio e l'usura, e il criterio della
|
||||
guida «sotto 40 entro 3 anni» non sarebbe più vero; con la linea resta 75 con 2 guasti. I numeri
|
||||
dell'accettazione F4 con gli eventi disattivati restano 35 / 20 guasti senza la linea e 75 / 2 con
|
||||
la linea. I mondi generati (`WorldFactory`) hanno gli eventi della difficoltà scelta.
|
||||
9. **IA.** Le compagnie IA non reagiscono agli eventi: ne subiscono gli effetti attraverso i sistemi,
|
||||
ma non progettano linee su valori temporanei, che renderebbero permanente un effetto di pochi
|
||||
giorni. Nelle stime dei candidati usano la domanda delle città senza eventi
|
||||
(`DemandSystem.TownDemand(…, events: false)`), i posti scoperti contati sui presenti senza le
|
||||
assenze di epidemie e scioperi (`EmploymentSystem.PresentWithoutEvents`) e, per le industrie di
|
||||
trasformazione, l'efficienza divisa per il moltiplicatore di capacità (un impianto fermo per un
|
||||
incidente si rivaluta a evento finito, senza essere scartato). Gli effetti indiretti passati per le
|
||||
medie mobili (coperture a 30 giorni) restano, come per ogni altro cambiamento del mondo.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Ogni effetto è un moltiplicatore in un punto noto di un sistema esistente: aggiungere un tipo con
|
||||
un effetto già previsto è solo una voce del catalogo; un effetto nuovo richiede un caso in
|
||||
`EventEffectKind`, l'interrogazione in `WorldEventState`, la riga di compatibilità nel validatore e
|
||||
il punto del sistema che lo legge.
|
||||
- Le interrogazioni scorrono l'elenco degli eventi attivi (al massimo `maxActive`): per i treni il
|
||||
maltempo controlla prima un contatore e, senza eventi d'area, non costa nulla.
|
||||
- L'area del maltempo si misura sul punto medio dell'arco: un arco molto lungo è dentro o fuori
|
||||
per intero.
|
||||
- Una partita con eventi ha numeri diversi da una senza: per confronti e scenari didattici la
|
||||
frequenza si mette a 0 nella difficoltà o nello scenario.
|
||||
@@ -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.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 239 KiB |
@@ -47,6 +47,7 @@ public enum CommandType : ushort
|
||||
FundResearch = 37,
|
||||
DelegateRegion = 38,
|
||||
MergeCompany = 39,
|
||||
ShipGoods = 40,
|
||||
}
|
||||
|
||||
/// <summary>Codici di errore stabili degli esiti dei comandi.</summary>
|
||||
|
||||
@@ -51,18 +51,34 @@ public sealed record RejectAgreementCommand(AgreementId Agreement) : GameCommand
|
||||
public override CommandType Type => CommandType.RejectAgreement;
|
||||
}
|
||||
|
||||
/// <summary>Compra merce al prezzo locale in una stazione (commercio, livello 2).</summary>
|
||||
/// <summary>
|
||||
/// Compra fino a <paramref name="Units"/> unità del bene dai produttori e dagli hub nel bacino di una
|
||||
/// stazione della compagnia, al prezzo locale, senza superare <paramref name="MaxUnitPrice"/> per
|
||||
/// unità; la merce entra nel magazzino della stazione (commercio, sbloccato da tiers.json, ADR 0016).
|
||||
/// </summary>
|
||||
public sealed record BuyGoodsCommand(StationId Station, string Good, int Units, Money MaxUnitPrice) : GameCommand
|
||||
{
|
||||
public override CommandType Type => CommandType.BuyGoods;
|
||||
}
|
||||
|
||||
/// <summary>Vende merce della compagnia al prezzo locale in una stazione.</summary>
|
||||
/// <summary>
|
||||
/// Vende fino a <paramref name="Units"/> unità dal magazzino della stazione ai consumatori e agli hub
|
||||
/// del bacino, al prezzo locale, non sotto <paramref name="MinUnitPrice"/> per unità.
|
||||
/// </summary>
|
||||
public sealed record SellGoodsCommand(StationId Station, string Good, int Units, Money MinUnitPrice) : GameCommand
|
||||
{
|
||||
public override CommandType Type => CommandType.SellGoods;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spedisce fino a <paramref name="Units"/> unità dal magazzino di una stazione a quello di un'altra
|
||||
/// stazione della compagnia sulle sue linee, senza tariffa; id 40, aggiunto in F6 (ADR 0016).
|
||||
/// </summary>
|
||||
public sealed record ShipGoodsCommand(StationId From, StationId To, string Good, int Units) : GameCommand
|
||||
{
|
||||
public override CommandType Type => CommandType.ShipGoods;
|
||||
}
|
||||
|
||||
/// <summary>Offerta d'acquisto di un'industria.</summary>
|
||||
public sealed record BuyIndustryCommand(IndustryId Industry, Money Offer) : GameCommand
|
||||
{
|
||||
|
||||
@@ -13,6 +13,7 @@ public sealed class BalanceFile
|
||||
public required MapBalance Map { get; init; }
|
||||
public required MarketBalance Market { get; init; }
|
||||
public required LocalPriceBalance LocalPrice { get; init; }
|
||||
public required TradingBalance Trading { get; init; }
|
||||
public required IndustryBalance Industry { get; init; }
|
||||
public required GrowthBalance Growth { get; init; }
|
||||
public required TownBalance Town { get; init; }
|
||||
@@ -173,7 +174,27 @@ public sealed class MarketBalance
|
||||
public required double RatioMin { get; init; }
|
||||
public required double RatioMax { get; init; }
|
||||
public required WorldMarketParams World { get; init; }
|
||||
/// <summary>Giorni di prezzi globali conservati per bene (storico del pannello Mercato globale).</summary>
|
||||
public required int HistoryDays { get; init; }
|
||||
/// <summary>Analisi del mercato per il pannello «Mercato globale» (ADR 0015).</summary>
|
||||
public required MarketOutlookBalance Outlook { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Parametri dell'analisi del mercato (MarketOutlook, ADR 0015).</summary>
|
||||
public sealed class MarketOutlookBalance
|
||||
{
|
||||
/// <summary>Mesi di storico mensile (un campione per mese di calendario).</summary>
|
||||
public required int HistoryMonths { get; init; }
|
||||
/// <summary>Giorni della variazione del prezzo e dell'indice («30 giorni»).</summary>
|
||||
public required int ChangeDays { get; init; }
|
||||
/// <summary>Mesi di previsione dalla componente mondiale.</summary>
|
||||
public required int ForecastMonths { get; init; }
|
||||
/// <summary>Semiampiezza della banda di previsione per mese di distanza (frazione del prezzo).</summary>
|
||||
public required double ForecastBandPerMonth { get; init; }
|
||||
/// <summary>Destinazioni elencate in «Dove conviene vendere».</summary>
|
||||
public required int SellPlaces { get; init; }
|
||||
/// <summary>Shock mondiale minimo (frazione del prezzo base) perché sia un «evento in corso».</summary>
|
||||
public required double EventThreshold { get; init; }
|
||||
}
|
||||
|
||||
public sealed class WorldMarketParams
|
||||
@@ -191,6 +212,15 @@ public sealed class WorldMarketParams
|
||||
public required double PriceFloor { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Compravendita in proprio (F6, ADR 0016): magazzino della compagnia in ogni sua stazione.</summary>
|
||||
public sealed class TradingBalance
|
||||
{
|
||||
/// <summary>Unità complessive (tutti i beni, comprese le spedizioni in arrivo) per stazione.</summary>
|
||||
public required int WarehouseCapacity { get; init; }
|
||||
/// <summary>Costo di giacenza mensile per unità in magazzino (centesimi).</summary>
|
||||
public required long StorageCostPerUnitPerMonth { get; init; }
|
||||
}
|
||||
|
||||
public sealed class LocalPriceBalance
|
||||
{
|
||||
public required double Lambda { get; init; }
|
||||
|
||||
@@ -29,5 +29,6 @@ namespace RailEnterprise.Core.Data;
|
||||
[JsonSerializable(typeof(AiFile))]
|
||||
[JsonSerializable(typeof(ContractsFile))]
|
||||
[JsonSerializable(typeof(RegionsFile))]
|
||||
[JsonSerializable(typeof(EventsFile))]
|
||||
[JsonSerializable(typeof(DifficultyDef))]
|
||||
public sealed partial class DataJsonContext : JsonSerializerContext;
|
||||
@@ -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);
|
||||
@@ -145,6 +161,9 @@ public static class DataValidator
|
||||
var b = d.Balance;
|
||||
if (!b.Time.Speeds.Contains(0) || !b.Time.Speeds.Contains(1)) Err("balance.json", "time.speeds deve contenere 0 e 1");
|
||||
if (b.Market.MinPriceFactor >= 1 || b.Market.MaxPriceFactor <= 1) Err("balance.json", "market: i fattori di prezzo devono racchiudere 1");
|
||||
if (b.Market.Outlook.HistoryMonths * b.Time.DaysPerMonth > b.Market.HistoryDays)
|
||||
Err("balance.json", "market.outlook.historyMonths: lo storico mensile richiede più giorni di market.historyDays");
|
||||
if (b.Market.Outlook.ChangeDays >= b.Market.HistoryDays) Err("balance.json", "market.outlook.changeDays deve essere minore di market.historyDays");
|
||||
foreach (int size in b.Map.SizesKm)
|
||||
{
|
||||
string key = size.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
@@ -188,6 +207,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)
|
||||
{
|
||||
@@ -226,6 +249,7 @@ public static class DataValidator
|
||||
if (t.Kind is ContractKind.Deliver or ContractKind.Service && t.Quantity is null) Err("contracts.json", $"{t.Id}: richiede quantity");
|
||||
if (t.Kind == ContractKind.GreatWork && t.LengthKm is null) Err("contracts.json", $"{t.Id}: una grande opera richiede lengthKm");
|
||||
}
|
||||
ValidateEvents(d, goodIds, errors);
|
||||
Unique("regions.json", d.Regions.Regions.Select(r => r.Id), errors);
|
||||
Unique("regions.json", d.Regions.NamePools.Select(r => r.Id), errors);
|
||||
var pools = d.Regions.NamePools.Select(p => p.Id).ToHashSet(StringComparer.Ordinal);
|
||||
@@ -235,6 +259,44 @@ public static class DataValidator
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Effetti ammessi per ogni bersaglio (ADR 0017).</summary>
|
||||
public static bool EffectFits(EventTarget target, EventEffectKind effect) => effect switch
|
||||
{
|
||||
EventEffectKind.IndustryCapacity => target == EventTarget.Industry,
|
||||
EventEffectKind.TownDemand => target == EventTarget.Town,
|
||||
EventEffectKind.GoodDemand => target == EventTarget.TownGood,
|
||||
EventEffectKind.Attendance => target is EventTarget.Town or EventTarget.Depot,
|
||||
EventEffectKind.TrainSpeed or EventEffectKind.TrackWear => target == EventTarget.Area,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static void ValidateEvents(GameData d, HashSet<string> goodIds, List<string> errors)
|
||||
{
|
||||
const string file = "events.json";
|
||||
Unique(file, d.Events.Events.Select(e => e.Id), errors);
|
||||
foreach (var e in d.Events.Events)
|
||||
{
|
||||
string p = $"{e.Id}:";
|
||||
if (e.DurationDays[0] > e.DurationDays[1]) errors.Add($"{file}: {p} durationDays [min, max] invertito");
|
||||
bool zone = e.Target is EventTarget.Area or EventTarget.TownGood;
|
||||
if (zone && e.RadiusKm is null) errors.Add($"{file}: {p} il bersaglio «{e.Target}» richiede radiusKm");
|
||||
if (!zone && e.RadiusKm is not null) errors.Add($"{file}: {p} radiusKm vale solo per area e townGood");
|
||||
if (e.Goods is not null && e.Target != EventTarget.TownGood) errors.Add($"{file}: {p} goods vale solo per townGood");
|
||||
if (e.IndustryKinds is not null && e.Target != EventTarget.Industry) errors.Add($"{file}: {p} industryKinds vale solo per industry");
|
||||
foreach (string g in e.Goods ?? [])
|
||||
{
|
||||
if (!goodIds.Contains(g)) errors.Add($"{file}: {p} bene sconosciuto «{g}»");
|
||||
else if (d.Goods.First(x => x.Id == g).Town is null) errors.Add($"{file}: {p} «{g}» non è un bene di consumo delle città");
|
||||
}
|
||||
Unique(file, e.Effects.Select(x => x.Kind.ToString()), errors, $"{p} effetti");
|
||||
foreach (var x in e.Effects)
|
||||
{
|
||||
if (x.Min > x.Max) errors.Add($"{file}: {p} effetto {x.Kind} con min > max");
|
||||
if (!EffectFits(e.Target, x.Kind)) errors.Add($"{file}: {p} l'effetto {x.Kind} non si applica al bersaglio {e.Target}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckCarComponents(VehicleDef v, HashSet<string> carComponents, List<string> errors)
|
||||
{
|
||||
foreach (string c in v.Components.Keys)
|
||||
|
||||
@@ -42,6 +42,8 @@ public sealed record DifficultyDef
|
||||
public required double TariffMultiplier { get; init; }
|
||||
public required double WearMultiplier { get; init; }
|
||||
public required double MarketVolatilityMultiplier { get; init; }
|
||||
/// <summary>Frequenza degli eventi del mondo (events.json): 0 li disattiva (ADR 0017).</summary>
|
||||
public required double EventFrequencyMultiplier { get; init; }
|
||||
public required int AiCompetitors { get; init; }
|
||||
public required double AiCapitalMultiplier { get; init; }
|
||||
public required double AiCostDiscount { get; init; }
|
||||
|
||||
@@ -9,7 +9,7 @@ public static class DifficultyOverrides
|
||||
public static readonly string[] Keys =
|
||||
[
|
||||
"initialCapital", "initialCredit", "baseInterestRate", "constructionCostMultiplier", "tariffMultiplier", "wearMultiplier",
|
||||
"marketVolatilityMultiplier", "aiCompetitors", "aiCapitalMultiplier", "aiCostDiscount", "playerTakeover", "takeoverRansomYears",
|
||||
"marketVolatilityMultiplier", "eventFrequencyMultiplier", "aiCompetitors", "aiCapitalMultiplier", "aiCostDiscount", "playerTakeover", "takeoverRansomYears",
|
||||
"bankruptcyDays", "publicFromStart", "playerShareAtStart", "ironman", "depletion",
|
||||
];
|
||||
|
||||
@@ -29,6 +29,7 @@ public static class DifficultyOverrides
|
||||
"tariffMultiplier" => d with { TariffMultiplier = Range(key, value, 0.1, 10) },
|
||||
"wearMultiplier" => d with { WearMultiplier = Range(key, value, 0, 10) },
|
||||
"marketVolatilityMultiplier" => d with { MarketVolatilityMultiplier = Range(key, value, 0, 10) },
|
||||
"eventFrequencyMultiplier" => d with { EventFrequencyMultiplier = Range(key, value, 0, 10) },
|
||||
"aiCompetitors" => d with { AiCompetitors = (int)Range(key, value, 0, 8) },
|
||||
"aiCapitalMultiplier" => d with { AiCapitalMultiplier = Range(key, value, 0, 10) },
|
||||
"aiCostDiscount" => d with { AiCostDiscount = Range(key, value, 0, 0.9) },
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RailEnterprise.Core.Data;
|
||||
|
||||
// Contenuto di events.json: catalogo degli eventi del mondo (F6, ADR 0017).
|
||||
|
||||
/// <summary>Bersaglio di un evento del mondo.</summary>
|
||||
public enum EventTarget
|
||||
{
|
||||
/// <summary>Un'industria aperta di livello > 0.</summary>
|
||||
Industry,
|
||||
/// <summary>Una città.</summary>
|
||||
Town,
|
||||
/// <summary>Un bene di consumo nelle città entro <c>radiusKm</c> da una città.</summary>
|
||||
TownGood,
|
||||
/// <summary>Un'area circolare di raggio <c>radiusKm</c> intorno a una città.</summary>
|
||||
Area,
|
||||
/// <summary>Un deposito di una compagnia.</summary>
|
||||
Depot,
|
||||
}
|
||||
|
||||
/// <summary>Effetto di un evento: un moltiplicatore temporaneo letto da un sistema esistente.</summary>
|
||||
public enum EventEffectKind
|
||||
{
|
||||
/// <summary>Capacità produttiva dell'industria (IndustrySystem, DemandSystem).</summary>
|
||||
IndustryCapacity,
|
||||
/// <summary>Domanda di tutti i beni di consumo della città (DemandSystem).</summary>
|
||||
TownDemand,
|
||||
/// <summary>Domanda di un bene nelle città della zona (DemandSystem).</summary>
|
||||
GoodDemand,
|
||||
/// <summary>Presenze dei lavoratori della città o del personale del deposito (EmploymentSystem).</summary>
|
||||
Attendance,
|
||||
/// <summary>Velocità dei treni sugli archi dell'area (TrainSystem).</summary>
|
||||
TrainSpeed,
|
||||
/// <summary>Usura del binario dovuta al traffico sugli archi dell'area (ConstructionSystem).</summary>
|
||||
TrackWear,
|
||||
}
|
||||
|
||||
/// <summary>Gravità della notizia (stessi valori di <c>EventSeverity</c>).</summary>
|
||||
public enum NewsSeverity { Info, Opportunity, Warning, Critical }
|
||||
|
||||
public sealed class EventsFile
|
||||
{
|
||||
[JsonPropertyName("$schema")] public string? Schema { get; init; }
|
||||
public required int Version { get; init; }
|
||||
/// <summary>Numero massimo di eventi attivi insieme su tutta la mappa (leggibilità).</summary>
|
||||
public required int MaxActive { get; init; }
|
||||
public required List<WorldEventDef> Events { get; init; }
|
||||
}
|
||||
|
||||
public sealed class WorldEventDef
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
[JsonPropertyName("name_it")] public required string NameIt { get; init; }
|
||||
[JsonPropertyName("name_en")] public required string NameEn { get; init; }
|
||||
public required EventTarget Target { get; init; }
|
||||
/// <summary>Raggio della zona (TownGood, Area), in km dal centro della città.</summary>
|
||||
public double? RadiusKm { get; init; }
|
||||
/// <summary>Eventi attesi all'anno sull'intera mappa (difficoltà «Imprenditore»), non per bersaglio.</summary>
|
||||
public required double ChancePerYear { get; init; }
|
||||
/// <summary>Durata in giorni [min, max], estremi compresi.</summary>
|
||||
public required int[] DurationDays { get; init; }
|
||||
public required int MinYear { get; init; }
|
||||
/// <summary>Città bersaglio (Town, TownGood, Area) solo da questa popolazione.</summary>
|
||||
public int MinPopulation { get; init; }
|
||||
/// <summary>Beni ammessi per TownGood (assente = tutti i beni di consumo delle città).</summary>
|
||||
public List<string>? Goods { get; init; }
|
||||
/// <summary>Tipi di industria ammessi (assente = tutti).</summary>
|
||||
public List<IndustryKind>? IndustryKinds { get; init; }
|
||||
public required NewsSeverity Severity { get; init; }
|
||||
/// <summary>Effetti: il primo è quello principale, mostrato come {pct} nella notizia.</summary>
|
||||
public required List<EventEffectDef> Effects { get; init; }
|
||||
/// <summary>Notizia d'inizio: segnaposti {target}, {good}, {pct}, {days}, {until}.</summary>
|
||||
[JsonPropertyName("news_it")] public required string NewsIt { get; init; }
|
||||
/// <summary>Notizia di fine, con gli stessi segnaposti.</summary>
|
||||
[JsonPropertyName("newsEnd_it")] public required string NewsEndIt { get; init; }
|
||||
|
||||
/// <summary>Posizione nel catalogo (assegnata al caricamento).</summary>
|
||||
[JsonIgnore] public int Index { get; internal set; }
|
||||
|
||||
/// <summary>Indici dei beni ammessi (TownGood), risolti al caricamento.</summary>
|
||||
[JsonIgnore] public int[] GoodIndices { get; internal set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Moltiplicatore di un effetto: min + intensità·(max − min), con l'intensità dell'evento in [0, 1].</summary>
|
||||
public sealed class EventEffectDef
|
||||
{
|
||||
public required EventEffectKind Kind { get; init; }
|
||||
public required double Min { get; init; }
|
||||
public required double Max { get; init; }
|
||||
|
||||
public double At(double intensity) => Min + intensity * (Max - Min);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ public sealed class GameData
|
||||
[
|
||||
"goods.json", "industries.json", "vehicles.json", "eras.json", "tiers.json", "balance.json",
|
||||
"difficulty.json", "construction.json", "maintenance.json", "ai.json", "contracts.json", "regions.json",
|
||||
"events.json",
|
||||
];
|
||||
|
||||
public required IReadOnlyList<GoodDef> Goods { get; init; }
|
||||
@@ -31,6 +32,7 @@ public sealed class GameData
|
||||
public required AiFile Ai { get; init; }
|
||||
public required ContractsFile Contracts { get; init; }
|
||||
public required RegionsFile Regions { get; init; }
|
||||
public required EventsFile Events { get; init; }
|
||||
|
||||
/// <summary>XxHash64 del contenuto canonico (minificato) di tutti i file: client e server devono coincidere.</summary>
|
||||
public ulong Hash { get; private init; }
|
||||
@@ -72,6 +74,9 @@ public sealed class GameData
|
||||
return def is not null;
|
||||
}
|
||||
|
||||
/// <summary>Tipo di evento del mondo per id (null se assente dai dati).</summary>
|
||||
public WorldEventDef? EventType(string id) => Events.Events.FirstOrDefault(e => e.Id == id);
|
||||
|
||||
/// <summary>Preset di difficoltà per id.</summary>
|
||||
public DifficultyDef DifficultyPreset(string id) =>
|
||||
Difficulty.Presets.FirstOrDefault(p => p.Id == id) ?? throw new KeyNotFoundException($"Difficoltà sconosciuta: {id}");
|
||||
@@ -100,6 +105,7 @@ public sealed class GameData
|
||||
AiFile? ai = Read(source, "ai.json", DataJsonContext.Default.AiFile, errors, canonical);
|
||||
ContractsFile? contracts = Read(source, "contracts.json", DataJsonContext.Default.ContractsFile, errors, canonical);
|
||||
RegionsFile? regions = Read(source, "regions.json", DataJsonContext.Default.RegionsFile, errors, canonical);
|
||||
EventsFile? events = Read(source, "events.json", DataJsonContext.Default.EventsFile, errors, canonical);
|
||||
|
||||
if (errors.Count > 0) throw new DataValidationException(errors);
|
||||
|
||||
@@ -117,6 +123,7 @@ public sealed class GameData
|
||||
Ai = ai!,
|
||||
Contracts = contracts!,
|
||||
Regions = regions!,
|
||||
Events = events!,
|
||||
Hash = XxHash64.Hash(canonical.WrittenSpan),
|
||||
};
|
||||
|
||||
@@ -191,6 +198,13 @@ public sealed class GameData
|
||||
def.GoodIndices = def.Goods?.Select(g => _goodIndex[g]).ToArray() ?? [];
|
||||
}
|
||||
for (int i = 0; i < Eras.TrackClasses.Count; i++) Eras.TrackClasses[i].Index = i;
|
||||
for (int i = 0; i < Events.Events.Count; i++)
|
||||
{
|
||||
var e = Events.Events[i];
|
||||
e.Index = i;
|
||||
e.GoodIndices = (e.Goods ?? Goods.Where(g => g.Town is not null).Select(g => g.Id))
|
||||
.Select(id => _goodIndex[id]).ToArray();
|
||||
}
|
||||
SparePartsGood = _goodIndex["spare_parts"];
|
||||
MachineryGood = _goodIndex["machinery"];
|
||||
}
|
||||
|
||||
@@ -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,295 @@
|
||||
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.</summary>
|
||||
OtherIncome = 1,
|
||||
/// <summary>Costi d'esercizio, salari, penali.</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 amministrazione controllata i prestiti non si possono chiedere.</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,
|
||||
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))),
|
||||
new(IncomeLineKind.OperatingCosts, new Money(Sum(LedgerEntry.RunningCosts, LedgerEntry.Wages, LedgerEntry.Penalties))),
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,26 @@ public enum LedgerEntry : byte
|
||||
Subsidiaries = 20,
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public sealed class Loan
|
||||
{
|
||||
@@ -77,8 +97,28 @@ 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>
|
||||
/// 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
|
||||
{
|
||||
|
||||
@@ -49,7 +49,7 @@ public sealed class Market
|
||||
public RollingWindow[] Demand { get; private set; }
|
||||
public RollingWindow[] Supply { get; private set; }
|
||||
|
||||
/// <summary>Storico dei prezzi globali (un anno).</summary>
|
||||
/// <summary>Storico dei prezzi globali giornalieri (market.historyDays: 24 mesi dalla F6).</summary>
|
||||
public RollingWindow[] PriceHistory { get; private set; }
|
||||
|
||||
/// <summary>Giorni consecutivi con domanda insoddisfatta, per bene (nascita di nuove industrie).</summary>
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>Prezzo globale di un giorno (centesimi per unità).</summary>
|
||||
public readonly record struct PricePoint(long Day, double Price);
|
||||
|
||||
/// <summary>Prezzo previsto a una distanza in mesi, con la banda bassa e alta.</summary>
|
||||
public readonly record struct ForecastPoint(int Months, double Price, double Low, double High);
|
||||
|
||||
public enum SellPlaceKind : byte { Industry = 0, Hub = 1 }
|
||||
|
||||
/// <summary>
|
||||
/// Destinazione dove vendere un bene: industria che lo consuma (prezzo locale) o hub
|
||||
/// (prezzo d'esportazione), con la linea della compagnia che la serve (None se non collegata).
|
||||
/// </summary>
|
||||
public readonly record struct SellPlace(SellPlaceKind Kind, int Target, double Price, LineId Line);
|
||||
|
||||
/// <summary>Quadro di un bene per il pannello «Mercato globale».</summary>
|
||||
public sealed class GoodOutlook
|
||||
{
|
||||
public required int Good { get; init; }
|
||||
/// <summary>Bene già disponibile nell'era corrente.</summary>
|
||||
public required bool Available { get; init; }
|
||||
public required double Price { get; init; }
|
||||
/// <summary>Variazione del prezzo su market.outlook.changeDays giorni (frazione).</summary>
|
||||
public required double Change { get; init; }
|
||||
/// <summary>Offerta e domanda della mappa in un mese (finestre di 30 giorni riportate al mese).</summary>
|
||||
public required double SupplyMonth { get; init; }
|
||||
public required double DemandMonth { get; init; }
|
||||
/// <summary>Quota del mercato mondiale scambiata dagli hub in un mese (componente W di MarketSystem).</summary>
|
||||
public required double WorldSupplyMonth { get; init; }
|
||||
public required double WorldDemandMonth { get; init; }
|
||||
/// <summary>Giacenze nei magazzini delle industrie aperte e nelle stazioni.</summary>
|
||||
public required double StockUnits { get; init; }
|
||||
/// <summary>Giacenze diviso domanda mensile della mappa (−1 se la domanda è nulla).</summary>
|
||||
public required double StockMonths { get; init; }
|
||||
/// <summary>Un campione per mese di calendario, dal più vecchio; l'ultimo è il giorno corrente.</summary>
|
||||
public required List<PricePoint> History { get; init; }
|
||||
public required List<ForecastPoint> Forecast { get; init; }
|
||||
public required List<SellPlace> SellPlaces { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Hub verso il mercato mondiale visto dalla compagnia.</summary>
|
||||
public readonly record struct HubOutlook(HubId Hub, HubKind Kind, int MonthlyCapacity, double Duty, int UsedThisMonth, LineId Line);
|
||||
|
||||
/// <summary>Shock mondiale in corso più forte (Good −1 se nessuno supera la soglia).</summary>
|
||||
public readonly record struct MarketEvent(int Good, double Shock, double Months)
|
||||
{
|
||||
public static readonly MarketEvent None = new(-1, 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>Avanzamento verso il primo livello che sblocca la compravendita in proprio.</summary>
|
||||
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>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; }
|
||||
public required int TownsConnected { get; init; }
|
||||
public required int TownsRequired { get; init; }
|
||||
public required int TownPopulation { get; init; }
|
||||
public required CreditRating Rating { get; init; }
|
||||
public required CreditRating RatingRequired { get; init; }
|
||||
public required bool RatingMet { get; init; }
|
||||
}
|
||||
|
||||
public sealed class MarketOutlookReport
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
/// <summary>Indice materie prime: media di Pg/Pb × 100 sui beni disponibili.</summary>
|
||||
public required double Index { get; init; }
|
||||
public required double IndexChange { get; init; }
|
||||
public required List<GoodOutlook> Goods { get; init; }
|
||||
public required List<HubOutlook> Hubs { get; init; }
|
||||
public required MarketEvent Event { get; init; }
|
||||
/// <summary>Eventi del mondo in corso sulla domanda di un bene in una zona (ADR 0017), in ordine d'inizio.</summary>
|
||||
public required List<ActiveWorldEvent> GoodEvents { get; init; }
|
||||
public required TradingProgress Trading { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Analisi del mercato per il pannello «Mercato globale» (ADR 0015): pura funzione del mondo,
|
||||
/// nessuno stato nuovo e nessun numero casuale. Storico mensile dalla finestra dei prezzi,
|
||||
/// variazioni, offerta e domanda, scorte, indice materie prime, previsione dalla componente
|
||||
/// mondiale, destinazioni di vendita, hub, evento in corso e avanzamento verso il commercio.
|
||||
/// </summary>
|
||||
public static class MarketOutlook
|
||||
{
|
||||
public static MarketOutlookReport Build(World w, CompanyId company)
|
||||
{
|
||||
var data = w.Data;
|
||||
var stationLines = StationLines(w, company);
|
||||
var goods = new List<GoodOutlook>(data.GoodCount);
|
||||
for (int g = 0; g < data.GoodCount; g++) goods.Add(Good(w, g, company, stationLines));
|
||||
var (index, indexChange) = CommodityIndex(w);
|
||||
return new MarketOutlookReport
|
||||
{
|
||||
Day = w.Clock.Day,
|
||||
Index = index,
|
||||
IndexChange = indexChange,
|
||||
Goods = goods,
|
||||
Hubs = Hubs(w, company, stationLines),
|
||||
Event = StrongestEvent(w),
|
||||
GoodEvents = GoodEvents(w),
|
||||
Trading = Trading(w, company),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Bene disponibile nell'anno corrente (era).</summary>
|
||||
public static bool IsAvailable(World w, int good) => w.Data.Goods[good].Era <= w.Clock.Year;
|
||||
|
||||
public static GoodOutlook Good(World w, int g, CompanyId company, LineId[] stationLines)
|
||||
{
|
||||
var market = w.Market;
|
||||
bool available = IsAvailable(w, g);
|
||||
var (supply, demand, worldSupply, worldDemand) = MonthlyFlows(w, g);
|
||||
double stock = StockUnits(w, g);
|
||||
return new GoodOutlook
|
||||
{
|
||||
Good = g,
|
||||
Available = available,
|
||||
Price = market.GlobalPrice[g],
|
||||
Change = Change(w, g, w.Data.Balance.Market.Outlook.ChangeDays),
|
||||
SupplyMonth = supply,
|
||||
DemandMonth = demand,
|
||||
WorldSupplyMonth = worldSupply,
|
||||
WorldDemandMonth = worldDemand,
|
||||
StockUnits = stock,
|
||||
StockMonths = demand > 0 ? stock / demand : -1,
|
||||
History = MonthlyHistory(w, g, w.Data.Balance.Market.Outlook.HistoryMonths),
|
||||
Forecast = Forecast(w, g),
|
||||
SellPlaces = available ? SellPlaces(w, g, company, stationLines) : [],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Ultimo giorno registrato nello storico: il sistema del mercato gira al primo tick del giorno.</summary>
|
||||
public static long LastRecordedDay(World w) => w.Clock.TickOfDay == 0 ? w.Clock.Day - 1 : w.Clock.Day;
|
||||
|
||||
/// <summary>
|
||||
/// Storico mensile: il prezzo dell'ultimo giorno di ciascuno degli ultimi mesi di calendario
|
||||
/// conclusi più quello del giorno corrente, fino a <paramref name="months"/> campioni, dal più vecchio.
|
||||
/// </summary>
|
||||
public static List<PricePoint> MonthlyHistory(World w, int good, int months)
|
||||
{
|
||||
var history = w.Market.PriceHistory[good];
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
long last = LastRecordedDay(w);
|
||||
var points = new List<PricePoint>(months);
|
||||
for (int j = 0; j < months; j++)
|
||||
{
|
||||
long day = j == 0 ? last : last - last % dpm - 1 - (long)(j - 1) * dpm;
|
||||
long k = last - day;
|
||||
if (day < 0 || k >= history.Count) break;
|
||||
points.Add(new PricePoint(day, history.Ago((int)k)));
|
||||
}
|
||||
points.Reverse();
|
||||
return points;
|
||||
}
|
||||
|
||||
/// <summary>Giorni effettivi della variazione: quelli chiesti o quelli presenti nello storico.</summary>
|
||||
private static int ChangeSpan(RollingWindow history, int days) => Math.Min(days, history.Count - 1);
|
||||
|
||||
/// <summary>Variazione del prezzo globale negli ultimi <paramref name="days"/> giorni (frazione).</summary>
|
||||
public static double Change(World w, int good, int days)
|
||||
{
|
||||
var history = w.Market.PriceHistory[good];
|
||||
int k = ChangeSpan(history, days);
|
||||
if (k <= 0) return 0;
|
||||
double before = history.Ago(k);
|
||||
return before > 0 ? history.Ago(0) / before - 1 : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Offerta e domanda della mappa in un mese (finestre di 30 giorni riportate ai giorni del mese)
|
||||
/// e quota mondiale come in MarketSystem: V = max(baseline·giorni, quota·(D + S)/2) scambiato al
|
||||
/// prezzo mondiale Pw, domanda V·(Pw/Pg)^ε e offerta V·(Pg/Pw)^ε.
|
||||
/// </summary>
|
||||
public static (double Supply, double Demand, double WorldSupply, double WorldDemand) MonthlyFlows(World w, int g)
|
||||
{
|
||||
var market = w.Market;
|
||||
var m = w.Data.Balance.Market;
|
||||
int count = market.Demand[g].Count;
|
||||
if (count == 0) return (0, 0, 0, 0);
|
||||
double perMonth = (double)w.Calendar.DaysPerMonth / count;
|
||||
double d = market.Demand[g].Sum, s = market.Supply[g].Sum;
|
||||
if (!IsAvailable(w, g)) return (s * perMonth, d * perMonth, 0, 0);
|
||||
double pb = w.Data.Goods[g].BasePrice;
|
||||
double pg = Math.Max(1e-9, market.GlobalPrice[g]);
|
||||
double pw = pb * Math.Max(m.World.PriceFloor,
|
||||
1 + Market.WorldFactor(m, w.Difficulty.MarketVolatilityMultiplier, w.Clock.YearsElapsed, market.Shock[g]));
|
||||
double v = Math.Max(m.World.BaselinePerDay * count, m.World.VolumeShare * (d + s) / 2);
|
||||
double worldDemand = v * DMath.Pow(pw / pg, m.World.Elasticity);
|
||||
double worldSupply = v * DMath.Pow(pg / pw, m.World.Elasticity);
|
||||
return (s * perMonth, d * perMonth, worldSupply * perMonth, worldDemand * perMonth);
|
||||
}
|
||||
|
||||
/// <summary>Giacenze di un bene nei magazzini (input e output) delle industrie aperte e nelle stazioni (merci in attesa e magazzini delle compagnie).</summary>
|
||||
public static double StockUnits(World w, int good)
|
||||
{
|
||||
long sum = 0;
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed) continue;
|
||||
int i = ind.InputIndexOf(good);
|
||||
if (i >= 0) sum += ind.InputStock[i];
|
||||
int o = ind.OutputIndexOf(good);
|
||||
if (o >= 0) sum += ind.OutputStock[o];
|
||||
}
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (!w.Network.IsAlive(s)) continue;
|
||||
foreach (var p in s.Waiting)
|
||||
{
|
||||
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
|
||||
}
|
||||
sum += s.StockOf(good);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// <summary>Indice materie prime (media di Pg/Pb × 100 sui beni disponibili) e sua variazione.</summary>
|
||||
public static (double Index, double Change) CommodityIndex(World w)
|
||||
{
|
||||
var data = w.Data;
|
||||
int days = data.Balance.Market.Outlook.ChangeDays;
|
||||
double now = 0, before = 0;
|
||||
int n = 0;
|
||||
for (int g = 0; g < data.GoodCount; g++)
|
||||
{
|
||||
if (!IsAvailable(w, g)) continue;
|
||||
double pb = data.Goods[g].BasePrice;
|
||||
var history = w.Market.PriceHistory[g];
|
||||
int k = ChangeSpan(history, days);
|
||||
now += w.Market.GlobalPrice[g] / pb;
|
||||
before += (k > 0 ? history.Ago(k) : w.Market.GlobalPrice[g]) / pb;
|
||||
n++;
|
||||
}
|
||||
if (n == 0) return (100, 0);
|
||||
double index = now / n * 100, previous = before / n * 100;
|
||||
return (index, previous > 0 ? index / previous - 1 : 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Previsione a market.outlook.forecastMonths mesi dalla sola componente mondiale (ciclo e shock
|
||||
/// che decade come in MarketSystem): Pf = Pg·(1 + W(t + Δ))/(1 + W(t)), entro i limiti del prezzo,
|
||||
/// con una banda che si allarga di forecastBandPerMonth per mese.
|
||||
/// </summary>
|
||||
public static List<ForecastPoint> Forecast(World w, int g)
|
||||
{
|
||||
var m = w.Data.Balance.Market;
|
||||
var o = m.Outlook;
|
||||
var points = new List<ForecastPoint>(o.ForecastMonths);
|
||||
double pb = w.Data.Goods[g].BasePrice;
|
||||
double pg = w.Market.GlobalPrice[g];
|
||||
double min = m.MinPriceFactor * pb, max = m.MaxPriceFactor * pb;
|
||||
bool available = IsAvailable(w, g);
|
||||
double volatility = w.Difficulty.MarketVolatilityMultiplier;
|
||||
double years = w.Clock.YearsElapsed;
|
||||
double shock = w.Market.Shock[g];
|
||||
double w0 = Math.Max(m.World.PriceFloor, 1 + Market.WorldFactor(m, volatility, years, shock));
|
||||
for (int i = 1; i <= o.ForecastMonths; i++)
|
||||
{
|
||||
double days = (double)i * w.Calendar.DaysPerMonth;
|
||||
double price = pg;
|
||||
if (available)
|
||||
{
|
||||
double s = shock * DMath.Exp(-days / m.World.ShockDecayDays);
|
||||
double wi = Math.Max(m.World.PriceFloor, 1 + Market.WorldFactor(m, volatility, years + days / w.Calendar.DaysPerYear, s));
|
||||
price = DMath.Clamp(pg * wi / w0, min, max);
|
||||
}
|
||||
double band = o.ForecastBandPerMonth * i;
|
||||
points.Add(new ForecastPoint(i, price, DMath.Clamp(price * (1 - band), min, max), DMath.Clamp(price * (1 + band), min, max)));
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per ogni stazione: la linea della compagnia (id più basso) con almeno un treno che vi fa
|
||||
/// fermata, None altrimenti (stesso criterio di Tiers.ServedStations).
|
||||
/// </summary>
|
||||
public static LineId[] StationLines(World w, CompanyId company)
|
||||
{
|
||||
var result = new LineId[w.Network.Stations.Count];
|
||||
Array.Fill(result, LineId.None);
|
||||
if (!company.IsValid) return result;
|
||||
var lineHasTrain = new bool[w.Lines.Count];
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (t.Owner == company && t.Line.IsValid && !t.Removed) lineHasTrain[t.Line.Value] = true;
|
||||
}
|
||||
foreach (var l in w.Lines)
|
||||
{
|
||||
if (l.Owner != company || l.Removed || !lineHasTrain[l.Id.Value]) continue;
|
||||
foreach (var stop in l.Stops)
|
||||
{
|
||||
int s = stop.Station.Value;
|
||||
if (s >= 0 && s < result.Length && !result[s].IsValid) result[s] = l.Id;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Linea che collega un'industria o un hub: una stazione servita della compagnia con il bersaglio nel bacino.</summary>
|
||||
private static LineId LineFor(World w, CompanyId company, LineId[] stationLines, Func<Station, bool> inCatchment)
|
||||
{
|
||||
var best = LineId.None;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (s.Owner != company || !w.Network.IsAlive(s)) continue;
|
||||
var line = stationLines[s.Id.Value];
|
||||
if (!line.IsValid || !inCatchment(s)) continue;
|
||||
if (!best.IsValid || line.Value < best.Value) best = line;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public static LineId IndustryLine(World w, CompanyId company, LineId[] stationLines, IndustryId industry) =>
|
||||
LineFor(w, company, stationLines, s => s.Industries.Contains(industry));
|
||||
|
||||
public static LineId HubLine(World w, CompanyId company, LineId[] stationLines, HubId hub) =>
|
||||
LineFor(w, company, stationLines, s => s.Hubs.Contains(hub));
|
||||
|
||||
/// <summary>
|
||||
/// Dove conviene vendere: industrie aperte (livello > 0) che consumano il bene, al prezzo locale
|
||||
/// dell'ADR 0004 (Dl = consumo giornaliero a piena capacità × giorni di magazzino, Sl = giacenza
|
||||
/// dell'input), e hub al prezzo d'esportazione; i primi market.outlook.sellPlaces per prezzo.
|
||||
/// </summary>
|
||||
public static List<SellPlace> SellPlaces(World w, int g, CompanyId company, LineId[] stationLines)
|
||||
{
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
double pg = w.Market.GlobalPrice[g];
|
||||
var candidates = new List<(SellPlaceKind Kind, int Target, double Price)>();
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || ind.Level <= 0) continue;
|
||||
int i = ind.InputIndexOf(g);
|
||||
if (i < 0) continue;
|
||||
double desired = IndustryMath.InputCapacity(ind, i, dpm);
|
||||
candidates.Add((SellPlaceKind.Industry, ind.Id.Value, Market.LocalPrice(pg, desired, ind.InputStock[i], lp)));
|
||||
}
|
||||
// un hub che ha esaurito la capacità del mese non compra più fino al mese successivo
|
||||
foreach (var h in w.Hubs)
|
||||
{
|
||||
if (h.RemainingCapacity > 0) candidates.Add((SellPlaceKind.Hub, h.Id.Value, h.BuyPrice(pg)));
|
||||
}
|
||||
// ordine stabile: prezzo decrescente, poi industrie prima degli hub, poi id
|
||||
var top = candidates.OrderByDescending(c => c.Price).ThenBy(c => c.Kind).ThenBy(c => c.Target)
|
||||
.Take(w.Data.Balance.Market.Outlook.SellPlaces).ToList();
|
||||
var result = new List<SellPlace>(top.Count);
|
||||
foreach (var c in top)
|
||||
{
|
||||
var line = c.Kind == SellPlaceKind.Industry
|
||||
? IndustryLine(w, company, stationLines, new IndustryId(c.Target))
|
||||
: HubLine(w, company, stationLines, new HubId(c.Target));
|
||||
result.Add(new SellPlace(c.Kind, c.Target, c.Price, line));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<HubOutlook> Hubs(World w, CompanyId company, LineId[] stationLines) =>
|
||||
w.Hubs.Select(h => new HubOutlook(h.Id, h.Kind, h.MonthlyCapacity, h.Duty, h.UsedThisMonth, HubLine(w, company, stationLines, h.Id))).ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Evento di mercato in corso: lo shock mondiale più forte in valore assoluto tra i beni
|
||||
/// disponibili, se supera market.outlook.eventThreshold, con i mesi stimati prima che il decadimento
|
||||
/// esponenziale (shockDecayDays) lo porti sotto la soglia.
|
||||
/// </summary>
|
||||
public static MarketEvent StrongestEvent(World w)
|
||||
{
|
||||
var m = w.Data.Balance.Market;
|
||||
int best = -1;
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
{
|
||||
if (!IsAvailable(w, g)) continue;
|
||||
if (best < 0 || Math.Abs(w.Market.Shock[g]) > Math.Abs(w.Market.Shock[best])) best = g;
|
||||
}
|
||||
if (best < 0) return MarketEvent.None;
|
||||
double shock = w.Market.Shock[best];
|
||||
double threshold = m.Outlook.EventThreshold;
|
||||
if (Math.Abs(shock) <= threshold) return MarketEvent.None;
|
||||
double days = threshold > 0 ? m.World.ShockDecayDays * DMath.Log(Math.Abs(shock) / threshold) : 0;
|
||||
return new MarketEvent(best, shock, days / w.Calendar.DaysPerMonth);
|
||||
}
|
||||
|
||||
/// <summary>Eventi del mondo in corso che cambiano la domanda di un bene (boom o crollo in una zona).</summary>
|
||||
public static List<ActiveWorldEvent> GoodEvents(World w) =>
|
||||
w.WorldEvents.Active.Where(e => e.Good >= 0 && e.Has(Data.EventEffectKind.GoodDemand)).ToList();
|
||||
|
||||
/// <summary>Avanzamento della compagnia verso il primo livello di tiers.json che sblocca il commercio.</summary>
|
||||
public static TradingProgress Trading(World w, CompanyId company)
|
||||
{
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
var target = tiers.FirstOrDefault(t => t.Unlocks.Trading);
|
||||
var c = company.IsValid && company.Value < w.Companies.Count ? w.Companies[company.Value] : null;
|
||||
if (target is null || c is null)
|
||||
{
|
||||
// senza compagnia (o senza un livello che sblocca) si mostrano comunque i requisiti, mai soddisfatti
|
||||
var r = target?.Requirements;
|
||||
return new TradingProgress
|
||||
{
|
||||
Unlocked = false, Level = target?.Level ?? 0, Fraction = 0, NetWorth = c?.NetWorth ?? Money.Zero,
|
||||
NetWorthRequired = new Money(r?.NetWorth ?? 0),
|
||||
TownsConnected = 0, TownsRequired = r?.ConnectedTownsOver.Count ?? 0, TownPopulation = r?.ConnectedTownsOver.Population ?? 0,
|
||||
Rating = c?.Rating ?? CreditRating.D, RatingRequired = r?.CreditRating ?? CreditRating.D, RatingMet = false,
|
||||
};
|
||||
}
|
||||
// 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 : 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,29 @@ public sealed class RollingWindow
|
||||
return _values[i];
|
||||
}
|
||||
|
||||
/// <summary>Media degli ultimi n valori (o di quelli presenti, se sono meno).</summary>
|
||||
public double AverageOfLast(int n)
|
||||
{
|
||||
int k = Math.Min(n, _count);
|
||||
if (k <= 0) return 0;
|
||||
double s = 0;
|
||||
for (int i = 0; i < k; i++) s += Ago(i);
|
||||
return s / k;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copia della finestra con una lunghezza maggiore: gli stessi valori, nello stesso ordine
|
||||
/// (dal più vecchio), aggiunti uno per uno alla finestra nuova. Serve a migrare i salvataggi
|
||||
/// quando i dati allungano la finestra (per esempio lo storico dei prezzi da 12 a 24 mesi).
|
||||
/// </summary>
|
||||
public RollingWindow Extended(int length)
|
||||
{
|
||||
if (length < _values.Length) throw new ArgumentOutOfRangeException(nameof(length), "la finestra non si accorcia");
|
||||
var window = new RollingWindow(length);
|
||||
for (int k = _count - 1; k >= 0; k--) window.Add(Ago(k));
|
||||
return window;
|
||||
}
|
||||
|
||||
internal void Save(Persistence.SaveWriter w)
|
||||
{
|
||||
w.Write(_values.Length);
|
||||
|
||||
@@ -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,68 @@
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo in corso (corpo del salvataggio dalla versione 5, ADR 0017): tipo e bene per id
|
||||
/// testuale, bersaglio, giorni d'inizio e fine, intensità. Le versioni precedenti si caricano senza
|
||||
/// eventi attivi. Entra nell'hash giornaliero con lo stato dinamico.
|
||||
/// </summary>
|
||||
public static class EventSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
var state = w.WorldEvents;
|
||||
s.Write(state.NextId);
|
||||
s.Write(state.Active.Count);
|
||||
foreach (var e in state.Active)
|
||||
{
|
||||
s.Write(e.Id);
|
||||
s.Write(e.Def.Id);
|
||||
s.Write((byte)e.TargetKind);
|
||||
s.Write(e.Target);
|
||||
s.Write(e.Good >= 0 ? w.Data.Goods[e.Good].Id : "");
|
||||
s.Write(e.StartDay);
|
||||
s.Write(e.EndDay);
|
||||
s.Write(e.Intensity);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
var state = w.WorldEvents;
|
||||
state.Clear();
|
||||
state.NextId = r.ReadInt32();
|
||||
int n = r.ReadInt32();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int id = r.ReadInt32();
|
||||
string type = r.ReadRequiredString();
|
||||
var kind = (EntityKind)r.ReadByte();
|
||||
int target = r.ReadInt32();
|
||||
string goodId = r.ReadRequiredString();
|
||||
long start = r.ReadInt64();
|
||||
long end = r.ReadInt64();
|
||||
double intensity = r.ReadDouble();
|
||||
// un tipo o un bene tolti dai dati fanno finire l'evento al caricamento
|
||||
var def = w.Data.EventType(type);
|
||||
if (def is null) continue;
|
||||
int good = -1;
|
||||
if (goodId.Length > 0 && !w.Data.TryGoodIndex(goodId, out good)) continue;
|
||||
var (center, radius2) = EventSystem.Zone(w, def, kind, target);
|
||||
state.Add(new ActiveWorldEvent
|
||||
{
|
||||
Id = id,
|
||||
Def = def,
|
||||
TargetKind = kind,
|
||||
Target = target,
|
||||
Good = good,
|
||||
StartDay = start,
|
||||
EndDay = end,
|
||||
Intensity = intensity,
|
||||
Center = center,
|
||||
RadiusSquaredM = radius2,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -342,6 +342,7 @@ public static class RailSerializer
|
||||
};
|
||||
var incoming = r.ReadInt32Array();
|
||||
st.Incoming = new int[goods];
|
||||
st.Stock = new int[goods];
|
||||
for (int g = 0; g < incoming.Length; g++)
|
||||
{
|
||||
int m = MapGood(g);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Compravendita in proprio (corpo del salvataggio dalla versione 4, ADR 0016): magazzini della
|
||||
/// compagnia nelle stazioni (beni salvati per id testuale) e pacchetti di merce propria in stazione
|
||||
/// e a bordo, indicati per id. I salvataggi precedenti si caricano con i magazzini vuoti.
|
||||
/// </summary>
|
||||
public static class TradingSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
var goods = w.Data.Goods;
|
||||
s.Write(w.Network.Stations.Count);
|
||||
foreach (var st in w.Network.Stations)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (int u in st.Stock) if (u != 0) n++;
|
||||
s.Write(n);
|
||||
for (int g = 0; g < st.Stock.Length; g++)
|
||||
{
|
||||
if (st.Stock[g] == 0) continue;
|
||||
s.Write(goods[g].Id);
|
||||
s.Write(st.Stock[g]);
|
||||
}
|
||||
WriteOwned(s, st.Waiting);
|
||||
}
|
||||
s.Write(w.Trains.Count);
|
||||
foreach (var t in w.Trains) WriteOwned(s, t.Cargo);
|
||||
}
|
||||
|
||||
private static void WriteOwned(SaveWriter s, List<Packet> packets)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (var p in packets) if (p.Owned) n++;
|
||||
s.Write(n);
|
||||
foreach (var p in packets)
|
||||
{
|
||||
if (p.Owned) s.Write(p.Id);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int stations = r.ReadInt32();
|
||||
for (int i = 0; i < stations; i++)
|
||||
{
|
||||
var st = i < w.Network.Stations.Count ? w.Network.Stations[i] : null;
|
||||
int n = r.ReadInt32();
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
string id = r.ReadRequiredString();
|
||||
int units = r.ReadInt32();
|
||||
// un bene tolto dai dati sparisce dal magazzino, come negli altri depositi rimappati
|
||||
if (st is not null && w.Data.TryGoodIndex(id, out int g)) Simulation.Systems.TradingMath.AddToWarehouse(st, g, units, w.Data.GoodCount);
|
||||
}
|
||||
ReadOwned(r, st?.Waiting);
|
||||
}
|
||||
int trains = r.ReadInt32();
|
||||
for (int i = 0; i < trains; i++) ReadOwned(r, i < w.Trains.Count ? w.Trains[i].Cargo : null);
|
||||
}
|
||||
|
||||
private static void ReadOwned(SaveReader r, List<Packet>? packets)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n == 0) return;
|
||||
var ids = new HashSet<int>();
|
||||
for (int k = 0; k < n; k++) ids.Add(r.ReadInt32());
|
||||
if (packets is null) return;
|
||||
for (int i = 0; i < packets.Count; i++)
|
||||
{
|
||||
var p = packets[i];
|
||||
if (!ids.Contains(p.Id)) continue;
|
||||
p.Owned = true;
|
||||
packets[i] = p;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Salvataggi delle versioni 1–3: nessuna merce della compagnia, magazzini vuoti.</summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
foreach (var st in w.Network.Stations)
|
||||
{
|
||||
if (st.Stock.Length < w.Data.GoodCount) st.Stock = new int[w.Data.GoodCount];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,16 +14,23 @@ namespace RailEnterprise.Core.Persistence;
|
||||
public static class WorldSerializer
|
||||
{
|
||||
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
|
||||
public const int BodyVersion = 3;
|
||||
public const int BodyVersion = 6;
|
||||
|
||||
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
|
||||
public static void Write(World w, SaveWriter s)
|
||||
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
|
||||
|
||||
/// <summary>
|
||||
/// Scrive il corpo nel formato di una versione precedente (le sezioni nate dopo si omettono):
|
||||
/// serve a provare le migrazioni dei salvataggi.
|
||||
/// </summary>
|
||||
public static void Write(World w, SaveWriter s, int bodyVersion)
|
||||
{
|
||||
s.Write(BodyVersion);
|
||||
if (bodyVersion < 1 || bodyVersion > BodyVersion) throw new ArgumentOutOfRangeException(nameof(bodyVersion));
|
||||
s.Write(bodyVersion);
|
||||
WriteDictionary(w.Data, s);
|
||||
WriteSettings(w.Settings, s);
|
||||
WriteSettings(w.Settings, s, bodyVersion);
|
||||
WriteTerrain(w.Terrain, w.SeaSide, s);
|
||||
WriteDynamic(w, s);
|
||||
WriteDynamic(w, s, bodyVersion);
|
||||
s.Write(w.LastStateHash);
|
||||
s.Write(w.LastHashDay);
|
||||
WriteEvents(w.Events, s);
|
||||
@@ -33,7 +40,9 @@ public static class WorldSerializer
|
||||
/// Stato dinamico (tutto tranne terreno, impostazioni ed eventi): è ciò che entra nell'hash
|
||||
/// giornaliero. Il terreno vi entra attraverso il suo hash.
|
||||
/// </summary>
|
||||
public static void WriteDynamic(World w, SaveWriter s)
|
||||
public static void WriteDynamic(World w, SaveWriter s) => WriteDynamic(w, s, BodyVersion);
|
||||
|
||||
private static void WriteDynamic(World w, SaveWriter s, int version)
|
||||
{
|
||||
if (w.TerrainHash == 0) w.TerrainHash = w.Terrain.ComputeHash();
|
||||
s.Write(w.TerrainHash);
|
||||
@@ -234,8 +243,11 @@ public static class WorldSerializer
|
||||
}
|
||||
|
||||
RailSerializer.Write(w, s);
|
||||
MaintenanceSerializer.Write(w, s);
|
||||
CorporateSerializer.Write(w, s);
|
||||
if (version >= 2) MaintenanceSerializer.Write(w, s);
|
||||
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);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -255,7 +267,7 @@ public static class WorldSerializer
|
||||
foreach (var g in data.Goods) s.Write(g.Id);
|
||||
}
|
||||
|
||||
private static void WriteSettings(WorldSettings st, SaveWriter s)
|
||||
private static void WriteSettings(WorldSettings st, SaveWriter s, int version)
|
||||
{
|
||||
s.Write(st.Seed);
|
||||
s.Write(st.SizeKm);
|
||||
@@ -283,6 +295,8 @@ public static class WorldSerializer
|
||||
s.Write(d.PlayerShareAtStart);
|
||||
s.Write((byte)d.Ironman);
|
||||
s.Write((byte)d.Depletion);
|
||||
// versione 5 (F6): frequenza degli eventi del mondo
|
||||
if (version >= 5) s.Write(d.EventFrequencyMultiplier);
|
||||
}
|
||||
|
||||
private static void WriteTerrain(Terrain t, MapSide seaSide, SaveWriter s)
|
||||
@@ -330,7 +344,7 @@ public static class WorldSerializer
|
||||
goodMap[g] = data.TryGoodIndex(id, out int idx) ? idx : -1;
|
||||
}
|
||||
|
||||
var settings = ReadSettings(r);
|
||||
var settings = ReadSettings(data, r, version);
|
||||
var (terrain, seaSide) = ReadTerrain(r);
|
||||
var w = new World(data, settings, terrain, seaSide);
|
||||
ReadDynamic(w, r, goodMap, version);
|
||||
@@ -340,7 +354,7 @@ public static class WorldSerializer
|
||||
return w;
|
||||
}
|
||||
|
||||
private static WorldSettings ReadSettings(SaveReader r)
|
||||
private static WorldSettings ReadSettings(GameData data, SaveReader r, int version)
|
||||
{
|
||||
ulong seed = r.ReadUInt64();
|
||||
int size = r.ReadInt32();
|
||||
@@ -369,6 +383,15 @@ public static class WorldSerializer
|
||||
PlayerShareAtStart = r.ReadDouble(),
|
||||
Ironman = (IronmanRule)r.ReadByte(),
|
||||
Depletion = (DepletionRate)r.ReadByte(),
|
||||
EventFrequencyMultiplier = 0,
|
||||
};
|
||||
// le versioni 1–4 non hanno la frequenza degli eventi: si prende quella del preset con lo
|
||||
// stesso id nei dati correnti (1 per una difficoltà personalizzata sconosciuta)
|
||||
d = d with
|
||||
{
|
||||
EventFrequencyMultiplier = version >= 5
|
||||
? r.ReadDouble()
|
||||
: data.Difficulty.Presets.FirstOrDefault(p => p.Id == d.Id)?.EventFrequencyMultiplier ?? 1.0,
|
||||
};
|
||||
return new WorldSettings { Seed = seed, SizeKm = size, StartYear = startYear, RegionId = region, Endless = endless, Difficulty = d };
|
||||
}
|
||||
@@ -571,6 +594,9 @@ public static class WorldSerializer
|
||||
var sw = RollingWindow.Load(r);
|
||||
var hw = RollingWindow.Load(r);
|
||||
if (g < 0) continue;
|
||||
// salvataggi con uno storico più corto dei dati (360 giorni fino alla F5): si allunga
|
||||
// conservando i prezzi, senza cambiare il formato (ADR 0015)
|
||||
if (hw.Length < m.PriceHistory[g].Length) hw = hw.Extended(m.PriceHistory[g].Length);
|
||||
m.GlobalPrice[g] = price;
|
||||
m.Shock[g] = shock;
|
||||
m.DemandToday[g] = dt;
|
||||
@@ -616,7 +642,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++)
|
||||
{
|
||||
@@ -677,6 +704,14 @@ public static class WorldSerializer
|
||||
// versione 3 (F5): industrie, borsa, offerte, aste, fine partita, agenti IA
|
||||
if (version >= 3) CorporateSerializer.Read(w, r);
|
||||
else CorporateSerializer.Migrate(w);
|
||||
// versione 4 (F6): magazzini della compagnia e merce propria in viaggio
|
||||
if (version >= 4) TradingSerializer.Read(w, r);
|
||||
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);
|
||||
}
|
||||
|
||||
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
|
||||
|
||||
@@ -23,7 +23,11 @@ public sealed class LineGraph
|
||||
private readonly record struct Segment(int From, int To, LineId Line, double Minutes, ulong Carries);
|
||||
|
||||
private readonly Dictionary<int, List<Segment>> _out = new();
|
||||
private readonly Dictionary<(int, ulong), Dictionary<int, Connection>> _reach = new();
|
||||
private readonly Dictionary<(int, ulong, bool), Dictionary<int, Connection>> _reach = new();
|
||||
// per (linea, stazione): almeno una fermata carica (bit 1) o scarica (bit 2)
|
||||
private readonly Dictionary<(int Line, int Station), byte> _stopFlags = new();
|
||||
private const byte LoadFlag = 1;
|
||||
private const byte UnloadFlag = 2;
|
||||
private readonly double _transferMinutes;
|
||||
|
||||
/// <summary>Bit del carico «lavoratori» (i bit bassi sono i beni, uno per indice).</summary>
|
||||
@@ -82,6 +86,14 @@ public sealed class LineGraph
|
||||
}
|
||||
}
|
||||
Carries[line.Id.Value] = carries;
|
||||
foreach (var stop in line.Stops)
|
||||
{
|
||||
var key = (line.Id.Value, stop.Station.Value);
|
||||
_stopFlags.TryGetValue(key, out byte flags);
|
||||
if (stop.Load) flags |= LoadFlag;
|
||||
if (stop.Unload) flags |= UnloadFlag;
|
||||
_stopFlags[key] = flags;
|
||||
}
|
||||
// sosta stimata a ogni fermata: scarico e carico completi del treno più capiente
|
||||
double dwell = sp.MinDwellMinutes;
|
||||
foreach (var t in trains)
|
||||
@@ -139,10 +151,13 @@ public sealed class LineGraph
|
||||
/// <summary>
|
||||
/// Collegamenti migliori da una stazione verso tutte le stazioni raggiungibili con linee i cui
|
||||
/// treni portano il carico indicato (maschera: beni, <see cref="WorkersCargo"/>, <see cref="StaffCargo"/>).
|
||||
/// Con <paramref name="stopFlags"/> si sale su una linea solo dove una sua fermata carica e, ai
|
||||
/// cambi, si scende solo dove una fermata della linea lasciata scarica (merce della compagnia,
|
||||
/// ADR 0016); senza, il grafo ignora i flag delle fermate come per i pacchetti dei clienti.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<int, Connection> From(StationId origin, ulong cargo)
|
||||
public IReadOnlyDictionary<int, Connection> From(StationId origin, ulong cargo, bool stopFlags = false)
|
||||
{
|
||||
if (_reach.TryGetValue((origin.Value, cargo), out var cached)) return cached;
|
||||
if (_reach.TryGetValue((origin.Value, cargo, stopFlags), out var cached)) return cached;
|
||||
var result = new Dictionary<int, Connection>();
|
||||
// stato = (stazione, linea su cui si viaggia); linea −1 = a terra all'origine
|
||||
var best = new Dictionary<(int, int), double>();
|
||||
@@ -160,6 +175,12 @@ public sealed class LineGraph
|
||||
foreach (var seg in segs)
|
||||
{
|
||||
if ((seg.Carries & cargo) == 0) continue;
|
||||
if (stopFlags && seg.Line.Value != state.Line)
|
||||
{
|
||||
// salita sulla linea del tratto e, se si cambia, discesa da quella su cui si viaggia
|
||||
if (!HasFlag(seg.Line.Value, state.Station, LoadFlag)) continue;
|
||||
if (state.Line >= 0 && !HasFlag(state.Line, state.Station, UnloadFlag)) continue;
|
||||
}
|
||||
double c = cost + seg.Minutes + (state.Line >= 0 && state.Line != seg.Line.Value ? _transferMinutes : 0);
|
||||
var next = (seg.To, seg.Line.Value);
|
||||
if (best.TryGetValue(next, out double old) && old <= c) continue;
|
||||
@@ -168,10 +189,12 @@ public sealed class LineGraph
|
||||
open.Enqueue(next, (c, seg.To, seg.Line.Value));
|
||||
}
|
||||
}
|
||||
_reach[(origin.Value, cargo)] = result;
|
||||
_reach[(origin.Value, cargo, stopFlags)] = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
private bool HasFlag(int line, int station, byte flag) => _stopFlags.TryGetValue((line, station), out byte f) && (f & flag) != 0;
|
||||
|
||||
private static Connection BuildConnection((int Station, int Line) state, double cost,
|
||||
Dictionary<(int, int), ((int, int) Prev, Segment Seg)> came, int origin)
|
||||
{
|
||||
|
||||
@@ -213,6 +213,26 @@ public sealed class Station
|
||||
/// <summary>Unità in arrivo per bene (merci già in viaggio verso questa stazione).</summary>
|
||||
public int[] Incoming { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Magazzino della compagnia proprietaria (compravendita in proprio, ADR 0016): unità per bene.
|
||||
/// Vuoto (lunghezza 0) finché non serve.
|
||||
/// </summary>
|
||||
public int[] Stock { get; set; } = [];
|
||||
|
||||
/// <summary>Unità nel magazzino della compagnia, tutti i beni.</summary>
|
||||
public int StockTotal
|
||||
{
|
||||
get
|
||||
{
|
||||
int n = 0;
|
||||
foreach (int u in Stock) n += u;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Unità del bene nel magazzino della compagnia.</summary>
|
||||
public int StockOf(int good) => good >= 0 && good < Stock.Length ? Stock[good] : 0;
|
||||
|
||||
/// <summary>Industrie, città e hub nel bacino (ricalcolati quando cambia il mondo).</summary>
|
||||
public List<IndustryId> Industries { get; } = [];
|
||||
public List<TownId> Towns { get; } = [];
|
||||
|
||||
@@ -255,4 +255,9 @@ public struct Packet
|
||||
public bool ReturnTrip;
|
||||
/// <summary>Consegnato alla stazione di destinazione ma non ancora ai consumatori del bacino.</summary>
|
||||
public bool AwaitingConsumer;
|
||||
/// <summary>
|
||||
/// Merce della compagnia (spedizione tra magazzini, ADR 0016): niente tariffa né consumatore,
|
||||
/// all'arrivo entra nel magazzino della stazione di destinazione.
|
||||
/// </summary>
|
||||
public bool Owned;
|
||||
}
|
||||
@@ -646,8 +646,16 @@ internal sealed class AiAgent
|
||||
if (who == _c.Id) continue;
|
||||
if (who.IsValid && !(_p.TargetsPlayer && who == _w.Player.Id)) continue;
|
||||
// produzione attesa: le primarie lavorano un po' meglio quando sono servite; le industrie di
|
||||
// trasformazione producono solo quanto i loro input consentono (efficienza attuale)
|
||||
double eff = prod.Def.Kind == IndustryKind.Primary ? _plan.AssumedEfficiency : Math.Min(prod.Efficiency, _plan.AssumedEfficiency);
|
||||
// trasformazione producono solo quanto i loro input consentono (efficienza attuale, senza
|
||||
// il moltiplicatore temporaneo di incidenti e boom: ADR 0017 §9)
|
||||
double eff = _plan.AssumedEfficiency;
|
||||
if (prod.Def.Kind != IndustryKind.Primary)
|
||||
{
|
||||
double capacity = _w.WorldEvents.IndustryCapacity(prod.Id);
|
||||
// impianto fermo per un incidente: non si giudica oggi, se ne riparla a evento finito
|
||||
if (capacity <= 0) break;
|
||||
eff = Math.Min(prod.Efficiency / capacity, eff);
|
||||
}
|
||||
double supply = (double)prod.Def.Capacity(prod.Level) * outputs[o].PerCycle / outputs[0].PerCycle * months * eff;
|
||||
if (supply <= 0) continue;
|
||||
foreach (var cons in _w.Industries)
|
||||
@@ -688,7 +696,8 @@ internal sealed class AiAgent
|
||||
}
|
||||
foreach (var town in _w.Towns)
|
||||
{
|
||||
double perDay = DemandSystem.TownDemand(_w, town, good, _ctx.Year);
|
||||
// domanda di base: una fiera o un boom di qualche settimana non vale un anno (ADR 0017 §9)
|
||||
double perDay = DemandSystem.TownDemand(_w, town, good, _ctx.Year, events: false);
|
||||
if (perDay <= 0) continue;
|
||||
double km = _w.TownEdgeDistanceKm(town, prod.Position);
|
||||
if (km < minKm || km > maxKm) continue;
|
||||
@@ -715,7 +724,11 @@ internal sealed class AiAgent
|
||||
if (ind.Closed || ind.Level <= 0 || servedBy[ind.Id.Value] != _c.Id) continue;
|
||||
for (int cls = 0; cls < 2; cls++)
|
||||
{
|
||||
double uncovered = cls == 0 ? ind.JobsWorkers - ind.WorkersPresent : ind.JobsStaff - ind.StaffPresent;
|
||||
// posti scoperti senza le assenze di epidemie e scioperi: un vuoto di pochi giorni non
|
||||
// giustifica una linea nuova (ADR 0017 §9)
|
||||
double uncovered = cls == 0
|
||||
? ind.JobsWorkers - EmploymentSystem.PresentWithoutEvents(_w, ind, PaxClass.Worker)
|
||||
: ind.JobsStaff - EmploymentSystem.PresentWithoutEvents(_w, ind, PaxClass.Staff);
|
||||
if (uncovered < _plan.MinCommuters) continue;
|
||||
var paxClass = cls == 0 ? PaxClass.Worker : PaxClass.Staff;
|
||||
foreach (var town in _w.Towns)
|
||||
|
||||
@@ -59,6 +59,17 @@ public static class CommandProcessor
|
||||
OrderPartsCommand c => MaintenanceCommandHandlers.OrderParts(w, company, c, Reply),
|
||||
AcceptAgreementCommand c => MaintenanceCommandHandlers.AcceptAgreement(w, company, c, Reply),
|
||||
RejectAgreementCommand c => MaintenanceCommandHandlers.RejectAgreement(w, company, c, Reply),
|
||||
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"),
|
||||
};
|
||||
}
|
||||
@@ -69,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,6 +96,18 @@ public static class CommandProcessor
|
||||
return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni");
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
var loan = company.Loans.FirstOrDefault(l => l.Id == c.Loan);
|
||||
|
||||
@@ -177,6 +177,9 @@ public static class Corporate
|
||||
}
|
||||
s.Waiting.Clear();
|
||||
Array.Clear(s.Incoming);
|
||||
// merce dei magazzini della compagnia: persa con la liquidazione (ADR 0016)
|
||||
for (int g = 0; g < s.Stock.Length; g++) w.Goods.Decayed[g] += s.Stock[g];
|
||||
Array.Clear(s.Stock);
|
||||
}
|
||||
foreach (var com in w.Commutes)
|
||||
{
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -18,6 +18,8 @@ public enum EventKind : byte
|
||||
Maintenance = 7,
|
||||
Employment = 8,
|
||||
Company = 9,
|
||||
/// <summary>Evento del mondo (events.json, ADR 0017): inizio e fine.</summary>
|
||||
World = 10,
|
||||
}
|
||||
|
||||
/// <summary>Riferimento facoltativo all'entità coinvolta.</summary>
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -24,6 +24,7 @@ public static class MaintenanceCommandHandlers
|
||||
train.Reserve = true;
|
||||
if (train.Line.IsValid)
|
||||
{
|
||||
StationWork.DropOwnedCargo(w, train, train.Line);
|
||||
train.Line = LineId.None;
|
||||
w.LineGraphs.Touch();
|
||||
}
|
||||
|
||||
@@ -125,6 +125,7 @@ public static class RailCommandHandlers
|
||||
BuiltDay = w.Clock.Day,
|
||||
BuildCostCents = cost.Cents,
|
||||
Incoming = new int[w.Data.GoodCount],
|
||||
Stock = new int[w.Data.GoodCount],
|
||||
};
|
||||
node.Station = station.Id;
|
||||
w.Network.Stations.Add(station);
|
||||
@@ -254,6 +255,10 @@ public static class RailCommandHandlers
|
||||
if (node.Station != st.Id) return reply(CommandError.NotFound, "Stazione già demolita");
|
||||
if (st.PlatformTrain.Any(t => t >= 0)) return reply(CommandError.Blocked, "Ci sono treni in stazione");
|
||||
if (w.Lines.Any(l => !l.Removed && l.Stops.Any(s => s.Station == st.Id))) return reply(CommandError.NotAllowed, "La stazione è fermata di una linea");
|
||||
if (st.StockTotal > 0) return reply(CommandError.NotAllowed, "Il magazzino della stazione contiene merce: vendila o spediscila prima di demolire");
|
||||
// merce della compagnia spedita da qui e non ancora caricata, o in viaggio verso qui
|
||||
if (st.Waiting.Any(p => p.Owned) || TradingMath.ReservedByStation(w)[st.Id.Value] > 0)
|
||||
return reply(CommandError.NotAllowed, "C'è merce della compagnia in partenza o in arrivo in questa stazione: aspetta che arrivi o che torni in magazzino");
|
||||
if (st.Waiting.Any(p => p.Kind == PacketKind.Freight))
|
||||
{
|
||||
foreach (var p in st.Waiting.Where(p => p.Kind == PacketKind.Freight)) w.Goods.Decayed[p.Good] += p.Units;
|
||||
@@ -544,6 +549,7 @@ public static class RailCommandHandlers
|
||||
train.Covering = TrainId.None;
|
||||
}
|
||||
if (c.Line.IsValid) train.Reserve = false;
|
||||
if (train.Line != c.Line) StationWork.DropOwnedCargo(w, train, train.Line);
|
||||
train.Line = c.Line;
|
||||
train.StopIndex = 0;
|
||||
if (!train.MaintenanceDepot.IsValid || train.GoingToDepot != train.MaintenanceDepot) train.GoingToDepot = DepotId.None;
|
||||
@@ -568,6 +574,7 @@ public static class RailCommandHandlers
|
||||
train.Covering = TrainId.None;
|
||||
}
|
||||
train.GoingToDepot = c.Depot;
|
||||
StationWork.DropOwnedCargo(w, train, train.Line);
|
||||
train.Line = LineId.None;
|
||||
if (train.State == TrainState.NoRoute) train.State = TrainState.Waiting;
|
||||
w.LineGraphs.Touch();
|
||||
|
||||
@@ -16,6 +16,11 @@ public sealed class ScenarioFile
|
||||
public string Difficulty { get; set; } = "imprenditore";
|
||||
/// <summary>Numero di concorrenti IA (sostituisce quello della difficoltà; null = come la difficoltà).</summary>
|
||||
public int? AiCompetitors { get; set; }
|
||||
/// <summary>
|
||||
/// Frequenza degli eventi del mondo (sostituisce quella della difficoltà; null = come la difficoltà,
|
||||
/// 0 = nessun evento casuale): gli scenari di accettazione la mettono a 0 (ADR 0017).
|
||||
/// </summary>
|
||||
public double? EventFrequencyMultiplier { get; set; }
|
||||
public required ScenarioTerrain Terrain { get; init; }
|
||||
public List<ScenarioTown> Towns { get; set; } = [];
|
||||
public List<ScenarioIndustry> Industries { get; set; } = [];
|
||||
|
||||
@@ -29,6 +29,15 @@ public sealed record LoadedScenario(World World, ScenarioFile File)
|
||||
/// <summary>Costruisce un mondo da uno scenario JSON (terreno a mano + entità in posizioni date).</summary>
|
||||
public static class ScenarioLoader
|
||||
{
|
||||
/// <summary>Ritocchi della difficoltà scritti nello scenario (concorrenti IA, frequenza degli eventi).</summary>
|
||||
private static List<(string Key, double Value)> Overrides(ScenarioFile file)
|
||||
{
|
||||
var list = new List<(string Key, double Value)>();
|
||||
if (file.AiCompetitors is { } ai) list.Add(("aiCompetitors", ai));
|
||||
if (file.EventFrequencyMultiplier is { } events) list.Add(("eventFrequencyMultiplier", events));
|
||||
return list;
|
||||
}
|
||||
|
||||
public static LoadedScenario LoadFile(GameData data, string path) => Load(data, File.ReadAllText(path));
|
||||
|
||||
public static LoadedScenario Load(GameData data, string json)
|
||||
@@ -104,8 +113,8 @@ public static class ScenarioLoader
|
||||
StartYear = file.StartYear,
|
||||
DifficultyId = file.Difficulty,
|
||||
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria",
|
||||
DifficultyOverride = file.AiCompetitors is { } ai
|
||||
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), [("aiCompetitors", ai)])
|
||||
DifficultyOverride = Overrides(file) is { Count: > 0 } overrides
|
||||
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), overrides)
|
||||
: null,
|
||||
};
|
||||
var world = WorldFactory.FromMap(data, map, settings);
|
||||
|
||||
@@ -42,6 +42,7 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
|
||||
new FinanceSystem(),
|
||||
new StockMarketSystem(),
|
||||
new AiSystem(),
|
||||
new EventSystem(),
|
||||
new HashSystem(),
|
||||
]);
|
||||
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
@@ -158,7 +154,8 @@ public sealed class ConstructionSystem : ISimSystem
|
||||
}
|
||||
var owner = w.Companies[e.Owner.Value];
|
||||
double before = e.Condition;
|
||||
double wear = e.WearToday / tw.K * w.Difficulty.WearMultiplier;
|
||||
// il maltempo sull'area accelera l'usura del traffico (ADR 0017)
|
||||
double wear = e.WearToday / tw.K * w.Difficulty.WearMultiplier * w.WorldEvents.EdgeWear(e);
|
||||
e.TonnesThisYear += e.WearToday;
|
||||
e.WearToday = 0;
|
||||
// la manutenzione ordinaria pagata annulla la deriva naturale; senza (bancarotta) il binario deperisce
|
||||
|
||||
@@ -43,7 +43,8 @@ public sealed class DemandSystem : ISimSystem
|
||||
market.DemandToday[data.SparePartsGood] += (double)IndustryMath.MonthlyPartsUse(ind, im) / dpm;
|
||||
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
|
||||
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
|
||||
// capacità modificata dagli eventi del mondo (incidente, boom: ADR 0017)
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * w.WorldEvents.IndustryCapacity(ind.Id);
|
||||
var inputs = ind.Def.Recipe.Inputs;
|
||||
for (int i = 0; i < inputs.Count; i++)
|
||||
{
|
||||
@@ -54,14 +55,18 @@ public sealed class DemandSystem : ISimSystem
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Domanda giornaliera di una città per un bene, in unità.</summary>
|
||||
public static double TownDemand(World w, Town town, int good, int year)
|
||||
/// <summary>
|
||||
/// Domanda giornaliera di una città per un bene, in unità, con i moltiplicatori degli eventi del
|
||||
/// mondo in corso (fiera, epidemia, domanda del bene nella zona: ADR 0017) se <paramref name="events"/>.
|
||||
/// </summary>
|
||||
public static double TownDemand(World w, Town town, int good, int year, bool events = true)
|
||||
{
|
||||
var def = w.Data.Goods[good];
|
||||
if (def.Town is not { } td || def.Era > year || (td.UntilYear is { } until && year >= until)) return 0;
|
||||
double ratio = w.Market.GlobalPrice[good] / def.BasePrice;
|
||||
var tb = w.Data.Balance.Town;
|
||||
double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), tb.DemandPriceFactorMin, tb.DemandPriceFactorMax);
|
||||
return town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
|
||||
double d = town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
|
||||
return events ? d * w.WorldEvents.TownDemand(town, good) : d;
|
||||
}
|
||||
}
|
||||
@@ -422,6 +422,28 @@ public sealed class EmploymentSystem : ISimSystem
|
||||
public static int OpenJobs(int jobs, double share, int contracted) =>
|
||||
Math.Max(0, (int)Math.Ceiling(jobs - OnSite(jobs, share) - contracted - 1e-9));
|
||||
|
||||
/// <summary>
|
||||
/// Lavoratori (o personale) che sarebbero presenti oggi senza gli eventi del mondo: lo stesso conto
|
||||
/// di <c>UpdatePresence</c> senza le presenze ridotte da epidemie e scioperi. Serve alle stime che
|
||||
/// portano a investimenti duraturi (IA, ADR 0017 §9), che non devono leggere un vuoto temporaneo
|
||||
/// come posti scoperti. Senza eventi sulle presenze è il valore del giorno.
|
||||
/// </summary>
|
||||
public static double PresentWithoutEvents(World w, Industry ind, PaxClass cls)
|
||||
{
|
||||
bool staff = cls == PaxClass.Staff;
|
||||
if (!w.WorldEvents.AnyWith(EventEffectKind.Attendance)) return staff ? ind.StaffPresent : ind.WorkersPresent;
|
||||
var ib = w.Data.Balance.Industry;
|
||||
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
|
||||
double present = OnSite(jobs, staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare);
|
||||
var me = WorkplaceRef.Of(ind.Id);
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
if (c.Workplace != me || (c.Category == PaxClass.Staff) != staff) continue;
|
||||
present += c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
|
||||
}
|
||||
return Math.Min(present, jobs);
|
||||
}
|
||||
|
||||
private static void UpdatePresence(WorldContext ctx)
|
||||
{
|
||||
var w = ctx.World;
|
||||
@@ -446,6 +468,8 @@ public sealed class EmploymentSystem : ISimSystem
|
||||
c.Coverage = Ema.Step(c.Coverage, ratio, eb.CoverageEmaDays);
|
||||
if (!c.Walking) c.LowCoverageDays = c.Coverage < eb.DissolveCoverage ? c.LowCoverageDays + 1 : 0;
|
||||
double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
|
||||
// eventi del mondo: epidemia o sciopero in città, sciopero in deposito (ADR 0017)
|
||||
present *= w.WorldEvents.Attendance(c.Town, c.Workplace);
|
||||
var p = Workplace(w, c.Workplace);
|
||||
if (c.Category == PaxClass.Staff) p.StaffPresent += present;
|
||||
else p.WorkersPresent += present;
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo (F6, ADR 0017): ogni giorno chiude quelli scaduti, poi per ogni tipo del
|
||||
/// catalogo (events.json, in ordine) estrae con il flusso dedicato «events» se ne nasce uno, con
|
||||
/// probabilità chancePerYear × difficoltà / giorni dell'anno, e sceglie il bersaglio tra i candidati
|
||||
/// in ordine di id. Nessun doppione dello stesso tipo sullo stesso bersaglio, né zone sovrapposte di
|
||||
/// due maltempi o di due eventi sulla domanda dello stesso bene; al massimo maxActive eventi insieme.
|
||||
/// Inizio e fine danno una notizia (<see cref="EventKind.World"/>). Gli effetti sono moltiplicatori
|
||||
/// letti dai sistemi tramite <see cref="WorldEventState"/>.
|
||||
/// Gira dopo le IA e prima dell'hash, quindi dopo i sistemi giornalieri del giorno: un evento estratto
|
||||
/// oggi inizia domani (StartDay) ed è in vigore nei giorni [StartDay, EndDay), cioè esattamente per la
|
||||
/// durata estratta, per i sistemi giornalieri come per i treni a ogni tick e per l'usura del loro
|
||||
/// traffico; esce dall'elenco il mattino di EndDay, con la notizia di fine.
|
||||
/// </summary>
|
||||
public sealed class EventSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Events";
|
||||
|
||||
private readonly List<(EntityKind Kind, int Target, int Good)> _candidates = [];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
Expire(w, ctx.Day);
|
||||
|
||||
double frequency = w.Difficulty.EventFrequencyMultiplier;
|
||||
if (frequency <= 0) return;
|
||||
var catalog = w.Data.Events;
|
||||
var rng = w.Stream("events");
|
||||
double days = w.Calendar.DaysPerYear;
|
||||
foreach (var def in catalog.Events)
|
||||
{
|
||||
if (ctx.Year < def.MinYear) continue;
|
||||
if (!rng.Chance(def.ChancePerYear * frequency / days)) continue;
|
||||
if (w.WorldEvents.Active.Count >= catalog.MaxActive) continue;
|
||||
Candidates(w, def, _candidates);
|
||||
if (_candidates.Count == 0) continue;
|
||||
var (kind, target, good) = _candidates[rng.NextInt(_candidates.Count)];
|
||||
int duration = rng.NextInt(def.DurationDays[0], def.DurationDays[1] + 1);
|
||||
double intensity = rng.NextDouble();
|
||||
Begin(w, def, kind, target, good, ctx.Day + 1, duration, intensity);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chiude gli eventi scaduti o il cui bersaglio non esiste più (industria chiusa, deposito demolito).</summary>
|
||||
private static void Expire(World w, long day)
|
||||
{
|
||||
var state = w.WorldEvents;
|
||||
for (int i = 0; i < state.Active.Count;)
|
||||
{
|
||||
var e = state.Active[i];
|
||||
bool alive = TargetAlive(w, e.TargetKind, e.Target);
|
||||
// oggi è il primo giorno senza l'evento: i sistemi giornalieri e l'usura del traffico di
|
||||
// ieri (ConstructionSystem) lo hanno già letto per l'ultima volta
|
||||
if (day < e.EndDay && alive)
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
state.RemoveAt(i);
|
||||
if (alive) Announce(w, e, e.Def.NewsEndIt, NewsSeverity.Info);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fa iniziare subito un evento sul bersaglio indicato (test, scenari e strumenti; in partita li
|
||||
/// estrae il sistema). Restituisce null se il bersaglio non è ammesso dal tipo, se un evento dello
|
||||
/// stesso tipo è già in corso lì (o, per le zone, su una zona sovrapposta) o se la durata non è
|
||||
/// positiva. Non usa numeri casuali e non controlla maxActive né l'anno minimo. Chiamato tra un
|
||||
/// giorno e l'altro (fuori dalla pipeline), l'evento agisce già sul giorno che sta per cominciare;
|
||||
/// a giornata iniziata, da domani.
|
||||
/// </summary>
|
||||
public static ActiveWorldEvent? Force(World w, string typeId, int target, int good = -1, int? durationDays = null, double intensity = 1.0)
|
||||
{
|
||||
var def = w.Data.EventType(typeId) ?? throw new ArgumentException($"Tipo di evento sconosciuto: {typeId}", nameof(typeId));
|
||||
var list = new List<(EntityKind Kind, int Target, int Good)>();
|
||||
Candidates(w, def, list);
|
||||
var kind = KindOf(def.Target);
|
||||
if (!list.Contains((kind, target, def.Target == EventTarget.TownGood ? good : -1))) return null;
|
||||
int duration = durationDays ?? def.DurationDays[0];
|
||||
if (duration <= 0) return null;
|
||||
long start = w.Clock.Tick % w.Calendar.TicksPerDay == 0 ? w.Clock.Day : w.Clock.Day + 1;
|
||||
return Begin(w, def, kind, target, good, start, duration, Math.Clamp(intensity, 0, 1));
|
||||
}
|
||||
|
||||
private static ActiveWorldEvent Begin(World w, WorldEventDef def, EntityKind kind, int target, int good, long start, int duration, double intensity)
|
||||
{
|
||||
var (center, radius2) = Zone(w, def, kind, target);
|
||||
var e = new ActiveWorldEvent
|
||||
{
|
||||
Id = w.WorldEvents.NextId++,
|
||||
Def = def,
|
||||
TargetKind = kind,
|
||||
Target = target,
|
||||
Good = def.Target == EventTarget.TownGood ? good : -1,
|
||||
StartDay = start,
|
||||
EndDay = start + duration,
|
||||
Intensity = intensity,
|
||||
Center = center,
|
||||
RadiusSquaredM = radius2,
|
||||
};
|
||||
w.WorldEvents.Add(e);
|
||||
Announce(w, e, def.NewsIt, def.Severity);
|
||||
return e;
|
||||
}
|
||||
|
||||
/// <summary>Centro e raggio al quadrato della zona di un evento (dal catalogo e dalla città bersaglio).</summary>
|
||||
public static (Vec2 Center, double RadiusSquaredM) Zone(World w, WorldEventDef def, EntityKind kind, int target)
|
||||
{
|
||||
if (kind != EntityKind.Town || def.RadiusKm is not { } km || target < 0 || target >= w.Towns.Count) return (Vec2.Zero, 0);
|
||||
double r = km * 1000;
|
||||
return (w.Towns[target].Position, r * r);
|
||||
}
|
||||
|
||||
public static EntityKind KindOf(EventTarget target) => target switch
|
||||
{
|
||||
EventTarget.Industry => EntityKind.Industry,
|
||||
EventTarget.Depot => EntityKind.Depot,
|
||||
_ => EntityKind.Town,
|
||||
};
|
||||
|
||||
private static bool TargetAlive(World w, EntityKind kind, int target) => kind switch
|
||||
{
|
||||
EntityKind.Industry => target < w.Industries.Count && !w.Industries[target].Closed && w.Industries[target].Level > 0,
|
||||
EntityKind.Depot => target < w.Network.Depots.Count && w.Network.IsAlive(w.Network.Depots[target]),
|
||||
EntityKind.Town => target < w.Towns.Count,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Bersagli ammessi in ordine deterministico (id dell'entità, poi indice del bene).</summary>
|
||||
private static void Candidates(World w, WorldEventDef def, List<(EntityKind, int, int)> into)
|
||||
{
|
||||
into.Clear();
|
||||
var state = w.WorldEvents;
|
||||
switch (def.Target)
|
||||
{
|
||||
case EventTarget.Industry:
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || ind.Level <= 0) continue;
|
||||
if (def.IndustryKinds is { } kinds && !kinds.Contains(ind.Def.Kind)) continue;
|
||||
if (state.IsActive(def, EntityKind.Industry, ind.Id.Value)) continue;
|
||||
into.Add((EntityKind.Industry, ind.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.Depot:
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (!w.Network.IsAlive(d) || state.IsActive(def, EntityKind.Depot, d.Id.Value)) continue;
|
||||
into.Add((EntityKind.Depot, d.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.Town:
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.Population < def.MinPopulation || state.IsActive(def, EntityKind.Town, t.Id.Value)) continue;
|
||||
into.Add((EntityKind.Town, t.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.Area:
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.Population < def.MinPopulation || state.IsActive(def, EntityKind.Town, t.Id.Value)) continue;
|
||||
// due maltempi sullo stesso arco si moltiplicherebbero: zone separate
|
||||
if (Overlaps(state, def, t.Position, -1)) continue;
|
||||
into.Add((EntityKind.Town, t.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.TownGood:
|
||||
int year = w.Clock.Year;
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.Population < def.MinPopulation || state.IsActive(def, EntityKind.Town, t.Id.Value)) continue;
|
||||
foreach (int g in def.GoodIndices)
|
||||
{
|
||||
// solo i beni che la città consuma quest'anno (era e fine del consumo)
|
||||
if (DemandSystem.TownDemand(w, t, g, year, events: false) <= 0) continue;
|
||||
// né due boom né boom e crollo dello stesso bene sulle stesse città
|
||||
if (Overlaps(state, def, t.Position, g)) continue;
|
||||
into.Add((EntityKind.Town, t.Id.Value, g));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Vero se la zona centrata in <paramref name="center"/> si sovrappone a quella di un evento in
|
||||
/// elenco con lo stesso bersaglio di zona (maltempo; per la domanda, lo stesso bene): le due zone
|
||||
/// possono avere una città o un arco in comune quando i centri distano al più la somma dei raggi.
|
||||
/// </summary>
|
||||
private static bool Overlaps(WorldEventState state, WorldEventDef def, Vec2 center, int good)
|
||||
{
|
||||
if (def.RadiusKm is not { } km) return false;
|
||||
foreach (var e in state.Active)
|
||||
{
|
||||
if (e.Def.Target != def.Target || e.Good != good || e.Def.RadiusKm is not { } other) continue;
|
||||
double reach = (km + other) * 1000;
|
||||
if ((e.Center - center).LengthSquared <= reach * reach) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void Announce(World w, ActiveWorldEvent e, string template, NewsSeverity severity)
|
||||
{
|
||||
string text = Format(w, e, template);
|
||||
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.World, (EventSeverity)(byte)severity, text, e.TargetKind, e.Target));
|
||||
}
|
||||
|
||||
/// <summary>Testo della notizia con i segnaposti {target}, {good}, {pct}, {days}, {until} (ultimo giorno dell'evento).</summary>
|
||||
public static string Format(World w, ActiveWorldEvent e, string template) => template
|
||||
.Replace("{target}", TargetName(w, e.TargetKind, e.Target), StringComparison.Ordinal)
|
||||
.Replace("{good}", e.Good >= 0 ? w.Data.Goods[e.Good].NameIt.ToLowerInvariant() : "", StringComparison.Ordinal)
|
||||
.Replace("{pct}", $"{Math.Round(e.Primary * 100):0}%", StringComparison.Ordinal)
|
||||
.Replace("{days}", e.DurationDays.ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.Ordinal)
|
||||
.Replace("{until}", w.Calendar.DateOfDay(e.EndDay - 1).ToString(), StringComparison.Ordinal);
|
||||
|
||||
public static string TargetName(World w, EntityKind kind, int target) => kind switch
|
||||
{
|
||||
EntityKind.Industry when target < w.Industries.Count => w.Industries[target].Name,
|
||||
EntityKind.Depot when target < w.Network.Depots.Count => w.Network.Depots[target].Name,
|
||||
EntityKind.Town when target < w.Towns.Count => w.Towns[target].Name,
|
||||
_ => "?",
|
||||
};
|
||||
}
|
||||
@@ -83,34 +83,78 @@ public sealed class FinanceSystem : ISimSystem
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo.</summary>
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo,
|
||||
/// 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));
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
|
||||
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][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][goods] += OwnedGoodsValue(t.Cargo, prices);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static long OwnedGoodsValue(List<Rail.Packet> packets, double[] prices)
|
||||
{
|
||||
long value = 0;
|
||||
foreach (var p in packets)
|
||||
{
|
||||
if (p.Owned && p.Kind == Rail.PacketKind.Freight) value += (long)(p.Units * prices[p.Good]);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>Rata mensile costante (alla francese) per il residuo e i mesi restanti.</summary>
|
||||
@@ -168,11 +212,7 @@ public sealed class FinanceSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(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;
|
||||
}
|
||||
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.</summary>
|
||||
public static double LoanRate(World w, Company c) =>
|
||||
|
||||
@@ -240,7 +240,7 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
{
|
||||
if (p.Kind != PacketKind.Freight) continue;
|
||||
w.Goods.Decayed[p.Good] += p.Units;
|
||||
if (!p.AwaitingConsumer && p.Destination.IsValid)
|
||||
if (!p.AwaitingConsumer && !p.Owned && p.Destination.IsValid)
|
||||
{
|
||||
var dest = net.Stations[p.Destination.Value];
|
||||
dest.Incoming[p.Good] = Math.Max(0, dest.Incoming[p.Good] - p.Units);
|
||||
@@ -585,6 +585,7 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
t.CoveredBy = TrainId.None;
|
||||
if (r.Covering != t.Id) return;
|
||||
r.Covering = TrainId.None;
|
||||
StationWork.DropOwnedCargo(w, r, r.Line);
|
||||
r.Line = LineId.None;
|
||||
if (r.HomeDepot.IsValid && w.Network.IsAlive(w.Network.Depots[r.HomeDepot.Value]) && w.Network.Depots[r.HomeDepot.Value].Node != r.AtNode)
|
||||
r.GoingToDepot = r.HomeDepot;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -60,9 +60,11 @@ public sealed class IndustrySystem : ISimSystem
|
||||
if (frac < ib.DepletionStartFraction) depletion = frac / ib.DepletionStartFraction;
|
||||
}
|
||||
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion;
|
||||
// eventi del mondo: incidente (capacità ridotta o nulla) e boom di produzione (ADR 0017)
|
||||
double capacity = w.WorldEvents.IndustryCapacity(ind.Id);
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion * capacity;
|
||||
for (int o = 0; o < recipe.Outputs.Count && !stopped; o++)
|
||||
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * recipe.Outputs[o].PerCycle;
|
||||
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * capacity * recipe.Outputs[o].PerCycle;
|
||||
|
||||
// copertura degli input di oggi: limita la produzione alle scorte disponibili
|
||||
double covInToday = 1.0;
|
||||
@@ -109,7 +111,7 @@ public sealed class IndustrySystem : ISimSystem
|
||||
double extracted = whole * recipe.Outputs[0].PerCycle * data.Difficulty.DepletionMultipliers.For(w.Difficulty.Depletion);
|
||||
site.ReserveTonnes = Math.Max(0, site.ReserveTonnes - extracted);
|
||||
}
|
||||
ind.Efficiency = eLabor * covInToday * depletion;
|
||||
ind.Efficiency = eLabor * covInToday * depletion * capacity;
|
||||
|
||||
// salari giornalieri ai presenti
|
||||
double wages = (ind.WorkersPresent * ib.WagePerWorkerPerMonth + ind.StaffPresent * ib.WagePerStaffPerMonth) / dpm;
|
||||
|
||||
@@ -28,9 +28,11 @@ public sealed class StationSystem : ISimSystem
|
||||
if (net.IsAlive(s)) RailCommandHandlers.UpdateCatchment(w, s);
|
||||
}
|
||||
}
|
||||
if (ctx.IsNewMonth) TradingCommandHandlers.ChargeStorage(w);
|
||||
foreach (var s in net.Stations)
|
||||
{
|
||||
if (net.Nodes[s.Node.Value].Station != s.Id) continue;
|
||||
RerouteOwned(w, s);
|
||||
Expire(ctx, s);
|
||||
RetryDeliveries(w, s);
|
||||
}
|
||||
@@ -91,6 +93,27 @@ public sealed class StationSystem : ISimSystem
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merce della compagnia in attesa (ADR 0016): ogni giorno ricalcola il tratto sulle linee di oggi,
|
||||
/// così una linea modificata non la lascia ad aspettare un treno che non passa più; senza
|
||||
/// percorso entra nel magazzino della stazione.
|
||||
/// </summary>
|
||||
private static void RerouteOwned(World w, Station s)
|
||||
{
|
||||
for (int i = s.Waiting.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var p = s.Waiting[i];
|
||||
if (!p.Owned) continue;
|
||||
if (StationWork.Route(w, s, ref p))
|
||||
{
|
||||
s.Waiting[i] = p;
|
||||
continue;
|
||||
}
|
||||
s.Waiting.RemoveAt(i);
|
||||
TradingCommandHandlers.Store(w, s, p);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Expire(WorldContext ctx, Station s)
|
||||
{
|
||||
var w = ctx.World;
|
||||
@@ -101,7 +124,7 @@ public sealed class StationSystem : ISimSystem
|
||||
s.Waiting.RemoveAt(i);
|
||||
if (p.Kind != PacketKind.Freight) continue;
|
||||
w.Goods.Decayed[p.Good] += p.Units;
|
||||
if (!p.AwaitingConsumer)
|
||||
if (!p.AwaitingConsumer && !p.Owned)
|
||||
{
|
||||
var dest = w.Network.Stations[p.Destination.Value];
|
||||
dest.Incoming[p.Good] = Math.Max(0, dest.Incoming[p.Good] - p.Units);
|
||||
|
||||
@@ -104,20 +104,83 @@ public static class StationWork
|
||||
{
|
||||
var p = t.Cargo[i];
|
||||
bool final = p.Destination == s.Id;
|
||||
if (p.Owned && !final && !StillOnHop(w, t, p))
|
||||
{
|
||||
// merce della compagnia il cui tratto non è più su questa linea (linea modificata o
|
||||
// treno riassegnato): scende qui e riparte da questa stazione o entra nel suo magazzino
|
||||
t.Cargo.RemoveAt(i);
|
||||
RemoveFromVehicles(w, t, p);
|
||||
moved += p.Units;
|
||||
Transfer(w, ctx.Tick, s, p);
|
||||
continue;
|
||||
}
|
||||
if (p.HopEnd != s.Id && !final) continue;
|
||||
if (!final && !unloadOrders) continue;
|
||||
t.Cargo.RemoveAt(i);
|
||||
RemoveFromVehicles(w, t, p);
|
||||
moved += p.Units;
|
||||
if (final) Deliver(ctx, t, s, p);
|
||||
else Transfer(ctx, s, p);
|
||||
else Transfer(w, ctx.Tick, s, p);
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Il pacchetto a bordo viaggia ancora sul suo tratto: il treno serve la linea del tratto e
|
||||
/// una fermata della linea alla fine del tratto lo scarica (o è la destinazione).
|
||||
/// </summary>
|
||||
private static bool StillOnHop(World w, Train t, Packet p)
|
||||
{
|
||||
if (!t.Line.IsValid || t.Line != p.HopLine) return false;
|
||||
var line = w.Lines[t.Line.Value];
|
||||
if (line.Removed) return false;
|
||||
foreach (var stop in line.Stops)
|
||||
{
|
||||
if (stop.Station == p.HopEnd && (stop.Unload || p.HopEnd == p.Destination)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Il treno lascia la linea <paramref name="line"/> (riassegnato, mandato al deposito, messo in
|
||||
/// riserva): la merce della compagnia a bordo scende alla stazione dove si trova il treno o alla
|
||||
/// prossima fermata della linea, e da lì riparte o entra nel magazzino (ADR 0016). Senza nessuna
|
||||
/// stazione della compagnia a disposizione la merce va persa.
|
||||
/// </summary>
|
||||
public static void DropOwnedCargo(World w, Train t, LineId line)
|
||||
{
|
||||
if (!t.Cargo.Any(p => p.Owned)) return;
|
||||
var net = w.Network;
|
||||
Station? here = null;
|
||||
if (t.AtNode.IsValid && net.Nodes[t.AtNode.Value].Station is { IsValid: true } sid) here = net.Stations[sid.Value];
|
||||
else if (line.IsValid && line.Value < w.Lines.Count && w.Lines[line.Value] is { Removed: false, Stops.Count: > 0 } l)
|
||||
here = net.Stations[l.Stops[t.StopIndex % l.Stops.Count].Station.Value];
|
||||
for (int i = t.Cargo.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var p = t.Cargo[i];
|
||||
if (!p.Owned) continue;
|
||||
t.Cargo.RemoveAt(i);
|
||||
RemoveFromVehicles(w, t, p);
|
||||
var s = here;
|
||||
if (s is null || !net.IsAlive(s) || s.Owner != t.Owner) s = p.Origin.IsValid ? net.Stations[p.Origin.Value] : null;
|
||||
if (s is null || !net.IsAlive(s) || s.Owner != t.Owner)
|
||||
{
|
||||
if (p.Kind == PacketKind.Freight) w.Goods.Decayed[p.Good] += p.Units;
|
||||
continue;
|
||||
}
|
||||
Transfer(w, w.Context.Tick, s, p);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Deliver(WorldContext ctx, Train t, Station s, Packet p)
|
||||
{
|
||||
var w = ctx.World;
|
||||
// merce della compagnia: niente tariffa né consumatore, entra nel magazzino (ADR 0016)
|
||||
if (p.Owned)
|
||||
{
|
||||
TradingCommandHandlers.Store(w, s, p);
|
||||
return;
|
||||
}
|
||||
var origin = w.Network.Stations[p.Origin.Value];
|
||||
double km = Vec2.Distance(origin.Position, s.Position) / 1000;
|
||||
double days = (ctx.Tick - p.CreatedTick) / (double)w.Calendar.TicksPerDay;
|
||||
@@ -166,14 +229,21 @@ public static class StationWork
|
||||
if (Route(w, s, ref back)) s.Waiting.Add(back);
|
||||
}
|
||||
|
||||
private static void Transfer(WorldContext ctx, Station s, Packet p)
|
||||
private static void Transfer(World w, long tick, Station s, Packet p)
|
||||
{
|
||||
var w = ctx.World;
|
||||
if (Route(w, s, ref p))
|
||||
{
|
||||
// merce della compagnia: la scadenza in stazione riparte a ogni trasbordo (ADR 0016)
|
||||
if (p.Owned) p.ExpiresTick = tick + (long)w.Data.Goods[p.Good].DecayDaysAtStation * w.Calendar.TicksPerDay;
|
||||
s.Waiting.Add(p);
|
||||
return;
|
||||
}
|
||||
// merce della compagnia senza più un percorso: resta nel magazzino di questa stazione (ADR 0016)
|
||||
if (p.Owned)
|
||||
{
|
||||
TradingCommandHandlers.Store(w, s, p);
|
||||
return;
|
||||
}
|
||||
// nessun collegamento ulteriore: le merci provano a essere consegnate qui, i passeggeri rinunciano
|
||||
if (p.Kind == PacketKind.Freight)
|
||||
{
|
||||
@@ -183,11 +253,14 @@ public static class StationWork
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Assegna al pacchetto il prossimo tratto verso la destinazione; false se irraggiungibile.</summary>
|
||||
/// <summary>
|
||||
/// Assegna al pacchetto il prossimo tratto verso la destinazione; false se irraggiungibile. La
|
||||
/// merce della compagnia segue solo i percorsi dove le fermate la caricano e la scaricano ai cambi.
|
||||
/// </summary>
|
||||
public static bool Route(World w, Station from, ref Packet p)
|
||||
{
|
||||
var graph = w.LineGraphs.For(w, from.Owner);
|
||||
if (!graph.From(from.Id, LineGraph.CargoOf(p)).TryGetValue(p.Destination.Value, out var conn)) return false;
|
||||
if (!graph.From(from.Id, LineGraph.CargoOf(p), p.Owned).TryGetValue(p.Destination.Value, out var conn)) return false;
|
||||
p.HopLine = conn.First.Line;
|
||||
p.HopEnd = conn.First.To;
|
||||
if (p.ExpectedDays <= 0) p.ExpectedDays = w.Calendar.TrainMinutesToDays(conn.Minutes);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Venditore o compratore nel bacino di una stazione per la compravendita in proprio.</summary>
|
||||
public enum TradePartyKind : byte { Industry = 0, Hub = 1 }
|
||||
|
||||
/// <summary>
|
||||
/// Controparte di uno scambio: industria (con l'indice dell'output o dell'input del bene) o hub;
|
||||
/// <see cref="Limit"/> è il massimo di unità che può dare o ricevere, <see cref="Units"/> quelle
|
||||
/// già scambiate, <see cref="Cents"/> il loro valore non arrotondato.
|
||||
/// </summary>
|
||||
public sealed class TradeParty
|
||||
{
|
||||
public required TradePartyKind Kind { get; init; }
|
||||
public required int Target { get; init; }
|
||||
public required int Slot { get; init; }
|
||||
public required int Limit { get; init; }
|
||||
public int Units { get; set; }
|
||||
public double Cents { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Quotazione di un bene in una stazione: prezzo della prossima unità e unità disponibili (−1 senza controparti).</summary>
|
||||
public readonly record struct TradeQuote(double BuyPrice, int BuyUnits, double SellPrice, int SellUnits);
|
||||
|
||||
/// <summary>
|
||||
/// Formule della compravendita in proprio (ADR 0016), senza stato: prezzi locali marginali
|
||||
/// (ADR 0004 §3) di produttori e consumatori del bacino, prezzi degli hub, spazio del magazzino.
|
||||
/// </summary>
|
||||
public static class TradingMath
|
||||
{
|
||||
/// <summary>
|
||||
/// Prezzo locale della prossima unità comprata da un produttore che ne ha <paramref name="stock"/>
|
||||
/// in magazzino: Dl = spazio libero del magazzino dell'output, Sl = giacenza. Pieno vale
|
||||
/// (1 − λ)·Pg, a metà Pg, quasi vuoto fino a (1 + λ)·Pg, entro ±maxDeviation.
|
||||
/// </summary>
|
||||
public static double ProducerPrice(World w, Industry ind, int output, int stock)
|
||||
{
|
||||
int capacity = IndustryMath.OutputCapacity(ind, output, w.Calendar.DaysPerMonth);
|
||||
int good = ind.Def.Recipe.Outputs[output].GoodIndex;
|
||||
return Market.LocalPrice(w.Market.GlobalPrice[good], Math.Max(0, capacity - stock), stock, w.Data.Balance.LocalPrice);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo locale della prossima unità venduta a un consumatore che ne ha <paramref name="stock"/>
|
||||
/// nell'input: Dl = capienza dell'input (scorta desiderata), Sl = giacenza, come «Dove conviene vendere».
|
||||
/// </summary>
|
||||
public static double ConsumerPrice(World w, Industry ind, int input, int stock)
|
||||
{
|
||||
int desired = IndustryMath.InputCapacity(ind, input, w.Calendar.DaysPerMonth);
|
||||
int good = ind.Def.Recipe.Inputs[input].GoodIndex;
|
||||
return Market.LocalPrice(w.Market.GlobalPrice[good], desired, stock, w.Data.Balance.LocalPrice);
|
||||
}
|
||||
|
||||
/// <summary>Venditori del bene nel bacino: produttori aperti con il bene in magazzino e hub con capacità.</summary>
|
||||
public static List<TradeParty> Sellers(World w, Station s, int good)
|
||||
{
|
||||
var list = new List<TradeParty>();
|
||||
foreach (var id in s.Industries)
|
||||
{
|
||||
var ind = w.Industries[id.Value];
|
||||
int o = ind.OutputIndexOf(good);
|
||||
if (ind.Closed || o < 0 || ind.OutputStock[o] <= 0) continue;
|
||||
list.Add(new TradeParty { Kind = TradePartyKind.Industry, Target = ind.Id.Value, Slot = o, Limit = ind.OutputStock[o] });
|
||||
}
|
||||
foreach (var id in s.Hubs)
|
||||
{
|
||||
var hub = w.Hubs[id.Value];
|
||||
if (hub.RemainingCapacity > 0) list.Add(new TradeParty { Kind = TradePartyKind.Hub, Target = hub.Id.Value, Slot = -1, Limit = hub.RemainingCapacity });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Compratori del bene nel bacino: industrie aperte con il bene in ricetta e spazio nell'input, hub con capacità.</summary>
|
||||
public static List<TradeParty> Buyers(World w, Station s, int good)
|
||||
{
|
||||
var list = new List<TradeParty>();
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
foreach (var id in s.Industries)
|
||||
{
|
||||
var ind = w.Industries[id.Value];
|
||||
int i = ind.InputIndexOf(good);
|
||||
if (ind.Closed || ind.Level <= 0 || i < 0) continue;
|
||||
int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
|
||||
if (free > 0) list.Add(new TradeParty { Kind = TradePartyKind.Industry, Target = ind.Id.Value, Slot = i, Limit = free });
|
||||
}
|
||||
foreach (var id in s.Hubs)
|
||||
{
|
||||
var hub = w.Hubs[id.Value];
|
||||
if (hub.RemainingCapacity > 0) list.Add(new TradeParty { Kind = TradePartyKind.Hub, Target = hub.Id.Value, Slot = -1, Limit = hub.RemainingCapacity });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Prezzo della prossima unità comprata dal venditore (dopo quelle già prese).</summary>
|
||||
public static double NextBuyPrice(World w, TradeParty p, int good)
|
||||
{
|
||||
if (p.Kind == TradePartyKind.Hub) return w.Hubs[p.Target].SellPrice(w.Market.GlobalPrice[good]);
|
||||
var ind = w.Industries[p.Target];
|
||||
return ProducerPrice(w, ind, p.Slot, ind.OutputStock[p.Slot] - p.Units);
|
||||
}
|
||||
|
||||
/// <summary>Prezzo della prossima unità venduta al compratore (dopo quelle già date).</summary>
|
||||
public static double NextSellPrice(World w, TradeParty p, int good)
|
||||
{
|
||||
if (p.Kind == TradePartyKind.Hub) return w.Hubs[p.Target].BuyPrice(w.Market.GlobalPrice[good]);
|
||||
var ind = w.Industries[p.Target];
|
||||
return ConsumerPrice(w, ind, p.Slot, ind.InputStock[p.Slot] + p.Units);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Venditore con la prossima unità più conveniente (prezzo crescente, poi industrie prima degli
|
||||
/// hub, poi id), null se nessuno ha ancora unità.
|
||||
/// </summary>
|
||||
public static TradeParty? CheapestSeller(World w, List<TradeParty> sellers, int good, out double price)
|
||||
{
|
||||
TradeParty? best = null;
|
||||
price = double.PositiveInfinity;
|
||||
foreach (var p in sellers)
|
||||
{
|
||||
if (p.Units >= p.Limit) continue;
|
||||
double q = NextBuyPrice(w, p, good);
|
||||
if (best is null || q < price || (q == price && Before(p, best)))
|
||||
{
|
||||
best = p;
|
||||
price = q;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compratore che paga di più la prossima unità (prezzo decrescente, poi industrie prima degli
|
||||
/// hub, poi id), null se nessuno ha ancora spazio; le industrie senza cassa per l'unità si saltano.
|
||||
/// </summary>
|
||||
public static TradeParty? BestBuyer(World w, List<TradeParty> buyers, int good, out double price)
|
||||
{
|
||||
TradeParty? best = null;
|
||||
price = double.NegativeInfinity;
|
||||
foreach (var p in buyers)
|
||||
{
|
||||
if (p.Units >= p.Limit) continue;
|
||||
double q = NextSellPrice(w, p, good);
|
||||
if (p.Kind == TradePartyKind.Industry && !CanPay(w.Industries[p.Target], p.Cents + q)) continue;
|
||||
if (best is null || q > price || (q == price && Before(p, best)))
|
||||
{
|
||||
best = p;
|
||||
price = q;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>L'industria ha cassa per pagare <paramref name="cents"/> (arrotondati al centesimo).</summary>
|
||||
public static bool CanPay(Industry ind, double cents) => Common.Money.FromCentsRounded(cents).Cents <= ind.Cash.Cents;
|
||||
|
||||
private static bool Before(TradeParty a, TradeParty b) => a.Kind != b.Kind ? a.Kind < b.Kind : a.Target < b.Target;
|
||||
|
||||
/// <summary>
|
||||
/// Unità di merce della compagnia in viaggio (pacchetti propri in stazione e a bordo) verso
|
||||
/// ciascuna stazione: occupano già il magazzino di destinazione.
|
||||
/// </summary>
|
||||
public static int[] ReservedByStation(World w)
|
||||
{
|
||||
var reserved = new int[w.Network.Stations.Count];
|
||||
foreach (var s in w.Network.Stations) AddReserved(s.Waiting, reserved);
|
||||
foreach (var t in w.Trains) AddReserved(t.Cargo, reserved);
|
||||
return reserved;
|
||||
}
|
||||
|
||||
private static void AddReserved(List<Packet> packets, int[] reserved)
|
||||
{
|
||||
foreach (var p in packets)
|
||||
{
|
||||
if (!p.Owned || p.Kind != PacketKind.Freight) continue;
|
||||
int d = p.Destination.Value;
|
||||
if (d >= 0 && d < reserved.Length) reserved[d] += p.Units;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Spazio libero nel magazzino di una stazione (capacità − giacenza − spedizioni in arrivo).</summary>
|
||||
public static int FreeSpace(World w, Station s, int reserved) =>
|
||||
Math.Max(0, w.Data.Balance.Trading.WarehouseCapacity - s.StockTotal - reserved);
|
||||
|
||||
/// <summary>Aggiunge unità al magazzino della compagnia nella stazione (allarga il vettore se serve).</summary>
|
||||
public static void AddToWarehouse(Station s, int good, int units, int goodCount)
|
||||
{
|
||||
if (s.Stock.Length < goodCount) s.Stock = [.. s.Stock, .. new int[goodCount - s.Stock.Length]];
|
||||
s.Stock[good] += units;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quotazione di un bene in una stazione: prezzo della prossima unità al venditore più
|
||||
/// conveniente e al compratore migliore, con le unità disponibili (cassa delle industrie esclusa).
|
||||
/// </summary>
|
||||
public static TradeQuote Quote(World w, Station s, int good)
|
||||
{
|
||||
var sellers = Sellers(w, s, good);
|
||||
var buyers = Buyers(w, s, good);
|
||||
double buy = -1, sell = -1;
|
||||
if (CheapestSeller(w, sellers, good, out double p) is not null) buy = p;
|
||||
foreach (var b in buyers) sell = Math.Max(sell, NextSellPrice(w, b, good));
|
||||
return new TradeQuote(buy, sellers.Sum(x => x.Limit), sell, buyers.Sum(x => x.Limit));
|
||||
}
|
||||
}
|
||||
@@ -243,7 +243,8 @@ public sealed class TrainSystem : ISimSystem
|
||||
// 2. velocità obiettivo: limiti presenti e futuri, fine dell'autorizzazione, fermata
|
||||
var step = t.Route[t.RouteIndex];
|
||||
var edge = net.Edges[step.Edge.Value];
|
||||
double cond = ConstructionSystem.ConditionFactor(w, edge);
|
||||
// condizione del binario e maltempo sull'area (ADR 0017)
|
||||
double cond = ConstructionSystem.ConditionFactor(w, edge) * w.WorldEvents.EdgeSpeed(edge);
|
||||
double limit = Math.Min(t.TopSpeedKmh, LimitAt(edge, step.Forward, t.StepPos) * cond) / 3.6;
|
||||
double target = Math.Min(limit, Math.Sqrt(2 * _brake * Math.Max(0, ma - 1)));
|
||||
target = Math.Min(target, LookaheadCap(w, t, needed + 500));
|
||||
@@ -657,7 +658,7 @@ public sealed class TrainSystem : ISimSystem
|
||||
{
|
||||
var step = t.Route[s];
|
||||
var e = net.Edges[step.Edge.Value];
|
||||
double cond = ConstructionSystem.ConditionFactor(w, e);
|
||||
double cond = ConstructionSystem.ConditionFactor(w, e) * w.WorldEvents.EdgeSpeed(e);
|
||||
double start = s == t.RouteIndex ? t.StepPos : 0;
|
||||
int n = e.S.Length;
|
||||
if (step.Forward)
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation;
|
||||
|
||||
/// <summary>
|
||||
/// Compravendita in proprio (F6, ADR 0016): comprare dai produttori e dagli hub del bacino di una
|
||||
/// stazione al prezzo locale, rivendere ai consumatori e agli hub, spedire la merce tra i magazzini
|
||||
/// della compagnia sulle sue linee. Ogni comando valida tutto prima di cambiare il mondo; il denaro
|
||||
/// passa dal registro e la merce resta sempre in un magazzino tracciato.
|
||||
/// </summary>
|
||||
public static class TradingCommandHandlers
|
||||
{
|
||||
public static CommandResult Buy(World w, Company company, BuyGoodsCommand c, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Check(w, company, c.Station, c.Good, c.Units, true, out var s, out int good, out var error)) return reply(error.Error, error.Message);
|
||||
if (!MarketOutlook.IsAvailable(w, good))
|
||||
return reply(CommandError.EraLocked, $"{GoodName(w, good)} non è ancora disponibile (dal {w.Data.Goods[good].Era})");
|
||||
int free = TradingMath.FreeSpace(w, s, TradingMath.ReservedByStation(w)[s.Id.Value]);
|
||||
if (free <= 0)
|
||||
return reply(CommandError.Blocked, $"Magazzino di {s.Name} pieno ({w.Data.Balance.Trading.WarehouseCapacity} unità comprese le spedizioni in arrivo)");
|
||||
var sellers = TradingMath.Sellers(w, s, good);
|
||||
if (TradingMath.CheapestSeller(w, sellers, good, out double first) is null)
|
||||
return reply(CommandError.NotFound, $"Nessun produttore né hub nel bacino di {s.Name} vende {GoodName(w, good)}");
|
||||
if (first > c.MaxUnitPrice.Cents)
|
||||
return reply(CommandError.InvalidArgument, $"Il prezzo più basso è {PerUnit(w, good, first)}, oltre il tetto di {PerUnit(w, good, c.MaxUnitPrice.Cents)}");
|
||||
|
||||
int want = Math.Min(c.Units, free);
|
||||
int bought = 0;
|
||||
long committed = 0;
|
||||
bool shortOfCash = false;
|
||||
string stop = want < c.Units ? "magazzino pieno" : "";
|
||||
while (bought < want)
|
||||
{
|
||||
var best = TradingMath.CheapestSeller(w, sellers, good, out double price);
|
||||
if (best is null)
|
||||
{
|
||||
stop = "esaurita la merce in vendita nel bacino";
|
||||
break;
|
||||
}
|
||||
if (price > c.MaxUnitPrice.Cents)
|
||||
{
|
||||
stop = "nessun'altra unità sotto il tetto di prezzo";
|
||||
break;
|
||||
}
|
||||
long next = committed - Rounded(best.Cents) + Rounded(best.Cents + price);
|
||||
if (next > company.Cash.Cents)
|
||||
{
|
||||
shortOfCash = true;
|
||||
stop = "cassa esaurita";
|
||||
break;
|
||||
}
|
||||
committed = next;
|
||||
best.Units++;
|
||||
best.Cents += price;
|
||||
bought++;
|
||||
}
|
||||
if (bought == 0)
|
||||
return reply(CommandError.InsufficientFunds, shortOfCash ? $"Cassa insufficiente: un'unità costa {PerUnit(w, good, first)}" : "Nessuna unità acquistabile");
|
||||
|
||||
var from = Account.Of(company.Id);
|
||||
foreach (var p in sellers)
|
||||
{
|
||||
if (p.Units == 0) continue;
|
||||
var amount = Money.FromCentsRounded(p.Cents);
|
||||
if (p.Kind == TradePartyKind.Industry)
|
||||
{
|
||||
var ind = w.Industries[p.Target];
|
||||
ind.OutputStock[p.Slot] -= p.Units;
|
||||
w.Money.Transfer(from, Account.Of(ind.Id), amount, LedgerEntry.Trading);
|
||||
ind.SalesToday += amount.Cents;
|
||||
if (p.Slot == 0) ind.ShippedToday += p.Units;
|
||||
ind.LastServedDay = w.Clock.Day;
|
||||
}
|
||||
else
|
||||
{
|
||||
var hub = w.Hubs[p.Target];
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ImportedThisMonth[good] += p.Units;
|
||||
w.Goods.Imported[good] += p.Units;
|
||||
w.Money.Transfer(from, Account.External, amount, LedgerEntry.Trading);
|
||||
}
|
||||
}
|
||||
TradingMath.AddToWarehouse(s, good, bought, w.Data.GoodCount);
|
||||
var total = new Money(committed);
|
||||
string limit = bought < c.Units ? $" ({stop})" : "";
|
||||
return reply(CommandError.None,
|
||||
$"Comprate {bought} {Unit(w, good)} di {GoodName(w, good)} a {s.Name} per {total} (in media {PerUnit(w, good, (double)committed / bought)}){limit}");
|
||||
}
|
||||
|
||||
public static CommandResult Sell(World w, Company company, SellGoodsCommand c, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Check(w, company, c.Station, c.Good, c.Units, false, out var s, out int good, out var error)) return reply(error.Error, error.Message);
|
||||
int stock = s.StockOf(good);
|
||||
if (stock <= 0) return reply(CommandError.NotFound, $"Nel magazzino di {s.Name} non c'è {GoodName(w, good)}");
|
||||
var buyers = TradingMath.Buyers(w, s, good);
|
||||
if (buyers.Count == 0)
|
||||
{
|
||||
bool consumers = s.Industries.Any(id => w.Industries[id.Value] is { Closed: false } ind && ind.Level > 0 && ind.InputIndexOf(good) >= 0);
|
||||
return reply(CommandError.NotFound, consumers
|
||||
? $"I consumatori di {GoodName(w, good)} nel bacino di {s.Name} hanno il magazzino pieno"
|
||||
: $"Nessun consumatore né hub nel bacino di {s.Name} compra {GoodName(w, good)}");
|
||||
}
|
||||
var top = TradingMath.BestBuyer(w, buyers, good, out double first);
|
||||
if (top is null) return reply(CommandError.InsufficientFunds, $"Le industrie del bacino di {s.Name} non hanno cassa per pagare {GoodName(w, good)}");
|
||||
if (first < c.MinUnitPrice.Cents)
|
||||
return reply(CommandError.InvalidArgument, $"Il prezzo più alto è {PerUnit(w, good, first)}, sotto il minimo di {PerUnit(w, good, c.MinUnitPrice.Cents)}");
|
||||
|
||||
int want = Math.Min(c.Units, stock);
|
||||
int sold = 0;
|
||||
double cents = 0;
|
||||
while (sold < want)
|
||||
{
|
||||
var best = TradingMath.BestBuyer(w, buyers, good, out double price);
|
||||
if (best is null || price < c.MinUnitPrice.Cents) break;
|
||||
best.Units++;
|
||||
best.Cents += price;
|
||||
cents += price;
|
||||
sold++;
|
||||
}
|
||||
|
||||
var to = Account.Of(company.Id);
|
||||
long received = 0;
|
||||
foreach (var p in buyers)
|
||||
{
|
||||
if (p.Units == 0) continue;
|
||||
var amount = Money.FromCentsRounded(p.Cents);
|
||||
received += amount.Cents;
|
||||
if (p.Kind == TradePartyKind.Industry)
|
||||
{
|
||||
var ind = w.Industries[p.Target];
|
||||
ind.InputStock[p.Slot] += p.Units;
|
||||
w.Money.Transfer(Account.Of(ind.Id), to, amount, LedgerEntry.Trading);
|
||||
ind.PurchasesToday += amount.Cents;
|
||||
ind.LastServedDay = w.Clock.Day;
|
||||
}
|
||||
else
|
||||
{
|
||||
var hub = w.Hubs[p.Target];
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ExportedThisMonth[good] += p.Units;
|
||||
w.Goods.Exported[good] += p.Units;
|
||||
w.Money.Transfer(Account.External, to, amount, LedgerEntry.Trading);
|
||||
}
|
||||
}
|
||||
s.Stock[good] -= sold;
|
||||
string rest = sold < c.Units ? $" ({(sold < stock ? "i compratori del bacino non ne prendono altre a questo prezzo" : "tutto il magazzino")})" : "";
|
||||
return reply(CommandError.None,
|
||||
$"Vendute {sold} {Unit(w, good)} di {GoodName(w, good)} a {s.Name} per {new Money(received)} (in media {PerUnit(w, good, cents / sold)}){rest}");
|
||||
}
|
||||
|
||||
public static CommandResult Ship(World w, Company company, ShipGoodsCommand c, WorldContext ctx, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Check(w, company, c.From, c.Good, c.Units, false, out var from, out int good, out var error)) return reply(error.Error, error.Message);
|
||||
if (!TryOwnStation(w, company, c.To, out var to, out error)) return reply(error.Error, error.Message);
|
||||
if (to.Id == from.Id) return reply(CommandError.InvalidArgument, "La stazione di partenza e quella di arrivo coincidono");
|
||||
int stock = from.StockOf(good);
|
||||
if (stock <= 0) return reply(CommandError.NotFound, $"Nel magazzino di {from.Name} non c'è {GoodName(w, good)}");
|
||||
// percorso con i flag delle fermate: si carica alla partenza e si scarica a ogni cambio
|
||||
var graph = w.LineGraphs.For(w, company.Id);
|
||||
var cargo = LineGraph.GoodCargo(good);
|
||||
if (!graph.From(from.Id, cargo, stopFlags: true).TryGetValue(to.Id.Value, out var conn))
|
||||
{
|
||||
return graph.From(from.Id, cargo).ContainsKey(to.Id.Value)
|
||||
? reply(CommandError.Blocked,
|
||||
$"Le linee da {from.Name} a {to.Name} non caricano la merce a {from.Name} o non la scaricano ai cambi: controlla carico e scarico delle fermate")
|
||||
: reply(CommandError.NotFound, $"Nessuna linea della compagnia porta {GoodName(w, good)} da {from.Name} a {to.Name}");
|
||||
}
|
||||
int free = TradingMath.FreeSpace(w, to, TradingMath.ReservedByStation(w)[to.Id.Value]);
|
||||
if (free <= 0)
|
||||
return reply(CommandError.Blocked, $"Magazzino di {to.Name} pieno ({w.Data.Balance.Trading.WarehouseCapacity} unità comprese le spedizioni in arrivo)");
|
||||
|
||||
int units = Math.Min(Math.Min(c.Units, stock), free);
|
||||
var packet = new Packet
|
||||
{
|
||||
Id = w.NextIds.Packet++,
|
||||
Kind = PacketKind.Freight,
|
||||
Good = good,
|
||||
Units = units,
|
||||
Origin = from.Id,
|
||||
Destination = to.Id,
|
||||
HopLine = conn.First.Line,
|
||||
HopEnd = conn.First.To,
|
||||
CreatedTick = ctx.Tick,
|
||||
ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay,
|
||||
ExpectedDays = w.Calendar.TrainMinutesToDays(conn.Minutes),
|
||||
Contract = -1,
|
||||
Owned = true,
|
||||
};
|
||||
from.Stock[good] -= units;
|
||||
from.Waiting.Add(packet);
|
||||
string limit = units < c.Units ? $" ({(units == stock ? "tutta la giacenza" : $"limitate dallo spazio libero a {to.Name}")})" : "";
|
||||
return reply(CommandError.None,
|
||||
$"Spedite {units} {Unit(w, good)} di {GoodName(w, good)} da {from.Name} a {to.Name}, circa {packet.ExpectedDays:0.#} giorni di viaggio{limit}",
|
||||
packet.Id);
|
||||
}
|
||||
|
||||
/// <summary>Merce della compagnia arrivata a destinazione o senza più un percorso: entra nel magazzino della stazione.</summary>
|
||||
public static void Store(World w, Station s, Packet p) => TradingMath.AddToWarehouse(s, p.Good, p.Units, w.Data.GoodCount);
|
||||
|
||||
/// <summary>
|
||||
/// Costo di giacenza mensile (trading.storageCostPerUnitPerMonth) per ogni unità nei magazzini
|
||||
/// delle stazioni, addebitato alla compagnia proprietaria sulla voce «Commercio».
|
||||
/// </summary>
|
||||
public static void ChargeStorage(World w)
|
||||
{
|
||||
long perUnit = w.Data.Balance.Trading.StorageCostPerUnitPerMonth;
|
||||
if (perUnit <= 0) return;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ validazione
|
||||
|
||||
/// <summary>
|
||||
/// Validazione comune. Lo sblocco del livello serve solo per comprare (<paramref name="needsUnlock"/>):
|
||||
/// la merce già in magazzino, per esempio ereditata con una fusione, si vende e si spedisce sempre.
|
||||
/// </summary>
|
||||
private static bool Check(World w, Company company, StationId station, string goodId, int units, bool needsUnlock, out Station s, out int good,
|
||||
out (CommandError Error, string Message) error)
|
||||
{
|
||||
good = -1;
|
||||
s = null!;
|
||||
if (needsUnlock && !Tiers.Unlocks(w, company).Trading)
|
||||
{
|
||||
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;
|
||||
if (!w.Data.TryGoodIndex(goodId ?? "", out good))
|
||||
{
|
||||
error = (CommandError.NotFound, $"Merce sconosciuta: {goodId}");
|
||||
return false;
|
||||
}
|
||||
if (units <= 0)
|
||||
{
|
||||
error = (CommandError.InvalidArgument, "Quantità non valida");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryOwnStation(World w, Company company, StationId id, out Station s, out (CommandError Error, string Message) error)
|
||||
{
|
||||
s = null!;
|
||||
error = default;
|
||||
if (!id.IsValid || id.Value >= w.Network.Stations.Count || !w.Network.IsAlive(w.Network.Stations[id.Value]))
|
||||
{
|
||||
error = (CommandError.NotFound, "Stazione inesistente o demolita");
|
||||
return false;
|
||||
}
|
||||
s = w.Network.Stations[id.Value];
|
||||
if (s.Owner != company.Id)
|
||||
{
|
||||
error = (CommandError.NotAllowed, $"{s.Name} non è una stazione della compagnia");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static long Rounded(double cents) => Money.FromCentsRounded(cents).Cents;
|
||||
|
||||
private static string GoodName(World w, int good) => w.Data.Goods[good].NameIt.ToLowerInvariant();
|
||||
|
||||
private static string Unit(World w, int good) => w.Data.Goods[good].Unit;
|
||||
|
||||
private static string PerUnit(World w, int good, double cents) => $"{Money.FromCentsRounded(cents)}/{Unit(w, good)}";
|
||||
}
|
||||
@@ -24,6 +24,7 @@ public sealed class World
|
||||
Settings = settings;
|
||||
Calendar = new Calendar(data.Balance.Time, settings.StartYear);
|
||||
Clock = new GameClock(Calendar);
|
||||
WorldEvents = new WorldEventState(Clock);
|
||||
Rng = new Rng(settings.Seed);
|
||||
Terrain = terrain;
|
||||
Sampler = new TerrainSampler(terrain);
|
||||
@@ -95,6 +96,9 @@ public sealed class World
|
||||
public GoodsCounters Goods { get; }
|
||||
public EventLog Events { get; } = new();
|
||||
|
||||
/// <summary>Eventi del mondo in corso con i loro effetti temporanei (ADR 0017).</summary>
|
||||
public WorldEventState WorldEvents { get; }
|
||||
|
||||
/// <summary>Avvisi di manutenzione del giorno (non salvati): il server li inoltra come MaintenanceAlert.</summary>
|
||||
public List<FleetAlert> Alerts { get; } = [];
|
||||
|
||||
@@ -184,6 +188,7 @@ public sealed class World
|
||||
{
|
||||
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
|
||||
}
|
||||
sum += s.StockOf(good);
|
||||
}
|
||||
foreach (var tr in Trains)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Time;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation;
|
||||
|
||||
/// <summary>
|
||||
/// Evento del mondo in corso (ADR 0017): tipo del catalogo, bersaglio, bene (per la domanda di un
|
||||
/// bene), giorno d'inizio e di fine e intensità in [0, 1] da cui si ricavano i moltiplicatori.
|
||||
/// </summary>
|
||||
public sealed class ActiveWorldEvent
|
||||
{
|
||||
public required int Id { get; init; }
|
||||
public required WorldEventDef Def { get; init; }
|
||||
/// <summary>Entità bersaglio: industria, città (anche centro di zona e area) o deposito.</summary>
|
||||
public required EntityKind TargetKind { get; init; }
|
||||
public required int Target { get; init; }
|
||||
/// <summary>Bene coinvolto (TownGood), altrimenti −1.</summary>
|
||||
public int Good { get; init; } = -1;
|
||||
public required long StartDay { get; init; }
|
||||
/// <summary>Primo giorno senza l'evento: dura EndDay − StartDay giorni.</summary>
|
||||
public required long EndDay { get; init; }
|
||||
public required double Intensity { get; init; }
|
||||
|
||||
/// <summary>Centro della zona in metri (città bersaglio), per area e domanda di un bene.</summary>
|
||||
public Vec2 Center { get; init; }
|
||||
|
||||
/// <summary>Quadrato del raggio della zona in metri (0 senza zona).</summary>
|
||||
public double RadiusSquaredM { get; init; }
|
||||
|
||||
public int DurationDays => (int)(EndDay - StartDay);
|
||||
|
||||
/// <summary>Vero se l'evento è in vigore nel giorno indicato: [StartDay, EndDay).</summary>
|
||||
public bool InForce(long day) => StartDay <= day && day < EndDay;
|
||||
|
||||
/// <summary>Moltiplicatore dell'effetto indicato (1 se il tipo non ce l'ha).</summary>
|
||||
public double Effect(EventEffectKind kind)
|
||||
{
|
||||
foreach (var e in Def.Effects)
|
||||
{
|
||||
if (e.Kind == kind) return e.At(Intensity);
|
||||
}
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
public bool Has(EventEffectKind kind)
|
||||
{
|
||||
foreach (var e in Def.Effects)
|
||||
{
|
||||
if (e.Kind == kind) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Moltiplicatore dell'effetto principale (il primo del catalogo).</summary>
|
||||
public double Primary => Def.Effects[0].At(Intensity);
|
||||
|
||||
public bool InZone(Vec2 p) => RadiusSquaredM > 0 && (p - Center).LengthSquared <= RadiusSquaredM;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo in corso: unica sorgente dei moltiplicatori temporanei letti dai sistemi. Ogni
|
||||
/// interrogazione restituisce il prodotto degli effetti attivi sull'entità (1 senza eventi), così a
|
||||
/// evento scaduto tutto torna come prima. L'elenco è in ordine d'inizio (id crescente) e contiene
|
||||
/// gli eventi dall'estrazione fino al mattino del primo giorno libero: le interrogazioni contano solo
|
||||
/// quelli in vigore nel giorno dell'orologio (<see cref="ActiveWorldEvent.InForce"/>), così un evento
|
||||
/// estratto oggi agisce da domani anche sui treni e l'ultimo giorno agisce per intero (ADR 0017 §5).
|
||||
/// </summary>
|
||||
public sealed class WorldEventState(GameClock clock)
|
||||
{
|
||||
private readonly List<ActiveWorldEvent> _active = [];
|
||||
private int _areaEvents;
|
||||
|
||||
private long Today => clock.Day;
|
||||
|
||||
public IReadOnlyList<ActiveWorldEvent> Active => _active;
|
||||
|
||||
/// <summary>Prossimo id libero (mai riutilizzato).</summary>
|
||||
public int NextId { get; set; }
|
||||
|
||||
internal void Add(ActiveWorldEvent e)
|
||||
{
|
||||
_active.Add(e);
|
||||
Recount();
|
||||
}
|
||||
|
||||
internal void RemoveAt(int index)
|
||||
{
|
||||
_active.RemoveAt(index);
|
||||
Recount();
|
||||
}
|
||||
|
||||
internal void Clear()
|
||||
{
|
||||
_active.Clear();
|
||||
Recount();
|
||||
}
|
||||
|
||||
private void Recount()
|
||||
{
|
||||
_areaEvents = 0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def.Target == EventTarget.Area) _areaEvents++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Vero se un evento dello stesso tipo è già in corso sullo stesso bersaglio.</summary>
|
||||
public bool IsActive(WorldEventDef def, EntityKind kind, int target)
|
||||
{
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def == def && e.TargetKind == kind && e.Target == target) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Vero se un evento in elenco (anche non ancora iniziato) ha l'effetto indicato.</summary>
|
||||
public bool AnyWith(EventEffectKind kind)
|
||||
{
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Has(kind)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Eventi il cui bersaglio diretto è l'entità (anche non ancora iniziati).</summary>
|
||||
public IEnumerable<ActiveWorldEvent> For(EntityKind kind, int index)
|
||||
{
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.TargetKind == kind && e.Target == index) yield return e;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Capacità produttiva dell'industria (IndustrySystem, DemandSystem).</summary>
|
||||
public double IndustryCapacity(IndustryId industry)
|
||||
{
|
||||
double f = 1.0;
|
||||
long day = Today;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.TargetKind == EntityKind.Industry && e.Target == industry.Value && e.InForce(day)) f *= e.Effect(EventEffectKind.IndustryCapacity);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Domanda della città per un bene: eventi sulla città e sul bene nella zona.</summary>
|
||||
public double TownDemand(Town town, int good)
|
||||
{
|
||||
if (_active.Count == 0) return 1.0;
|
||||
double f = 1.0;
|
||||
long day = Today;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (!e.InForce(day)) continue;
|
||||
switch (e.Def.Target)
|
||||
{
|
||||
case EventTarget.Town when e.Target == town.Id.Value:
|
||||
f *= e.Effect(EventEffectKind.TownDemand);
|
||||
break;
|
||||
case EventTarget.TownGood when e.Good == good && (e.Target == town.Id.Value || e.InZone(town.Position)):
|
||||
f *= e.Effect(EventEffectKind.GoodDemand);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quota dei pendolari che si presenta al lavoro: eventi sulla città di provenienza (epidemia,
|
||||
/// sciopero) e sul deposito di destinazione (sciopero del personale).
|
||||
/// </summary>
|
||||
public double Attendance(TownId town, WorkplaceRef workplace)
|
||||
{
|
||||
if (_active.Count == 0) return 1.0;
|
||||
double f = 1.0;
|
||||
long day = Today;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (!e.InForce(day)) continue;
|
||||
bool hit = e.Def.Target switch
|
||||
{
|
||||
EventTarget.Town => e.Target == town.Value,
|
||||
EventTarget.Depot => workplace.Kind == WorkplaceKind.Depot && e.Target == workplace.Index,
|
||||
_ => false,
|
||||
};
|
||||
if (hit) f *= e.Effect(EventEffectKind.Attendance);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Velocità dei treni sull'arco (TrainSystem, a ogni tick): aree di maltempo in vigore oggi che contengono il suo punto medio.</summary>
|
||||
public double EdgeSpeed(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrainSpeed, Today);
|
||||
|
||||
/// <summary>
|
||||
/// Usura del binario dovuta al traffico sull'arco (ConstructionSystem): il sistema la applica al
|
||||
/// mattino al traffico del giorno prima, quindi conta il maltempo in vigore ieri.
|
||||
/// </summary>
|
||||
public double EdgeWear(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrackWear, Today - 1);
|
||||
|
||||
private double AreaEffect(TrackEdge edge, EventEffectKind kind, long day)
|
||||
{
|
||||
int mid = edge.X.Length / 2;
|
||||
var p = new Vec2(edge.X[mid], edge.Y[mid]);
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def.Target == EventTarget.Area && e.InForce(day) && e.InZone(p)) f *= e.Effect(kind);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,12 @@ public sealed class ClientWorld(GameData data)
|
||||
public Dictionary<int, IndustryCard> IndustryCards { get; } = [];
|
||||
public Chronicle? Chronicle { get; private set; }
|
||||
|
||||
/// <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>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
|
||||
public int TapeVersion { get; private set; }
|
||||
|
||||
@@ -127,6 +133,14 @@ public sealed class ClientWorld(GameData data)
|
||||
Chronicle = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case MarketReport m:
|
||||
Market = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case ClimbReport m:
|
||||
Climb = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case MaintenanceAlert m:
|
||||
Alerts.Insert(0, m);
|
||||
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
|
||||
@@ -146,6 +160,8 @@ public sealed class ClientWorld(GameData data)
|
||||
CompanyCards.Clear();
|
||||
IndustryCards.Clear();
|
||||
Chronicle = null;
|
||||
Market = null;
|
||||
Climb = null;
|
||||
Alerts.Clear();
|
||||
Summary = m.Summary;
|
||||
SessionId = m.SessionId;
|
||||
|
||||
@@ -161,6 +161,12 @@ public static class CommandCodec
|
||||
w.Money(c.Budget);
|
||||
break;
|
||||
case MergeCompanyCommand c: w.I32(c.Subsidiary.Value); break;
|
||||
case ShipGoodsCommand c:
|
||||
w.I32(c.From.Value);
|
||||
w.I32(c.To.Value);
|
||||
w.String(c.Good);
|
||||
w.I32(c.Units);
|
||||
break;
|
||||
default:
|
||||
throw new ProtocolException($"comando senza codifica: {command.Type}");
|
||||
}
|
||||
@@ -225,6 +231,7 @@ public static class CommandCodec
|
||||
CommandType.FundResearch => new FundResearchCommand(r.String(), r.Money()),
|
||||
CommandType.DelegateRegion => new DelegateRegionCommand(new RegionId(r.I32()), r.String(), r.Money()),
|
||||
CommandType.MergeCompany => new MergeCompanyCommand(new CompanyId(r.I32())),
|
||||
CommandType.ShipGoods => new ShipGoodsCommand(new StationId(r.I32()), new StationId(r.I32()), r.String(), r.I32()),
|
||||
_ => throw new ProtocolException($"tipo di comando sconosciuto: {(ushort)type}"),
|
||||
};
|
||||
byte flags = r.Flags();
|
||||
|
||||
@@ -37,10 +37,14 @@ public enum MessageId : ushort
|
||||
IndustryCard = 127,
|
||||
/// <summary>Cronaca finale della partita del giocatore (F5).</summary>
|
||||
Chronicle = 128,
|
||||
/// <summary>Quadro del mercato globale: beni, storico a 24 mesi, previsione, hub (F6).</summary>
|
||||
MarketReport = 129,
|
||||
CommandResult = 130,
|
||||
Notification = 131,
|
||||
Newspaper = 132,
|
||||
SaveList = 133,
|
||||
/// <summary>Quadro della scalata: livelli, sblocchi, requisiti, stato patrimoniale (F6).</summary>
|
||||
ClimbReport = 134,
|
||||
}
|
||||
|
||||
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
|
||||
|
||||
@@ -237,6 +237,10 @@ public enum DetailKind : byte
|
||||
Industry = 5,
|
||||
/// <summary>Cronaca finale (risposta Chronicle, F5; Id ignorato).</summary>
|
||||
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>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,287 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
|
||||
namespace RailEnterprise.Protocol.Messages;
|
||||
|
||||
// Messaggi della fase F6: pannello «Mercato globale» (immagine di riferimento 06). Il quadro del
|
||||
// mercato arriva su richiesta (RequestDetail con DetailKind.Market) ed è calcolato dal server con
|
||||
// MarketOutlook (ADR 0015): il client lo mostra com'è, senza logica di gioco.
|
||||
|
||||
/// <summary>Prezzo globale di un giorno (centesimi per unità).</summary>
|
||||
public sealed class PricePointInfo
|
||||
{
|
||||
public long Day { get; init; }
|
||||
public double Price { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.F64(Price);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static PricePointInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new PricePointInfo { Day = r.I64(), Price = r.F64() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prezzo previsto a una distanza in mesi, con la banda bassa e alta (centesimi).</summary>
|
||||
public sealed class ForecastInfo
|
||||
{
|
||||
public byte Months { get; init; }
|
||||
public double Price { get; init; }
|
||||
public double Low { get; init; }
|
||||
public double High { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Months); w.F64(Price); w.F64(Low); w.F64(High);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ForecastInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new ForecastInfo { Months = r.U8(), Price = r.F64(), Low = r.F64(), High = r.F64() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Destinazione di vendita: Kind 0 industria, 1 hub; Line −1 se la compagnia non la collega.</summary>
|
||||
public sealed class SellPlaceInfo
|
||||
{
|
||||
public const byte Industry = 0;
|
||||
public const byte Hub = 1;
|
||||
|
||||
public byte Kind { get; init; }
|
||||
public int Target { get; init; }
|
||||
public double Price { get; init; }
|
||||
public int Line { get; init; } = -1;
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.I32(Target); w.F64(Price); w.I32(Line);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static SellPlaceInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new SellPlaceInfo { Kind = r.U8(), Target = r.I32(), Price = r.F64(), Line = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Quadro di un bene: prezzo, variazione, offerta e domanda, scorte, storico, previsione, vendite.</summary>
|
||||
public sealed class GoodMarketInfo
|
||||
{
|
||||
public int Good { get; init; }
|
||||
public bool Available { get; init; }
|
||||
public double Price { get; init; }
|
||||
/// <summary>Variazione a 30 giorni (frazione).</summary>
|
||||
public float Change { get; init; }
|
||||
/// <summary>Offerta e domanda della mappa in un mese (unità).</summary>
|
||||
public double SupplyMonth { get; init; }
|
||||
public double DemandMonth { get; init; }
|
||||
/// <summary>Quota mondiale scambiata dagli hub in un mese (unità).</summary>
|
||||
public double WorldSupplyMonth { get; init; }
|
||||
public double WorldDemandMonth { get; init; }
|
||||
public double StockUnits { get; init; }
|
||||
/// <summary>Scorte in mesi di domanda della mappa (−1 senza domanda).</summary>
|
||||
public float StockMonths { get; init; } = -1;
|
||||
public List<PricePointInfo> History { get; init; } = [];
|
||||
public List<ForecastInfo> Forecast { get; init; } = [];
|
||||
public List<SellPlaceInfo> SellPlaces { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Good); w.Bool(Available); w.F64(Price); w.F32(Change);
|
||||
w.F64(SupplyMonth); w.F64(DemandMonth); w.F64(WorldSupplyMonth); w.F64(WorldDemandMonth); w.F64(StockUnits); w.F32(StockMonths);
|
||||
w.Count(History.Count);
|
||||
foreach (var p in History) p.Write(ref w);
|
||||
w.Count(Forecast.Count);
|
||||
foreach (var f in Forecast) f.Write(ref w);
|
||||
w.Count(SellPlaces.Count);
|
||||
foreach (var s in SellPlaces) s.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static GoodMarketInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new GoodMarketInfo
|
||||
{
|
||||
Good = r.I32(), Available = r.Bool(), Price = r.F64(), Change = r.F32(),
|
||||
SupplyMonth = r.F64(), DemandMonth = r.F64(), WorldSupplyMonth = r.F64(), WorldDemandMonth = r.F64(), StockUnits = r.F64(), StockMonths = r.F32(),
|
||||
};
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.History.Add(PricePointInfo.Read(ref r));
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Forecast.Add(ForecastInfo.Read(ref r));
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.SellPlaces.Add(SellPlaceInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Hub verso il mercato mondiale: Kind 0 porto, 1 valico; Line −1 se la compagnia non lo collega.</summary>
|
||||
public sealed class HubMarketInfo
|
||||
{
|
||||
public int Hub { get; init; }
|
||||
public byte Kind { get; init; }
|
||||
public int MonthlyCapacity { get; init; }
|
||||
public float Duty { get; init; }
|
||||
public int UsedThisMonth { get; init; }
|
||||
public int Line { get; init; } = -1;
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Hub); w.U8(Kind); w.I32(MonthlyCapacity); w.F32(Duty); w.I32(UsedThisMonth); w.I32(Line);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static HubMarketInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new HubMarketInfo { Hub = r.I32(), Kind = r.U8(), MonthlyCapacity = r.I32(), Duty = r.F32(), UsedThisMonth = r.I32(), Line = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bene nel magazzino di una stazione della compagnia (compravendita in proprio, ADR 0016): unità
|
||||
/// possedute e quotazione della prossima unità al venditore più conveniente e al compratore migliore
|
||||
/// del bacino (−1 senza controparti), con le unità che offrono o accettano.
|
||||
/// </summary>
|
||||
public sealed class WarehouseGoodInfo
|
||||
{
|
||||
public int Good { get; init; }
|
||||
public int Units { get; init; }
|
||||
public double BuyPrice { get; init; } = -1;
|
||||
public int BuyUnits { get; init; }
|
||||
public double SellPrice { get; init; } = -1;
|
||||
public int SellUnits { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Good); w.I32(Units); w.F64(BuyPrice); w.I32(BuyUnits); w.F64(SellPrice); w.I32(SellUnits);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WarehouseGoodInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WarehouseGoodInfo { Good = r.I32(), Units = r.I32(), BuyPrice = r.F64(), BuyUnits = r.I32(), SellPrice = r.F64(), SellUnits = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Magazzino della compagnia in una sua stazione: capacità, merce in arrivo e beni.</summary>
|
||||
public sealed class WarehouseInfo
|
||||
{
|
||||
public int Station { get; init; }
|
||||
public int Capacity { get; init; }
|
||||
/// <summary>Unità di merce propria in viaggio verso la stazione (occupano già il magazzino).</summary>
|
||||
public int Incoming { get; init; }
|
||||
public List<WarehouseGoodInfo> Goods { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Station); w.I32(Capacity); w.I32(Incoming);
|
||||
w.Count(Goods.Count);
|
||||
foreach (var g in Goods) g.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WarehouseInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WarehouseInfo { Station = r.I32(), Capacity = r.I32(), Incoming = r.I32() };
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Goods.Add(WarehouseGoodInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro del mercato globale per la compagnia della sessione (F6): indice materie prime, beni con
|
||||
/// storico mensile e previsione, hub, evento in corso (shock mondiale ed eventi del mondo sulla domanda
|
||||
/// di un bene) e avanzamento verso la compravendita in proprio.
|
||||
/// </summary>
|
||||
public sealed class MarketReport : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.MarketReport;
|
||||
public long Day { get; init; }
|
||||
/// <summary>Indice materie prime (100 = prezzi base) e variazione a 30 giorni (frazione).</summary>
|
||||
public float Index { get; init; }
|
||||
public float IndexChange { get; init; }
|
||||
public List<GoodMarketInfo> Goods { get; init; } = [];
|
||||
public List<HubMarketInfo> Hubs { get; init; } = [];
|
||||
/// <summary>Evento in corso: bene (−1 nessuno), shock mondiale con segno (frazione del prezzo base), mesi stimati.</summary>
|
||||
public int EventGood { get; init; } = -1;
|
||||
public float EventShock { get; init; }
|
||||
public float EventMonths { get; init; }
|
||||
/// <summary>Compravendita in proprio: sbloccata, livello che la sblocca, avanzamento 0–1 e requisiti.</summary>
|
||||
public bool TradingUnlocked { get; init; }
|
||||
public byte TradingTier { get; init; }
|
||||
public float TradingProgress { get; init; }
|
||||
public Money NetWorth { get; init; }
|
||||
public Money NetWorthRequired { get; init; }
|
||||
public int TownsConnected { get; init; }
|
||||
public int TownsRequired { get; init; }
|
||||
public int TownPopulation { get; init; }
|
||||
public string Rating { get; init; } = "";
|
||||
public string RatingRequired { get; init; } = "";
|
||||
public bool RatingMet { get; init; }
|
||||
/// <summary>Blocco 1: magazzini della compagnia nelle sue stazioni vive (ADR 0016).</summary>
|
||||
public List<WarehouseInfo> Warehouses { get; init; } = [];
|
||||
/// <summary>Blocco 2 (ADR 0017): eventi del mondo in corso sulla domanda di un bene (boom o crollo in una zona).</summary>
|
||||
public List<WorldEventInfo> GoodEvents { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.F32(Index); w.F32(IndexChange);
|
||||
w.Count(Goods.Count);
|
||||
foreach (var g in Goods) g.Write(ref w);
|
||||
w.Count(Hubs.Count);
|
||||
foreach (var h in Hubs) h.Write(ref w);
|
||||
w.I32(EventGood); w.F32(EventShock); w.F32(EventMonths);
|
||||
w.Bool(TradingUnlocked); w.U8(TradingTier); w.F32(TradingProgress); w.Money(NetWorth); w.Money(NetWorthRequired);
|
||||
w.I32(TownsConnected); w.I32(TownsRequired); w.I32(TownPopulation); w.String(Rating); w.String(RatingRequired); w.Bool(RatingMet);
|
||||
w.Flags((byte)((Warehouses.Count > 0 ? 1 : 0) | (GoodEvents.Count > 0 ? 2 : 0)));
|
||||
if (Warehouses.Count > 0)
|
||||
{
|
||||
w.Count(Warehouses.Count);
|
||||
foreach (var h in Warehouses) h.Write(ref w);
|
||||
}
|
||||
if (GoodEvents.Count > 0)
|
||||
{
|
||||
w.Count(GoodEvents.Count);
|
||||
foreach (var e in GoodEvents) e.Write(ref w);
|
||||
}
|
||||
}
|
||||
|
||||
public static MarketReport Read(ref SpanReader r)
|
||||
{
|
||||
long day = r.I64();
|
||||
float index = r.F32(), change = r.F32();
|
||||
var goods = new List<GoodMarketInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) goods.Add(GoodMarketInfo.Read(ref r));
|
||||
var hubs = new List<HubMarketInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) hubs.Add(HubMarketInfo.Read(ref r));
|
||||
var m = new MarketReport
|
||||
{
|
||||
Day = day, Index = index, IndexChange = change, Goods = goods, Hubs = hubs,
|
||||
EventGood = r.I32(), EventShock = r.F32(), EventMonths = r.F32(),
|
||||
TradingUnlocked = r.Bool(), TradingTier = r.U8(), TradingProgress = r.F32(), NetWorth = r.Money(), NetWorthRequired = r.Money(),
|
||||
TownsConnected = r.I32(), TownsRequired = r.I32(), TownPopulation = r.I32(), Rating = r.String(), RatingRequired = r.String(), RatingMet = r.Bool(),
|
||||
};
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Warehouses.Add(WarehouseInfo.Read(ref r));
|
||||
}
|
||||
if ((flags & 2) != 0)
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.GoodEvents.Add(WorldEventInfo.Read(ref r));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ public static class MessageCodec
|
||||
MessageId.CompanyCard => CompanyCard.Read(ref r),
|
||||
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.MarketTape => MarketTape.Read(ref r),
|
||||
MessageId.CommandResult => CommandResultMessage.Read(ref r),
|
||||
MessageId.Notification => Notification.Read(ref r),
|
||||
|
||||
@@ -542,6 +542,49 @@ public sealed class EventInfo : IWritable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evento del mondo in corso (F6, ADR 0017): tipo del catalogo (id di events.json), bersaglio
|
||||
/// (entità come in <see cref="EventInfo"/>), bene (−1 se nessuno), giorni d'inizio e di fine
|
||||
/// (escluso) e valori dei moltiplicatori nell'ordine degli effetti del catalogo.
|
||||
/// </summary>
|
||||
public sealed class WorldEventInfo : IWritable
|
||||
{
|
||||
public int Id { get; init; }
|
||||
public string Type { get; init; } = "";
|
||||
public byte Entity { get; init; }
|
||||
public int EntityIndex { get; init; } = -1;
|
||||
public int Good { get; init; } = -1;
|
||||
public long StartDay { get; init; }
|
||||
public long EndDay { get; init; }
|
||||
public byte Severity { get; init; }
|
||||
public float[] Effects { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Id); w.String(Type); w.U8(Entity); w.I32(EntityIndex); w.I32(Good); w.I64(StartDay); w.I64(EndDay); w.U8(Severity);
|
||||
w.Count(Effects.Length);
|
||||
foreach (float f in Effects) w.F32(f);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WorldEventInfo Read(ref SpanReader r)
|
||||
{
|
||||
int id = r.I32();
|
||||
string type = r.String();
|
||||
byte entity = r.U8();
|
||||
int index = r.I32(), good = r.I32();
|
||||
long start = r.I64(), end = r.I64();
|
||||
byte severity = r.U8();
|
||||
var effects = new float[r.Count()];
|
||||
for (int i = 0; i < effects.Length; i++) effects[i] = r.F32();
|
||||
r.Flags();
|
||||
return new WorldEventInfo
|
||||
{
|
||||
Id = id, Type = type, Entity = entity, EntityIndex = index, Good = good, StartDay = start, EndDay = end, Severity = severity, Effects = effects,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tratto di moto di un treno: arco percorso nel verso indicato tra due progressive.</summary>
|
||||
public readonly record struct MotionSegment(int Edge, bool Forward, double FromS, double ToS)
|
||||
{
|
||||
|
||||
@@ -320,6 +320,8 @@ public sealed class DailyDigest : IMessage
|
||||
public bool Slow { get; init; }
|
||||
public byte Speed { get; init; }
|
||||
public float TickMs { get; init; }
|
||||
/// <summary>Blocco 1 (F6, ADR 0017): eventi del mondo in corso su tutta la mappa.</summary>
|
||||
public List<WorldEventInfo> WorldEvents { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
@@ -329,7 +331,10 @@ public sealed class DailyDigest : IMessage
|
||||
w.Count(Events.Count);
|
||||
foreach (var e in Events) e.Write(ref w);
|
||||
w.U64(StateHash); w.Bool(Slow); w.U8(Speed); w.F32(TickMs);
|
||||
w.Flags(0);
|
||||
w.Flags(WorldEvents.Count > 0 ? (byte)1 : (byte)0);
|
||||
if (WorldEvents.Count == 0) return;
|
||||
w.Count(WorldEvents.Count);
|
||||
foreach (var e in WorldEvents) e.Write(ref w);
|
||||
}
|
||||
|
||||
public static DailyDigest Read(ref SpanReader r)
|
||||
@@ -348,7 +353,11 @@ public sealed class DailyDigest : IMessage
|
||||
Day = day, Tick = tick, Date = date, Cash = cash, NetWorth = worth, Rating = rating, Prices = prices, Events = events,
|
||||
StateHash = r.U64(), Slow = r.Bool(), Speed = r.U8(), TickMs = r.F32(),
|
||||
};
|
||||
r.Flags();
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.WorldEvents.Add(WorldEventInfo.Read(ref r));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -658,6 +658,12 @@ public sealed class GameHost : IDisposable
|
||||
case DetailKind.Chronicle:
|
||||
s.Send(Projection.Chronicle(w));
|
||||
break;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -410,6 +410,7 @@ public static class Projection
|
||||
Slow = slow,
|
||||
Speed = speed,
|
||||
TickMs = tickMs,
|
||||
WorldEvents = w.WorldEvents.Active.Select(WorldEvent).ToList(),
|
||||
};
|
||||
|
||||
/// <summary>Hash di un record serializzato (per i delta per sessione).</summary>
|
||||
@@ -518,4 +519,108 @@ public static class Projection
|
||||
Highlights = report.Highlights,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Quadro del mercato globale per la compagnia della sessione (MarketOutlook, ADR 0015).</summary>
|
||||
public static MarketReport Market(World w, CompanyId company)
|
||||
{
|
||||
var report = MarketOutlook.Build(w, company);
|
||||
var trading = report.Trading;
|
||||
return new MarketReport
|
||||
{
|
||||
Day = report.Day,
|
||||
Index = (float)report.Index,
|
||||
IndexChange = (float)report.IndexChange,
|
||||
Goods = report.Goods.Select(g => new GoodMarketInfo
|
||||
{
|
||||
Good = g.Good, Available = g.Available, Price = g.Price, Change = (float)g.Change,
|
||||
SupplyMonth = g.SupplyMonth, DemandMonth = g.DemandMonth, WorldSupplyMonth = g.WorldSupplyMonth, WorldDemandMonth = g.WorldDemandMonth,
|
||||
StockUnits = g.StockUnits, StockMonths = (float)g.StockMonths,
|
||||
History = g.History.Select(p => new PricePointInfo { Day = p.Day, Price = p.Price }).ToList(),
|
||||
Forecast = g.Forecast.Select(f => new ForecastInfo { Months = (byte)f.Months, Price = f.Price, Low = f.Low, High = f.High }).ToList(),
|
||||
SellPlaces = g.SellPlaces.Select(p => new SellPlaceInfo { Kind = (byte)p.Kind, Target = p.Target, Price = p.Price, Line = p.Line.Value }).ToList(),
|
||||
}).ToList(),
|
||||
Hubs = report.Hubs.Select(h => new HubMarketInfo
|
||||
{
|
||||
Hub = h.Hub.Value, Kind = (byte)h.Kind, MonthlyCapacity = h.MonthlyCapacity, Duty = (float)h.Duty, UsedThisMonth = h.UsedThisMonth, Line = h.Line.Value,
|
||||
}).ToList(),
|
||||
EventGood = report.Event.Good, EventShock = (float)report.Event.Shock, EventMonths = (float)report.Event.Months,
|
||||
TradingUnlocked = trading.Unlocked, TradingTier = (byte)trading.Level, TradingProgress = (float)trading.Fraction,
|
||||
NetWorth = trading.NetWorth, NetWorthRequired = trading.NetWorthRequired, TownsConnected = trading.TownsConnected,
|
||||
TownsRequired = trading.TownsRequired, TownPopulation = trading.TownPopulation, Rating = trading.Rating.ToString(),
|
||||
RatingRequired = trading.RatingRequired.ToString(), RatingMet = trading.RatingMet,
|
||||
Warehouses = Warehouses(w, company),
|
||||
GoodEvents = report.GoodEvents.Select(WorldEvent).ToList(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <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>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
|
||||
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
|
||||
{
|
||||
Id = e.Id, Type = e.Def.Id, Entity = (byte)e.TargetKind, EntityIndex = e.Target, Good = e.Good,
|
||||
StartDay = e.StartDay, EndDay = e.EndDay, Severity = (byte)e.Def.Severity,
|
||||
Effects = e.Def.Effects.Select(x => (float)x.At(e.Intensity)).ToArray(),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Magazzini della compagnia nelle sue stazioni vive (ADR 0016): giacenze, merce in arrivo e
|
||||
/// quotazioni locali dei beni disponibili che si possono comprare, vendere o che sono in magazzino.
|
||||
/// </summary>
|
||||
public static List<WarehouseInfo> Warehouses(World w, CompanyId company)
|
||||
{
|
||||
var list = new List<WarehouseInfo>();
|
||||
if (!company.IsValid) return list;
|
||||
int[]? reserved = null;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (s.Owner != company || !w.Network.IsAlive(s)) continue;
|
||||
reserved ??= TradingMath.ReservedByStation(w);
|
||||
var goods = new List<WarehouseGoodInfo>();
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
{
|
||||
int units = s.StockOf(g);
|
||||
if (units <= 0 && !MarketOutlook.IsAvailable(w, g)) continue;
|
||||
var q = TradingMath.Quote(w, s, g);
|
||||
if (units <= 0 && q.BuyUnits <= 0 && q.SellUnits <= 0) continue;
|
||||
goods.Add(new WarehouseGoodInfo { Good = g, Units = units, BuyPrice = q.BuyPrice, BuyUnits = q.BuyUnits, SellPrice = q.SellPrice, SellUnits = q.SellUnits });
|
||||
}
|
||||
list.Add(new WarehouseInfo { Station = s.Id.Value, Capacity = w.Data.Balance.Trading.WarehouseCapacity, Incoming = reserved[s.Id.Value], Goods = goods });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,7 @@ public sealed class SimulateCommand : IToolCommand
|
||||
for (int g = 0; g < data.GoodCount; g++)
|
||||
{
|
||||
var def = data.Goods[g];
|
||||
double price = w.Market.PriceHistory[g].Average / 100.0;
|
||||
double price = w.Market.PriceHistory[g].AverageOfLast(w.Calendar.DaysPerYear) / 100.0;
|
||||
long produced = w.Goods.Produced[g] - lastProduced[g];
|
||||
long consumed = w.Goods.Consumed[g] - lastConsumed[g];
|
||||
string note = def.Era > year ? "non ancora disponibile" : "";
|
||||
|
||||
@@ -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,237 @@
|
||||
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.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>Mercato globale (F6, ADR 0015): storico a 24 mesi, migrazione della finestra, previsione, analisi.</summary>
|
||||
public static class MarketOutlookTests
|
||||
{
|
||||
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
|
||||
|
||||
[Test(Description = "Una finestra allungata conserva i valori nello stesso ordine e continua a scorrere")]
|
||||
public static void ExtendedWindowKeepsValuesInOrder()
|
||||
{
|
||||
var window = new RollingWindow(5);
|
||||
for (int v = 1; v <= 8; v++) window.Add(v);
|
||||
var longer = window.Extended(10);
|
||||
Assert.Equal(10, longer.Length);
|
||||
Assert.Equal(5, longer.Count);
|
||||
for (int k = 0; k < 5; k++) Assert.Equal(8.0 - k, longer.Ago(k));
|
||||
Assert.Equal(30.0, longer.Sum);
|
||||
longer.Add(9);
|
||||
Assert.Equal(6, longer.Count);
|
||||
Assert.Equal(9.0, longer.Ago(0));
|
||||
Assert.Equal(4.0, longer.Ago(5));
|
||||
Assert.Equal(39.0, longer.Sum);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => window.Extended(4));
|
||||
Assert.Approx(8.5, longer.AverageOfLast(2), 1e-12);
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Un salvataggio con lo storico dei prezzi di 360 giorni si carica con la finestra di 720 e gli stessi prezzi")]
|
||||
public static void OldSavesWithAShortPriceHistoryAreExtended()
|
||||
{
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
var balance = JsonNode.Parse(files["balance.json"])!;
|
||||
balance["market"]!["historyDays"] = 360;
|
||||
balance["market"]!["outlook"]!["historyMonths"] = 12;
|
||||
files["balance.json"] = balance.ToJsonString();
|
||||
var oldData = GameData.Load(new MemoryDataSource(files));
|
||||
Assert.Equal(360, oldData.Balance.Market.HistoryDays);
|
||||
|
||||
var settings = new NewGameSettings { Seed = 1501, SizeKm = 64, DifficultyId = "imprenditore" };
|
||||
var old = WorldFactory.Create(oldData, settings);
|
||||
old.RunDays(400);
|
||||
byte[] save = SaveFile.Save(old, "test");
|
||||
|
||||
var loaded = SaveFile.Load(TestData.Data, save);
|
||||
int expected = TestData.Data.Balance.Market.HistoryDays;
|
||||
Assert.Equal(720, expected);
|
||||
for (int g = 0; g < TestData.Data.GoodCount; g++)
|
||||
{
|
||||
var before = old.Market.PriceHistory[g];
|
||||
var after = loaded.Market.PriceHistory[g];
|
||||
Assert.Equal(expected, after.Length);
|
||||
Assert.Equal(before.Count, after.Count);
|
||||
for (int k = 0; k < before.Count; k++) Assert.Equal(before.Ago(k), after.Ago(k), $"bene {g}, {k} giorni fa");
|
||||
}
|
||||
|
||||
// la partita continua e lo storico cresce oltre i 360 giorni
|
||||
loaded.RunDays(30);
|
||||
Assert.Equal(390, loaded.Market.PriceHistory[0].Count);
|
||||
Assert.True(MarketOutlook.MonthlyHistory(loaded, 0, 24).Count >= 13, "storico mensile oltre l'anno");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Storico mensile: un campione per mese di calendario (l'ultimo giorno) più il giorno corrente, 24 mesi")]
|
||||
public static void MonthlyHistoryTakesOneSamplePerMonth()
|
||||
{
|
||||
var w = TestWorlds.NoAi(1502);
|
||||
w.RunDays(800);
|
||||
w.RunTicks(5); // a metà giornata: il giorno corrente è già nello storico
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
int coal = GoodIndex(w, "coal");
|
||||
var history = MarketOutlook.MonthlyHistory(w, coal, 24);
|
||||
Assert.Equal(24, history.Count);
|
||||
long last = MarketOutlook.LastRecordedDay(w);
|
||||
Assert.Equal(w.Clock.Day, last);
|
||||
Assert.Equal(last, history[^1].Day);
|
||||
Assert.Equal(w.Market.GlobalPrice[coal], history[^1].Price);
|
||||
for (int i = 0; i < history.Count - 1; i++)
|
||||
{
|
||||
Assert.Equal((long)dpm - 1, history[i].Day % dpm, $"campione {i} all'ultimo giorno del mese");
|
||||
if (i > 0) Assert.Equal((long)dpm, history[i].Day - history[i - 1].Day);
|
||||
Assert.Equal(w.Market.PriceHistory[coal].Ago((int)(last - history[i].Day)), history[i].Price);
|
||||
}
|
||||
Assert.True(history[^2].Day < last && last - history[^2].Day <= dpm, "penultimo campione nel mese precedente");
|
||||
|
||||
// all'inizio di un giorno (prima del sistema del mercato) l'ultimo campione è quello di ieri
|
||||
var fresh = TestWorlds.NoAi(1503);
|
||||
fresh.RunDays(45);
|
||||
Assert.Equal(fresh.Clock.Day - 1, MarketOutlook.LastRecordedDay(fresh));
|
||||
var short_ = MarketOutlook.MonthlyHistory(fresh, coal, 24);
|
||||
Assert.Equal(2, short_.Count);
|
||||
Assert.Equal(29L, short_[0].Day);
|
||||
Assert.Equal(44L, short_[1].Day);
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "La previsione segue la componente mondiale, è deterministica, resta entro i limiti e la banda si allarga")]
|
||||
public static void ForecastIsDeterministicAndWithinLimits()
|
||||
{
|
||||
var a = TestWorlds.NoAi(1504);
|
||||
var b = TestWorlds.NoAi(1504);
|
||||
a.RunDays(200);
|
||||
b.RunDays(200);
|
||||
var m = a.Data.Balance.Market;
|
||||
for (int g = 0; g < a.Data.GoodCount; g++)
|
||||
{
|
||||
var fa = MarketOutlook.Forecast(a, g);
|
||||
var fb = MarketOutlook.Forecast(b, g);
|
||||
Assert.SequenceEqual(fa, fb, $"previsione del bene {g}");
|
||||
Assert.Equal(m.Outlook.ForecastMonths, fa.Count);
|
||||
double pb = a.Data.Goods[g].BasePrice;
|
||||
for (int i = 0; i < fa.Count; i++)
|
||||
{
|
||||
var p = fa[i];
|
||||
Assert.Equal(i + 1, p.Months);
|
||||
Assert.InRange(p.Price, m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
|
||||
Assert.True(p.Low <= p.Price && p.Price <= p.High, $"banda del bene {g} al mese {p.Months}");
|
||||
Assert.InRange(p.Low, m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
|
||||
Assert.InRange(p.High, m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
|
||||
}
|
||||
}
|
||||
|
||||
// uno shock positivo forte decade: il prezzo previsto scende mese dopo mese e la banda si allarga
|
||||
int coal = GoodIndex(a, "coal");
|
||||
a.Market.GlobalPrice[coal] = a.Data.Goods[coal].BasePrice;
|
||||
for (int g = 0; g < a.Data.GoodCount; g++) a.Market.Shock[g] = 0;
|
||||
a.Market.Shock[coal] = 0.25;
|
||||
var forecast = MarketOutlook.Forecast(a, coal);
|
||||
Assert.True(forecast[^1].Price < a.Market.GlobalPrice[coal], $"previsione {forecast[^1].Price:0} sotto il prezzo attuale");
|
||||
for (int i = 1; i < forecast.Count; i++)
|
||||
{
|
||||
Assert.True(forecast[i].Price < forecast[i - 1].Price, $"mese {i + 1} sotto il mese {i}");
|
||||
Assert.True(forecast[i].High / forecast[i].Price > forecast[i - 1].High / forecast[i - 1].Price, "la banda si allarga");
|
||||
}
|
||||
|
||||
// lo stesso shock è l'evento in corso, con i mesi prima che scenda sotto la soglia
|
||||
var e = MarketOutlook.StrongestEvent(a);
|
||||
Assert.Equal(coal, e.Good);
|
||||
Assert.Equal(0.25, e.Shock);
|
||||
double months = m.World.ShockDecayDays * Math.Log(0.25 / m.Outlook.EventThreshold) / a.Calendar.DaysPerMonth;
|
||||
Assert.Approx(months, e.Months, 1e-6);
|
||||
a.Market.Shock[coal] = -m.Outlook.EventThreshold / 2;
|
||||
Assert.Equal(-1, MarketOutlook.StrongestEvent(a).Good);
|
||||
}
|
||||
|
||||
[Test(Description = "Analisi del mercato su Valdoria: beni, vendite ordinate con la linea che collega, hub, indice, commercio; nessun effetto sul mondo")]
|
||||
public static void OutlookOnValdoria()
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var w = f.W;
|
||||
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)) }));
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
|
||||
// la linea senza treni non collega
|
||||
Assert.False(MarketOutlook.IndustryLine(w, f.Me, MarketOutlook.StationLines(w, f.Me), steel.Id).IsValid, "linea senza treni");
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
w.RunDays(40);
|
||||
var lines = MarketOutlook.StationLines(w, f.Me);
|
||||
Assert.Equal(line, MarketOutlook.IndustryLine(w, f.Me, lines, steel.Id).Value);
|
||||
Assert.False(MarketOutlook.IndustryLine(w, CompanyId.None, MarketOutlook.StationLines(w, CompanyId.None), steel.Id).IsValid);
|
||||
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
var report = MarketOutlook.Build(w, f.Me);
|
||||
Assert.Equal(hash, StateHasher.Compute(w), "l'analisi non cambia il mondo");
|
||||
|
||||
Assert.Equal(w.Data.GoodCount, report.Goods.Count);
|
||||
Assert.Equal(w.Hubs.Count, report.Hubs.Count);
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var good = report.Goods[ore];
|
||||
Assert.True(good.Available);
|
||||
Assert.Equal(w.Market.GlobalPrice[ore], good.Price);
|
||||
Assert.True(good.History.Count >= 2, "storico di almeno due mesi");
|
||||
Assert.True(good.SellPlaces.Count is > 0 and <= 3, $"destinazioni: {good.SellPlaces.Count}");
|
||||
for (int i = 1; i < good.SellPlaces.Count; i++) Assert.True(good.SellPlaces[i - 1].Price >= good.SellPlaces[i].Price, "ordinate per prezzo");
|
||||
|
||||
// ogni destinazione industriale consuma il bene, con il prezzo locale dell'ADR 0004
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
foreach (var p in good.SellPlaces)
|
||||
{
|
||||
if (p.Kind == SellPlaceKind.Hub)
|
||||
{
|
||||
Assert.Equal(w.Hubs[p.Target].BuyPrice(good.Price), p.Price);
|
||||
continue;
|
||||
}
|
||||
var ind = w.Industries[p.Target];
|
||||
int input = ind.InputIndexOf(ore);
|
||||
Assert.True(input >= 0 && !ind.Closed && ind.Level > 0, $"{ind.Name} consuma minerale");
|
||||
Assert.InRange(p.Price, good.Price * (1 - lp.MaxDeviation) - 1e-9, good.Price * (1 + lp.MaxDeviation) + 1e-9);
|
||||
Assert.Equal(MarketOutlook.IndustryLine(w, f.Me, lines, ind.Id), p.Line);
|
||||
}
|
||||
|
||||
// tutte le industrie che consumano minerale e gli hub sono candidati: il migliore è davvero il primo
|
||||
double best = w.Hubs.Select(h => h.BuyPrice(good.Price)).Concat(w.Industries
|
||||
.Where(i => !i.Closed && i.Level > 0 && i.InputIndexOf(ore) >= 0)
|
||||
.Select(i => Market.LocalPrice(good.Price, Core.Simulation.Systems.IndustryMath.InputCapacity(i, i.InputIndexOf(ore), w.Calendar.DaysPerMonth), i.InputStock[i.InputIndexOf(ore)], lp)))
|
||||
.Max();
|
||||
Assert.Equal(best, good.SellPlaces[0].Price);
|
||||
|
||||
// scorte e domanda
|
||||
Assert.Equal(MarketOutlook.StockUnits(w, ore), good.StockUnits);
|
||||
if (good.DemandMonth > 0) Assert.Approx(good.StockUnits / good.DemandMonth, good.StockMonths, 1e-9);
|
||||
Assert.True(good.WorldDemandMonth > 0 && good.WorldSupplyMonth > 0, "quota mondiale");
|
||||
|
||||
// indice materie prime: media di Pg/Pb × 100 sui beni disponibili
|
||||
var available = Enumerable.Range(0, w.Data.GoodCount).Where(g => w.Data.Goods[g].Era <= w.Clock.Year).ToList();
|
||||
Assert.Approx(available.Average(g => w.Market.GlobalPrice[g] / w.Data.Goods[g].BasePrice) * 100, report.Index, 1e-9);
|
||||
foreach (var g in report.Goods.Where(g => !g.Available)) Assert.Equal(0, g.SellPlaces.Count);
|
||||
|
||||
// hub: nessuna stazione della compagnia al porto
|
||||
Assert.True(report.Hubs.All(h => !h.Line.IsValid), "hub non collegati");
|
||||
Assert.Equal(w.Hubs[0].MonthlyCapacity, report.Hubs[0].MonthlyCapacity);
|
||||
|
||||
// compravendita in proprio: dal livello 2 di tiers.json
|
||||
var trading = report.Trading;
|
||||
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading);
|
||||
Assert.Equal(tier.Level, trading.Level);
|
||||
Assert.False(trading.Unlocked);
|
||||
Assert.Equal(tier.Requirements.CreditRating, trading.RatingRequired);
|
||||
Assert.InRange(trading.Fraction, 0, 1);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
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.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
using static RailEnterprise.Tests.Rail.RailFixture;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>Compravendita in proprio e spedizione della merce tra stazioni (F6, issue #31, ADR 0016).</summary>
|
||||
public static class TradingTests
|
||||
{
|
||||
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
|
||||
|
||||
private static void AssertInvariants(World w, string when)
|
||||
{
|
||||
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro {when}");
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} {when}");
|
||||
}
|
||||
|
||||
/// <summary>Merce creata dal test nel magazzino di una stazione, contabilizzata come prodotta (ADR 0004 §4).</summary>
|
||||
private static void Inject(World w, Station s, int good, int units)
|
||||
{
|
||||
TradingMath.AddToWarehouse(s, good, units, w.Data.GoodCount);
|
||||
w.Goods.Produced[good] += units;
|
||||
}
|
||||
|
||||
private static void Unlock(World w) => w.Player.Tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading).Level;
|
||||
|
||||
/// <summary>Valdoria con le stazioni delle miniere, dell'acciaieria e del porto, senza binari.</summary>
|
||||
private static (RailFixture F, Station Mine, Station Mill, Station Port) Stations()
|
||||
{
|
||||
var f = Valdoria();
|
||||
int mine = f.Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
|
||||
int mill = f.Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
|
||||
int port = f.Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
|
||||
var net = f.W.Network;
|
||||
return (f, net.Stations[mine], net.Stations[mill], net.Stations[port]);
|
||||
}
|
||||
|
||||
[Test(Description = "Compra dal produttore del bacino al prezzo locale marginale: prezzo, cassa, registro e giacenze esatti")]
|
||||
public static void BuyFromProducerAtTheLocalPrice()
|
||||
{
|
||||
var (f, mine, _, _) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var producer = w.Industries.First(i => i.Def.Id == "iron_mine");
|
||||
Assert.True(mine.Industries.Contains(producer.Id), "la miniera è nel bacino");
|
||||
int cap = IndustryMath.OutputCapacity(producer, 0, w.Calendar.DaysPerMonth);
|
||||
int start = cap / 2;
|
||||
Assert.True(start > 60, $"capienza del minerale della miniera: {cap}");
|
||||
w.Goods.Produced[ore] += start - producer.OutputStock[0];
|
||||
producer.OutputStock[0] = start;
|
||||
|
||||
// prezzo atteso: ogni unità al prezzo locale con la giacenza che resta (Dl = spazio libero, Sl = giacenza)
|
||||
const int units = 40;
|
||||
double pg = w.Market.GlobalPrice[ore];
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
double expected = 0;
|
||||
for (int k = 0; k < units; k++) expected += Market.LocalPrice(pg, cap - (start - k), start - k, lp);
|
||||
Assert.Approx(pg, Market.LocalPrice(pg, cap - start, start, lp), pg * 0.02, "a metà magazzino il prezzo è quello globale");
|
||||
var cost = Money.FromCentsRounded(expected);
|
||||
var cash = w.Player.Cash;
|
||||
var industryCash = producer.Cash;
|
||||
long trading = w.Player.MonthEntries[(int)LedgerEntry.Trading];
|
||||
|
||||
var r = f.Do(new BuyGoodsCommand(mine.Id, "iron_ore", units, Money.FromLire(1000)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.True(r.Message.Contains("Comprate 40 t", StringComparison.Ordinal), r.Message);
|
||||
Assert.Equal(units, mine.StockOf(ore));
|
||||
Assert.Equal(cash - cost, w.Player.Cash);
|
||||
Assert.Equal(industryCash + cost, producer.Cash);
|
||||
Assert.Equal(trading - cost.Cents, w.Player.MonthEntries[(int)LedgerEntry.Trading]);
|
||||
Assert.True(producer.LastServedDay >= w.Clock.Day - 1, "la miniera è servita");
|
||||
AssertInvariants(w, "dopo l'acquisto");
|
||||
|
||||
// il prezzo sale man mano che il produttore si svuota: con un tetto sotto il prossimo prezzo si compra meno
|
||||
double next = Market.LocalPrice(pg, cap - (producer.OutputStock[0]), producer.OutputStock[0], lp);
|
||||
var capped = f.Do(new BuyGoodsCommand(mine.Id, "iron_ore", 1000, Money.FromCentsRounded(next + 30)));
|
||||
Assert.True(capped.Ok, capped.Message);
|
||||
Assert.True(mine.StockOf(ore) > units && mine.StockOf(ore) < units + start - units, $"comprate {mine.StockOf(ore) - units} unità sotto il tetto");
|
||||
Assert.True(capped.Message.Contains("tetto", StringComparison.Ordinal), capped.Message);
|
||||
AssertInvariants(w, "dopo l'acquisto con il tetto");
|
||||
}
|
||||
|
||||
[Test(Description = "Compra dall'hub del bacino al prezzo d'importazione: conta come importato e usa la capacità dell'hub")]
|
||||
public static void BuyFromHubCountsAsImported()
|
||||
{
|
||||
var (f, _, _, port) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int coal = GoodIndex(w, "coal");
|
||||
var hub = w.Hubs[0];
|
||||
Assert.True(port.Hubs.Contains(hub.Id), "il porto è nel bacino");
|
||||
int imported = (int)w.Goods.Imported[coal];
|
||||
int used = hub.UsedThisMonth;
|
||||
double price = hub.SellPrice(w.Market.GlobalPrice[coal]);
|
||||
var cash = w.Player.Cash;
|
||||
var external = w.Money.External;
|
||||
|
||||
var r = f.Do(new BuyGoodsCommand(port.Id, "coal", 60, Money.FromCentsRounded(price + 1)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(60, port.StockOf(coal));
|
||||
Assert.Equal(imported + 60L, w.Goods.Imported[coal]);
|
||||
Assert.Equal(used + 60, hub.UsedThisMonth);
|
||||
Assert.Approx(60 * price, (cash - w.Player.Cash).Cents, 1);
|
||||
Assert.Equal(external + (cash - w.Player.Cash), w.Money.External);
|
||||
AssertInvariants(w, "dopo l'importazione");
|
||||
|
||||
// il tetto sotto il prezzo dell'hub rifiuta senza cambiare nulla
|
||||
var refused = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromCentsRounded(price - 100)));
|
||||
Assert.Equal(CommandError.InvalidArgument, refused.Error);
|
||||
Assert.Equal(60, port.StockOf(coal));
|
||||
}
|
||||
|
||||
[Test(Description = "Vende al consumatore del bacino al prezzo locale (decrescente), entro spazio e cassa dell'industria")]
|
||||
public static void SellToConsumerWithinSpaceAndCash()
|
||||
{
|
||||
var (f, _, mill, _) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
int input = steel.InputIndexOf(ore);
|
||||
int desired = IndustryMath.InputCapacity(steel, input, w.Calendar.DaysPerMonth);
|
||||
Assert.True(mill.Industries.Contains(steel.Id) && desired > 10, $"acciaieria nel bacino, capienza {desired}");
|
||||
w.Goods.Consumed[ore] += steel.InputStock[input];
|
||||
steel.InputStock[input] = 0;
|
||||
Inject(w, mill, ore, desired + 50);
|
||||
// cassa dell'acciaieria abbondante
|
||||
w.Money.Transfer(Account.External, Account.Of(steel.Id), Money.FromLire(1_000_000), LedgerEntry.Other);
|
||||
|
||||
double pg = w.Market.GlobalPrice[ore];
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
int units = desired / 2;
|
||||
double expected = 0;
|
||||
for (int k = 0; k < units; k++) expected += Market.LocalPrice(pg, desired, k, lp);
|
||||
Assert.True(Market.LocalPrice(pg, desired, 0, lp) > pg * 1.3, "a magazzino vuoto il consumatore paga di più");
|
||||
var cash = w.Player.Cash;
|
||||
var r = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", units, Money.FromLire(1)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(units, steel.InputStock[input]);
|
||||
Assert.Equal(desired + 50 - units, mill.StockOf(ore));
|
||||
Assert.Equal(cash + Money.FromCentsRounded(expected), w.Player.Cash);
|
||||
AssertInvariants(w, "dopo la vendita");
|
||||
|
||||
// il prezzo minimo sopra quello offerto rifiuta
|
||||
var refused = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 5, Money.FromLire(10_000)));
|
||||
Assert.Equal(CommandError.InvalidArgument, refused.Error);
|
||||
|
||||
// un'industria con poca cassa compra solo quanto può pagare
|
||||
w.Money.Transfer(Account.Of(steel.Id), Account.External, steel.Cash, LedgerEntry.Other);
|
||||
double one = Market.LocalPrice(pg, desired, steel.InputStock[input], lp);
|
||||
w.Money.Transfer(Account.External, Account.Of(steel.Id), Money.FromCentsRounded(one * 3.5), LedgerEntry.Other);
|
||||
var poor = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 20, Money.FromLire(1)));
|
||||
Assert.True(poor.Ok, poor.Message);
|
||||
Assert.Equal(units + 3, steel.InputStock[input]);
|
||||
Assert.True(steel.Cash.Cents >= 0, "l'industria non va in rosso");
|
||||
AssertInvariants(w, "dopo la vendita a credito limitato");
|
||||
|
||||
// senza cassa nessuna vendita
|
||||
w.Money.Transfer(Account.Of(steel.Id), Account.External, steel.Cash, LedgerEntry.Other);
|
||||
Assert.Equal(CommandError.InsufficientFunds, f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 5, Money.FromLire(1))).Error);
|
||||
}
|
||||
|
||||
[Test(Description = "Vende all'hub del bacino al prezzo d'esportazione: conta come esportato")]
|
||||
public static void SellToHubCountsAsExported()
|
||||
{
|
||||
var (f, _, _, port) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int coal = GoodIndex(w, "coal");
|
||||
var hub = w.Hubs[0];
|
||||
Inject(w, port, coal, 40);
|
||||
long exported = w.Goods.Exported[coal];
|
||||
double price = hub.BuyPrice(w.Market.GlobalPrice[coal]);
|
||||
var cash = w.Player.Cash;
|
||||
var r = f.Do(new SellGoodsCommand(port.Id, "coal", 100, Money.FromCentsRounded(price - 1)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(0, port.StockOf(coal));
|
||||
Assert.Equal(exported + 40, w.Goods.Exported[coal]);
|
||||
Assert.Approx(40 * price, (w.Player.Cash - cash).Cents, 1);
|
||||
AssertInvariants(w, "dopo l'esportazione");
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new SellGoodsCommand(port.Id, "coal", 1, Money.Zero)).Error);
|
||||
}
|
||||
|
||||
[Test(Description = "Rifiuti: livello, stazione altrui o demolita, merce sconosciuta o dell'era futura, prezzo, cassa, magazzino pieno")]
|
||||
public static void InvalidTradesAreRefusedWithoutEffects()
|
||||
{
|
||||
var (f, mine, mill, port) = Stations();
|
||||
var w = f.W;
|
||||
int coal = GoodIndex(w, "coal");
|
||||
Assert.Equal(1, w.Player.Tier);
|
||||
var locked = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)));
|
||||
Assert.Equal(CommandError.TierLocked, locked.Error);
|
||||
Assert.True(locked.Message.Contains("Compagnia regionale", StringComparison.Ordinal), locked.Message);
|
||||
// senza lo sblocco la merce già in magazzino (per esempio ereditata da una fusione) si vende e si spedisce
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new ShipGoodsCommand(port.Id, mill.Id, "coal", 1)).Error, "magazzino vuoto, non livello");
|
||||
Inject(w, port, coal, 5);
|
||||
var inherited = f.Do(new SellGoodsCommand(port.Id, "coal", 5, Money.FromLire(1)));
|
||||
Assert.True(inherited.Ok, inherited.Message);
|
||||
Assert.Equal(0, port.StockOf(coal));
|
||||
Unlock(w);
|
||||
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(port.Id, "unobtainium", 10, Money.FromLire(1000))).Error);
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(new StationId(999), "coal", 10, Money.FromLire(1000))).Error);
|
||||
Assert.Equal(CommandError.InvalidArgument, f.Do(new BuyGoodsCommand(port.Id, "coal", 0, Money.FromLire(1000))).Error);
|
||||
var future = w.Data.Goods.First(g => g.Era > w.Clock.Year);
|
||||
Assert.Equal(CommandError.EraLocked, f.Do(new BuyGoodsCommand(port.Id, future.Id, 10, Money.FromLire(1000))).Error);
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(mill.Id, "goods", 10, Money.FromLire(1000))).Error, "nessun venditore");
|
||||
|
||||
// stazione di un'altra compagnia
|
||||
var owner = port.Owner;
|
||||
port.Owner = new CompanyId(owner.Value + 1);
|
||||
var foreign = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)));
|
||||
Assert.Equal(CommandError.NotAllowed, foreign.Error);
|
||||
port.Owner = owner;
|
||||
|
||||
// cassa insufficiente
|
||||
var cash = w.Player.Cash;
|
||||
w.Money.Transfer(Account.Of(f.Me), Account.External, cash, LedgerEntry.Other);
|
||||
Assert.Equal(CommandError.InsufficientFunds, f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000))).Error);
|
||||
w.Money.Transfer(Account.External, Account.Of(f.Me), cash, LedgerEntry.Other);
|
||||
|
||||
// magazzino pieno
|
||||
int capacity = w.Data.Balance.Trading.WarehouseCapacity;
|
||||
Inject(w, port, coal, capacity);
|
||||
var full = f.Do(new BuyGoodsCommand(port.Id, "coal", 1, Money.FromLire(1000)));
|
||||
Assert.Equal(CommandError.Blocked, full.Error);
|
||||
Assert.Equal(capacity, port.StockOf(coal));
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new ShipGoodsCommand(port.Id, mine.Id, "coal", 10)).Error, "nessun percorso");
|
||||
Assert.Equal(CommandError.InvalidArgument, f.Do(new ShipGoodsCommand(port.Id, port.Id, "coal", 10)).Error);
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new SellGoodsCommand(mine.Id, "coal", 10, Money.Zero)).Error, "magazzino vuoto");
|
||||
|
||||
// una stazione con merce in magazzino non si demolisce
|
||||
var demolish = f.Do(new DemolishCommand(DemolishTarget.Station, port.Id.Value));
|
||||
Assert.Equal(CommandError.NotAllowed, demolish.Error);
|
||||
Assert.True(w.Network.IsAlive(port));
|
||||
AssertInvariants(w, "dopo i rifiuti");
|
||||
}
|
||||
|
||||
[Test(Description = "Una stazione con merce della compagnia in attesa di partire o in arrivo non si demolisce")]
|
||||
public static void StationsWithOwnedGoodsInTransitAreNotDemolished()
|
||||
{
|
||||
var (f, mine, _, port) = Stations();
|
||||
var w = f.W;
|
||||
int coal = GoodIndex(w, "coal");
|
||||
port.Waiting.Add(new Packet
|
||||
{
|
||||
Id = w.NextIds.Packet++, Kind = PacketKind.Freight, Good = coal, Units = 30, Origin = port.Id, Destination = mine.Id,
|
||||
HopLine = LineId.None, HopEnd = mine.Id, CreatedTick = w.Context.Tick, ExpiresTick = w.Context.Tick + w.Calendar.TicksPerDay * 30,
|
||||
Contract = -1, Owned = true,
|
||||
});
|
||||
w.Goods.Produced[coal] += 30;
|
||||
var leaving = f.Do(new DemolishCommand(DemolishTarget.Station, port.Id.Value));
|
||||
Assert.Equal(CommandError.NotAllowed, leaving.Error, leaving.Message);
|
||||
var arriving = f.Do(new DemolishCommand(DemolishTarget.Station, mine.Id.Value));
|
||||
Assert.Equal(CommandError.NotAllowed, arriving.Error, arriving.Message);
|
||||
Assert.True(w.Network.IsAlive(port) && w.Network.IsAlive(mine));
|
||||
Assert.Equal(30, port.Waiting.Single(p => p.Owned).Units);
|
||||
|
||||
// senza linee il giorno dopo la merce torna nel magazzino della stazione, che resta da svuotare
|
||||
w.RunDays(1);
|
||||
Assert.False(port.Waiting.Any(p => p.Owned), "nessun pacchetto proprio in attesa");
|
||||
Assert.Equal(30, port.StockOf(coal));
|
||||
Assert.Equal(0, TradingMath.ReservedByStation(w)[mine.Id.Value]);
|
||||
AssertInvariants(w, "dopo il rientro in magazzino");
|
||||
}
|
||||
|
||||
[Test(Description = "La merce in magazzino e in viaggio entra nel valore contabile al prezzo globale")]
|
||||
public static void OwnedGoodsCountInTheBookValue()
|
||||
{
|
||||
var (f, mine, _, port) = Stations();
|
||||
var w = f.W;
|
||||
int coal = GoodIndex(w, "coal");
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
FinanceSystem.UpdateBookValues(w);
|
||||
var before = w.Player.AssetBookValue;
|
||||
Inject(w, port, coal, 100);
|
||||
mine.Waiting.Add(new Packet
|
||||
{
|
||||
Id = w.NextIds.Packet++, Kind = PacketKind.Freight, Good = ore, Units = 40, Origin = mine.Id, Destination = port.Id,
|
||||
HopLine = LineId.None, HopEnd = port.Id, CreatedTick = 0, ExpiresTick = long.MaxValue, Contract = -1, Owned = true,
|
||||
});
|
||||
w.Goods.Produced[ore] += 40;
|
||||
FinanceSystem.UpdateBookValues(w);
|
||||
long expected = (long)(100 * w.Market.GlobalPrice[coal]) + (long)(40 * w.Market.GlobalPrice[ore]);
|
||||
Assert.Equal(expected, (w.Player.AssetBookValue - before).Cents);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rete merci di Valdoria con un treno di carri coperti tra le miniere e l'acciaieria: la linea non
|
||||
/// porta minerale né acciaio, quindi le uniche merci a bordo sono quelle spedite dalla compagnia.
|
||||
/// </summary>
|
||||
private static (RailFixture F, Station Mine, Station Mill, Train Train) BoxLine()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int train = f.Train(depot, "Coperti 1", ("loco_steam_1850", 1), ("wagon_box", 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)));
|
||||
Unlock(f.W);
|
||||
return (f, f.W.Network.Stations[mine], f.W.Network.Stations[mill], f.W.Trains[train]);
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Spedizione tra due stazioni della compagnia: consegnata nel magazzino di destinazione, senza tariffa né consumatori")]
|
||||
public static void ShippedGoodsReachTheDestinationWarehouseWithoutFare()
|
||||
{
|
||||
var (f, mine, mill, train) = BoxLine();
|
||||
var w = f.W;
|
||||
int goods = GoodIndex(w, "goods");
|
||||
Inject(w, mine, goods, 50);
|
||||
|
||||
var r = f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 80));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(1, r.Created.Length);
|
||||
Assert.Equal(0, mine.StockOf(goods));
|
||||
Assert.Equal(50, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
Assert.Equal(w.Data.Balance.Trading.WarehouseCapacity - 50, TradingMath.FreeSpace(w, mill, 50));
|
||||
var packet = mine.Waiting.Single(p => p.Owned);
|
||||
Assert.Equal(r.Created[0], packet.Id);
|
||||
Assert.Equal(0, mill.Incoming[goods]);
|
||||
AssertInvariants(w, "alla spedizione");
|
||||
|
||||
// ricavi merci giorno per giorno (le voci annuali si azzerano a capodanno)
|
||||
long revenue = 0, before = w.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
|
||||
int year = w.Clock.Year;
|
||||
bool onBoard = false;
|
||||
bool arrived = f.RunUntil(() =>
|
||||
{
|
||||
onBoard |= train.Cargo.Any(p => p.Owned);
|
||||
long now = w.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
|
||||
if (w.Clock.Year != year)
|
||||
{
|
||||
revenue += w.Player.LastYearEntries[(int)LedgerEntry.FreightRevenue] - before;
|
||||
before = 0;
|
||||
year = w.Clock.Year;
|
||||
}
|
||||
revenue += now - before;
|
||||
before = now;
|
||||
return mill.StockOf(goods) == 50;
|
||||
}, 120);
|
||||
Assert.True(arrived, "la merce arriva all'acciaieria");
|
||||
Assert.True(onBoard, "la merce ha viaggiato sul treno");
|
||||
Assert.Equal(0L, revenue, "nessuna tariffa per la merce propria");
|
||||
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
Assert.False(mill.Waiting.Any(p => p.Owned) || train.Cargo.Any(p => p.Owned), "nessun pacchetto proprio rimasto");
|
||||
AssertInvariants(w, "all'arrivo");
|
||||
|
||||
// il magazzino pieno a destinazione rifiuta la spedizione a priori
|
||||
Inject(w, mine, goods, 10);
|
||||
Inject(w, mill, goods, w.Data.Balance.Trading.WarehouseCapacity - 50);
|
||||
Assert.Equal(CommandError.Blocked, f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 10)).Error);
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Non si spedisce dove la fermata di partenza non carica; una linea modificata riporta in magazzino la merce in attesa")]
|
||||
public static void ShippingFollowsTheLoadAndUnloadFlagsOfTheStops()
|
||||
{
|
||||
var (f, mine, mill, train) = BoxLine();
|
||||
var w = f.W;
|
||||
int goods = GoodIndex(w, "goods");
|
||||
var line = train.Line;
|
||||
Inject(w, mine, goods, 60);
|
||||
f.Ok(new EditLineCommand(line, new[] { new LineStop(mine.Id, Load: false), new LineStop(mill.Id) }));
|
||||
var refused = f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 60));
|
||||
Assert.Equal(CommandError.Blocked, refused.Error, refused.Message);
|
||||
Assert.Equal(60, mine.StockOf(goods));
|
||||
Assert.False(mine.Waiting.Any(p => p.Owned), "nessun pacchetto creato");
|
||||
|
||||
// spedita con la fermata che carica, poi la linea smette di caricare lì prima che passi il treno
|
||||
f.Ok(new EditLineCommand(line, new[] { new LineStop(mine.Id), new LineStop(mill.Id) }));
|
||||
Assert.True(f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 60)).Ok);
|
||||
Assert.Equal(0, mine.StockOf(goods));
|
||||
f.Ok(new EditLineCommand(line, new[] { new LineStop(mine.Id, Load: false), new LineStop(mill.Id) }));
|
||||
w.RunDays(1);
|
||||
Assert.False(mine.Waiting.Any(p => p.Owned) || train.Cargo.Any(p => p.Owned), "il pacchetto non aspetta più un treno che non lo carica");
|
||||
Assert.Equal(60, mine.StockOf(goods));
|
||||
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
AssertInvariants(w, "dopo il rientro in magazzino");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Un treno che lascia la linea con merce propria a bordo la lascia in un magazzino e libera lo spazio prenotato")]
|
||||
public static void OwnedCargoLeavesATrainTakenOffItsLine()
|
||||
{
|
||||
var (f, mine, mill, train) = BoxLine();
|
||||
var w = f.W;
|
||||
int goods = GoodIndex(w, "goods");
|
||||
Inject(w, mine, goods, 50);
|
||||
Assert.True(f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 50)).Ok);
|
||||
Assert.True(f.RunUntil(() => train.Cargo.Any(p => p.Owned) && !train.AtNode.IsValid, 60), "la merce è a bordo e il treno in viaggio");
|
||||
Assert.Equal(50, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
|
||||
f.Ok(new AssignTrainCommand(train.Id, LineId.None));
|
||||
Assert.False(train.Cargo.Any(p => p.Owned), "nessun pacchetto proprio a bordo");
|
||||
Assert.True(train.Vehicles.All(v => w.Vehicles[v.Value].Load == 0), "carri vuoti");
|
||||
// in viaggio verso l'acciaieria, che è la destinazione: la merce entra nel suo magazzino
|
||||
Assert.Equal(50, mill.StockOf(goods));
|
||||
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
AssertInvariants(w, "dopo il ritiro del treno");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Una linea modificata con la merce propria a bordo: scende alla prima fermata e torna in magazzino")]
|
||||
public static void OwnedCargoOffTheEditedLineIsUnloaded()
|
||||
{
|
||||
var (f, mine, mill, train) = BoxLine();
|
||||
var w = f.W;
|
||||
int goods = GoodIndex(w, "goods");
|
||||
Inject(w, mine, goods, 50);
|
||||
Assert.True(f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 50)).Ok);
|
||||
Assert.True(f.RunUntil(() => train.Cargo.Any(p => p.Owned) && !train.AtNode.IsValid, 60), "la merce è a bordo e il treno in viaggio");
|
||||
|
||||
// la linea non arriva più all'acciaieria: il treno torna alle miniere
|
||||
f.Ok(new EditLineCommand(train.Line, new[] { new LineStop(mine.Id), new LineStop(mine.Id) }));
|
||||
Assert.True(f.RunUntil(() => !train.Cargo.Any(p => p.Owned), 60), "la merce scende dal treno");
|
||||
Assert.Equal(50, mine.StockOf(goods));
|
||||
Assert.Equal(0, mill.StockOf(goods));
|
||||
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
AssertInvariants(w, "dopo lo scarico");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Al trasbordo la scadenza in stazione della merce propria riparte da zero")]
|
||||
public static void OwnedGoodsExpiryRestartsAtTransfer()
|
||||
{
|
||||
var (f, mine, mill, train) = BoxLine();
|
||||
var w = f.W;
|
||||
int goods = GoodIndex(w, "goods");
|
||||
Assert.Equal(0, train.StopIndex);
|
||||
// merce propria a bordo che scende alle miniere per proseguire verso l'acciaieria, con la scadenza già passata
|
||||
int id = w.NextIds.Packet++;
|
||||
train.Cargo.Add(new Packet
|
||||
{
|
||||
Id = id, Kind = PacketKind.Freight, Good = goods, Units = 20, Origin = mill.Id, Destination = mill.Id,
|
||||
HopLine = train.Line, HopEnd = mine.Id, CreatedTick = 0, ExpiresTick = 0, Contract = -1, Owned = true,
|
||||
});
|
||||
var wagon = w.Vehicles[train.Vehicles.First(v => w.Vehicles[v.Value].Def.Kind == RailEnterprise.Core.Data.VehicleKind.Wagon).Value];
|
||||
wagon.Good = goods;
|
||||
wagon.Load = 20;
|
||||
w.Goods.Produced[goods] += 20;
|
||||
long decay = (long)w.Data.Goods[goods].DecayDaysAtStation * w.Calendar.TicksPerDay;
|
||||
|
||||
Packet? after = null;
|
||||
Assert.True(f.RunUntil(() =>
|
||||
{
|
||||
foreach (var p in mine.Waiting.Concat(train.Cargo))
|
||||
if (p.Id == id && p.ExpiresTick != 0) after = p;
|
||||
return after is not null || mill.StockOf(goods) > 0;
|
||||
}, 60), "il pacchetto passa dalle miniere");
|
||||
Assert.True(after is { } a && a.ExpiresTick > w.Context.Tick - w.Calendar.TicksPerDay && a.ExpiresTick <= w.Context.Tick + decay,
|
||||
$"scadenza rinnovata al trasbordo: {after?.ExpiresTick} al tick {w.Context.Tick}");
|
||||
long decayed = w.Goods.Decayed[goods];
|
||||
Assert.True(f.RunUntil(() => mill.StockOf(goods) == 20, 120), "la merce arriva all'acciaieria");
|
||||
Assert.Equal(decayed, w.Goods.Decayed[goods], "niente merce deperita");
|
||||
AssertInvariants(w, "all'arrivo");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Un anno di commercio sulla rete merci di Valdoria (treno a tramogge): ogni mese si compra
|
||||
/// minerale dalla miniera, lo si spedisce all'acciaieria e si vende quello arrivato; restituisce il mondo.
|
||||
/// </summary>
|
||||
private static World TradingYear(Func<World, World>? midway = null, Action<string>? log = null)
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mineId, millId, depot) = f.BuildFreightNetwork();
|
||||
int portId = f.Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
|
||||
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(mineId)), new LineStop(new StationId(millId)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
Unlock(f.W);
|
||||
var w = f.W;
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
for (int month = 0; month < 12; month++)
|
||||
{
|
||||
var mine = w.Network.Stations[mineId];
|
||||
var mill = w.Network.Stations[millId];
|
||||
Enqueue(w, new BuyGoodsCommand(mine.Id, "iron_ore", 30, Money.FromLire(1000)));
|
||||
Enqueue(w, new ShipGoodsCommand(mine.Id, mill.Id, "iron_ore", 30));
|
||||
Enqueue(w, new SellGoodsCommand(mill.Id, "iron_ore", 25, Money.FromLire(1)));
|
||||
Enqueue(w, new BuyGoodsCommand(mill.Id, "steel", 5, Money.FromLire(1000)));
|
||||
// al porto: importazione e rivendita all'hub di metà del carbone comprato
|
||||
var port = w.Network.Stations[portId];
|
||||
Enqueue(w, new BuyGoodsCommand(port.Id, "coal", 40, Money.FromLire(1000)));
|
||||
Enqueue(w, new SellGoodsCommand(port.Id, "coal", 20, Money.FromLire(1)));
|
||||
if (month == 6 && midway is not null)
|
||||
{
|
||||
// salvataggio a due giorni dai comandi: la merce spedita è ancora in viaggio
|
||||
w.RunDays(2);
|
||||
foreach (var r in w.DrainResults()) log?.Invoke($"{r.Type}: {r.Error} {r.Message}");
|
||||
w = midway(w);
|
||||
w.RunDays(dpm - 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
w.RunDays(dpm);
|
||||
}
|
||||
foreach (var r in w.DrainResults()) log?.Invoke($"{r.Type}: {r.Error} {r.Message}");
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} al mese {month}");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro al mese {month}");
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
private static void Enqueue(World w, GameCommand c) => w.Enqueue(c with { Issuer = w.Player.Id });
|
||||
|
||||
[Test(Slow = true, Description = "Un anno di compravendita e spedizioni: invarianti di denaro e merci sempre veri, giacenze addebitate")]
|
||||
public static void InvariantsHoldThroughAYearOfTrading()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
var w = TradingYear(log: lines.Add);
|
||||
int Ok(string type) => lines.Count(l => l.StartsWith(type + ": None", StringComparison.Ordinal));
|
||||
Console.WriteLine($" riusciti: acquisti {Ok("BuyGoods")}, spedizioni {Ok("ShipGoods")}, vendite {Ok("SellGoods")} su {lines.Count} comandi");
|
||||
Assert.True(Ok("BuyGoods") >= 12 && Ok("ShipGoods") >= 6 && Ok("SellGoods") >= 6, string.Join(Environment.NewLine, lines));
|
||||
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Trading] != 0 || w.Player.LastYearEntries[(int)LedgerEntry.Trading] != 0, "voce «Commercio» movimentata");
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
Assert.True(steel.LastServedDay >= 0, "l'acciaieria è stata servita");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Determinismo e salvataggi: stessi comandi di commercio → stesso hash, anche passando da un salvataggio con merce in magazzino e in viaggio")]
|
||||
public static void TradingIsDeterministicAndSurvivesSaves()
|
||||
{
|
||||
bool sawStock = false, sawTransit = false;
|
||||
World ThroughSave(World w)
|
||||
{
|
||||
sawStock = w.Network.Stations.Any(s => s.StockTotal > 0);
|
||||
sawTransit = w.Network.Stations.Any(s => s.Waiting.Any(p => p.Owned)) || w.Trains.Any(t => t.Cargo.Any(p => p.Owned));
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "hash subito dopo il caricamento");
|
||||
for (int i = 0; i < w.Network.Stations.Count; i++)
|
||||
{
|
||||
Assert.SequenceEqual(w.Network.Stations[i].Stock, loaded.Network.Stations[i].Stock, $"magazzino della stazione {i}");
|
||||
Assert.SequenceEqual(w.Network.Stations[i].Waiting.Select(p => p.Owned), loaded.Network.Stations[i].Waiting.Select(p => p.Owned));
|
||||
}
|
||||
for (int i = 0; i < w.Trains.Count; i++)
|
||||
Assert.SequenceEqual(w.Trains[i].Cargo.Select(p => p.Owned), loaded.Trains[i].Cargo.Select(p => p.Owned), $"carico del treno {i}");
|
||||
return loaded;
|
||||
}
|
||||
var a = TradingYear();
|
||||
var b = TradingYear();
|
||||
var c = TradingYear(ThroughSave);
|
||||
Assert.Equal(a.LastStateHash, b.LastStateHash, "stesso seme e stessi comandi");
|
||||
Assert.True(sawStock, "il salvataggio contiene merce in magazzino");
|
||||
Assert.True(sawTransit, "il salvataggio contiene merce in viaggio");
|
||||
Assert.Equal(a.LastStateHash, c.LastStateHash, "salvare e ricaricare non cambia il futuro");
|
||||
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(c));
|
||||
}
|
||||
|
||||
[Test(Description = "Un salvataggio della versione 3 (prima del commercio) si carica con i magazzini vuoti e lo stesso stato")]
|
||||
public static void VersionThreeSavesLoadWithEmptyWarehouses()
|
||||
{
|
||||
var (f, _, _, port) = Stations();
|
||||
var w = f.W;
|
||||
w.RunDays(5);
|
||||
var body = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, body, 3);
|
||||
var loaded = WorldSerializer.Read(TestData.Data, new SaveReader(body.WrittenSpan.ToArray()));
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso stato dinamico");
|
||||
Assert.True(loaded.Network.Stations.All(s => s.Stock.Length == TestData.Data.GoodCount && s.StockTotal == 0), "magazzini vuoti");
|
||||
|
||||
// la partita caricata commercia normalmente
|
||||
Unlock(loaded);
|
||||
loaded.Enqueue(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)) { Issuer = loaded.Player.Id });
|
||||
loaded.RunTicks(1);
|
||||
Assert.True(loaded.DrainResults().Last().Ok);
|
||||
Assert.Equal(10, loaded.Network.Stations[port.Id.Value].StockOf(GoodIndex(loaded, "coal")));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => WorldSerializer.Write(w, new SaveWriter(16), WorldSerializer.BodyVersion + 1));
|
||||
}
|
||||
|
||||
[Test(Description = "Il quadro del mercato porta al client i magazzini della compagnia con giacenze e prezzi locali")]
|
||||
public static void MarketReportCarriesTheWarehouses()
|
||||
{
|
||||
var (f, mine, _, port) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
Assert.True(f.Do(new BuyGoodsCommand(port.Id, "coal", 25, Money.FromLire(1000))).Ok);
|
||||
var report = RailEnterprise.Server.Projection.Market(w, f.Me);
|
||||
Assert.Equal(3, report.Warehouses.Count);
|
||||
var house = report.Warehouses.Single(h => h.Station == port.Id.Value);
|
||||
Assert.Equal(w.Data.Balance.Trading.WarehouseCapacity, house.Capacity);
|
||||
int coal = GoodIndex(w, "coal");
|
||||
var g = house.Goods.Single(x => x.Good == coal);
|
||||
Assert.Equal(25, g.Units);
|
||||
Assert.Approx(w.Hubs[0].SellPrice(w.Market.GlobalPrice[coal]), g.BuyPrice, 1e-9);
|
||||
Assert.Approx(w.Hubs[0].BuyPrice(w.Market.GlobalPrice[coal]), g.SellPrice, 1e-9);
|
||||
var ore = report.Warehouses.Single(h => h.Station == mine.Id.Value).Goods.Single(x => x.Good == GoodIndex(w, "iron_ore"));
|
||||
Assert.True(ore.BuyUnits > 0 && ore.BuyPrice > 0, "la miniera vende minerale");
|
||||
|
||||
// round-trip del blocco 1 di MarketReport
|
||||
var decoded = (MarketReport)Frame.Decode(Frame.Encode(report));
|
||||
Assert.Equal(report.Warehouses.Count, decoded.Warehouses.Count);
|
||||
Assert.Equal(25, decoded.Warehouses.Single(h => h.Station == port.Id.Value).Goods.Single(x => x.Good == coal).Units);
|
||||
// la merce in magazzino entra nelle scorte del mercato globale
|
||||
Assert.Equal(MarketOutlook.StockUnits(w, coal), w.Industries.Where(i => !i.Closed && i.InputIndexOf(coal) >= 0).Sum(i => (double)i.InputStock[i.InputIndexOf(coal)])
|
||||
+ w.Industries.Where(i => !i.Closed && i.OutputIndexOf(coal) >= 0).Sum(i => (double)i.OutputStock[i.OutputIndexOf(coal)])
|
||||
+ w.Network.Stations.Where(s => w.Network.IsAlive(s)).Sum(s => s.Waiting.Where(p => p.Kind == PacketKind.Freight && p.Good == coal).Sum(p => (double)p.Units) + s.StockOf(coal)));
|
||||
}
|
||||
|
||||
[Test(Description = "ShipGoods (comando 40) sopravvive al round-trip del protocollo con tutti i campi")]
|
||||
public static void ShipGoodsRoundTrips()
|
||||
{
|
||||
var c = new ShipGoodsCommand(new StationId(3), new StationId(7), "iron_ore", 120);
|
||||
var decoded = (ShipGoodsCommand)((CommandMessage)Frame.Decode(Frame.Encode(new CommandMessage { Seq = 5, Command = c }))).Command;
|
||||
Assert.Equal((ushort)40, (ushort)decoded.Type);
|
||||
Assert.Equal(c.From, decoded.From);
|
||||
Assert.Equal(c.To, decoded.To);
|
||||
Assert.Equal("iron_ore", decoded.Good);
|
||||
Assert.Equal(120, decoded.Units);
|
||||
Assert.Equal(5u, decoded.Seq);
|
||||
}
|
||||
}
|
||||
@@ -125,6 +125,69 @@ public static class ProtocolTests
|
||||
Records = [new RecordInfo { Title = "Patrimonio massimo", Value = "₤ 1.000.000", Year = 1855 }],
|
||||
Highlights = ["Fondata nel 1850", "Livello 3 nel 1858"],
|
||||
};
|
||||
yield return new MarketReport
|
||||
{
|
||||
Day = 720, Index = 104.2f, IndexChange = 0.021f,
|
||||
Goods =
|
||||
[
|
||||
new GoodMarketInfo
|
||||
{
|
||||
Good = 8, Available = true, Price = 15200.5, Change = 0.124f, SupplyMonth = 41200, DemandMonth = 52800.25, WorldSupplyMonth = 900,
|
||||
WorldDemandMonth = 1100.5, StockUnits = 74000, StockMonths = 1.4f,
|
||||
History = [new PricePointInfo { Day = 689, Price = 14800 }, new PricePointInfo { Day = 720, Price = 15200.5 }],
|
||||
Forecast = [new ForecastInfo { Months = 1, Price = 15400, Low = 14900, High = 15900 }],
|
||||
SellPlaces =
|
||||
[
|
||||
new SellPlaceInfo { Kind = SellPlaceInfo.Hub, Target = 0, Price = 16100, Line = 6 },
|
||||
new SellPlaceInfo { Kind = SellPlaceInfo.Industry, Target = 12, Price = 15800, Line = -1 },
|
||||
],
|
||||
},
|
||||
new GoodMarketInfo { Good = 14, Available = false, Price = 9000, StockMonths = -1 },
|
||||
],
|
||||
Hubs = [new HubMarketInfo { Hub = 0, Kind = 0, MonthlyCapacity = 1200, Duty = 0.04f, UsedThisMonth = 864, Line = 6 }],
|
||||
EventGood = 8, EventShock = -0.18f, EventMonths = 5.9f,
|
||||
TradingUnlocked = false, TradingTier = 2, TradingProgress = 0.58f, NetWorth = new Money(23_200_000), NetWorthRequired = new Money(40_000_000),
|
||||
TownsConnected = 1, TownsRequired = 2, TownPopulation = 800, Rating = "BBB", RatingRequired = "BB", RatingMet = true,
|
||||
Warehouses =
|
||||
[
|
||||
new WarehouseInfo
|
||||
{
|
||||
Station = 3, Capacity = 500, Incoming = 40,
|
||||
Goods = [new WarehouseGoodInfo { Good = 8, Units = 120, BuyPrice = 9900.5, BuyUnits = 300, SellPrice = 14200.25, SellUnits = 80 }, new WarehouseGoodInfo { Good = 2, Units = 0 }],
|
||||
},
|
||||
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 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.")] };
|
||||
@@ -233,6 +296,7 @@ public static class ProtocolTests
|
||||
yield return new FundResearchCommand("electric_traction", Money.FromLire(20000));
|
||||
yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000));
|
||||
yield return new MergeCompanyCommand(new CompanyId(2));
|
||||
yield return new ShipGoodsCommand(new StationId(1), new StationId(4), "iron_ore", 75);
|
||||
}
|
||||
|
||||
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
|
||||
|
||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user