Files
Rail_Enterprise/src/RailEnterprise.Core/Simulation/Systems/StationSystem.cs
T
Alby96andClaude Opus 5.5 596ce2c376
CI / Build e test (pull_request) Successful in 1m19s
CI / Immagine Docker (pull_request) Successful in 29s
F6: compravendita in proprio, correzioni della revisione
La revisione ha trovato casi in cui la merce della compagnia, già pagata,
poteva perdersi o restare bloccata, e il magazzino di destinazione
restare prenotato per sempre. Le correzioni:

- Il percorso della merce propria rispetta i flag carico e scarico delle
  fermate: LineGraph.From ha l'opzione stopFlags. ShipGoods rifiuta con
  Blocked la spedizione che esiste solo ignorando i flag. I pacchetti dei
  clienti non cambiano: l'accettazione F4 dà ancora 35/20 e 75/2.
- La scadenza in stazione della merce propria riparte a ogni trasbordo.
- La merce propria in attesa ricalcola ogni giorno il tratto sulle linee
  di quel giorno; se non c'è più un percorso torna nel magazzino.
- La merce propria a bordo scende alla prima fermata quando il suo tratto
  non è più sulla linea del treno. Un treno che lascia la linea
  (riassegnato, al deposito, in riserva, fine copertura) la lascia alla
  stazione dove si trova o alla prossima fermata.
- Una stazione con merce propria in partenza o in arrivo non si demolisce.
- La merce propria, in magazzino e in viaggio, entra nel valore contabile
  al prezzo globale: un acquisto non abbassa più il patrimonio netto
  dell'intero importo.
- Solo l'acquisto richiede lo sblocco del livello: la merce ereditata con
  una fusione si vende e si spedisce, e il riquadro del pannello compare.
- Nel riquadro, la stazione di arrivo predefinita è diversa da quella di
  partenza.

ADR 0016 e STATE aggiornati; sei test nuovi in TradingTests.

Refs #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:05:29 +01:00

333 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>
/// Stazioni (guida 7): bacini di utenza, industrie servite, merci che passano dalle industrie
/// del bacino alla stazione con una destinazione scelta sul grafo delle linee, scadenza dei
/// pacchetti in attesa, nuovi tentativi di consegna ai consumatori.
/// </summary>
public sealed class StationSystem : ISimSystem
{
public string Name => "Stations";
private readonly List<(int Station, double Score)> _candidates = [];
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
var net = w.Network;
if (ctx.IsNewMonth || ctx.Day == 0)
{
foreach (var s in net.Stations)
{
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);
}
foreach (var s in net.Stations)
{
if (net.Nodes[s.Node.Value].Station != s.Id || !LoadsHere(w, s)) continue;
LocalService(w, s, w.Data.SparePartsGood);
LocalService(w, s, w.Data.MachineryGood);
CollectFreight(ctx, s);
}
}
/// <summary>
/// Trasbordo nel bacino (ADR 0011): una stazione servita passa ricambi e macchinari dai produttori
/// e dagli hub del suo bacino alle officine e alle industrie dello stesso bacino, senza treno.
/// </summary>
private static void LocalService(World w, Station s, int good)
{
if (ServiceNeed(w, s, good) <= 0) return;
foreach (var id in s.Industries)
{
var producer = w.Industries[id.Value];
int o = producer.OutputIndexOf(good);
if (producer.Closed || o < 0 || producer.OutputStock[o] <= 0) continue;
int offered = producer.OutputStock[o];
int sold = offered - StationWork.DeliverService(w, s, good, offered, w.Market.GlobalPrice[good]);
if (sold <= 0) continue;
producer.OutputStock[o] -= sold;
var sale = Money.FromCentsRounded(sold * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.External, Account.Of(producer.Id), sale, LedgerEntry.Other);
producer.SalesToday += sale.Cents;
producer.LastServedDay = w.Clock.Day;
if (o == 0) producer.ShippedToday += sold;
}
foreach (var id in s.Hubs)
{
var hub = w.Hubs[id.Value];
int units = Math.Min(ServiceNeed(w, s, good), hub.RemainingCapacity);
if (units <= 0) continue;
int delivered = units - StationWork.DeliverService(w, s, good, units, hub.SellPrice(w.Market.GlobalPrice[good]));
if (delivered <= 0) continue;
hub.UsedThisMonth += delivered;
hub.ImportedThisMonth[good] += delivered;
w.Goods.Imported[good] += delivered;
}
}
private static bool LoadsHere(World w, Station s)
{
foreach (var line in w.Lines)
{
if (line.Removed || line.Owner != s.Owner) continue;
foreach (var st in line.Stops)
{
if (st.Station == s.Id && st.Load) return true;
}
}
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;
for (int i = s.Waiting.Count - 1; i >= 0; i--)
{
var p = s.Waiting[i];
if (p.ExpiresTick > ctx.Tick) continue;
s.Waiting.RemoveAt(i);
if (p.Kind != PacketKind.Freight) continue;
w.Goods.Decayed[p.Good] += p.Units;
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);
}
}
}
private static void RetryDeliveries(World w, Station s)
{
for (int i = s.Waiting.Count - 1; i >= 0; i--)
{
var p = s.Waiting[i];
if (!p.AwaitingConsumer) continue;
p.Units = StationWork.DeliverToConsumers(w, s, p.Good, p.Units);
if (p.Units <= 0) s.Waiting.RemoveAt(i);
else s.Waiting[i] = p;
}
}
/// <summary>
/// Le industrie del bacino affidano la produzione alla stazione se esiste una destinazione
/// raggiungibile con un consumatore; si sceglie quella con più bisogno, a parità la più vicina.
/// </summary>
private void CollectFreight(WorldContext ctx, Station s)
{
var w = ctx.World;
var graph = w.LineGraphs.For(w, s.Owner);
foreach (var id in s.Industries)
{
var ind = w.Industries[id.Value];
if (ind.Closed) continue;
var outputs = ind.Def.Recipe.Outputs;
for (int o = 0; o < outputs.Count; o++)
{
int good = outputs[o].GoodIndex;
int units = ind.OutputStock[o];
if (units <= 0) continue;
var reach = graph.From(s.Id, LineGraph.GoodCargo(good));
if (reach.Count == 0) continue;
var dest = BestDestination(w, s, reach, good);
if (dest is null) continue;
var p = new Packet
{
Id = w.NextIds.Packet++,
Kind = PacketKind.Freight,
Good = good,
Units = units,
Origin = s.Id,
Destination = dest.Destination,
HopLine = dest.First.Line,
HopEnd = dest.First.To,
CreatedTick = ctx.Tick,
ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay,
ExpectedDays = w.Calendar.TrainMinutesToDays(dest.Minutes),
Contract = -1,
};
ind.OutputStock[o] = 0;
ind.LastServedDay = ctx.Day;
s.Waiting.Add(p);
w.Network.Stations[dest.Destination.Value].Incoming[good] += units;
var sale = Money.FromCentsRounded(units * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.External, Account.Of(ind.Id), sale, LedgerEntry.Other);
ind.SalesToday += sale.Cents;
if (o == 0) ind.ShippedToday += units;
}
}
if (s.Hubs.Count > 0)
{
ImportServiceGood(ctx, s, graph, w.Data.SparePartsGood);
ImportServiceGood(ctx, s, graph, w.Data.MachineryGood);
}
}
/// <summary>
/// Un hub nel bacino importa ricambi e macchinari richiesti dalle officine e dalle industrie
/// raggiungibili sulle linee (10.2, 11): li spedisce verso la stazione con più bisogno, entro la
/// capacità mensile dell'hub.
/// </summary>
private void ImportServiceGood(WorldContext ctx, Station s, LineGraph graph, int good)
{
var w = ctx.World;
var reach = graph.From(s.Id, LineGraph.GoodCargo(good));
if (reach.Count == 0) return;
_candidates.Clear();
foreach (var key in reach.Keys) _candidates.Add((key, 0));
_candidates.Sort((a, b) => a.Station.CompareTo(b.Station));
Connection? best = null;
int bestNeed = 0;
foreach (var (sid, _) in _candidates)
{
var dest = w.Network.Stations[sid];
int need = ServiceNeed(w, dest, good) - dest.Incoming[good];
if (need <= bestNeed) continue;
bestNeed = need;
best = reach[sid];
}
if (best is null) return;
foreach (var id in s.Hubs)
{
if (bestNeed <= 0) return;
var hub = w.Hubs[id.Value];
int units = Math.Min(bestNeed, hub.RemainingCapacity);
if (units <= 0) continue;
hub.UsedThisMonth += units;
hub.ImportedThisMonth[good] += units;
w.Goods.Imported[good] += units;
bestNeed -= units;
s.Waiting.Add(new Packet
{
Id = w.NextIds.Packet++,
Kind = PacketKind.Freight,
Good = good,
Units = units,
Origin = s.Id,
Destination = best.Destination,
HopLine = best.First.Line,
HopEnd = best.First.To,
CreatedTick = ctx.Tick,
ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay,
ExpectedDays = w.Calendar.TrainMinutesToDays(best.Minutes),
Contract = -1,
});
w.Network.Stations[best.Destination.Value].Incoming[good] += units;
}
}
/// <summary>Ricambi o macchinari mancanti a officine e industrie nel bacino della stazione.</summary>
private static int ServiceNeed(World w, Station s, int good)
{
int need = good == w.Data.SparePartsGood ? DepotNeed(w, s) : 0;
foreach (var id in s.Industries) need += IndustryMath.ServiceNeed(w, w.Industries[id.Value], good);
return need;
}
/// <summary>Ricambi mancanti alle officine nel bacino della stazione (scorta desiderata − scorta).</summary>
private static int DepotNeed(World w, Station s)
{
int need = 0;
foreach (var id in s.Depots)
{
var d = w.Network.Depots[id.Value];
if (w.Network.IsAlive(d)) need += Math.Max(0, d.PartsTarget - d.SpareParts);
}
return need;
}
private Connection? BestDestination(World w, Station from, IReadOnlyDictionary<int, Connection> reach, int good)
{
Connection? best = null;
double bestScore = double.NegativeInfinity;
int dpm = w.Calendar.DaysPerMonth;
var tb = w.Data.Balance.Town;
_candidates.Clear();
foreach (var key in reach.Keys) _candidates.Add((key, 0));
_candidates.Sort((a, b) => a.Station.CompareTo(b.Station));
foreach (var (sid, _) in _candidates)
{
var dest = w.Network.Stations[sid];
var conn = reach[sid];
double need = 0;
bool consumer = false;
foreach (var id in dest.Industries)
{
var ind = w.Industries[id.Value];
if (ind.Closed) continue;
int service = IndustryMath.ServiceNeed(w, ind, good);
if (service > 0)
{
consumer = true;
need += service;
}
int i = ind.InputIndexOf(good);
if (i < 0) continue;
consumer = true;
need += IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
}
foreach (var id in dest.Towns)
{
var town = w.Towns[id.Value];
if (town.DemandToday[good] <= 0) continue;
consumer = true;
need += town.DemandToday[good] * tb.StockDays - town.Stock[good];
}
foreach (var id in dest.Hubs)
{
consumer = true;
need += w.Hubs[id.Value].RemainingCapacity;
}
if (good == w.Data.SparePartsGood && dest.Depots.Count > 0)
{
consumer = true;
need += DepotNeed(w, dest);
}
if (!consumer) continue;
need -= dest.Incoming[good];
double score = need / (1 + conn.Minutes / 60);
if (score > bestScore)
{
bestScore = score;
best = conn;
}
}
return best;
}
}