F2: rete ferroviaria, cantieri, treni con fisica e blocchi, merci in stazione

- RailNetwork: nodi, archi con profilo campionato, divisione degli archi agli
  agganci (anche in cantiere), indice spaziale, cavalcavia sui binari altrui
- Comandi: binari, stazioni, depositi, segnali, demolizioni, rinnovi,
  ammodernamenti, veicoli, composizioni, linee, assegnazioni, rientro
- ConstructionSystem: squadre per livello, avanzamento, usura dei binari e
  invecchiamento delle strutture; costi d'esercizio e valore contabile
- TrainSystem: A* con vincolo di svolta, prenotazione a blocchi con catena
  fino a un punto sicuro sul binario semplice, fisica 8.4, stallo in salita
- StationSystem e StationWork: bacini, merci con destinazione sul grafo
  delle linee, carico sui carri, consegne con tariffa, trasbordi
- Salvataggi estesi a tutto lo stato ferroviario; 11 nuovi test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-01 23:19:34 +00:00
1 parent 32997ff1e5
commit 18b5e2c2e1
28 files changed
+4122 -6

No files matched your search

@@ -0,0 +1,193 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Cantieri (guida 8.2) e usura dei binari (8.3). Ogni giorno le squadre libere di ogni compagnia
/// prendono i progetti in coda nell'ordine di apertura; un progetto avanza di un giorno per giorno
/// di lavoro. Poi si applica l'usura del traffico, la manutenzione ordinaria e l'invecchiamento
/// di ponti e gallerie.
/// </summary>
public sealed class ConstructionSystem : ISimSystem
{
public string Name => "Construction";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
Projects(ctx, w);
Wear(ctx, w);
}
/// <summary>Squadre disponibili per una compagnia secondo il livello.</summary>
public static int Crews(World w, Company c)
{
var byTier = w.Data.Construction.Crews.CrewsByTier;
return byTier[Math.Clamp(c.Tier, 1, byTier.Length) - 1];
}
private static void Projects(WorldContext ctx, World w)
{
var net = w.Network;
foreach (var company in w.Companies)
{
int crews = Crews(w, company);
int busy = 0;
foreach (var p in net.Projects)
{
if (!p.Done && p.Owner == company.Id && p.Crew >= 0) busy++;
}
foreach (var p in net.Projects)
{
if (p.Done || p.Owner != company.Id || p.Crew >= 0) continue;
if (busy >= crews) break;
p.Crew = FreeCrew(net, company.Id, crews);
p.StartedDay = ctx.Day;
busy++;
}
}
foreach (var p in net.Projects)
{
if (p.Done || p.Crew < 0) continue;
p.ProgressDays += 1;
if (p.ProgressDays + 1e-9 < p.TotalDays) continue;
Complete(ctx, w, p);
}
}
private static int FreeCrew(RailNetwork net, CompanyId company, int crews)
{
for (int c = 0; c < crews; c++)
{
bool used = false;
foreach (var p in net.Projects)
{
if (!p.Done && p.Owner == company && p.Crew == c) { used = true; break; }
}
if (!used) return c;
}
return crews - 1;
}
private static void Complete(WorldContext ctx, World w, ConstructionProject p)
{
var net = w.Network;
p.Done = true;
p.Crew = -1;
foreach (var id in p.Edges)
{
var e = net.Edges[id.Value];
if (e.State == EdgeState.Demolished) continue;
e.Project = -1;
switch (p.Kind)
{
case ProjectKind.NewTrack:
e.BuiltDay = ctx.Day;
e.LastRenewalDay = ctx.Day;
e.LastInspectionDay = ctx.Day;
break;
case ProjectKind.Renewal:
e.Condition = 100;
e.StructureCondition = 100;
e.LastRenewalDay = ctx.Day;
e.LastInspectionDay = ctx.Day;
break;
case ProjectKind.Upgrade:
ApplyUpgrade(w, e, p);
break;
}
e.State = EdgeState.Active;
e.ResetBlocks();
}
net.Touch();
string what = p.Kind switch
{
ProjectKind.NewTrack => "Binario completato",
ProjectKind.Renewal => "Rinnovo completato",
_ => "Ammodernamento completato",
};
double km = p.Edges.Sum(id => net.Edges[id.Value].Length) / 1000;
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Construction, EventSeverity.Info,
$"{what}: {km:F1} km in {p.ProgressDays:F0} giorni", EntityKind.None, -1, p.Owner));
}
private static void ApplyUpgrade(World w, TrackEdge e, ConstructionProject p)
{
var classes = w.Data.Eras.TrackClasses;
double oldSpeed = classes[e.TrackClass].SpeedKmh;
double newSpeed = classes[p.UpgradeClass].SpeedKmh;
for (int i = 0; i < e.SpeedLimitKmh.Length; i++)
{
// i tratti limitati dalle curve restano limitati dal raggio
e.SpeedLimitKmh[i] = e.SpeedLimitKmh[i] < oldSpeed - 1e-9 ? Math.Min(newSpeed, e.SpeedLimitKmh[i]) : newSpeed;
}
e.TrackClass = p.UpgradeClass;
e.DoubleTrack = p.UpgradeDouble;
e.Electrified = p.UpgradeElectrified;
e.Condition = 100;
}
private static void Wear(WorldContext ctx, World w)
{
var tw = w.Data.Construction.TrackWear;
var st = w.Data.Construction.Structures;
int daysPerYear = w.Calendar.DaysPerYear;
foreach (var e in w.Network.Edges)
{
if (e.State is EdgeState.Demolished or EdgeState.UnderConstruction)
{
e.WearToday = 0;
continue;
}
var owner = w.Companies[e.Owner.Value];
double before = e.Condition;
double wear = e.WearToday / tw.K * w.Difficulty.WearMultiplier;
e.TonnesThisYear += e.WearToday;
e.WearToday = 0;
// la manutenzione ordinaria pagata annulla la deriva naturale; senza (bancarotta) il binario deperisce
if (owner.Bankrupt) wear += tw.MaintenanceDriftPerDay;
else
{
var cost = Money.FromCentsRounded(e.Length / 1000 * tw.MaintenanceCostPerKmPerDay * (e.DoubleTrack ? 2 : 1));
w.Money.Transfer(Account.Of(owner.Id), Account.External, cost, LedgerEntry.TrackMaintenance);
}
e.Condition = Math.Max(0, e.Condition - wear);
if (before >= 60 && e.Condition < 60)
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Warning,
$"Binario {e.Id.Value}: condizione sotto 60, velocità ridotta al {tw.LimitBelow60 * 100:F0}%", EntityKind.None, e.Id.Value, owner.Id));
// strutture: ispezione annuale obbligatoria e invecchiamento oltre la vita utile
double structures = e.LengthOf(WorkKind.Bridge) + e.LengthOf(WorkKind.Tunnel);
if (structures <= 0) continue;
if (ctx.Day - e.LastInspectionDay >= st.InspectionIntervalDays && !owner.Bankrupt)
{
double share = structures / Math.Max(1, e.Length);
var cost = Money.FromCentsRounded(e.BuildCostCents * share * st.InspectionCostShare);
w.Money.Transfer(Account.Of(owner.Id), Account.External, cost, LedgerEntry.TrackMaintenance);
e.LastInspectionDay = ctx.Day;
}
double age = (ctx.Day - e.LastRenewalDay) / (double)daysPerYear;
double structureBefore = e.StructureCondition;
if (ctx.Day - e.LastInspectionDay > st.InspectionIntervalDays) e.StructureCondition -= st.MissedInspectionWearPerDay;
if (age > st.RenewalYears) e.StructureCondition -= 100.0 / (10.0 * daysPerYear);
e.StructureCondition = Math.Max(0, e.StructureCondition);
if (structureBefore >= st.CloseBelow && e.StructureCondition < st.CloseBelow)
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Critical,
$"Binario {e.Id.Value}: ponti e gallerie da rinnovare, velocità minima", EntityKind.None, e.Id.Value, owner.Id));
}
}
/// <summary>Fattore di velocità dovuto alla condizione di binario e strutture (8.3).</summary>
public static double ConditionFactor(World w, TrackEdge e)
{
var tw = w.Data.Construction.TrackWear;
var st = w.Data.Construction.Structures;
double f = e.Condition < 30 ? tw.LimitBelow30 : e.Condition < 60 ? tw.LimitBelow60 : 1.0;
if (e.StructureCondition < st.SpeedLimitBelow) f = Math.Min(f, st.SpeedLimitFactor);
if (e.StructureCondition < st.CloseBelow) f = Math.Min(f, 0.1);
return f;
}
}
@@ -12,10 +12,13 @@ public sealed class FinanceSystem : ISimSystem
{
public string Name => "Finance";
private double[] _running = [];
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
PayRunningCosts(w);
foreach (var c in w.Companies)
{
if (c.Bankrupt) continue;
@@ -29,6 +32,7 @@ public sealed class FinanceSystem : ISimSystem
}
if (ctx.IsNewMonth && ctx.Day > 0)
{
UpdateBookValues(w);
foreach (var c in w.Companies)
{
if (!c.Bankrupt) PayLoans(w, c);
@@ -46,6 +50,62 @@ public sealed class FinanceSystem : ISimSystem
}
}
/// <summary>Costi d'esercizio giornalieri: veicoli posseduti, binari di stazione, depositi.</summary>
private void PayRunningCosts(World w)
{
if (_running.Length < w.Companies.Count) _running = new double[w.Companies.Count];
Array.Clear(_running);
double days = w.Calendar.DaysPerYear;
foreach (var v in w.Vehicles)
{
if (!v.Sold) _running[v.Owner.Value] += v.Def.RunningCostPerYear / days;
}
var sp = w.Data.Construction.Stations;
foreach (var s in w.Network.Stations)
{
if (w.Network.Nodes[s.Node.Value].Station == s.Id) _running[s.Owner.Value] += s.Platforms * sp.UpkeepPerPlatformPerYear / days;
}
foreach (var d in w.Network.Depots)
{
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) _running[d.Owner.Value] += sp.DepotUpkeepPerYear[d.Size] / days;
}
for (int i = 0; i < w.Companies.Count; i++)
{
if (_running[i] <= 0 || w.Companies[i].Bankrupt) continue;
w.Money.Transfer(Account.Of(w.Companies[i].Id), Account.External, Money.FromCentsRounded(_running[i]), LedgerEntry.RunningCosts);
}
}
/// <summary>Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo.</summary>
public static void UpdateBookValues(World w)
{
var fb = w.Data.Balance.Finance;
var values = new long[w.Companies.Count];
double daysPerYear = w.Calendar.DaysPerYear;
long today = w.Clock.Day;
foreach (var e in w.Network.Edges)
{
if (e.State == Rail.EdgeState.Demolished) continue;
double age = (today - e.BuiltDay) / daysPerYear;
values[e.Owner.Value] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
}
foreach (var s in w.Network.Stations)
{
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value] += s.BuildCostCents;
}
foreach (var d in w.Network.Depots)
{
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value] += d.BuildCostCents;
}
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
double age = (today - v.BoughtDay) / daysPerYear;
values[v.Owner.Value] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
}
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
}
/// <summary>Rata mensile costante (alla francese) per il residuo e i mesi restanti.</summary>
public static Money MonthlyPayment(Money remaining, double annualRate, int monthsLeft)
{
@@ -0,0 +1,206 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.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) RailCommandHandlers.UpdateCatchment(w, s);
}
MarkServed(w);
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;
CollectFreight(ctx, s);
}
}
/// <summary>Un'industria è servita se sta nel bacino di una stazione fermata di una linea con treni.</summary>
private static void MarkServed(World w)
{
foreach (var i in w.Industries) i.Served = false;
foreach (var s in w.Network.Stations)
{
if (!IsServedStation(w, s)) continue;
foreach (var id in s.Industries) w.Industries[id.Value].Served = true;
}
}
private static bool IsServedStation(World w, Station s)
{
foreach (var line in w.Lines)
{
if (line.Removed || line.Owner != s.Owner) continue;
bool stops = false;
foreach (var st in line.Stops) if (st.Station == s.Id) { stops = true; break; }
if (!stops) continue;
foreach (var t in w.Trains)
{
if (!t.Removed && t.Line == line.Id) return true;
}
}
return false;
}
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);
var reach = graph.From(s.Id);
if (reach.Count == 0) return;
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 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;
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;
}
}
}
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];
int i = ind.InputIndexOf(good);
if (i < 0 || ind.Closed) 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 (!consumer) continue;
need -= dest.Incoming[good];
double score = need / (1 + conn.Minutes / 60);
if (score > bestScore)
{
bestScore = score;
best = conn;
}
}
return best;
}
}
@@ -0,0 +1,365 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Operazioni dei treni in stazione: scarico (consegna con tariffa o trasbordo), carico dei
/// pacchetti diretti lungo la linea del treno, sosta proporzionale alle unità movimentate,
/// attesa del pieno con tempo massimo.
/// </summary>
public static class StationWork
{
/// <summary>Fermata della linea che il treno sta servendo in questa stazione, se coincide.</summary>
public static LineStop? CurrentStop(World w, Train t, Station s)
{
if (!t.Line.IsValid) return null;
var line = w.Lines[t.Line.Value];
if (line.Removed || line.Stops.Count == 0 || t.StopIndex >= line.Stops.Count) return null;
var stop = line.Stops[t.StopIndex];
return stop.Station == s.Id ? stop : null;
}
public static void Arrive(WorldContext ctx, Train t, Station s)
{
var w = ctx.World;
t.State = TrainState.Loading;
t.ArrivedTick = ctx.Tick;
var stop = CurrentStop(w, t, s);
int moved = Unload(ctx, t, s, stop?.Unload ?? true);
if (stop is null || stop.Load) moved += Load(ctx, t, s);
var sp = w.Data.Construction.Stations;
double minDwell = sp.MinDwellMinutes * 60 / w.Calendar.TrainSecondsPerTick;
t.DwellTicks = Math.Max(minDwell, moved / Math.Max(0.001, UnitsPerTick(w, t)));
}
/// <summary>Unità movimentate per tick (media tra carri e carrozze del treno).</summary>
private static double UnitsPerTick(World w, Train t)
{
var sp = w.Data.Construction.Stations;
int wagons = 0, coaches = 0;
foreach (var id in t.Vehicles)
{
var k = w.Vehicles[id.Value].Def.Kind;
if (k == VehicleKind.Wagon) wagons++;
else if (k == VehicleKind.Coach) coaches++;
}
double perMinute = wagons * sp.FreightUnitsPerMinutePerWagon + coaches * sp.PaxPerMinutePerCoach;
return Math.Max(1, perMinute) * w.Calendar.TrainSecondsPerTick / 60;
}
public static void Dwell(WorldContext ctx, Train t)
{
var w = ctx.World;
t.DwellTicks -= 1;
// in attesa del pieno: ogni mattina si caricano le merci arrivate in stazione
if (ctx.IsNewDay && t.AtNode.IsValid && w.Network.Nodes[t.AtNode.Value].Station is { IsValid: true } sid)
{
var s = w.Network.Stations[sid.Value];
var stop = CurrentStop(w, t, s);
if (stop is { Load: true, WaitFull: true })
{
int loaded = Load(ctx, t, s);
if (loaded > 0) t.DwellTicks = Math.Max(t.DwellTicks, loaded / Math.Max(0.001, UnitsPerTick(w, t)));
}
}
}
public static bool ReadyToDepart(WorldContext ctx, Train t)
{
if (t.DwellTicks > 0) return false;
var w = ctx.World;
if (!t.AtNode.IsValid || !w.Network.Nodes[t.AtNode.Value].Station.IsValid) return true;
var s = w.Network.Stations[w.Network.Nodes[t.AtNode.Value].Station.Value];
var stop = CurrentStop(w, t, s);
if (stop is not { WaitFull: true }) return true;
int maxDays = stop.MaxWaitDays > 0 ? stop.MaxWaitDays : w.Data.Construction.Operations.DefaultMaxWaitDays;
if (ctx.Tick - t.ArrivedTick >= (long)maxDays * w.Calendar.TicksPerDay) return true;
return IsFull(w, t);
}
public static void Depart(WorldContext ctx, Train t)
{
var w = ctx.World;
if (t.Line.IsValid && !w.Lines[t.Line.Value].Removed && t.AtNode.IsValid)
{
var line = w.Lines[t.Line.Value];
var node = w.Network.Nodes[t.AtNode.Value];
if (line.Stops.Count > 0 && node.Station.IsValid && line.Stops[t.StopIndex % line.Stops.Count].Station == node.Station)
t.StopIndex = (t.StopIndex + 1) % line.Stops.Count;
}
t.Platform = -1;
}
// ------------------------------------------------------------------ scarico
private static int Unload(WorldContext ctx, Train t, Station s, bool unloadOrders)
{
var w = ctx.World;
int moved = 0;
for (int i = t.Cargo.Count - 1; i >= 0; i--)
{
var p = t.Cargo[i];
bool final = p.Destination == s.Id;
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);
}
return moved;
}
private static void Deliver(WorldContext ctx, Train t, Station s, Packet p)
{
var w = ctx.World;
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;
var company = w.Companies[t.Owner.Value];
var tariffs = w.Data.Balance.Tariffs;
if (p.Kind == PacketKind.Freight)
{
var def = w.Data.Goods[p.Good];
var fare = Tariffs.Freight(p.Units, km, w.Market.GlobalPrice[p.Good], def.BasePrice, days, p.ExpectedDays, tariffs, w.Difficulty.TariffMultiplier);
w.Money.Transfer(Account.External, Account.Of(company.Id), fare, LedgerEntry.FreightRevenue);
t.RevenueThisYear += fare.Cents;
if (s.Incoming.Length > p.Good) s.Incoming[p.Good] = Math.Max(0, s.Incoming[p.Good] - p.Units);
p.AwaitingConsumer = true;
p.Units = DeliverToConsumers(w, s, p.Good, p.Units);
if (p.Units > 0)
{
p.ExpiresTick = ctx.Tick + (long)w.Data.Goods[p.Good].DecayDaysAtStation * w.Calendar.TicksPerDay;
s.Waiting.Add(p);
}
return;
}
// passeggeri
var cls = p.Kind == PacketKind.Staff ? PaxClass.Staff : PaxClass.Worker;
var fareP = Tariffs.Passenger(p.Units, km, cls, days, p.ExpectedDays, tariffs, w.Difficulty.TariffMultiplier);
w.Money.Transfer(Account.External, Account.Of(company.Id), fareP, LedgerEntry.PassengerRevenue);
t.RevenueThisYear += fareP.Cents;
if (p.ReturnTrip || p.Contract < 0) return;
var contract = w.Commutes.FirstOrDefault(c => c.Id.Value == p.Contract);
if (contract is null) return;
contract.ArrivedToday += p.Units;
// il ritorno a casa parte all'arrivo
var back = new Packet
{
Id = w.NextIds.Packet++,
Kind = p.Kind,
Good = -1,
Units = p.Units,
Origin = s.Id,
Destination = p.Origin,
CreatedTick = ctx.Tick,
ExpiresTick = ctx.Tick + (long)w.Data.Balance.Employment.ReturnBoardDays * w.Calendar.TicksPerDay,
Contract = p.Contract,
ReturnTrip = true,
};
if (Route(w, s, ref back)) s.Waiting.Add(back);
}
private static void Transfer(WorldContext ctx, Station s, Packet p)
{
var w = ctx.World;
if (Route(w, s, ref p))
{
s.Waiting.Add(p);
return;
}
// nessun collegamento ulteriore: le merci provano a essere consegnate qui, i passeggeri rinunciano
if (p.Kind == PacketKind.Freight)
{
p.AwaitingConsumer = true;
p.Units = DeliverToConsumers(w, s, p.Good, p.Units);
if (p.Units > 0) s.Waiting.Add(p);
}
}
/// <summary>Assegna al pacchetto il prossimo tratto verso la destinazione; false se irraggiungibile.</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).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);
return true;
}
/// <summary>
/// Consegna le unità ai consumatori del bacino (industrie con spazio, città con domanda, hub
/// per l'esportazione) e restituisce quelle rimaste. Le industrie pagano al prezzo globale.
/// </summary>
public static int DeliverToConsumers(World w, Station s, int good, int units)
{
int dpm = w.Calendar.DaysPerMonth;
foreach (var id in s.Industries)
{
if (units <= 0) return 0;
var ind = w.Industries[id.Value];
if (ind.Closed) continue;
int i = ind.InputIndexOf(good);
if (i < 0) continue;
int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
int take = Math.Min(units, Math.Max(0, free));
if (take <= 0) continue;
ind.InputStock[i] += take;
units -= take;
var cost = Money.FromCentsRounded(take * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.Of(ind.Id), Account.External, cost, LedgerEntry.Other);
ind.PurchasesToday += cost.Cents;
}
var tb = w.Data.Balance.Town;
foreach (var id in s.Towns)
{
if (units <= 0) return 0;
var town = w.Towns[id.Value];
double demand = town.DemandToday[good];
if (demand <= 0) continue;
int free = (int)Math.Ceiling(demand * tb.StockDays) - town.Stock[good];
int take = Math.Min(units, Math.Max(0, free));
if (take <= 0) continue;
town.Stock[good] += take;
units -= take;
}
foreach (var id in s.Hubs)
{
if (units <= 0) return 0;
var hub = w.Hubs[id.Value];
int take = Math.Min(units, hub.RemainingCapacity);
if (take <= 0) continue;
hub.UsedThisMonth += take;
hub.ExportedThisMonth[good] += take;
w.Goods.Exported[good] += take;
units -= take;
}
return units;
}
// ------------------------------------------------------------------ carico
/// <summary>Carica i pacchetti in attesa che viaggiano sulla linea del treno; restituisce le unità caricate.</summary>
public static int Load(WorldContext ctx, Train t, Station s)
{
var w = ctx.World;
if (!t.Line.IsValid) return 0;
int loaded = 0;
for (int i = 0; i < s.Waiting.Count; i++)
{
var p = s.Waiting[i];
if (p.AwaitingConsumer || p.HopLine != t.Line) continue;
int capacity = FreeCapacity(w, t, p);
if (capacity <= 0) continue;
int take = Math.Min(capacity, p.Units);
var aboard = p;
aboard.Units = take;
if (take < p.Units)
{
aboard.Id = w.NextIds.Packet++;
p.Units -= take;
s.Waiting[i] = p;
}
else
{
s.Waiting.RemoveAt(i);
i--;
}
AddToVehicles(w, t, aboard);
t.Cargo.Add(aboard);
loaded += take;
}
return loaded;
}
private static int FreeCapacity(World w, Train t, Packet p)
{
int free = 0;
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
if (p.Kind == PacketKind.Freight)
{
if (v.Def.Kind != VehicleKind.Wagon || Array.IndexOf(v.Def.GoodIndices, p.Good) < 0) continue;
if (v.Good >= 0 && v.Good != p.Good) continue;
free += (v.Def.Capacity ?? 0) - v.Load;
}
else
{
if (v.Def.Kind != VehicleKind.Coach) continue;
if ((v.Def.Class == PaxClass.Staff) != (p.Kind == PacketKind.Staff)) continue;
free += (v.Def.PaxCapacity ?? 0) - v.Pax;
}
}
return free;
}
private static void AddToVehicles(World w, Train t, Packet p)
{
int units = p.Units;
foreach (var id in t.Vehicles)
{
if (units <= 0) return;
var v = w.Vehicles[id.Value];
if (p.Kind == PacketKind.Freight)
{
if (v.Def.Kind != VehicleKind.Wagon || Array.IndexOf(v.Def.GoodIndices, p.Good) < 0) continue;
if (v.Good >= 0 && v.Good != p.Good) continue;
int take = Math.Min(units, (v.Def.Capacity ?? 0) - v.Load);
if (take <= 0) continue;
v.Good = p.Good;
v.Load += take;
units -= take;
}
else
{
if (v.Def.Kind != VehicleKind.Coach || (v.Def.Class == PaxClass.Staff) != (p.Kind == PacketKind.Staff)) continue;
int take = Math.Min(units, (v.Def.PaxCapacity ?? 0) - v.Pax);
if (take <= 0) continue;
v.Pax += take;
units -= take;
}
}
}
private static void RemoveFromVehicles(World w, Train t, Packet p)
{
int units = p.Units;
foreach (var id in t.Vehicles)
{
if (units <= 0) return;
var v = w.Vehicles[id.Value];
if (p.Kind == PacketKind.Freight)
{
if (v.Good != p.Good) continue;
int take = Math.Min(units, v.Load);
v.Load -= take;
units -= take;
if (v.Load == 0) v.Good = -1;
}
else
{
if (v.Def.Kind != VehicleKind.Coach || (v.Def.Class == PaxClass.Staff) != (p.Kind == PacketKind.Staff)) continue;
int take = Math.Min(units, v.Pax);
v.Pax -= take;
units -= take;
}
}
}
private static bool IsFull(World w, Train t)
{
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
if (v.Def.Kind == VehicleKind.Wagon && v.Load < (v.Def.Capacity ?? 0)) return false;
if (v.Def.Kind == VehicleKind.Coach && v.Pax < (v.Def.PaxCapacity ?? 0)) return false;
}
return true;
}
}
@@ -0,0 +1,590 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Marcia dei treni (guida 8.4) con il segnalamento a blocchi:
/// - percorsi A* fino alla prossima fermata;
/// - autorizzazione al movimento: sezioni di blocco prenotate davanti alla testa; su binario
/// semplice si blocca il verso di tutti gli archi fino al primo punto sicuro (stazione con
/// binario libero, deposito, doppio binario, destinazione), così due treni non si trovano mai
/// faccia a faccia;
/// - fisica: a = (Ft − R)/m con Ft = min(P/v, sforzo di trazione, aderenza) e
/// R = m·g·(attrito + pendenza) + 0,6·v²·cx; frenata costante con anticipo sui limiti;
/// - le risorse si liberano quando la coda le ha superate.
/// Nessuna allocazione nel ciclo per treno: liste del treno riutilizzate.
/// </summary>
public sealed class TrainSystem : ISimSystem
{
public string Name => "Trains";
private const byte HeldBlock = 0;
private const byte HeldPlatform = 1;
private const byte HeldLock = 2;
private double _dt, _brake, _g, _rolling, _aero, _adhesion, _stallSpeed, _stallSeconds, _margin, _maxTurn;
private int _ticksPerDay;
public void Step(WorldContext ctx)
{
var w = ctx.World;
var phys = w.Data.Construction.Physics;
_dt = w.Calendar.TrainSecondsPerTick;
_brake = phys.BrakingMs2;
_g = phys.Gravity;
_rolling = phys.RollingResistance;
_aero = phys.AeroCoefficient;
_adhesion = phys.Adhesion * phys.AdhesionFactor;
_stallSpeed = phys.StallSpeedKmh / 3.6;
_stallSeconds = phys.StallSeconds;
_margin = w.Data.Construction.Operations.LookaheadMarginM;
_maxTurn = w.Data.Construction.Operations.MaxTurnDeg;
_ticksPerDay = w.Calendar.TicksPerDay;
foreach (var t in w.Trains)
{
if (t.Removed) continue;
switch (t.State)
{
case TrainState.InDepot:
if (WantsToLeaveDepot(w, t)) TryPlanLeg(ctx, t);
break;
case TrainState.Loading:
StationWork.Dwell(ctx, t);
if (t.State == TrainState.Loading && StationWork.ReadyToDepart(ctx, t))
{
StationWork.Depart(ctx, t);
TryPlanLeg(ctx, t);
}
break;
case TrainState.NoRoute:
if ((ctx.Tick + t.Id.Value) % _ticksPerDay == 0) TryPlanLeg(ctx, t);
break;
case TrainState.Waiting:
case TrainState.Moving:
case TrainState.Stalled:
Move(ctx, t);
break;
}
}
}
private static bool WantsToLeaveDepot(World w, Train t)
{
if (t.GoingToDepot.IsValid) return w.Network.Depots[t.GoingToDepot.Value].Node != t.AtNode;
return t.Line.IsValid && !w.Lines[t.Line.Value].Removed && w.Lines[t.Line.Value].Stops.Count > 0;
}
// ------------------------------------------------------------------ pianificazione
/// <summary>Calcola il percorso verso la prossima destinazione del treno fermo in un nodo.</summary>
public void TryPlanLeg(WorldContext ctx, Train t)
{
var w = ctx.World;
var net = w.Network;
NodeId target;
if (t.GoingToDepot.IsValid) target = net.Depots[t.GoingToDepot.Value].Node;
else if (t.Line.IsValid && !w.Lines[t.Line.Value].Removed && w.Lines[t.Line.Value].Stops.Count > 0)
{
var line = w.Lines[t.Line.Value];
if (t.StopIndex >= line.Stops.Count) t.StopIndex = 0;
target = net.Stations[line.Stops[t.StopIndex].Station.Value].Node;
}
else if (t.HomeDepot.IsValid && net.Depots[t.HomeDepot.Value].Node != t.AtNode) target = net.Depots[t.HomeDepot.Value].Node;
else
{
if (t.AtNode.IsValid && net.Nodes[t.AtNode.Value].Depot.IsValid) t.State = TrainState.InDepot;
return;
}
if (t.AtNode == target)
{
t.Route.Clear();
Arrive(ctx, t, target);
return;
}
var arrived = Pathfinder.IsTurningPoint(net, net.Nodes[t.AtNode.Value]) ? EdgeId.None : t.ArrivedVia;
if (!w.Pathfinder.FindPath(net, t.Owner, t.AtNode, arrived, target, t.MaxSpeedKmh, t.NeedsElectrification, _maxTurn, t.Route))
{
if (t.State != TrainState.NoRoute)
{
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Train, EventSeverity.Warning,
$"{t.Name}: nessun percorso verso la prossima fermata", EntityKind.Train, t.Id.Value, t.Owner));
}
t.State = TrainState.NoRoute;
return;
}
// lascia il nodo di partenza: deposito (nessuna risorsa) o stazione (il binario resta tenuto finché la coda non esce)
for (int i = 0; i < t.Held.Count; i++)
{
var h = t.Held[i];
if (h.Kind == HeldPlatform && double.IsNaN(h.LeftAt))
{
h.LeftAt = t.Odometer;
t.Held[i] = h;
}
}
t.RouteIndex = 0;
t.StepPos = 0;
t.Speed = 0;
t.ReservedStep = -1;
t.ReservedBlock = -1;
t.ArrivalPlatform = -1;
t.State = TrainState.Waiting;
t.WaitingSinceTick = ctx.Tick;
t.WaitWarned = false;
t.StallSeconds = 0;
t.AtNode = NodeId.None;
}
// ------------------------------------------------------------------ marcia
private void Move(WorldContext ctx, Train t)
{
var w = ctx.World;
var net = w.Network;
if (t.Route.Count == 0)
{
t.State = TrainState.NoRoute;
return;
}
// 1. estende l'autorizzazione al movimento fino alla distanza di frenata con margine
double needed = t.Speed * t.Speed / (2 * _brake) + t.Speed * _dt * 2 + _margin;
double ma = MaDistance(net, t);
while (ma < needed && TryReserveNext(w, t))
ma = MaDistance(net, t);
// 2. velocità obiettivo: limiti presenti e futuri, fine dell'autorizzazione, fermata
var step = t.Route[t.RouteIndex];
var edge = net.Edges[step.Edge.Value];
double cond = ConstructionSystem.ConditionFactor(w, edge);
double limit = Math.Min(t.MaxSpeedKmh, LimitAt(edge, step.Forward, t.StepPos) * cond) / 3.6;
double target = Math.Min(limit, Math.Sqrt(2 * _brake * Math.Max(0, ma - 1)));
target = Math.Min(target, LookaheadCap(w, t, needed + 500));
// 3. dinamica
double cargoT = CargoMassT(w, t);
double mass = (t.EmptyMassT + cargoT) * 1000;
double grade = step.Forward ? edge.GradeAt(t.StepPos) : -edge.GradeAt(edge.Length - t.StepPos);
double v = t.Speed;
double resist = mass * _g * (_rolling + grade) + _aero * v * v * t.Cx;
double traction = Math.Min(Math.Min(t.PowerKw * 1000 / Math.Max(v, 1), t.TractiveKn * 1000), _adhesion * t.LocoMassT * 1000 * _g);
double a = (traction - resist) / mass;
double vNew;
if (v < target - 1e-3) vNew = Math.Min(target, v + a * _dt);
else vNew = Math.Max(target, v - _brake * _dt);
if (vNew < 0) vNew = 0;
// stallo: vuole muoversi ma non riesce a vincere la salita
if (target > _stallSpeed && vNew < _stallSpeed && a <= 0)
{
t.StallSeconds += _dt;
if (t.StallSeconds >= _stallSeconds && t.State != TrainState.Stalled)
{
t.State = TrainState.Stalled;
w.Events.Add(new GameEvent(ctx.Day, EventKind.Train, EventSeverity.Critical,
$"{t.Name} non supera la salita del {Math.Abs(grade) * 100:F1}%: aggiungi una locomotiva o cambia tracciato",
EntityKind.Train, t.Id.Value, t.Owner));
}
}
else if (vNew > _stallSpeed)
{
t.StallSeconds = 0;
if (t.State == TrainState.Stalled) t.State = TrainState.Moving;
}
double dist = (v + vNew) / 2 * _dt;
if (dist >= ma)
{
dist = Math.Max(0, ma);
vNew = 0;
}
t.Speed = vNew;
if (t.State != TrainState.Stalled) t.State = vNew > 0.01 || dist > 0.01 ? TrainState.Moving : TrainState.Waiting;
if (t.State == TrainState.Moving) t.WaitingSinceTick = ctx.Tick;
else if (!t.WaitWarned && ctx.Tick - t.WaitingSinceTick > (long)w.Data.Construction.Operations.WaitWarningDays * _ticksPerDay)
{
t.WaitWarned = true;
w.Events.Add(new GameEvent(ctx.Day, EventKind.Train, EventSeverity.Warning,
$"{t.Name} è fermo da {w.Data.Construction.Operations.WaitWarningDays} giorni in attesa di via libera: possibile stallo della rete",
EntityKind.Train, t.Id.Value, t.Owner));
}
// 4. avanzamento lungo il percorso
if (dist > 0) Advance(ctx, t, dist, v, cargoT);
ReleaseBehind(net, t);
}
private void Advance(WorldContext ctx, Train t, double dist, double v, double cargoT)
{
var w = ctx.World;
var net = w.Network;
while (dist > 1e-9)
{
var step = t.Route[t.RouteIndex];
var edge = net.Edges[step.Edge.Value];
double remaining = edge.Length - t.StepPos;
double move = Math.Min(dist, remaining);
double before = t.StepPos;
t.StepPos += move;
t.Odometer += move;
t.KmThisYear += move / 1000;
dist -= move;
// usura: tonnellate × fattori, ripartite sulla frazione d'arco percorsa
double grade = Math.Abs(step.Forward ? edge.GradeAt(before) : edge.GradeAt(edge.Length - before));
double vmaxEdge = Math.Max(1, w.Data.Eras.TrackClasses[edge.TrackClass].SpeedKmh / 3.6);
var tw = w.Data.Construction.TrackWear;
edge.WearToday += (t.EmptyMassT + cargoT) * (move / edge.Length) * (1 + tw.GradientWeight * grade) * (1 + tw.SpeedWeight * v / vmaxEdge);
// sezioni di blocco superate dalla testa
int blockBefore = BlockOf(edge, step.Forward, before);
int blockAfter = BlockOf(edge, step.Forward, Math.Min(t.StepPos, edge.Length - 1e-6));
for (int b = blockBefore; b < blockAfter; b++) MarkLeft(t, HeldBlock, edge.Id.Value, b, step.Forward, t.Odometer);
if (t.StepPos < edge.Length - 1e-6) break;
// la testa lascia l'arco
MarkLeft(t, HeldBlock, edge.Id.Value, LastBlock(edge), step.Forward, t.Odometer);
MarkLeft(t, HeldLock, edge.Id.Value, 0, step.Forward, t.Odometer);
var node = step.Forward ? edge.B : edge.A;
if (t.RouteIndex == t.Route.Count - 1)
{
Arrive(ctx, t, node);
return;
}
// binario di stazione attraversato (punto sicuro intermedio)
var through = net.Nodes[node.Value];
if (through.Station.IsValid) MarkLeft(t, HeldPlatform, through.Station.Value, -1, true, t.Odometer);
t.RouteIndex++;
t.StepPos = 0;
}
}
private static void MarkLeft(Train t, byte kind, int id, int index, bool forward, double odometer)
{
for (int i = 0; i < t.Held.Count; i++)
{
var h = t.Held[i];
if (h.Kind != kind || h.Id != id || !double.IsNaN(h.LeftAt)) continue;
if (kind == HeldBlock && (h.Index != index || h.Forward != forward)) continue;
if (kind == HeldLock && h.Forward != forward) continue;
h.LeftAt = odometer;
t.Held[i] = h;
return;
}
}
/// <summary>Libera le risorse superate dalla coda.</summary>
private static void ReleaseBehind(RailNetwork net, Train t)
{
for (int i = t.Held.Count - 1; i >= 0; i--)
{
var h = t.Held[i];
if (double.IsNaN(h.LeftAt) || t.Odometer - h.LeftAt < t.LengthM) continue;
Release(net, t, h);
t.Held.RemoveAt(i);
}
}
private static void Release(RailNetwork net, Train t, HeldResource h)
{
switch (h.Kind)
{
case HeldBlock:
{
var e = net.Edges[h.Id];
var blocks = h.Forward ? e.BlocksForward : e.BlocksBackward;
if (h.Index < blocks.Length && blocks[h.Index] == t.Id.Value) blocks[h.Index] = -1;
break;
}
case HeldLock:
{
var e = net.Edges[h.Id];
if (e.LockCount > 0) e.LockCount--;
if (e.LockCount == 0) e.LockDir = -1;
break;
}
default:
{
var s = net.Stations[h.Id];
for (int p = 0; p < s.PlatformTrain.Length; p++)
{
if (s.PlatformTrain[p] == t.Id.Value && (h.Index < 0 || h.Index == p)) s.PlatformTrain[p] = -1;
}
break;
}
}
}
/// <summary>Libera immediatamente tutto (treno rimosso o rientrato in deposito).</summary>
public static void ReleaseAll(RailNetwork net, Train t)
{
foreach (var h in t.Held) Release(net, t, h);
t.Held.Clear();
}
private void Arrive(WorldContext ctx, Train t, NodeId node)
{
var w = ctx.World;
var net = w.Network;
var n = net.Nodes[node.Value];
// in stazione e in deposito il treno è tutto dentro: le risorse dell'arco d'arrivo si liberano
for (int i = 0; i < t.Held.Count; i++)
{
var h = t.Held[i];
if (h.Kind == HeldPlatform && h.Id == n.Station.Value && n.Station.IsValid) continue;
if (double.IsNaN(h.LeftAt)) h.LeftAt = t.Odometer;
h.LeftAt -= t.LengthM;
t.Held[i] = h;
}
ReleaseBehind(net, t);
if (t.Route.Count > 0) t.ArrivedVia = t.Route[^1].Edge;
t.Route.Clear();
t.RouteIndex = 0;
t.StepPos = 0;
t.Speed = 0;
t.AtNode = node;
t.ReservedStep = -1;
t.ReservedBlock = -1;
if (n.Depot.IsValid && (t.GoingToDepot == n.Depot || (!t.Line.IsValid && t.HomeDepot == n.Depot)))
{
ReleaseAll(net, t);
t.State = TrainState.InDepot;
t.GoingToDepot = DepotId.None;
return;
}
if (n.Station.IsValid)
{
t.Platform = t.ArrivalPlatform;
t.ArrivalPlatform = -1;
StationWork.Arrive(ctx, t, net.Stations[n.Station.Value]);
return;
}
// nodo qualunque (deposito di passaggio, binario morto): ripianifica
t.State = TrainState.Waiting;
TryPlanLeg(ctx, t);
}
// ------------------------------------------------------------------ prenotazioni
/// <summary>Distanza dalla testa alla fine dell'autorizzazione al movimento.</summary>
private static double MaDistance(RailNetwork net, Train t)
{
if (t.ReservedStep < t.RouteIndex) return 0;
double dist = 0;
for (int s = t.RouteIndex; s <= t.ReservedStep; s++)
{
var step = t.Route[s];
var e = net.Edges[step.Edge.Value];
double from = s == t.RouteIndex ? t.StepPos : 0;
double to = s == t.ReservedStep ? BlockEnd(e, step.Forward, t.ReservedBlock) : e.Length;
dist += Math.Max(0, to - from);
}
return dist;
}
private bool TryReserveNext(World w, Train t)
{
var net = w.Network;
if (t.ReservedStep >= 0)
{
var cur = t.Route[t.ReservedStep];
var ce = net.Edges[cur.Edge.Value];
if (t.ReservedBlock < LastBlock(ce))
{
// sezione successiva sullo stesso arco
var blocks = cur.Forward ? ce.BlocksForward : ce.BlocksBackward;
int next = t.ReservedBlock + 1;
if (blocks[next] >= 0 && blocks[next] != t.Id.Value) return false;
blocks[next] = t.Id.Value;
t.Held.Add(new HeldResource { Kind = HeldBlock, Id = ce.Id.Value, Index = next, Forward = cur.Forward, LeftAt = double.NaN });
t.ReservedBlock = next;
return true;
}
if (t.ReservedStep >= t.Route.Count - 1) return false; // tutto prenotato fino alla destinazione
}
int s = t.ReservedStep + 1;
return EnterStep(w, t, s);
}
// prenota la prima sezione del passo s; su binario semplice blocca il verso fino a un punto sicuro
private bool EnterStep(World w, Train t, int s)
{
var net = w.Network;
var step = t.Route[s];
var edge = net.Edges[step.Edge.Value];
if (!edge.IsUsable) return false;
var blocks = step.Forward ? edge.BlocksForward : edge.BlocksBackward;
if (blocks[0] >= 0 && blocks[0] != t.Id.Value) return false;
int dir = step.Forward ? 0 : 1;
// catena di archi a binario semplice da bloccare insieme
int last = s;
if (!edge.DoubleTrack)
{
while (last < t.Route.Count - 1 && !IsSafePoint(net, t, last))
{
var ne = net.Edges[t.Route[last + 1].Edge.Value];
if (ne.DoubleTrack) break;
last++;
}
}
// verifica tutto prima di prenotare
for (int k = s; k <= last; k++)
{
var e = net.Edges[t.Route[k].Edge.Value];
if (e.DoubleTrack || HoldsLock(t, e.Id.Value)) continue;
int d = t.Route[k].Forward ? 0 : 1;
if (!e.IsUsable || (e.LockDir >= 0 && e.LockDir != d)) return false;
}
int platform = -1;
StationId platformStation = StationId.None;
var endNode = net.Nodes[(t.Route[last].Forward ? net.Edges[t.Route[last].Edge.Value].B : net.Edges[t.Route[last].Edge.Value].A).Value];
bool chainNeedsPlatform = endNode.Station.IsValid && (last == t.Route.Count - 1 || !edge.DoubleTrack);
if (chainNeedsPlatform && !HoldsPlatform(t, endNode.Station.Value))
{
var st = net.Stations[endNode.Station.Value];
platform = Array.IndexOf(st.PlatformTrain, -1);
if (platform < 0) return false;
platformStation = st.Id;
}
// prenota
for (int k = s; k <= last; k++)
{
var e = net.Edges[t.Route[k].Edge.Value];
if (e.DoubleTrack || HoldsLock(t, e.Id.Value)) continue;
int d = t.Route[k].Forward ? 0 : 1;
e.LockDir = d;
e.LockCount++;
t.Held.Add(new HeldResource { Kind = HeldLock, Id = e.Id.Value, Forward = t.Route[k].Forward, LeftAt = double.NaN });
}
blocks[0] = t.Id.Value;
t.Held.Add(new HeldResource { Kind = HeldBlock, Id = edge.Id.Value, Index = 0, Forward = step.Forward, LeftAt = double.NaN });
if (platformStation.IsValid)
{
var st = net.Stations[platformStation.Value];
st.PlatformTrain[platform] = t.Id.Value;
t.Held.Add(new HeldResource { Kind = HeldPlatform, Id = st.Id.Value, Index = platform, Forward = true, LeftAt = double.NaN });
if (last == t.Route.Count - 1) t.ArrivalPlatform = platform;
}
t.ReservedStep = s;
t.ReservedBlock = 0;
_ = dir;
return true;
}
// punto sicuro alla fine del passo k: stazione o deposito, destinazione, o arco successivo a doppio binario
private static bool IsSafePoint(RailNetwork net, Train t, int k)
{
if (k >= t.Route.Count - 1) return true;
var e = net.Edges[t.Route[k].Edge.Value];
var node = net.Nodes[(t.Route[k].Forward ? e.B : e.A).Value];
if (node.Station.IsValid || node.Depot.IsValid) return true;
return net.Edges[t.Route[k + 1].Edge.Value].DoubleTrack;
}
private static bool HoldsLock(Train t, int edge)
{
foreach (var h in t.Held)
{
if (h.Kind == HeldLock && h.Id == edge && double.IsNaN(h.LeftAt)) return true;
}
return false;
}
private static bool HoldsPlatform(Train t, int station)
{
foreach (var h in t.Held)
{
if (h.Kind == HeldPlatform && h.Id == station && double.IsNaN(h.LeftAt)) return true;
}
return false;
}
// ------------------------------------------------------------------ geometria dei blocchi
/// <summary>Indice dell'ultima sezione di blocco dell'arco.</summary>
public static int LastBlock(TrackEdge e) => e.Signals.Count;
/// <summary>Fine (progressiva nel verso di marcia) della sezione j.</summary>
public static double BlockEnd(TrackEdge e, bool forward, int j)
{
int n = e.Signals.Count;
if (j >= n) return e.Length;
return forward ? e.Signals[j] : e.Length - e.Signals[n - 1 - j];
}
/// <summary>Sezione che contiene la progressiva pos (nel verso di marcia).</summary>
public static int BlockOf(TrackEdge e, bool forward, double pos)
{
int j = 0;
while (j < e.Signals.Count && pos >= BlockEnd(e, forward, j)) j++;
return j;
}
// ------------------------------------------------------------------ limiti e anticipo
private static double LimitAt(TrackEdge e, bool forward, double pos)
{
double s = forward ? pos : e.Length - pos;
return e.SpeedLimitKmh[e.SampleIndex(s)];
}
// velocità massima compatibile con i limiti più bassi entro la distanza di osservazione
private double LookaheadCap(World w, Train t, double horizon)
{
var net = w.Network;
double cap = double.MaxValue;
double dist = 0;
for (int s = t.RouteIndex; s < t.Route.Count && dist < horizon; s++)
{
var step = t.Route[s];
var e = net.Edges[step.Edge.Value];
double cond = ConstructionSystem.ConditionFactor(w, e);
double start = s == t.RouteIndex ? t.StepPos : 0;
int n = e.S.Length;
if (step.Forward)
{
for (int i = e.SampleIndex(start) + 1; i < n - 1; i++)
{
double d = dist + e.S[i] - start;
if (d > horizon) break;
double vl = Math.Min(t.MaxSpeedKmh, e.SpeedLimitKmh[i] * cond) / 3.6;
cap = Math.Min(cap, Math.Sqrt(vl * vl + 2 * _brake * Math.Max(0, d)));
}
}
else
{
double sGeo = e.Length - start;
for (int i = e.SampleIndex(sGeo); i > 0; i--)
{
double d = dist + (sGeo - e.S[i]);
if (d > horizon) break;
double vl = Math.Min(t.MaxSpeedKmh, e.SpeedLimitKmh[i - 1] * cond) / 3.6;
cap = Math.Min(cap, Math.Sqrt(vl * vl + 2 * _brake * Math.Max(0, d)));
}
}
dist += e.Length - start;
}
// fermata a fine percorso
if (dist < horizon) cap = Math.Min(cap, Math.Sqrt(2 * _brake * Math.Max(0, dist)));
return cap;
}
private static double CargoMassT(World w, Train t)
{
double m = 0;
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
m += v.Load + v.Pax * 0.08;
}
return m;
}
}