F6: compravendita in proprio e spedizione della merce tra stazioni #32
No files matched your search
@@ -517,3 +517,24 @@ 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."
|
||||
|
@@ -33,6 +33,7 @@ public partial class MarketPanel : VBoxContainer
|
||||
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;
|
||||
@@ -46,6 +47,9 @@ public partial class MarketPanel : VBoxContainer
|
||||
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;
|
||||
|
||||
@@ -111,6 +115,12 @@ public partial class MarketPanel : VBoxContainer
|
||||
_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;
|
||||
|
||||
@@ -118,7 +128,11 @@ public partial class MarketPanel : VBoxContainer
|
||||
{
|
||||
_selected = good;
|
||||
foreach (var (id, row) in _rowByGood) row.SetSelected(id == good);
|
||||
if (_session.World.Market is { } report) ShowGood(_session.World, report);
|
||||
if (_session.World.Market is { } report)
|
||||
{
|
||||
ShowGood(_session.World, report);
|
||||
_trade.Update(report, good, report.TradingUnlocked);
|
||||
}
|
||||
}
|
||||
|
||||
private static VBoxContainer Column(HBoxContainer body, float ratio)
|
||||
@@ -425,6 +439,8 @@ public partial class MarketPanel : VBoxContainer
|
||||
|
||||
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));
|
||||
@@ -485,7 +501,7 @@ public partial class MarketPanel : VBoxContainer
|
||||
return card;
|
||||
}
|
||||
|
||||
private static Control TradingCard(ClientWorld w, MarketReport report)
|
||||
private Control TradingCard(ClientWorld w, MarketReport report)
|
||||
{
|
||||
var card = Card(Palette.Panel, Palette.Border);
|
||||
var col = (VBoxContainer)card.GetChild(0);
|
||||
@@ -494,12 +510,20 @@ public partial class MarketPanel : VBoxContainer
|
||||
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(Bar(1, Palette.Amber));
|
||||
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.Pct(report.TradingProgress, 0)}", 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}",
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -53,6 +53,7 @@
|
||||
"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,
|
||||
|
||||
@@ -339,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": {
|
||||
@@ -489,6 +507,7 @@
|
||||
"map",
|
||||
"market",
|
||||
"localPrice",
|
||||
"trading",
|
||||
"industry",
|
||||
"growth",
|
||||
"town",
|
||||
|
||||
@@ -92,7 +92,8 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio.
|
||||
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno.
|
||||
- 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.
|
||||
- Interpretazioni delle formule della guida: ADR 0004.
|
||||
|
||||
## 7. Salvataggi
|
||||
@@ -102,6 +103,7 @@ 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).
|
||||
|
||||
## 8. Server
|
||||
|
||||
|
||||
+8
-3
@@ -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
|
||||
|
||||
@@ -152,7 +155,7 @@ 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` (su richiesta, F6; ADR 0015) |
|
||||
| 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) (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)]` |
|
||||
@@ -193,6 +196,8 @@ Record (ognuno chiude con `flags`):
|
||||
- `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) }] }`
|
||||
- `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
|
||||
|
||||
|
||||
+14
-4
@@ -101,11 +101,20 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- 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).
|
||||
- Restano della F6: commercio (`BuyGoods`/`SellGoods`), eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
- **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).
|
||||
- Restano della F6: eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F6: hub e commercio (`BuyGoods`/`SellGoods`, con i prezzi e le destinazioni di `MarketOutlook`), eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
- F6: eventi, finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
|
||||
## Limiti noti
|
||||
|
||||
@@ -113,14 +122,15 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Senza vettori il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004).
|
||||
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 (F6, non ancora provato in Godot: qui manca l'editor); Industria, Scalata e la schermata di connessione vanno allineati in F6.
|
||||
- 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).
|
||||
- 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.
|
||||
- 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,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).
|
||||
@@ -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; }
|
||||
@@ -211,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; }
|
||||
|
||||
@@ -199,7 +199,7 @@ public static class MarketOutlook
|
||||
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.</summary>
|
||||
/// <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;
|
||||
@@ -218,6 +218,7 @@ public static class MarketOutlook
|
||||
{
|
||||
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
|
||||
}
|
||||
sum += s.StockOf(good);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
@@ -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 = 4;
|
||||
|
||||
/// <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);
|
||||
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,9 @@ 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);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -680,6 +690,9 @@ 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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -59,6 +59,9 @@ 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),
|
||||
_ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -83,7 +83,10 @@ 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,
|
||||
/// merce della compagnia (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016).
|
||||
/// </summary>
|
||||
public static void UpdateBookValues(World w)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
@@ -110,9 +113,30 @@ public sealed class FinanceSystem : ISimSystem
|
||||
double age = (today - v.BoughtDay) / daysPerYear;
|
||||
values[v.Owner.Value] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
|
||||
}
|
||||
var prices = w.Market.GlobalPrice;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (!s.Owner.IsValid || s.Owner.Value >= values.Length) continue;
|
||||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value] += (long)(s.Stock[g] * prices[g]);
|
||||
values[s.Owner.Value] += OwnedGoodsValue(s.Waiting, prices);
|
||||
}
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value] += OwnedGoodsValue(t.Cargo, prices);
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
|
||||
}
|
||||
|
||||
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>
|
||||
public static Money MonthlyPayment(Money remaining, double annualRate, int monthsLeft)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
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)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.Trading);
|
||||
error = (CommandError.TierLocked, tier is null
|
||||
? "La compravendita in proprio non è disponibile"
|
||||
: $"La compravendita in proprio si sblocca al livello «{tier.NameIt}»");
|
||||
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)}";
|
||||
}
|
||||
@@ -184,6 +184,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)
|
||||
{
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -146,6 +146,60 @@ public sealed class HubMarketInfo
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 e avanzamento verso la compravendita in proprio.
|
||||
@@ -175,6 +229,8 @@ public sealed class MarketReport : IMessage
|
||||
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; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
@@ -186,7 +242,10 @@ public sealed class MarketReport : IMessage
|
||||
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(0);
|
||||
w.Flags(Warehouses.Count > 0 ? (byte)1 : (byte)0);
|
||||
if (Warehouses.Count == 0) return;
|
||||
w.Count(Warehouses.Count);
|
||||
foreach (var h in Warehouses) h.Write(ref w);
|
||||
}
|
||||
|
||||
public static MarketReport Read(ref SpanReader r)
|
||||
@@ -204,7 +263,11 @@ public sealed class MarketReport : IMessage
|
||||
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(),
|
||||
};
|
||||
r.Flags();
|
||||
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));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -547,6 +547,34 @@ public static class Projection
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,15 @@ public static class ProtocolTests
|
||||
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 CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
|
||||
yield return new Notification { Event = SampleEvent() };
|
||||
@@ -257,6 +266,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")]
|
||||
|
||||
Reference in new issue
Block a user