Files
Rail_Enterprise/src/RailEnterprise.Core/Simulation/Systems/StationSystem.cs
T
Alby96andClaude Opus 5.5 c1a0049bcf
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s
Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

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

310 lines
12 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);
}
}
foreach (var s in net.Stations)
{
if (net.Nodes[s.Node.Value].Station != s.Id) continue;
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;
}
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)
{
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;
}
}