From 18b5e2c2e1ba33a1c35e8156aec9c2f1b2e6c6fe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 23:19:34 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL --- data/balance.json | 3 +- data/construction.json | 22 +- data/schema/construction.schema.json | 30 +- data/vehicles.json | 2 +- src/ViaFerrea.Core/Commands/GameCommand.cs | 4 +- src/ViaFerrea.Core/Commands/RailCommands.cs | 92 +++ src/ViaFerrea.Core/Data/BalanceDefs.cs | 5 + src/ViaFerrea.Core/Data/ConstructionDefs.cs | 28 + src/ViaFerrea.Core/Data/DataValidator.cs | 1 + .../Persistence/RailSerializer.cs | 543 ++++++++++++++++ .../Persistence/WorldSerializer.cs | 4 + src/ViaFerrea.Core/Rail/LineGraph.cs | 170 +++++ src/ViaFerrea.Core/Rail/Network.cs | 269 ++++++++ src/ViaFerrea.Core/Rail/Pathfinder.cs | 113 ++++ src/ViaFerrea.Core/Rail/RailNetwork.cs | 310 +++++++++ src/ViaFerrea.Core/Rail/Trains.cs | 173 +++++ .../Simulation/CommandProcessor.cs | 16 + .../Simulation/RailCommandHandlers.cs | 597 ++++++++++++++++++ .../Simulation/SystemPipeline.cs | 3 + .../Simulation/Systems/ConstructionSystem.cs | 193 ++++++ .../Simulation/Systems/FinanceSystem.cs | 60 ++ .../Simulation/Systems/StationSystem.cs | 206 ++++++ .../Simulation/Systems/StationWork.cs | 365 +++++++++++ .../Simulation/Systems/TrainSystem.cs | 590 +++++++++++++++++ src/ViaFerrea.Core/Simulation/World.cs | 27 + tests/ViaFerrea.Tests/Rail/RailFixture.cs | 81 +++ .../ViaFerrea.Tests/Rail/RailNetworkTests.cs | 127 ++++ tests/ViaFerrea.Tests/Rail/TrainTests.cs | 94 +++ 28 files changed, 4122 insertions(+), 6 deletions(-) create mode 100644 src/ViaFerrea.Core/Commands/RailCommands.cs create mode 100644 src/ViaFerrea.Core/Persistence/RailSerializer.cs create mode 100644 src/ViaFerrea.Core/Rail/LineGraph.cs create mode 100644 src/ViaFerrea.Core/Rail/Network.cs create mode 100644 src/ViaFerrea.Core/Rail/Pathfinder.cs create mode 100644 src/ViaFerrea.Core/Rail/RailNetwork.cs create mode 100644 src/ViaFerrea.Core/Rail/Trains.cs create mode 100644 src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs create mode 100644 src/ViaFerrea.Core/Simulation/Systems/ConstructionSystem.cs create mode 100644 src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs create mode 100644 src/ViaFerrea.Core/Simulation/Systems/StationWork.cs create mode 100644 src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs create mode 100644 tests/ViaFerrea.Tests/Rail/RailFixture.cs create mode 100644 tests/ViaFerrea.Tests/Rail/RailNetworkTests.cs create mode 100644 tests/ViaFerrea.Tests/Rail/TrainTests.cs diff --git a/data/balance.json b/data/balance.json index d506820..aecb0f4 100644 --- a/data/balance.json +++ b/data/balance.json @@ -103,7 +103,8 @@ }, "migration": { "share": 0.01, "satisfactionThreshold": 0.4, "maxDistanceKm": 60, "emigrationShareWhenNoTarget": 0.5 }, "employment": { "walkRadiusKm": 1.5, "workerMaxMinutes": 60, "staffMaxMinutes": 90, "coverageEmaDays": 30, - "dissolveCoverage": 0.5, "dissolveDays": 90, "walkSpeedKmh": 4.5 }, + "dissolveCoverage": 0.5, "dissolveDays": 90, "walkSpeedKmh": 4.5, "boardDays": 2, "returnBoardDays": 2, + "railStartCoverage": 0.5 }, "localTransport": { "enabled": true, "radiusKm": 3.0, "dailyShare": 0.25, "maxUnitsPerDay": 6 }, "hubs": { "port": { "name_it": "Porto", "monthlyCapacity": 3000, "duty": 0.08, "footprint": "large" }, diff --git a/data/construction.json b/data/construction.json index 4897d10..e627ca1 100644 --- a/data/construction.json +++ b/data/construction.json @@ -72,13 +72,31 @@ "speedLimitFactor": 0.5, "closeBelow": 15 }, + "stations": { + "catchmentKm": 2.0, + "areaRadiusM": 120, + "maxPlatforms": 8, + "snapM": 60, + "freightUnitsPerMinutePerWagon": 2.0, + "paxPerMinutePerCoach": 12, + "minDwellMinutes": 3, + "upkeepPerPlatformPerYear": 60000, + "depotUpkeepPerYear": { "small": 120000, "medium": 240000, "large": 480000 } + }, + "operations": { + "maxVehiclesPerTrain": 24, + "maxTurnDeg": 100, + "lookaheadMarginM": 60, + "waitWarningDays": 20, + "defaultMaxWaitDays": 2 + }, "physics": { "gravity": 9.81, - "adhesion": 0.3, + "adhesion": 1.0, "adhesionFactor": 0.3, "rollingResistance": 0.0015, "aeroCoefficient": 0.6, - "cxByKind": { "locomotive": 0.0025, "wagon": 0.0012, "coach": 0.0015 }, + "cxByKind": { "locomotive": 6.0, "wagon": 1.5, "coach": 1.8 }, "brakingMs2": 0.5, "stallSpeedKmh": 1.0, "stallSeconds": 120 diff --git a/data/schema/construction.schema.json b/data/schema/construction.schema.json index 18636ac..b7a8a69 100644 --- a/data/schema/construction.schema.json +++ b/data/schema/construction.schema.json @@ -164,6 +164,32 @@ "string" ] } + }, + "stations": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } + }, + "operations": { + "type": "object", + "additionalProperties": { + "type": [ + "number", + "integer", + "boolean", + "array", + "object", + "string" + ] + } } }, "required": [ @@ -177,7 +203,9 @@ "rules", "trackWear", "structures", - "physics" + "physics", + "stations", + "operations" ], "additionalProperties": false } diff --git a/data/vehicles.json b/data/vehicles.json index ea461f5..5d2cdca 100644 --- a/data/vehicles.json +++ b/data/vehicles.json @@ -3,7 +3,7 @@ "version": 1, "vehicles": [ { "id": "loco_steam_1850", "kind": "locomotive", "name_it": "Ardita 2-6-0", "name_en": "Ardita 2-6-0", - "eraFrom": 1850, "eraTo": 1905, "powerKw": 300, "tractiveEffortKn": 45, "maxSpeedKmh": 60, "massT": 38, "lengthM": 16, + "eraFrom": 1850, "eraTo": 1905, "powerKw": 300, "tractiveEffortKn": 70, "maxSpeedKmh": 60, "massT": 38, "lengthM": 16, "price": 1800000, "runningCostPerYear": 240000, "lifeYears": 25, "traction": "steam", "components": { "engine": 1.0, "wheelsets": 0.8, "brakes": 1.0, "electrics": 0.6 } }, { "id": "loco_steam_1878", "kind": "locomotive", "name_it": "Vittoria 2-8-0", "name_en": "Vittoria 2-8-0", diff --git a/src/ViaFerrea.Core/Commands/GameCommand.cs b/src/ViaFerrea.Core/Commands/GameCommand.cs index 9f35777..ad5ce3f 100644 --- a/src/ViaFerrea.Core/Commands/GameCommand.cs +++ b/src/ViaFerrea.Core/Commands/GameCommand.cs @@ -79,10 +79,12 @@ public abstract record GameCommand public abstract CommandType Type { get; } } -/// Esito di un comando. +/// Esito di un comando; Created elenca gli id delle entità create (binari, stazioni, treni…). public sealed record CommandResult(CompanyId Issuer, uint Seq, CommandType Type, CommandError Error, string Message, long Tick) { public bool Ok => Error == CommandError.None; + + public int[] Created { get; init; } = []; } /// Richiede un prestito entro il fido disponibile. diff --git a/src/ViaFerrea.Core/Commands/RailCommands.cs b/src/ViaFerrea.Core/Commands/RailCommands.cs new file mode 100644 index 0000000..2fa2768 --- /dev/null +++ b/src/ViaFerrea.Core/Commands/RailCommands.cs @@ -0,0 +1,92 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Rail; + +namespace ViaFerrea.Core.Commands; + +/// Costruisce un binario lungo la polilinea (metri). ExpectedCostCents ≠ 0 confronta l'anteprima del client. +public sealed record BuildTrackCommand(IReadOnlyList Polyline, double HeightOffsetM = 0, bool AllowBridges = true, bool AllowTunnels = true, + string TrackClass = "c60", bool DoubleTrack = false, bool Electrified = false, long ExpectedCostCents = 0) : GameCommand +{ + public override CommandType Type => CommandType.BuildTrack; +} + +/// Rinnova un arco (condizione e strutture a 100), chiudendolo per la durata dei lavori. +public sealed record RenewTrackCommand(EdgeId Edge) : GameCommand +{ + public override CommandType Type => CommandType.RenewTrack; +} + +/// Ammoderna un arco: classe di velocità, raddoppio, elettrificazione. +public sealed record UpgradeTrackCommand(EdgeId Edge, string TrackClass, bool DoubleTrack, bool Electrified) : GameCommand +{ + public override CommandType Type => CommandType.UpgradeTrack; +} + +/// Che cosa demolire. +public enum DemolishTarget : byte { Edge = 0, Station = 1, Depot = 2, Signal = 3 } + +/// Demolisce un arco, una stazione, un deposito o i segnali di un arco. +public sealed record DemolishCommand(DemolishTarget Target, int Id) : GameCommand +{ + public override CommandType Type => CommandType.Demolish; +} + +/// Costruisce una stazione (su un binario esistente lo divide, altrimenti crea un nodo isolato). +public sealed record BuildStationCommand(Vec2 Position, int Platforms, string? Name = null) : GameCommand +{ + public override CommandType Type => CommandType.BuildStation; +} + +/// Costruisce un deposito-officina di dimensione small, medium o large. +public sealed record BuildDepotCommand(Vec2 Position, string Size, string? Name = null) : GameCommand +{ + public override CommandType Type => CommandType.BuildDepot; +} + +/// Posa un segnale su un arco alla progressiva indicata (m dall'estremità A). +public sealed record PlaceSignalCommand(EdgeId Edge, double PositionM) : GameCommand +{ + public override CommandType Type => CommandType.PlaceSignal; +} + +/// Acquista veicoli in un deposito. +public sealed record BuyVehicleCommand(string VehicleType, DepotId Depot, int Count = 1) : GameCommand +{ + public override CommandType Type => CommandType.BuyVehicle; +} + +/// Vende un veicolo fermo in deposito. +public sealed record SellVehicleCommand(VehicleId Vehicle) : GameCommand +{ + public override CommandType Type => CommandType.SellVehicle; +} + +/// Compone un treno con veicoli fermi nello stesso deposito (almeno una locomotiva). +public sealed record ComposeTrainCommand(DepotId Depot, IReadOnlyList Vehicles, string? Name = null) : GameCommand +{ + public override CommandType Type => CommandType.ComposeTrain; +} + +/// Crea una linea con le fermate indicate. +public sealed record CreateLineCommand(string Name, string Color, IReadOnlyList Stops) : GameCommand +{ + public override CommandType Type => CommandType.CreateLine; +} + +/// Modifica le fermate (e il nome) di una linea. +public sealed record EditLineCommand(LineId Line, IReadOnlyList Stops, string? Name = null) : GameCommand +{ + public override CommandType Type => CommandType.EditLine; +} + +/// Assegna un treno a una linea (LineId.None lo toglie dal servizio). +public sealed record AssignTrainCommand(TrainId Train, LineId Line) : GameCommand +{ + public override CommandType Type => CommandType.AssignTrain; +} + +/// Manda un treno al deposito indicato. +public sealed record SendToDepotCommand(TrainId Train, DepotId Depot) : GameCommand +{ + public override CommandType Type => CommandType.SendToDepot; +} diff --git a/src/ViaFerrea.Core/Data/BalanceDefs.cs b/src/ViaFerrea.Core/Data/BalanceDefs.cs index e60ff1a..b45b036 100644 --- a/src/ViaFerrea.Core/Data/BalanceDefs.cs +++ b/src/ViaFerrea.Core/Data/BalanceDefs.cs @@ -267,6 +267,11 @@ public sealed class EmploymentBalance public required double DissolveCoverage { get; init; } public required int DissolveDays { get; init; } public required double WalkSpeedKmh { get; init; } + /// Giorni entro cui un pendolare deve salire sul treno, all'andata e al ritorno. + public required int BoardDays { get; init; } + public required int ReturnBoardDays { get; init; } + /// Copertura iniziale di un contratto su rotaia appena creato. + public required double RailStartCoverage { get; init; } } public sealed class LocalTransportBalance diff --git a/src/ViaFerrea.Core/Data/ConstructionDefs.cs b/src/ViaFerrea.Core/Data/ConstructionDefs.cs index 49113aa..dcedff5 100644 --- a/src/ViaFerrea.Core/Data/ConstructionDefs.cs +++ b/src/ViaFerrea.Core/Data/ConstructionDefs.cs @@ -17,9 +17,37 @@ public sealed class ConstructionFile public required ConstructionRules Rules { get; init; } public required TrackWearParams TrackWear { get; init; } public required StructureParams Structures { get; init; } + public required StationParams Stations { get; init; } + public required OperationsParams Operations { get; init; } public required PhysicsParams Physics { get; init; } } +public sealed class StationParams +{ + /// Raggio del bacino: industrie, città e hub serviti dalla stazione. + public required double CatchmentKm { get; init; } + /// Raggio dell'area occupata (vietata ai binari che non terminano lì). + public required double AreaRadiusM { get; init; } + public required int MaxPlatforms { get; init; } + /// Distanza di aggancio delle estremità dei binari a nodi e archi esistenti. + public required double SnapM { get; init; } + public required double FreightUnitsPerMinutePerWagon { get; init; } + public required double PaxPerMinutePerCoach { get; init; } + public required double MinDwellMinutes { get; init; } + public required long UpkeepPerPlatformPerYear { get; init; } + public required Dictionary DepotUpkeepPerYear { get; init; } +} + +public sealed class OperationsParams +{ + public required int MaxVehiclesPerTrain { get; init; } + /// Angolo massimo di svolta a un nodo che non sia stazione o deposito (niente inversioni sugli scambi). + public required double MaxTurnDeg { get; init; } + public required double LookaheadMarginM { get; init; } + public required int WaitWarningDays { get; init; } + public required int DefaultMaxWaitDays { get; init; } +} + public sealed class ProfileParams { public required double SampleSpacingM { get; init; } diff --git a/src/ViaFerrea.Core/Data/DataValidator.cs b/src/ViaFerrea.Core/Data/DataValidator.cs index 13ab95d..b4c08ed 100644 --- a/src/ViaFerrea.Core/Data/DataValidator.cs +++ b/src/ViaFerrea.Core/Data/DataValidator.cs @@ -193,6 +193,7 @@ public static class DataValidator if (!CellTypeKeys.Contains(k)) Err("construction.json", $"costs.terrainModifiers: tipo di cella sconosciuto «{k}»"); } RequireKeys("construction.json", "physics.cxByKind", c.Physics.CxByKind.Keys, ["locomotive", "wagon", "coach"], errors); + RequireKeys("construction.json", "stations.depotUpkeepPerYear", c.Stations.DepotUpkeepPerYear.Keys, SizeKeys, errors); if (c.Profile.SmoothingWindow % 2 == 0) Err("construction.json", "profile.smoothingWindow deve essere dispari"); if (c.Profile.RiverWidthMByClass.Length != 4) Err("construction.json", "profile.riverWidthMByClass deve avere 4 valori (classi 1–4)"); diff --git a/src/ViaFerrea.Core/Persistence/RailSerializer.cs b/src/ViaFerrea.Core/Persistence/RailSerializer.cs new file mode 100644 index 0000000..9223e84 --- /dev/null +++ b/src/ViaFerrea.Core/Persistence/RailSerializer.cs @@ -0,0 +1,543 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Rail; +using ViaFerrea.Core.Simulation; + +namespace ViaFerrea.Core.Persistence; + +/// Serializzazione dello stato ferroviario: rete, cantieri, veicoli, treni, linee, pacchetti. +public static class RailSerializer +{ + public static void Write(World w, SaveWriter s) + { + var net = w.Network; + s.Write(net.NextProject); + s.Write(net.Nodes.Count); + foreach (var n in net.Nodes) + { + s.Write(n.Position.X); + s.Write(n.Position.Y); + s.Write(n.HeightM); + s.Write(n.Owner.Value); + s.Write(n.Station.Value); + s.Write(n.Depot.Value); + s.Write(n.Removed); + s.Write(n.Edges.Count); + foreach (var e in n.Edges) s.Write(e.Value); + } + + s.Write(net.Edges.Count); + foreach (var e in net.Edges) + { + s.Write(e.A.Value); + s.Write(e.B.Value); + s.Write(e.Owner.Value); + s.Write(e.TrackClass); + s.Write(e.DoubleTrack); + s.Write(e.Electrified); + s.Write((byte)e.State); + s.Write(e.S); + s.Write(e.X); + s.Write(e.Y); + s.Write(e.H); + s.Write(e.Ground); + s.Write(e.Kinds.Length); + foreach (var k in e.Kinds) s.Write((byte)k); + s.Write(e.SpeedLimitKmh); + s.Write(e.Condition); + s.Write(e.StructureCondition); + s.Write(e.BuiltDay); + s.Write(e.LastRenewalDay); + s.Write(e.LastInspectionDay); + s.Write(e.BuildCostCents); + s.Write(e.Project); + s.Write(e.Signals.Count); + foreach (double sig in e.Signals) s.Write(sig); + s.Write(e.LockDir); + s.Write(e.LockCount); + s.Write(e.BlocksForward); + s.Write(e.BlocksBackward); + s.Write(e.WearToday); + s.Write(e.TonnesThisYear); + } + + s.Write(net.Stations.Count); + foreach (var st in net.Stations) + { + s.Write(st.Owner.Value); + s.Write(st.Name); + s.Write(st.Node.Value); + s.Write(st.Position.X); + s.Write(st.Position.Y); + s.Write(st.Platforms); + s.Write(st.BuiltDay); + s.Write(st.BuildCostCents); + s.Write(st.PlatformTrain); + s.Write(st.Incoming); + WriteIds(s, st.Industries.Select(i => i.Value)); + WriteIds(s, st.Towns.Select(i => i.Value)); + WriteIds(s, st.Hubs.Select(i => i.Value)); + WritePackets(s, st.Waiting); + } + + s.Write(net.Depots.Count); + foreach (var d in net.Depots) + { + s.Write(d.Owner.Value); + s.Write(d.Name); + s.Write(d.Node.Value); + s.Write(d.Position.X); + s.Write(d.Position.Y); + s.Write(d.Size); + s.Write(d.BuiltDay); + s.Write(d.BuildCostCents); + s.Write(d.SpareParts); + } + + s.Write(net.Projects.Count); + foreach (var p in net.Projects) + { + s.Write(p.Id); + s.Write(p.Owner.Value); + s.Write((byte)p.Kind); + WriteIds(s, p.Edges.Select(e => e.Value)); + s.Write(p.TotalDays); + s.Write(p.ProgressDays); + s.Write(p.Crew); + s.Write(p.QueuedDay); + s.Write(p.StartedDay); + s.Write(p.Done); + s.Write(p.UpgradeClass); + s.Write(p.UpgradeDouble); + s.Write(p.UpgradeElectrified); + s.Write(p.Works.Count); + foreach (var work in p.Works) + { + s.Write((byte)work.Kind); + s.Write(work.StartM); + s.Write(work.EndM); + s.Write(work.MaxHeightM); + s.Write(work.CostCents); + s.Write(work.Days); + s.Write(work.BridgeType); + } + } + + s.Write(w.Vehicles.Count); + foreach (var v in w.Vehicles) + { + s.Write(v.Def.Id); + s.Write(v.Owner.Value); + s.Write(v.BoughtDay); + s.Write(v.Train.Value); + s.Write(v.Depot.Value); + s.Write(v.Sold); + s.Write(v.Components); + s.Write(v.OdometerKm); + s.Write(v.Good); + s.Write(v.Load); + s.Write(v.Pax); + } + + s.Write(w.Lines.Count); + foreach (var l in w.Lines) + { + s.Write(l.Owner.Value); + s.Write(l.Name); + s.Write(l.Color); + s.Write(l.Removed); + s.Write(l.Stops.Count); + foreach (var st in l.Stops) + { + s.Write(st.Station.Value); + s.Write(st.Load); + s.Write(st.Unload); + s.Write(st.WaitFull); + s.Write(st.MaxWaitDays); + } + } + + s.Write(w.Trains.Count); + foreach (var t in w.Trains) + { + s.Write(t.Owner.Value); + s.Write(t.Name); + WriteIds(s, t.Vehicles.Select(v => v.Value)); + s.Write(t.HomeDepot.Value); + s.Write(t.Line.Value); + s.Write(t.StopIndex); + s.Write((byte)t.State); + s.Write(t.Removed); + s.Write(t.Reserve); + s.Write(t.GoingToDepot.Value); + s.Write(t.EmptyMassT); + s.Write(t.LocoMassT); + s.Write(t.PowerKw); + s.Write(t.TractiveKn); + s.Write(t.MaxSpeedKmh); + s.Write(t.LengthM); + s.Write(t.Cx); + s.Write(t.NeedsElectrification); + s.Write(t.Locomotives); + s.Write(t.AtNode.Value); + s.Write(t.ArrivedVia.Value); + s.Write(t.Route.Count); + foreach (var step in t.Route) + { + s.Write(step.Edge.Value); + s.Write(step.Forward); + } + s.Write(t.RouteIndex); + s.Write(t.StepPos); + s.Write(t.Speed); + s.Write(t.Odometer); + s.Write(t.ReservedStep); + s.Write(t.ReservedBlock); + s.Write(t.ArrivalPlatform); + s.Write(t.Held.Count); + foreach (var h in t.Held) + { + s.Write(h.Kind); + s.Write(h.Id); + s.Write(h.Index); + s.Write(h.Forward); + s.Write(h.LeftAt); + } + s.Write(t.DwellTicks); + s.Write(t.ArrivedTick); + s.Write(t.Platform); + s.Write(t.StallSeconds); + s.Write(t.WaitingSinceTick); + s.Write(t.WaitWarned); + WritePackets(s, t.Cargo); + s.Write(t.RevenueThisYear); + s.Write(t.RevenueLastYear); + s.Write(t.KmThisYear); + } + } + + private static void WriteIds(SaveWriter s, IEnumerable ids) + { + var list = ids.ToList(); + s.Write(list.Count); + foreach (int i in list) s.Write(i); + } + + private static void WritePackets(SaveWriter s, List packets) + { + s.Write(packets.Count); + foreach (var p in packets) + { + s.Write(p.Id); + s.Write((byte)p.Kind); + s.Write(p.Good); + s.Write(p.Units); + s.Write(p.Origin.Value); + s.Write(p.Destination.Value); + s.Write(p.HopLine.Value); + s.Write(p.HopEnd.Value); + s.Write(p.CreatedTick); + s.Write(p.ExpiresTick); + s.Write(p.ExpectedDays); + s.Write(p.Contract); + s.Write(p.ReturnTrip); + s.Write(p.AwaitingConsumer); + } + } + + // ------------------------------------------------------------------ lettura + + public static void Read(World w, SaveReader r, int[] goodMap) + { + var net = w.Network; + int goods = w.Data.GoodCount; + int MapGood(int g) => g < 0 ? g : g < goodMap.Length ? goodMap[g] : -1; + + net.NextProject = r.ReadInt32(); + int nodes = r.ReadInt32(); + for (int i = 0; i < nodes; i++) + { + var n = new TrackNode + { + Id = new NodeId(i), + Position = new Vec2(r.ReadDouble(), r.ReadDouble()), + HeightM = r.ReadDouble(), + Owner = new CompanyId(r.ReadInt32()), + Station = new StationId(r.ReadInt32()), + Depot = new DepotId(r.ReadInt32()), + Removed = r.ReadBool(), + }; + int count = r.ReadInt32(); + for (int k = 0; k < count; k++) n.Edges.Add(new EdgeId(r.ReadInt32())); + net.Nodes.Add(n); + } + + int edges = r.ReadInt32(); + for (int i = 0; i < edges; i++) + { + var a = new NodeId(r.ReadInt32()); + var b = new NodeId(r.ReadInt32()); + var owner = new CompanyId(r.ReadInt32()); + int cls = r.ReadInt32(); + bool dbl = r.ReadBool(); + bool ele = r.ReadBool(); + var state = (EdgeState)r.ReadByte(); + var S = r.ReadDoubleArray(); + var X = r.ReadDoubleArray(); + var Y = r.ReadDoubleArray(); + var H = r.ReadDoubleArray(); + var ground = r.ReadDoubleArray(); + var kinds = new WorkKind[r.ReadCount(1)]; + for (int k = 0; k < kinds.Length; k++) kinds[k] = (WorkKind)r.ReadByte(); + var limits = r.ReadDoubleArray(); + var e = new TrackEdge + { + Id = new EdgeId(i), + A = a, + B = b, + Owner = owner, + TrackClass = cls, + DoubleTrack = dbl, + Electrified = ele, + State = state, + S = S, + X = X, + Y = Y, + H = H, + Ground = ground, + Kinds = kinds, + SpeedLimitKmh = limits, + Condition = r.ReadDouble(), + StructureCondition = r.ReadDouble(), + BuiltDay = r.ReadInt64(), + LastRenewalDay = r.ReadInt64(), + LastInspectionDay = r.ReadInt64(), + BuildCostCents = r.ReadInt64(), + Project = r.ReadInt32(), + }; + int signals = r.ReadInt32(); + for (int k = 0; k < signals; k++) e.Signals.Add(r.ReadDouble()); + e.LockDir = r.ReadInt32(); + e.LockCount = r.ReadInt32(); + e.BlocksForward = r.ReadInt32Array(); + e.BlocksBackward = r.ReadInt32Array(); + e.WearToday = r.ReadDouble(); + e.TonnesThisYear = r.ReadDouble(); + net.Edges.Add(e); + } + + int stations = r.ReadInt32(); + for (int i = 0; i < stations; i++) + { + var st = new Station + { + Id = new StationId(i), + Owner = new CompanyId(r.ReadInt32()), + Name = r.ReadRequiredString(), + Node = new NodeId(r.ReadInt32()), + Position = new Vec2(r.ReadDouble(), r.ReadDouble()), + Platforms = r.ReadInt32(), + BuiltDay = r.ReadInt64(), + BuildCostCents = r.ReadInt64(), + PlatformTrain = r.ReadInt32Array(), + }; + var incoming = r.ReadInt32Array(); + st.Incoming = new int[goods]; + for (int g = 0; g < incoming.Length; g++) + { + int m = MapGood(g); + if (m >= 0) st.Incoming[m] = incoming[g]; + } + foreach (int id in ReadIds(r)) st.Industries.Add(new IndustryId(id)); + foreach (int id in ReadIds(r)) st.Towns.Add(new TownId(id)); + foreach (int id in ReadIds(r)) st.Hubs.Add(new HubId(id)); + ReadPackets(r, st.Waiting, MapGood); + net.Stations.Add(st); + } + + int depots = r.ReadInt32(); + for (int i = 0; i < depots; i++) + { + net.Depots.Add(new Depot + { + Id = new DepotId(i), + Owner = new CompanyId(r.ReadInt32()), + Name = r.ReadRequiredString(), + Node = new NodeId(r.ReadInt32()), + Position = new Vec2(r.ReadDouble(), r.ReadDouble()), + Size = r.ReadRequiredString(), + BuiltDay = r.ReadInt64(), + BuildCostCents = r.ReadInt64(), + SpareParts = r.ReadInt32(), + }); + } + + int projects = r.ReadInt32(); + for (int i = 0; i < projects; i++) + { + int id = r.ReadInt32(); + var owner = new CompanyId(r.ReadInt32()); + var kind = (ProjectKind)r.ReadByte(); + var edgeIds = ReadIds(r).Select(x => new EdgeId(x)).ToList(); + double total = r.ReadDouble(); + double progress = r.ReadDouble(); + int crew = r.ReadInt32(); + long queued = r.ReadInt64(); + long started = r.ReadInt64(); + bool done = r.ReadBool(); + int upClass = r.ReadInt32(); + bool upDouble = r.ReadBool(); + bool upElectric = r.ReadBool(); + int works = r.ReadInt32(); + var list = new List(works); + for (int k = 0; k < works; k++) + { + list.Add(new Work((WorkKind)r.ReadByte(), r.ReadDouble(), r.ReadDouble(), r.ReadDouble(), r.ReadInt64(), r.ReadInt32(), r.ReadString())); + } + net.Projects.Add(new ConstructionProject + { + Id = id, + Owner = owner, + Kind = kind, + Edges = edgeIds, + TotalDays = total, + ProgressDays = progress, + Crew = crew, + QueuedDay = queued, + StartedDay = started, + Done = done, + UpgradeClass = upClass, + UpgradeDouble = upDouble, + UpgradeElectrified = upElectric, + Works = list, + }); + } + net.Touch(); + + int vehicles = r.ReadInt32(); + for (int i = 0; i < vehicles; i++) + { + string defId = r.ReadRequiredString(); + if (!w.Data.TryVehicle(defId, out var def) || def is null) throw new InvalidDataException($"Veicolo «{defId}» assente dai dati correnti"); + var v = new Vehicle + { + Id = new VehicleId(i), + Def = def, + Owner = new CompanyId(r.ReadInt32()), + BoughtDay = r.ReadInt64(), + Train = new TrainId(r.ReadInt32()), + Depot = new DepotId(r.ReadInt32()), + Sold = r.ReadBool(), + Components = r.ReadDoubleArray(), + OdometerKm = r.ReadDouble(), + }; + v.Good = MapGood(r.ReadInt32()); + v.Load = r.ReadInt32(); + v.Pax = r.ReadInt32(); + w.Vehicles.Add(v); + } + + int lines = r.ReadInt32(); + for (int i = 0; i < lines; i++) + { + var l = new Line + { + Id = new LineId(i), + Owner = new CompanyId(r.ReadInt32()), + Name = r.ReadRequiredString(), + Color = r.ReadRequiredString(), + Removed = r.ReadBool(), + }; + int stops = r.ReadInt32(); + for (int k = 0; k < stops; k++) + l.Stops.Add(new LineStop(new StationId(r.ReadInt32()), r.ReadBool(), r.ReadBool(), r.ReadBool(), r.ReadInt32())); + w.Lines.Add(l); + } + + int trains = r.ReadInt32(); + for (int i = 0; i < trains; i++) + { + var t = new Train + { + Id = new TrainId(i), + Owner = new CompanyId(r.ReadInt32()), + Name = r.ReadRequiredString(), + }; + foreach (int v in ReadIds(r)) t.Vehicles.Add(new VehicleId(v)); + t.HomeDepot = new DepotId(r.ReadInt32()); + t.Line = new LineId(r.ReadInt32()); + t.StopIndex = r.ReadInt32(); + t.State = (TrainState)r.ReadByte(); + t.Removed = r.ReadBool(); + t.Reserve = r.ReadBool(); + t.GoingToDepot = new DepotId(r.ReadInt32()); + t.EmptyMassT = r.ReadDouble(); + t.LocoMassT = r.ReadDouble(); + t.PowerKw = r.ReadDouble(); + t.TractiveKn = r.ReadDouble(); + t.MaxSpeedKmh = r.ReadDouble(); + t.LengthM = r.ReadDouble(); + t.Cx = r.ReadDouble(); + t.NeedsElectrification = r.ReadBool(); + t.Locomotives = r.ReadInt32(); + t.AtNode = new NodeId(r.ReadInt32()); + t.ArrivedVia = new EdgeId(r.ReadInt32()); + int route = r.ReadInt32(); + for (int k = 0; k < route; k++) t.Route.Add(new RouteStep(new EdgeId(r.ReadInt32()), r.ReadBool())); + t.RouteIndex = r.ReadInt32(); + t.StepPos = r.ReadDouble(); + t.Speed = r.ReadDouble(); + t.Odometer = r.ReadDouble(); + t.ReservedStep = r.ReadInt32(); + t.ReservedBlock = r.ReadInt32(); + t.ArrivalPlatform = r.ReadInt32(); + int held = r.ReadInt32(); + for (int k = 0; k < held; k++) + t.Held.Add(new HeldResource { Kind = r.ReadByte(), Id = r.ReadInt32(), Index = r.ReadInt32(), Forward = r.ReadBool(), LeftAt = r.ReadDouble() }); + t.DwellTicks = r.ReadDouble(); + t.ArrivedTick = r.ReadInt64(); + t.Platform = r.ReadInt32(); + t.StallSeconds = r.ReadDouble(); + t.WaitingSinceTick = r.ReadInt64(); + t.WaitWarned = r.ReadBool(); + ReadPackets(r, t.Cargo, MapGood); + t.RevenueThisYear = r.ReadInt64(); + t.RevenueLastYear = r.ReadInt64(); + t.KmThisYear = r.ReadDouble(); + w.Trains.Add(t); + } + } + + private static List ReadIds(SaveReader r) + { + int n = r.ReadCount(4); + var list = new List(n); + for (int i = 0; i < n; i++) list.Add(r.ReadInt32()); + return list; + } + + private static void ReadPackets(SaveReader r, List target, Func mapGood) + { + int n = r.ReadCount(8); + for (int i = 0; i < n; i++) + { + var p = new Packet + { + Id = r.ReadInt32(), + Kind = (PacketKind)r.ReadByte(), + Good = mapGood(r.ReadInt32()), + Units = r.ReadInt32(), + Origin = new StationId(r.ReadInt32()), + Destination = new StationId(r.ReadInt32()), + HopLine = new LineId(r.ReadInt32()), + HopEnd = new StationId(r.ReadInt32()), + CreatedTick = r.ReadInt64(), + ExpiresTick = r.ReadInt64(), + ExpectedDays = r.ReadDouble(), + Contract = r.ReadInt32(), + ReturnTrip = r.ReadBool(), + AwaitingConsumer = r.ReadBool(), + }; + if (p.Kind != PacketKind.Freight || p.Good >= 0) target.Add(p); + } + } +} diff --git a/src/ViaFerrea.Core/Persistence/WorldSerializer.cs b/src/ViaFerrea.Core/Persistence/WorldSerializer.cs index 76a29e3..64622ba 100644 --- a/src/ViaFerrea.Core/Persistence/WorldSerializer.cs +++ b/src/ViaFerrea.Core/Persistence/WorldSerializer.cs @@ -232,6 +232,8 @@ public static class WorldSerializer s.Write(c.LowCoverageDays); s.Write(c.ArrivedToday); } + + RailSerializer.Write(w, s); } private static void WriteRecipeStock(List items, int[] stock, SaveWriter s) @@ -665,6 +667,8 @@ public static class WorldSerializer c.ArrivedToday = r.ReadInt32(); w.Commutes.Add(c); } + + RailSerializer.Read(w, r, goodMap); } private static void ReadRecipeStock(List items, int[] stock, SaveReader r) diff --git a/src/ViaFerrea.Core/Rail/LineGraph.cs b/src/ViaFerrea.Core/Rail/LineGraph.cs new file mode 100644 index 0000000..3dc20b6 --- /dev/null +++ b/src/ViaFerrea.Core/Rail/LineGraph.cs @@ -0,0 +1,170 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Rail; + +/// Tratto continuo su una linea: si sale in From e si scende in To. +public readonly record struct Hop(LineId Line, StationId From, StationId To, double Minutes); + +/// Collegamento migliore verso una stazione: minuti di orologio dei treni e tratti. +public sealed record Connection(StationId Destination, double Minutes, Hop[] Hops) +{ + public Hop First => Hops[0]; +} + +/// +/// Grafo delle linee di una compagnia (guida 7, 9): nodi = stazioni, archi = fermate +/// consecutive di una linea con il tempo di percorrenza stimato. Dijkstra sugli stati +/// (stazione, linea) con penalità di cambio. Ricostruito quando cambiano rete, linee o treni. +/// +public sealed class LineGraph +{ + private readonly record struct Segment(int From, int To, LineId Line, double Minutes); + + private readonly Dictionary> _out = new(); + private readonly Dictionary> _reach = new(); + private readonly double _transferMinutes; + + public CompanyId Company { get; } + public int Version { get; } + + /// Capacità giornaliera stimata per linea e classe (posti, unità merci). + public Dictionary DailyCapacity { get; } = new(); + + /// Durata di un giro completo per linea (minuti di orologio dei treni). + public Dictionary CycleMinutes { get; } = new(); + + public LineGraph(Simulation.World w, CompanyId company, int version) + { + Company = company; + Version = version; + var ops = w.Data.Construction.Operations; + double dwell = w.Data.Construction.Stations.MinDwellMinutes; + _transferMinutes = dwell * 2; + var net = w.Network; + var path = new List(); + foreach (var line in w.Lines) + { + if (line.Removed || line.Owner != company || line.Stops.Count < 2) continue; + var trains = w.Trains.Where(t => !t.Removed && t.Line == line.Id).ToList(); + double speed = trains.Count > 0 ? trains.Min(t => t.MaxSpeedKmh) : 60; + bool electric = trains.Any(t => t.NeedsElectrification); + double cycle = 0; + bool complete = true; + for (int i = 0; i < line.Stops.Count; i++) + { + var a = net.Stations[line.Stops[i].Station.Value]; + var b = net.Stations[line.Stops[(i + 1) % line.Stops.Count].Station.Value]; + if (a.Id == b.Id) continue; + if (!w.Pathfinder.FindPath(net, company, a.Node, EdgeId.None, b.Node, speed, electric, ops.MaxTurnDeg, path)) + { + complete = false; + continue; + } + double seconds = 0; + foreach (var step in path) seconds += Pathfinder.EdgeTime(net.Edges[step.Edge.Value], speed / 3.6); + double minutes = seconds / 60 * 1.15 + dwell; // margine per accelerazioni e frenate + cycle += minutes; + if (!_out.TryGetValue(a.Id.Value, out var list)) _out[a.Id.Value] = list = []; + list.Add(new Segment(a.Id.Value, b.Id.Value, line.Id, minutes)); + } + if (!complete || cycle <= 0) continue; + CycleMinutes[line.Id.Value] = cycle; + double tripsPerDay = w.Calendar.TrainMinutesPerDay / cycle; + double workers = 0, staff = 0, freight = 0; + foreach (var t in trains) + { + foreach (var vid in t.Vehicles) + { + var v = w.Vehicles[vid.Value]; + if (v.Def.Kind == Data.VehicleKind.Coach) + { + if (v.Def.Class == Data.PaxClass.Staff) staff += v.Def.PaxCapacity ?? 0; + else workers += v.Def.PaxCapacity ?? 0; + } + else if (v.Def.Kind == Data.VehicleKind.Wagon) freight += v.Def.Capacity ?? 0; + } + } + DailyCapacity[line.Id.Value] = (workers * tripsPerDay, staff * tripsPerDay, freight * tripsPerDay); + } + foreach (var list in _out.Values) list.Sort((x, y) => x.To != y.To ? x.To.CompareTo(y.To) : x.Line.Value.CompareTo(y.Line.Value)); + } + + /// Collegamenti migliori da una stazione verso tutte le stazioni raggiungibili. + public IReadOnlyDictionary From(StationId origin) + { + if (_reach.TryGetValue(origin.Value, out var cached)) return cached; + var result = new Dictionary(); + // stato = (stazione, linea su cui si viaggia); linea −1 = a terra all'origine + var best = new Dictionary<(int, int), double>(); + var came = new Dictionary<(int, int), ((int, int) Prev, Segment Seg)>(); + var open = new PriorityQueue<(int Station, int Line), (double, int, int)>(); + best[(origin.Value, -1)] = 0; + open.Enqueue((origin.Value, -1), (0, origin.Value, -1)); + while (open.TryDequeue(out var state, out var pri)) + { + double cost = pri.Item1; + if (best.TryGetValue(state, out double known) && known < cost) continue; + if (state.Station != origin.Value && !result.ContainsKey(state.Station)) + result[state.Station] = BuildConnection(state, cost, came, origin.Value); + if (!_out.TryGetValue(state.Station, out var segs)) continue; + foreach (var seg in segs) + { + 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; + best[next] = c; + came[next] = (state, seg); + open.Enqueue(next, (c, seg.To, seg.Line.Value)); + } + } + _reach[origin.Value] = result; + return result; + } + + private static Connection BuildConnection((int Station, int Line) state, double cost, + Dictionary<(int, int), ((int, int) Prev, Segment Seg)> came, int origin) + { + var segs = new List(); + var s = state; + while (came.TryGetValue(s, out var link)) + { + segs.Add(link.Seg); + s = link.Prev; + } + segs.Reverse(); + var hops = new List(); + foreach (var seg in segs) + { + if (hops.Count > 0 && hops[^1].Line == seg.Line) + { + var last = hops[^1]; + hops[^1] = last with { To = new StationId(seg.To), Minutes = last.Minutes + seg.Minutes }; + } + else + { + hops.Add(new Hop(seg.Line, new StationId(seg.From), new StationId(seg.To), seg.Minutes)); + } + } + return new Connection(new StationId(state.Station), cost, hops.ToArray()); + } +} + +/// Grafi delle linee per compagnia, ricostruiti quando cambia la versione della rete o delle linee. +public sealed class LineGraphCache +{ + private readonly Dictionary _graphs = new(); + + /// Contatore delle modifiche a linee, treni assegnati e composizioni. + public int LinesVersion { get; private set; } + + public void Touch() => LinesVersion++; + + public LineGraph For(Simulation.World w, CompanyId company) + { + int version = w.Network.Version * 100_003 + LinesVersion; + if (_graphs.TryGetValue(company.Value, out var g) && g.Version == version) return g; + g = new LineGraph(w, company, version); + _graphs[company.Value] = g; + return g; + } +} diff --git a/src/ViaFerrea.Core/Rail/Network.cs b/src/ViaFerrea.Core/Rail/Network.cs new file mode 100644 index 0000000..8b39aec --- /dev/null +++ b/src/ViaFerrea.Core/Rail/Network.cs @@ -0,0 +1,269 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Rail; + +/// Stato di un arco di binario. +public enum EdgeState : byte +{ + /// In cantiere: i treni non possono entrare. + UnderConstruction = 0, + Active = 1, + /// Chiuso per rinnovo o ammodernamento. + Closed = 2, + Demolished = 3, +} + +/// Nodo del grafo dei binari: estremità libera, scambio, stazione o deposito. +public sealed class TrackNode +{ + public required NodeId Id { get; init; } + public required Vec2 Position { get; set; } + public required double HeightM { get; set; } + public CompanyId Owner { get; set; } = CompanyId.None; + + /// Archi incidenti, in ordine di id. + public List Edges { get; } = []; + + public StationId Station { get; set; } = StationId.None; + public DepotId Depot { get; set; } = DepotId.None; + public bool Removed { get; set; } + + public void AddEdge(EdgeId e) + { + int i = 0; + while (i < Edges.Count && Edges[i].Value < e.Value) i++; + if (i < Edges.Count && Edges[i] == e) return; + Edges.Insert(i, e); + } +} + +/// +/// Arco di binario tra due nodi con la linea d'asse campionata ogni 25 m (posizione, quota del +/// binario, opera, velocità ammessa). L'orientamento canonico è da A a B; i treni possono +/// percorrerlo in entrambi i versi (doppio binario: ognuno sul proprio). +/// +public sealed class TrackEdge +{ + public required EdgeId Id { get; init; } + public required NodeId A { get; set; } + public required NodeId B { get; set; } + public required CompanyId Owner { get; init; } + public required int TrackClass { get; set; } + public required bool DoubleTrack { get; set; } + public required bool Electrified { get; set; } + public EdgeState State { get; set; } = EdgeState.UnderConstruction; + + /// Progressive dei campioni (m) da A, crescenti; l'ultima è la lunghezza. + public required double[] S { get; set; } + public required double[] X { get; set; } + public required double[] Y { get; set; } + /// Quota del binario (m) ai campioni. + public required double[] H { get; set; } + /// Quota del terreno (m) ai campioni (per il disegno delle opere). + public required double[] Ground { get; set; } + /// Opera di ogni campione. + public required WorkKind[] Kinds { get; set; } + /// Velocità ammessa dalla geometria (classe e curve) ai campioni, km/h. + public required double[] SpeedLimitKmh { get; set; } + + public double Length => S[^1]; + + /// Condizione del binario 0–100 (8.3). + public double Condition { get; set; } = 100; + + /// Condizione di ponti e gallerie 0–100. + public double StructureCondition { get; set; } = 100; + + public long BuiltDay { get; set; } + public long LastRenewalDay { get; set; } + public long LastInspectionDay { get; set; } + + /// Costo di costruzione (centesimi), base per rinnovi e valore contabile. + public long BuildCostCents { get; set; } + + /// Progetto di cantiere in corso (−1 se nessuno). + public int Project { get; set; } = -1; + + /// Posizioni dei segnali intermedi (m da A), crescenti. + public List Signals { get; } = []; + + // ---- occupazione (gestita dal sistema dei treni) + + /// Verso bloccato su binario semplice: −1 libero, 0 da A a B, 1 da B ad A. + public int LockDir { get; set; } = -1; + + /// Treni che tengono il blocco di verso. + public int LockCount { get; set; } + + /// Titolare di ogni sezione di blocco per verso (id treno o −1); dimensione Signals.Count + 1. + public int[] BlocksForward { get; set; } = [-1]; + public int[] BlocksBackward { get; set; } = [-1]; + + /// Usura accumulata nel giorno (t·fattori), convertita in condizione dal sistema di manutenzione. + public double WearToday { get; set; } + + /// Tonnellate transitate nell'ultimo anno (statistica). + public double TonnesThisYear { get; set; } + + public bool IsUsable => State == EdgeState.Active; + + public NodeId Other(NodeId n) => n == A ? B : A; + + /// Indice del campione che precede la progressiva s (ricerca binaria). + public int SampleIndex(double s) + { + int lo = 0, hi = S.Length - 1; + if (s <= 0) return 0; + if (s >= S[hi]) return hi - 1 < 0 ? 0 : hi - 1; + while (hi - lo > 1) + { + int mid = (lo + hi) >> 1; + if (S[mid] <= s) lo = mid; + else hi = mid; + } + return lo; + } + + /// Punto alla progressiva s da A. + public Vec2 PointAt(double s) + { + int i = SampleIndex(s); + int j = Math.Min(i + 1, S.Length - 1); + double t = j == i ? 0 : Math.Clamp((s - S[i]) / (S[j] - S[i]), 0, 1); + return new Vec2(X[i] + (X[j] - X[i]) * t, Y[i] + (Y[j] - Y[i]) * t); + } + + /// Quota del binario alla progressiva s da A. + public double HeightAt(double s) + { + int i = SampleIndex(s); + int j = Math.Min(i + 1, S.Length - 1); + double t = j == i ? 0 : Math.Clamp((s - S[i]) / (S[j] - S[i]), 0, 1); + return H[i] + (H[j] - H[i]) * t; + } + + /// Pendenza (positiva in salita da A verso B) dell'intervallo che contiene s. + public double GradeAt(double s) + { + int i = SampleIndex(s); + int j = Math.Min(i + 1, S.Length - 1); + return j == i ? 0 : (H[j] - H[i]) / (S[j] - S[i]); + } + + /// Pendenza media assoluta (statistica di usura). + public double AverageAbsGrade() + { + double sum = 0; + for (int i = 0; i < S.Length - 1; i++) sum += Math.Abs(H[i + 1] - H[i]); + return Length > 0 ? sum / Length : 0; + } + + /// Direzione (versore) all'estremità indicata, uscente dal nodo. + public Vec2 DirectionFrom(NodeId node) + { + if (node == A) return new Vec2(X[1] - X[0], Y[1] - Y[0]).Normalized(); + int n = S.Length; + return new Vec2(X[n - 2] - X[n - 1], Y[n - 2] - Y[n - 1]).Normalized(); + } + + /// Lunghezza delle opere di un tipo. + public double LengthOf(WorkKind kind) + { + double len = 0; + for (int i = 0; i < S.Length; i++) + { + if (Kinds[i] != kind) continue; + double left = i == 0 ? 0 : (S[i] - S[i - 1]) / 2; + double right = i == S.Length - 1 ? 0 : (S[i + 1] - S[i]) / 2; + len += left + right; + } + return len; + } + + /// Ricostruisce le sezioni di blocco dopo un cambio dei segnali (solo se libere). + public void ResetBlocks() + { + BlocksForward = Enumerable.Repeat(-1, Signals.Count + 1).ToArray(); + BlocksBackward = Enumerable.Repeat(-1, Signals.Count + 1).ToArray(); + } +} + +/// Stazione: nodo con binari di stazione, bacino di utenza e merci in attesa. +public sealed class Station +{ + public required StationId Id { get; init; } + public required CompanyId Owner { get; init; } + public required string Name { get; set; } + public required NodeId Node { get; init; } + public required Vec2 Position { get; init; } + public required int Platforms { get; set; } + public long BuiltDay { get; init; } + public long BuildCostCents { get; set; } + + /// Treno su ogni binario (−1 libero). + public int[] PlatformTrain { get; set; } = []; + + /// Pacchetti in attesa (merci e passeggeri). + public List Waiting { get; } = []; + + /// Unità in arrivo per bene (merci già in viaggio verso questa stazione). + public int[] Incoming { get; set; } = []; + + /// Industrie, città e hub nel bacino (ricalcolati quando cambia il mondo). + public List Industries { get; } = []; + public List Towns { get; } = []; + public List Hubs { get; } = []; + + public int FreePlatforms + { + get + { + int n = 0; + foreach (int t in PlatformTrain) if (t < 0) n++; + return n; + } + } +} + +/// Deposito e officina della compagnia: qui nascono i treni e si fa manutenzione (F4). +public sealed class Depot +{ + public required DepotId Id { get; init; } + public required CompanyId Owner { get; init; } + public required string Name { get; set; } + public required NodeId Node { get; init; } + public required Vec2 Position { get; init; } + public required string Size { get; init; } + public long BuiltDay { get; init; } + public long BuildCostCents { get; set; } + + /// Scorta di ricambi (sezione 10, F4). + public int SpareParts { get; set; } +} + +/// Tipo di progetto di cantiere. +public enum ProjectKind : byte { NewTrack = 0, Renewal = 1, Upgrade = 2 } + +/// Cantiere: le opere si costruiscono in ordine lungo la linea da una squadra (8.2). +public sealed class ConstructionProject +{ + public required int Id { get; init; } + public required CompanyId Owner { get; init; } + public required ProjectKind Kind { get; init; } + public required List Edges { get; init; } + public required double TotalDays { get; init; } + public double ProgressDays { get; set; } + /// Squadra assegnata (−1 in attesa). + public int Crew { get; set; } = -1; + public long QueuedDay { get; init; } + public long StartedDay { get; set; } = -1; + public bool Done { get; set; } + + /// Opere nell'ordine di costruzione, con i giorni di ciascuna (per l'avanzamento mostrato). + public List Works { get; init; } = []; + + /// Parametri dell'ammodernamento (classe, doppio binario, elettrificazione). + public int UpgradeClass { get; init; } = -1; + public bool UpgradeDouble { get; init; } + public bool UpgradeElectrified { get; init; } +} diff --git a/src/ViaFerrea.Core/Rail/Pathfinder.cs b/src/ViaFerrea.Core/Rail/Pathfinder.cs new file mode 100644 index 0000000..9b6a2a5 --- /dev/null +++ b/src/ViaFerrea.Core/Rail/Pathfinder.cs @@ -0,0 +1,113 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Rail; + +/// +/// Ricerca del percorso più rapido (A*) sul grafo dei binari di una compagnia. Gli stati sono +/// archi orientati, così si applica il vincolo di svolta: a uno scambio non si torna indietro +/// (angolo oltre il massimo), mentre in stazione, in deposito e ai binari morti sì. +/// I buffer sono riutilizzati tra le chiamate. +/// +public sealed class Pathfinder +{ + private double[] _cost = []; + private int[] _came = []; + private int[] _stamp = []; + private int _run; + private readonly PriorityQueue _open = new(); + private readonly List _reverse = []; + + /// + /// Percorso dal nodo «from» al nodo «to». arrivedVia è l'arco da cui si è giunti a «from» + /// (None se fermi in stazione o deposito). Restituisce false se non esiste. + /// + public bool FindPath(RailNetwork net, CompanyId company, NodeId from, EdgeId arrivedVia, NodeId to, double maxSpeedKmh, + bool needsElectrification, double maxTurnDeg, List result) + { + result.Clear(); + if (from == to) return true; + int states = net.Edges.Count * 2; + if (_cost.Length < states) + { + _cost = new double[states]; + _came = new int[states]; + _stamp = new int[states]; + } + _run++; + _open.Clear(); + double cosLimit = Math.Cos(maxTurnDeg * Math.PI / 180); + var target = net.Nodes[to.Value].Position; + double vmax = Math.Max(1, maxSpeedKmh / 3.6); + + // stati iniziali: tutti gli archi uscenti da «from» ammessi dal vincolo di svolta + var start = net.Nodes[from.Value]; + bool freeTurn = arrivedVia == EdgeId.None || IsTurningPoint(net, start); + Vec2 inDir = freeTurn ? default : -net.Edges[arrivedVia.Value].DirectionFrom(from); + foreach (var e in start.Edges) + { + var edge = net.Edges[e.Value]; + if (!Usable(edge, company, needsElectrification)) continue; + if (!freeTurn && Vec2.Dot(inDir, edge.DirectionFrom(from)) < cosLimit) continue; + int state = e.Value * 2 + (edge.A == from ? 0 : 1); + Relax(net, state, -1, EdgeTime(edge, vmax), target, vmax); + } + + while (_open.TryDequeue(out int state, out _)) + { + var edge = net.Edges[state >> 1]; + bool forward = (state & 1) == 0; + var at = forward ? edge.B : edge.A; + if (at == to) + { + _reverse.Clear(); + for (int s = state; s >= 0; s = _came[s]) _reverse.Add(s); + for (int i = _reverse.Count - 1; i >= 0; i--) + result.Add(new RouteStep(new EdgeId(_reverse[i] >> 1), (_reverse[i] & 1) == 0)); + return true; + } + var node = net.Nodes[at.Value]; + bool turning = IsTurningPoint(net, node); + var dirIn = -edge.DirectionFrom(at); + foreach (var e in node.Edges) + { + if (e == edge.Id && !turning) continue; + var next = net.Edges[e.Value]; + if (!Usable(next, company, needsElectrification)) continue; + if (!turning && Vec2.Dot(dirIn, next.DirectionFrom(at)) < cosLimit) continue; + int ns = e.Value * 2 + (next.A == at ? 0 : 1); + Relax(net, ns, state, _cost[state] + EdgeTime(next, vmax), target, vmax); + } + } + return false; + } + + private void Relax(RailNetwork net, int state, int from, double cost, Vec2 target, double vmax) + { + if (_stamp[state] == _run && _cost[state] <= cost) return; + _stamp[state] = _run; + _cost[state] = cost; + _came[state] = from; + var edge = net.Edges[state >> 1]; + var end = (state & 1) == 0 ? net.Nodes[edge.B.Value].Position : net.Nodes[edge.A.Value].Position; + _open.Enqueue(state, cost + Vec2.Distance(end, target) / vmax); + } + + private static bool Usable(TrackEdge e, CompanyId company, bool needsElectrification) => + e.State == EdgeState.Active && e.Owner == company && (!needsElectrification || e.Electrified); + + /// Stazioni, depositi e binari morti permettono di invertire la marcia. + public static bool IsTurningPoint(RailNetwork net, TrackNode node) => + node.Station.IsValid || node.Depot.IsValid || node.Edges.Count(e => net.Edges[e.Value].State != EdgeState.Demolished) <= 1; + + /// Tempo di percorrenza (s) alla velocità ammessa dal binario e dal treno. + public static double EdgeTime(TrackEdge e, double vmaxMs) + { + double t = 0; + for (int i = 0; i < e.S.Length - 1; i++) + { + double v = Math.Min(vmaxMs, Math.Max(1, e.SpeedLimitKmh[i] / 3.6)); + t += (e.S[i + 1] - e.S[i]) / v; + } + return t; + } +} diff --git a/src/ViaFerrea.Core/Rail/RailNetwork.cs b/src/ViaFerrea.Core/Rail/RailNetwork.cs new file mode 100644 index 0000000..d8004d7 --- /dev/null +++ b/src/ViaFerrea.Core/Rail/RailNetwork.cs @@ -0,0 +1,310 @@ +using ViaFerrea.Core.Common; + +namespace ViaFerrea.Core.Rail; + +/// Punto di aggancio di un'estremità di binario. +public readonly record struct AttachPoint(NodeId Node, EdgeId SplitEdge, int SplitIndex, Vec2 Position, double HeightM) +{ + /// Estremità libera: verrà creato un nodo nuovo alla quota del terreno. + public bool IsFree => !Node.IsValid && !SplitEdge.IsValid; +} + +/// +/// Grafo dei binari di tutte le compagnie, con stazioni, depositi e cantieri. Le liste sono +/// indicizzate per id e non si compattano mai: le entità rimosse restano marcate. +/// +public sealed class RailNetwork +{ + private const double GridCellM = 1000; + + public List Nodes { get; } = []; + public List Edges { get; } = []; + public List Stations { get; } = []; + public List Depots { get; } = []; + public List Projects { get; } = []; + public int NextProject { get; set; } + + /// Contatore delle modifiche topologiche: invalida percorsi e grafi delle linee. + public int Version { get; private set; } + + // indice spaziale dei segmenti degli archi (transitorio: si ricostruisce da solo) + private Dictionary>? _grid; + private int _gridVersion = -1; + + public void Touch() => Version++; + + public TrackNode AddNode(Vec2 position, double heightM, CompanyId owner) + { + var node = new TrackNode { Id = new NodeId(Nodes.Count), Position = position, HeightM = heightM, Owner = owner }; + Nodes.Add(node); + Touch(); + return node; + } + + /// Crea un arco dai campioni di un piano. + public TrackEdge AddEdge(NodeId a, NodeId b, CompanyId owner, TrackPlan plan, int trackClassIndex, long day) + { + int n = plan.Samples.Count; + var edge = new TrackEdge + { + Id = new EdgeId(Edges.Count), + A = a, + B = b, + Owner = owner, + TrackClass = trackClassIndex, + DoubleTrack = plan.Request.DoubleTrack, + Electrified = plan.Request.Electrified, + S = plan.Samples.Select(s => s.S).ToArray(), + X = plan.Samples.Select(s => s.Point.X).ToArray(), + Y = plan.Samples.Select(s => s.Point.Y).ToArray(), + H = plan.Samples.Select(s => s.TrackM).ToArray(), + Ground = plan.Samples.Select(s => s.TerrainM).ToArray(), + Kinds = plan.Samples.Select(s => s.Kind).ToArray(), + SpeedLimitKmh = plan.Samples.Select(s => s.SpeedLimitKmh).ToArray(), + BuiltDay = day, + LastRenewalDay = day, + LastInspectionDay = day, + BuildCostCents = plan.TotalCost.Cents, + }; + if (n < 2) throw new InvalidOperationException("Arco senza campioni"); + Edges.Add(edge); + Nodes[a.Value].AddEdge(edge.Id); + Nodes[b.Value].AddEdge(edge.Id); + Touch(); + return edge; + } + + /// + /// Divide un arco al campione k creando uno scambio. L'arco originale diventa A→nuovo nodo, + /// il nuovo arco nuovo nodo→B. Solo per archi attivi e liberi. + /// + public TrackNode SplitEdge(TrackEdge edge, int k) + { + if (k <= 0 || k >= edge.S.Length - 1) throw new ArgumentOutOfRangeException(nameof(k)); + var node = AddNode(new Vec2(edge.X[k], edge.Y[k]), edge.H[k], edge.Owner); + double sk = edge.S[k]; + var second = new TrackEdge + { + Id = new EdgeId(Edges.Count), + A = node.Id, + B = edge.B, + Owner = edge.Owner, + TrackClass = edge.TrackClass, + DoubleTrack = edge.DoubleTrack, + Electrified = edge.Electrified, + State = edge.State, + S = edge.S[k..].Select(s => s - sk).ToArray(), + X = edge.X[k..], + Y = edge.Y[k..], + H = edge.H[k..], + Ground = edge.Ground[k..], + Kinds = edge.Kinds[k..], + SpeedLimitKmh = edge.SpeedLimitKmh[k..], + Condition = edge.Condition, + StructureCondition = edge.StructureCondition, + BuiltDay = edge.BuiltDay, + LastRenewalDay = edge.LastRenewalDay, + LastInspectionDay = edge.LastInspectionDay, + BuildCostCents = (long)Math.Round(edge.BuildCostCents * (edge.Length - sk) / edge.Length), + Project = edge.Project, + }; + // la metà nuova di un arco in cantiere fa parte dello stesso progetto + if (edge.Project >= 0 && edge.Project < Projects.Count && !Projects[edge.Project].Done) + Projects[edge.Project].Edges.Add(second.Id); + foreach (double sig in edge.Signals.Where(s => s > sk)) second.Signals.Add(sig - sk); + second.ResetBlocks(); + + var oldB = Nodes[edge.B.Value]; + oldB.Edges.Remove(edge.Id); + oldB.AddEdge(second.Id); + edge.BuildCostCents -= second.BuildCostCents; + edge.B = node.Id; + edge.S = edge.S[..(k + 1)]; + edge.X = edge.X[..(k + 1)]; + edge.Y = edge.Y[..(k + 1)]; + edge.H = edge.H[..(k + 1)]; + edge.Ground = edge.Ground[..(k + 1)]; + edge.Kinds = edge.Kinds[..(k + 1)]; + edge.SpeedLimitKmh = edge.SpeedLimitKmh[..(k + 1)]; + edge.Signals.RemoveAll(s => s >= sk); + edge.ResetBlocks(); + + Edges.Add(second); + node.AddEdge(edge.Id); + node.AddEdge(second.Id); + Touch(); + return node; + } + + /// + /// Trova dove agganciare un'estremità: nodo esistente della compagnia (stazioni comprese), + /// oppure un campione interno di un arco della compagnia (da dividere), oppure nessuno. + /// + public AttachPoint FindAttach(Vec2 p, CompanyId company, double snapM, double stationRadiusM) + { + // stazioni e depositi: tutta l'area aggancia al nodo + foreach (var s in Stations) + { + if (s.Owner == company && Vec2.Distance(s.Position, p) <= stationRadiusM) + return new AttachPoint(s.Node, EdgeId.None, -1, Nodes[s.Node.Value].Position, Nodes[s.Node.Value].HeightM); + } + foreach (var d in Depots) + { + if (d.Owner == company && Vec2.Distance(d.Position, p) <= stationRadiusM) + return new AttachPoint(d.Node, EdgeId.None, -1, Nodes[d.Node.Value].Position, Nodes[d.Node.Value].HeightM); + } + TrackNode? bestNode = null; + double bestDist = snapM; + foreach (var n in Nodes) + { + if (n.Removed || n.Owner != company) continue; + double d = Vec2.Distance(n.Position, p); + if (d <= bestDist) + { + bestDist = d; + bestNode = n; + } + } + if (bestNode is not null) return new AttachPoint(bestNode.Id, EdgeId.None, -1, bestNode.Position, bestNode.HeightM); + + // arco: distanza dalla linea d'asse (segmenti tra campioni), divisione al campione più vicino + EnsureGrid(); + TrackEdge? bestEdge = null; + int bestIndex = -1; + double best = snapM; + foreach (var (ei, si) in Nearby(p, snapM + GridCellM / 10)) + { + var e = Edges[ei]; + if (e.Owner != company || e.State is not (EdgeState.Active or EdgeState.UnderConstruction) || si >= e.S.Length - 1) continue; + var a = new Vec2(e.X[si], e.Y[si]); + var b = new Vec2(e.X[si + 1], e.Y[si + 1]); + double d = DistanceToSegment(p, a, b, out double t); + int k = t < 0.5 ? si : si + 1; + if (k <= 0 || k >= e.S.Length - 1) continue; + if (d < best || (d == best && (bestEdge is null || ei < bestEdge.Id.Value))) + { + best = d; + bestEdge = e; + bestIndex = k; + } + } + if (bestEdge is not null) + return new AttachPoint(NodeId.None, bestEdge.Id, bestIndex, new Vec2(bestEdge.X[bestIndex], bestEdge.Y[bestIndex]), bestEdge.H[bestIndex]); + return new AttachPoint(NodeId.None, EdgeId.None, -1, p, double.NaN); + } + + /// Distanza di p dal segmento ab e parametro del punto più vicino. + public static double DistanceToSegment(Vec2 p, Vec2 a, Vec2 b, out double t) + { + var ab = b - a; + double len2 = ab.LengthSquared; + t = len2 <= 0 ? 0 : Math.Clamp(Vec2.Dot(p - a, ab) / len2, 0, 1); + return Vec2.Distance(p, a + ab * t); + } + + /// Vero se l'arco non ha treni né prenotazioni. + public static bool IsFree(TrackEdge e) => + e.LockCount == 0 && e.BlocksForward.All(b => b < 0) && e.BlocksBackward.All(b => b < 0); + + /// Interrogazioni per il pianificatore, ignorando gli agganci alle estremità. + public ITrackObstacles Obstacles(Vec2 start, Vec2 end, double ignoreRadiusM, double stationRadiusM) => + new ObstacleQuery(this, start, end, ignoreRadiusM, stationRadiusM); + + private sealed class ObstacleQuery(RailNetwork net, Vec2 start, Vec2 end, double ignore, double r) : ITrackObstacles + { + public void FindCrossings(Vec2 a, Vec2 b, CompanyId company, List results) + { + net.EnsureGrid(); + var seen = new HashSet(); + double margin = Vec2.Distance(a, b) + GridCellM; + foreach (var (ei, si) in net.Nearby(Vec2.Lerp(a, b, 0.5), margin)) + { + var e = net.Edges[ei]; + if (e.State == EdgeState.Demolished || si >= e.S.Length - 1) continue; + if (!seen.Add(((long)ei << 32) | (uint)si)) continue; + var p = new Vec2(e.X[si], e.Y[si]); + var q = new Vec2(e.X[si + 1], e.Y[si + 1]); + if (!SegmentIntersection(a, b, p, q, out double t, out double u)) continue; + var hit = Vec2.Lerp(a, b, t); + if (Vec2.Distance(hit, start) <= ignore || Vec2.Distance(hit, end) <= ignore) continue; + double h = e.H[si] + (e.H[si + 1] - e.H[si]) * u; + results.Add(new TrackCrossing(t, h, e.Owner != company)); + } + results.Sort((x, y) => x.T.CompareTo(y.T)); + } + + public bool IsStationArea(Vec2 p, CompanyId company, out bool foreign) + { + foreign = false; + foreach (var s in net.Stations) + { + if (Vec2.Distance(s.Position, p) > r) continue; + if (Vec2.Distance(p, start) <= r || Vec2.Distance(p, end) <= r) + { + if (s.Owner == company) continue; + } + foreign = s.Owner != company; + return true; + } + foreach (var d in net.Depots) + { + if (Vec2.Distance(d.Position, p) > r) continue; + if (d.Owner == company && (Vec2.Distance(p, start) <= r || Vec2.Distance(p, end) <= r)) continue; + foreign = d.Owner != company; + return true; + } + return false; + } + } + + /// Intersezione propria tra i segmenti ab e pq (t e u parametri su ciascuno). + public static bool SegmentIntersection(Vec2 a, Vec2 b, Vec2 p, Vec2 q, out double t, out double u) + { + var r = b - a; + var s = q - p; + double denom = Vec2.Cross(r, s); + t = u = 0; + if (Math.Abs(denom) < 1e-12) return false; + var ap = p - a; + t = Vec2.Cross(ap, s) / denom; + u = Vec2.Cross(ap, r) / denom; + return t >= 0 && t <= 1 && u >= 0 && u <= 1; + } + + private void EnsureGrid() + { + if (_grid is not null && _gridVersion == Version) return; + _grid = new Dictionary>(); + foreach (var e in Edges) + { + if (e.State == EdgeState.Demolished) continue; + for (int i = 0; i < e.S.Length; i++) + { + long key = Key(e.X[i], e.Y[i]); + if (!_grid.TryGetValue(key, out var list)) _grid[key] = list = []; + list.Add((e.Id.Value, i)); + } + } + _gridVersion = Version; + } + + private static long Key(double x, double y) => ((long)Math.Floor(x / GridCellM) << 32) ^ (uint)(int)Math.Floor(y / GridCellM); + + // campioni degli archi entro il raggio (in ordine deterministico: per cella, poi per inserimento) + private IEnumerable<(int Edge, int Index)> Nearby(Vec2 p, double radius) + { + int cx0 = (int)Math.Floor((p.X - radius) / GridCellM), cx1 = (int)Math.Floor((p.X + radius) / GridCellM); + int cy0 = (int)Math.Floor((p.Y - radius) / GridCellM), cy1 = (int)Math.Floor((p.Y + radius) / GridCellM); + for (int cy = cy0; cy <= cy1; cy++) + { + for (int cx = cx0; cx <= cx1; cx++) + { + long key = ((long)cx << 32) ^ (uint)cy; + if (_grid!.TryGetValue(key, out var list)) + { + foreach (var item in list) yield return item; + } + } + } + } +} diff --git a/src/ViaFerrea.Core/Rail/Trains.cs b/src/ViaFerrea.Core/Rail/Trains.cs new file mode 100644 index 0000000..40ab763 --- /dev/null +++ b/src/ViaFerrea.Core/Rail/Trains.cs @@ -0,0 +1,173 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; + +namespace ViaFerrea.Core.Rail; + +/// Veicolo posseduto: locomotiva, carro o carrozza. +public sealed class Vehicle +{ + public required VehicleId Id { get; init; } + public required VehicleDef Def { get; init; } + public required CompanyId Owner { get; init; } + public required long BoughtDay { get; init; } + public TrainId Train { get; set; } = TrainId.None; + public DepotId Depot { get; set; } = DepotId.None; + public bool Sold { get; set; } + + /// Condizione dei componenti 0–100 (sezione 10; ordine dei componenti di maintenance.json). + public double[] Components { get; set; } = []; + + /// Chilometri percorsi. + public double OdometerKm { get; set; } + + /// Carico corrente dei carri: bene (−1 vuoto) e unità. + public int Good { get; set; } = -1; + public int Load { get; set; } + + /// Passeggeri a bordo delle carrozze. + public int Pax { get; set; } +} + +/// Stato operativo di un treno. +public enum TrainState : byte +{ + InDepot = 0, + /// Fermo in attesa di via libera (blocco, binario o percorso). + Waiting = 1, + Moving = 2, + /// In stazione: carico e scarico. + Loading = 3, + /// Non riesce a superare la salita (8.4). + Stalled = 4, + /// Guasto in linea (F4). + Broken = 5, + /// Senza percorso verso la prossima fermata. + NoRoute = 6, +} + +/// Passo del percorso: un arco nel verso indicato (Forward = da A a B). +public readonly record struct RouteStep(EdgeId Edge, bool Forward); + +/// Risorsa occupata dal treno, liberata quando la coda la supera. +public struct HeldResource +{ + /// 0 = sezione di blocco di un arco, 1 = binario di stazione, 2 = blocco di verso di un arco a binario semplice. + public byte Kind; + public int Id; + public int Index; + public bool Forward; + /// Odometro (m) a cui la testa ha lasciato la risorsa; NaN se la testa è ancora dentro. + public double LeftAt; +} + +/// Treno: composizione, ordini, posizione, velocità, prenotazioni e carico. +public sealed class Train +{ + public required TrainId Id { get; init; } + public required CompanyId Owner { get; init; } + public required string Name { get; set; } + public List Vehicles { get; } = []; + public DepotId HomeDepot { get; set; } = DepotId.None; + public LineId Line { get; set; } = LineId.None; + public int StopIndex { get; set; } + public TrainState State { get; set; } = TrainState.InDepot; + public bool Removed { get; set; } + public bool Reserve { get; set; } + /// Destinazione speciale: rientro al deposito. + public DepotId GoingToDepot { get; set; } = DepotId.None; + + // ---- caratteristiche ricalcolate alla composizione + public double EmptyMassT { get; set; } + public double LocoMassT { get; set; } + public double PowerKw { get; set; } + public double TractiveKn { get; set; } + public double MaxSpeedKmh { get; set; } + public double LengthM { get; set; } + public double Cx { get; set; } + public bool NeedsElectrification { get; set; } + public int Locomotives { get; set; } + + // ---- posizione + /// Nodo in cui il treno è fermo (stazione o deposito), oppure None in linea. + public NodeId AtNode { get; set; } = NodeId.None; + /// Arco da cui è arrivato al nodo (per i vincoli di svolta). + public EdgeId ArrivedVia { get; set; } = EdgeId.None; + public List Route { get; } = []; + public int RouteIndex { get; set; } + /// Distanza percorsa dalla testa nel passo corrente, dall'estremità d'ingresso. + public double StepPos { get; set; } + /// Velocità (m/s). + public double Speed { get; set; } + /// Odometro della testa (m). + public double Odometer { get; set; } + + // ---- prenotazioni: ultimo passo e sezione di blocco prenotati davanti alla testa + public int ReservedStep { get; set; } = -1; + public int ReservedBlock { get; set; } = -1; + /// Binario prenotato nella stazione d'arrivo (−1 nessuno). + public int ArrivalPlatform { get; set; } = -1; + public List Held { get; } = []; + + // ---- fermata + public double DwellTicks { get; set; } + public long ArrivedTick { get; set; } + public int Platform { get; set; } = -1; + public double StallSeconds { get; set; } + public long WaitingSinceTick { get; set; } + public bool WaitWarned { get; set; } + + /// Pacchetti a bordo. + public List Cargo { get; } = []; + + // ---- statistiche + public long RevenueThisYear { get; set; } + public long RevenueLastYear { get; set; } + public double KmThisYear { get; set; } + + public bool IsRunning => State is TrainState.Moving or TrainState.Waiting or TrainState.Stalled; +} + +/// Fermata di una linea con le azioni da compiere. +public sealed record LineStop(StationId Station, bool Load = true, bool Unload = true, bool WaitFull = false, int MaxWaitDays = 0); + +/// Linea: sequenza ciclica di fermate percorsa dai treni assegnati. +public sealed class Line +{ + public required LineId Id { get; init; } + public required CompanyId Owner { get; init; } + public required string Name { get; set; } + public required string Color { get; set; } + public List Stops { get; } = []; + public bool Removed { get; set; } +} + +/// Tipo di carico di un pacchetto. +public enum PacketKind : byte { Freight = 0, Workers = 1, Staff = 2 } + +/// +/// Pacchetto: unità omogenee di merce o passeggeri con origine, destinazione e prossimo tratto +/// (linea e stazione di discesa) sul grafo delle linee. +/// +public struct Packet +{ + public int Id; + public PacketKind Kind; + /// Bene (merci) o −1 (passeggeri). + public int Good; + public int Units; + public StationId Origin; + public StationId Destination; + /// Linea del tratto corrente e stazione dove scendere. + public LineId HopLine; + public StationId HopEnd; + public long CreatedTick; + /// Tick oltre il quale un pacchetto in attesa decade (merci) o rinuncia (passeggeri). + public long ExpiresTick; + /// Giorni attesi per il viaggio (per il fattore di puntualità). + public double ExpectedDays; + /// Contratto di pendolarismo (passeggeri), −1 per le merci. + public int Contract; + public bool ReturnTrip; + /// Consegnato alla stazione di destinazione ma non ancora ai consumatori del bacino. + public bool AwaitingConsumer; +} diff --git a/src/ViaFerrea.Core/Simulation/CommandProcessor.cs b/src/ViaFerrea.Core/Simulation/CommandProcessor.cs index 67f451e..8b224e3 100644 --- a/src/ViaFerrea.Core/Simulation/CommandProcessor.cs +++ b/src/ViaFerrea.Core/Simulation/CommandProcessor.cs @@ -11,6 +11,8 @@ public static class CommandProcessor public static CommandResult Execute(World w, GameCommand command, WorldContext ctx) { CommandResult Result(CommandError error, string message) => new(command.Issuer, command.Seq, command.Type, error, message, ctx.Tick); + CommandResult Reply(CommandError error, string message, params int[] created) => + new(command.Issuer, command.Seq, command.Type, error, message, ctx.Tick) { Created = error == CommandError.None ? created : [] }; if (!command.Issuer.IsValid || command.Issuer.Value >= w.Companies.Count) return Result(CommandError.UnknownCompany, "Compagnia sconosciuta"); @@ -23,6 +25,20 @@ public static class CommandProcessor TakeLoanCommand c => TakeLoan(w, company, c, Result), RepayLoanCommand c => RepayLoan(w, company, c, Result), SetIndustryPolicyCommand c => SetIndustryPolicy(w, company, c, Result), + BuildTrackCommand c => RailCommandHandlers.BuildTrack(w, company, c, Reply), + BuildStationCommand c => RailCommandHandlers.BuildStation(w, company, c, Reply), + BuildDepotCommand c => RailCommandHandlers.BuildDepot(w, company, c, Reply), + PlaceSignalCommand c => RailCommandHandlers.PlaceSignal(w, company, c, Reply), + DemolishCommand c => RailCommandHandlers.Demolish(w, company, c, Reply), + RenewTrackCommand c => RailCommandHandlers.RenewTrack(w, company, c, Reply), + UpgradeTrackCommand c => RailCommandHandlers.UpgradeTrack(w, company, c, Reply), + BuyVehicleCommand c => RailCommandHandlers.BuyVehicle(w, company, c, Reply), + SellVehicleCommand c => RailCommandHandlers.SellVehicle(w, company, c, Reply), + ComposeTrainCommand c => RailCommandHandlers.ComposeTrain(w, company, c, Reply), + CreateLineCommand c => RailCommandHandlers.CreateLine(w, company, c, Reply), + EditLineCommand c => RailCommandHandlers.EditLine(w, company, c, Reply), + AssignTrainCommand c => RailCommandHandlers.AssignTrain(w, company, c, Reply), + SendToDepotCommand c => RailCommandHandlers.SendToDepot(w, company, c, Reply), _ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"), }; } diff --git a/src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs b/src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs new file mode 100644 index 0000000..ef4c635 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/RailCommandHandlers.cs @@ -0,0 +1,597 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Map; +using ViaFerrea.Core.Rail; + +namespace ViaFerrea.Core.Simulation; + +/// Esecuzione dei comandi ferroviari. Ogni gestore valida tutto prima di modificare il mondo. +public static class RailCommandHandlers +{ + public delegate CommandResult Reply(CommandError error, string message, params int[] created); + + /// Contesto del pianificatore per una compagnia (difficoltà e sconto IA inclusi). + public static TrackPlanContext PlanContext(World w, Company company, ITrackObstacles? obstacles = null) => new() + { + Data = w.Data, + Sampler = w.Sampler, + Year = w.Clock.Year, + CostMultiplier = w.Difficulty.ConstructionCostMultiplier * (company.IsPlayer ? 1.0 : 1.0 - w.Difficulty.AiCostDiscount), + Obstacles = obstacles, + NearestTownEdgeKm = p => w.Towns.Count == 0 ? double.MaxValue : w.Towns.Min(t => w.TownEdgeDistanceKm(t, p)), + }; + + /// + /// Prepara il piano di un binario come farebbe il comando: aggancia le estremità a nodi e archi + /// esistenti e considera gli attraversamenti. Usato anche per l'anteprima nel client. + /// + public static (TrackPlan Plan, AttachPoint Start, AttachPoint End) PreparePlan(World w, Company company, BuildTrackCommand c) + { + var sp = w.Data.Construction.Stations; + var net = w.Network; + var start = net.FindAttach(c.Polyline[0], company.Id, sp.SnapM, sp.AreaRadiusM); + var end = net.FindAttach(c.Polyline[^1], company.Id, sp.SnapM, sp.AreaRadiusM); + var points = c.Polyline.ToList(); + points[0] = start.Position; + points[^1] = end.Position; + var request = new TrackPlanRequest + { + Polyline = points, + HeightOffsetM = c.HeightOffsetM, + AllowBridges = c.AllowBridges, + AllowTunnels = c.AllowTunnels, + TrackClass = c.TrackClass, + DoubleTrack = c.DoubleTrack, + Electrified = c.Electrified, + Company = company.Id, + StartHeightM = start.IsFree ? null : start.HeightM, + EndHeightM = end.IsFree ? null : end.HeightM, + }; + var obstacles = net.Obstacles(start.Position, end.Position, sp.SnapM + 1, sp.AreaRadiusM); + return (TrackPlanner.Plan(PlanContext(w, company, obstacles), request), start, end); + } + + public static CommandResult BuildTrack(World w, Company company, BuildTrackCommand c, Reply reply) + { + if (c.Polyline.Count < 2) return reply(CommandError.InvalidArgument, "Servono almeno due punti"); + var (plan, start, end) = PreparePlan(w, company, c); + if (!plan.Valid) return reply(CommandError.InvalidTrack, plan.Errors[0].Message); + if (c.ExpectedCostCents != 0 && c.ExpectedCostCents != plan.TotalCost.Cents) + return reply(CommandError.PreviewMismatch, $"Il costo calcolato dal server ({plan.TotalCost}) differisce dall'anteprima"); + if (start.Node.IsValid && start.Node == end.Node) return reply(CommandError.InvalidTrack, "Le estremità coincidono"); + foreach (var a in new[] { start, end }) + { + if (a.SplitEdge.IsValid && !RailNetwork.IsFree(w.Network.Edges[a.SplitEdge.Value])) + return reply(CommandError.Blocked, "Il binario da raccordare è occupato da un treno"); + } + if (company.Cash < plan.TotalCost) return reply(CommandError.InsufficientFunds, $"Servono {plan.TotalCost}, in cassa {company.Cash}"); + + var net = w.Network; + NodeId Resolve(AttachPoint a) + { + if (a.Node.IsValid) return a.Node; + if (a.SplitEdge.IsValid) + { + // ricerca di nuovo: un'altra divisione può aver spostato i campioni + var again = net.FindAttach(a.Position, company.Id, 1.0, 0); + if (again.Node.IsValid) return again.Node; + var edge = net.Edges[again.SplitEdge.IsValid ? again.SplitEdge.Value : a.SplitEdge.Value]; + return net.SplitEdge(edge, again.SplitEdge.IsValid ? again.SplitIndex : a.SplitIndex).Id; + } + return net.AddNode(a.Position, w.Sampler.HeightAt(a.Position), company.Id).Id; + } + var na = Resolve(start); + var nb = Resolve(end); + int classIndex = w.Data.Eras.TrackClasses.First(t => t.Id == c.TrackClass).Index; + var edgeObj = net.AddEdge(na, nb, company.Id, plan, classIndex, w.Clock.Day); + var project = new ConstructionProject + { + Id = net.NextProject++, + Owner = company.Id, + Kind = ProjectKind.NewTrack, + Edges = [edgeObj.Id], + TotalDays = Math.Max(1, plan.Days), + QueuedDay = w.Clock.Day, + Works = plan.Works.ToList(), + }; + edgeObj.Project = project.Id; + net.Projects.Add(project); + w.Money.Transfer(Account.Of(company.Id), Account.External, plan.TotalCost, LedgerEntry.Construction); + return reply(CommandError.None, $"Cantiere aperto: {plan.LengthM / 1000:F1} km, {plan.TotalCost}, {plan.Days} giorni", + edgeObj.Id.Value, na.Value, nb.Value, project.Id); + } + + public static CommandResult BuildStation(World w, Company company, BuildStationCommand c, Reply reply) + { + var sp = w.Data.Construction.Stations; + if (c.Platforms < 1 || c.Platforms > sp.MaxPlatforms) return reply(CommandError.InvalidArgument, $"Binari di stazione tra 1 e {sp.MaxPlatforms}"); + if (!InsideMap(w, c.Position)) return reply(CommandError.InvalidArgument, "Fuori dalla mappa"); + var type = w.Sampler.TypeAt(c.Position); + if (type is CellType.Water or CellType.Sea or CellType.Town or CellType.Industry) + return reply(CommandError.NotAllowed, "La stazione deve stare su terreno libero, fuori da città e industrie"); + if (w.Network.Stations.Any(s => Vec2.Distance(s.Position, c.Position) < sp.AreaRadiusM * 2) + || w.Network.Depots.Any(d => Vec2.Distance(d.Position, c.Position) < sp.AreaRadiusM * 2)) + return reply(CommandError.NotAllowed, "Troppo vicino a un'altra stazione o deposito"); + var attach = w.Network.FindAttach(c.Position, company.Id, sp.SnapM, 0); + if (attach.Node.IsValid) + { + var n = w.Network.Nodes[attach.Node.Value]; + if (n.Station.IsValid || n.Depot.IsValid) return reply(CommandError.NotAllowed, "Il nodo ha già una stazione o un deposito"); + } + if (attach.SplitEdge.IsValid && !RailNetwork.IsFree(w.Network.Edges[attach.SplitEdge.Value])) + return reply(CommandError.Blocked, "Il binario è occupato da un treno"); + var cost = new Money(w.Data.Construction.Costs.StationBase + w.Data.Construction.Costs.StationPerPlatform * c.Platforms) + * (w.Difficulty.ConstructionCostMultiplier * (company.IsPlayer ? 1.0 : 1.0 - w.Difficulty.AiCostDiscount)); + if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}"); + + var node = attach.Node.IsValid ? w.Network.Nodes[attach.Node.Value] + : attach.SplitEdge.IsValid ? w.Network.SplitEdge(w.Network.Edges[attach.SplitEdge.Value], attach.SplitIndex) + : w.Network.AddNode(c.Position, w.Sampler.HeightAt(c.Position), company.Id); + string name = c.Name ?? DefaultName(w, node.Position, "Stazione"); + var station = new Station + { + Id = new StationId(w.Network.Stations.Count), + Owner = company.Id, + Name = name, + Node = node.Id, + Position = node.Position, + Platforms = c.Platforms, + PlatformTrain = Enumerable.Repeat(-1, c.Platforms).ToArray(), + BuiltDay = w.Clock.Day, + BuildCostCents = cost.Cents, + Incoming = new int[w.Data.GoodCount], + }; + node.Station = station.Id; + w.Network.Stations.Add(station); + w.NextIds.Station = w.Network.Stations.Count; + UpdateCatchment(w, station); + w.Network.Touch(); + w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.Construction); + return reply(CommandError.None, $"Stazione {name} costruita ({c.Platforms} binari)", station.Id.Value, node.Id.Value); + } + + public static CommandResult BuildDepot(World w, Company company, BuildDepotCommand c, Reply reply) + { + var costs = w.Data.Construction.Costs; + var sp = w.Data.Construction.Stations; + if (!costs.DepotBySize.TryGetValue(c.Size, out long baseCost)) return reply(CommandError.InvalidArgument, "Dimensione del deposito: small, medium o large"); + if (!InsideMap(w, c.Position)) return reply(CommandError.InvalidArgument, "Fuori dalla mappa"); + var type = w.Sampler.TypeAt(c.Position); + if (type is CellType.Water or CellType.Sea or CellType.Town or CellType.Industry) + return reply(CommandError.NotAllowed, "Il deposito deve stare su terreno libero"); + if (w.Network.Stations.Any(s => Vec2.Distance(s.Position, c.Position) < sp.AreaRadiusM * 2) + || w.Network.Depots.Any(d => Vec2.Distance(d.Position, c.Position) < sp.AreaRadiusM * 2)) + return reply(CommandError.NotAllowed, "Troppo vicino a un'altra stazione o deposito"); + var attach = w.Network.FindAttach(c.Position, company.Id, sp.SnapM, 0); + if (attach.Node.IsValid && (w.Network.Nodes[attach.Node.Value].Station.IsValid || w.Network.Nodes[attach.Node.Value].Depot.IsValid)) + return reply(CommandError.NotAllowed, "Il nodo ha già una stazione o un deposito"); + if (attach.SplitEdge.IsValid && !RailNetwork.IsFree(w.Network.Edges[attach.SplitEdge.Value])) + return reply(CommandError.Blocked, "Il binario è occupato da un treno"); + var cost = new Money(baseCost) * (w.Difficulty.ConstructionCostMultiplier * (company.IsPlayer ? 1.0 : 1.0 - w.Difficulty.AiCostDiscount)); + if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}"); + + var node = attach.Node.IsValid ? w.Network.Nodes[attach.Node.Value] + : attach.SplitEdge.IsValid ? w.Network.SplitEdge(w.Network.Edges[attach.SplitEdge.Value], attach.SplitIndex) + : w.Network.AddNode(c.Position, w.Sampler.HeightAt(c.Position), company.Id); + string name = c.Name ?? DefaultName(w, node.Position, "Deposito"); + var depot = new Depot + { + Id = new DepotId(w.Network.Depots.Count), + Owner = company.Id, + Name = name, + Node = node.Id, + Position = node.Position, + Size = c.Size, + BuiltDay = w.Clock.Day, + BuildCostCents = cost.Cents, + SpareParts = w.Data.Maintenance.Depots.InitialSpareParts, + }; + node.Depot = depot.Id; + w.Network.Depots.Add(depot); + w.NextIds.Depot = w.Network.Depots.Count; + w.Network.Touch(); + w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.Construction); + return reply(CommandError.None, $"{name} costruito", depot.Id.Value, node.Id.Value); + } + + public static CommandResult PlaceSignal(World w, Company company, PlaceSignalCommand c, Reply reply) + { + if (!TryEdge(w, c.Edge, company, out var edge)) return reply(CommandError.NotFound, "Binario inesistente"); + if (edge.State != EdgeState.Active) return reply(CommandError.NotAllowed, "Binario non in esercizio"); + if (c.PositionM < 50 || c.PositionM > edge.Length - 50) return reply(CommandError.InvalidArgument, "Il segnale deve stare ad almeno 50 m dalle estremità"); + if (edge.Signals.Any(s => Math.Abs(s - c.PositionM) < 100)) return reply(CommandError.InvalidArgument, "Troppo vicino a un altro segnale"); + if (!RailNetwork.IsFree(edge)) return reply(CommandError.Blocked, "Binario occupato: riprova quando è libero"); + var type = w.Data.Eras.Signals.Where(s => s.From <= w.Clock.Year).OrderByDescending(s => s.From).FirstOrDefault(); + if (type is null) return reply(CommandError.EraLocked, "Nessun segnale disponibile"); + var cost = new Money(type.Price); + if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}"); + int i = 0; + while (i < edge.Signals.Count && edge.Signals[i] < c.PositionM) i++; + edge.Signals.Insert(i, c.PositionM); + edge.ResetBlocks(); + w.Network.Touch(); + w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.Construction); + return reply(CommandError.None, $"{type.NameIt} posato"); + } + + public static CommandResult Demolish(World w, Company company, DemolishCommand c, Reply reply) + { + var net = w.Network; + double refundShare = w.Data.Construction.Costs.DemolitionRefund; + switch (c.Target) + { + case DemolishTarget.Edge: + { + if (!TryEdge(w, new EdgeId(c.Id), company, out var edge)) return reply(CommandError.NotFound, "Binario inesistente"); + if (edge.State == EdgeState.Demolished) return reply(CommandError.NotFound, "Già demolito"); + if (!RailNetwork.IsFree(edge)) return reply(CommandError.Blocked, "Binario occupato da un treno"); + if (edge.Project >= 0 && !net.Projects[edge.Project].Done) net.Projects[edge.Project].Done = true; + edge.State = EdgeState.Demolished; + net.Nodes[edge.A.Value].Edges.Remove(edge.Id); + net.Nodes[edge.B.Value].Edges.Remove(edge.Id); + net.Touch(); + var refund = new Money(edge.BuildCostCents) * refundShare; + w.Money.Transfer(Account.External, Account.Of(company.Id), refund, LedgerEntry.Construction); + return reply(CommandError.None, $"Binario demolito, recuperati {refund}"); + } + case DemolishTarget.Signal: + { + if (!TryEdge(w, new EdgeId(c.Id), company, out var edge)) return reply(CommandError.NotFound, "Binario inesistente"); + if (!RailNetwork.IsFree(edge)) return reply(CommandError.Blocked, "Binario occupato da un treno"); + edge.Signals.Clear(); + edge.ResetBlocks(); + net.Touch(); + return reply(CommandError.None, "Segnali rimossi"); + } + case DemolishTarget.Station: + { + if (c.Id < 0 || c.Id >= net.Stations.Count || net.Stations[c.Id].Owner != company.Id) return reply(CommandError.NotFound, "Stazione inesistente"); + var st = net.Stations[c.Id]; + var node = net.Nodes[st.Node.Value]; + 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.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; + } + st.Waiting.Clear(); + node.Station = StationId.None; + st.Industries.Clear(); + st.Towns.Clear(); + st.Hubs.Clear(); + net.Touch(); + var refund = new Money(st.BuildCostCents) * refundShare; + w.Money.Transfer(Account.External, Account.Of(company.Id), refund, LedgerEntry.Construction); + return reply(CommandError.None, $"Stazione demolita, recuperati {refund}"); + } + default: + { + if (c.Id < 0 || c.Id >= net.Depots.Count || net.Depots[c.Id].Owner != company.Id) return reply(CommandError.NotFound, "Deposito inesistente"); + var depot = net.Depots[c.Id]; + var node = net.Nodes[depot.Node.Value]; + if (node.Depot != depot.Id) return reply(CommandError.NotFound, "Deposito già demolito"); + if (w.Vehicles.Any(v => !v.Sold && v.Depot == depot.Id) || w.Trains.Any(t => !t.Removed && t.AtNode == depot.Node)) + return reply(CommandError.Blocked, "Ci sono veicoli nel deposito"); + node.Depot = DepotId.None; + net.Touch(); + var refund = new Money(depot.BuildCostCents) * refundShare; + w.Money.Transfer(Account.External, Account.Of(company.Id), refund, LedgerEntry.Construction); + return reply(CommandError.None, $"Deposito demolito, recuperati {refund}"); + } + } + } + + public static CommandResult RenewTrack(World w, Company company, RenewTrackCommand c, Reply reply) + { + if (!TryEdge(w, c.Edge, company, out var edge)) return reply(CommandError.NotFound, "Binario inesistente"); + if (edge.State != EdgeState.Active) return reply(CommandError.NotAllowed, "Binario non in esercizio"); + if (!RailNetwork.IsFree(edge)) return reply(CommandError.Blocked, "Binario occupato da un treno"); + var tw = w.Data.Construction.TrackWear; + var cost = new Money(edge.BuildCostCents) * tw.RenewalCostShare; + if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}"); + double days = Math.Max(1, Math.Ceiling(edge.Length / 1000 * tw.RenewalDaysPerKm)); + StartProject(w, company, edge, ProjectKind.Renewal, days); + w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.TrackMaintenance); + return reply(CommandError.None, $"Rinnovo avviato: {days:F0} giorni di chiusura, {cost}"); + } + + public static CommandResult UpgradeTrack(World w, Company company, UpgradeTrackCommand c, Reply reply) + { + if (!TryEdge(w, c.Edge, company, out var edge)) return reply(CommandError.NotFound, "Binario inesistente"); + if (edge.State != EdgeState.Active) return reply(CommandError.NotAllowed, "Binario non in esercizio"); + if (!RailNetwork.IsFree(edge)) return reply(CommandError.Blocked, "Binario occupato da un treno"); + var cls = w.Data.Eras.TrackClasses.FirstOrDefault(t => t.Id == c.TrackClass); + if (cls is null) return reply(CommandError.InvalidArgument, "Classe sconosciuta"); + if (cls.From > w.Clock.Year) return reply(CommandError.EraLocked, $"{cls.NameIt} disponibile dal {cls.From}"); + if (c.Electrified && w.Data.Eras.ElectrificationFrom > w.Clock.Year) return reply(CommandError.EraLocked, "Elettrificazione non ancora disponibile"); + var costs = w.Data.Construction.Costs; + var speedClasses = w.Data.Construction.SpeedClasses; + double oldMult = speedClasses.First(s => s.TrackClass == w.Data.Eras.TrackClasses[edge.TrackClass].Id).CostMultiplier; + double newMult = speedClasses.First(s => s.TrackClass == cls.Id).CostMultiplier; + // il raggio delle curve esistenti deve bastare alla nuova classe + double minRadius = speedClasses.First(s => s.TrackClass == cls.Id).MinRadiusM; + double baseCost = edge.Length * costs.BasePerMeter * w.Difficulty.ConstructionCostMultiplier; + double extra = Math.Max(0, newMult - oldMult) * baseCost + + (c.DoubleTrack && !edge.DoubleTrack ? (costs.DoubleTrackMultiplier - 1) * baseCost * newMult : 0) + + (c.Electrified && !edge.Electrified ? costs.ElectrificationExtra * baseCost * newMult : 0); + if (extra <= 0 && cls.Index == edge.TrackClass) return reply(CommandError.InvalidArgument, "Nessuna modifica"); + var cost = Money.FromCentsRounded(extra); + if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}"); + double days = Math.Max(1, Math.Ceiling(edge.Length / w.Data.Construction.Crews.MetersPerDay["natural"])); + StartProject(w, company, edge, ProjectKind.Upgrade, days, cls.Index, c.DoubleTrack || edge.DoubleTrack, c.Electrified || edge.Electrified); + w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.Construction); + _ = minRadius; + return reply(CommandError.None, $"Ammodernamento avviato: {days:F0} giorni, {cost}"); + } + + private static void StartProject(World w, Company company, TrackEdge edge, ProjectKind kind, double days, + int upgradeClass = -1, bool upgradeDouble = false, bool upgradeElectrified = false) + { + var net = w.Network; + var project = new ConstructionProject + { + Id = net.NextProject++, + Owner = company.Id, + Kind = kind, + Edges = [edge.Id], + TotalDays = days, + QueuedDay = w.Clock.Day, + UpgradeClass = upgradeClass, + UpgradeDouble = upgradeDouble, + UpgradeElectrified = upgradeElectrified, + }; + edge.Project = project.Id; + edge.State = EdgeState.Closed; + net.Projects.Add(project); + net.Touch(); + } + + public static CommandResult BuyVehicle(World w, Company company, BuyVehicleCommand c, Reply reply) + { + if (!w.Data.TryVehicle(c.VehicleType, out var def) || def is null) return reply(CommandError.NotFound, "Veicolo sconosciuto"); + if (c.Count < 1 || c.Count > 50) return reply(CommandError.InvalidArgument, "Quantità tra 1 e 50"); + int year = w.Clock.Year; + if (def.EraFrom > year || (def.EraTo is { } to && year > to)) return reply(CommandError.EraLocked, $"{def.NameIt} non è in produzione nel {year}"); + if (!c.Depot.IsValid || c.Depot.Value >= w.Network.Depots.Count || w.Network.Depots[c.Depot.Value].Owner != company.Id) + return reply(CommandError.NotFound, "Deposito inesistente"); + if (w.Network.Nodes[w.Network.Depots[c.Depot.Value].Node.Value].Depot != c.Depot) return reply(CommandError.NotFound, "Deposito demolito"); + var cost = new Money(def.Price) * c.Count; + if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}"); + var created = new int[c.Count]; + var components = def.Kind == VehicleKind.Locomotive ? w.Data.Maintenance.Components.Locomotive : w.Data.Maintenance.Components.Car; + for (int i = 0; i < c.Count; i++) + { + var v = new Vehicle + { + Id = new VehicleId(w.Vehicles.Count), + Def = def, + Owner = company.Id, + BoughtDay = w.Clock.Day, + Depot = c.Depot, + Components = Enumerable.Repeat(100.0, components.Count).ToArray(), + }; + w.Vehicles.Add(v); + created[i] = v.Id.Value; + } + w.NextIds.Vehicle = w.Vehicles.Count; + w.Money.Transfer(Account.Of(company.Id), Account.External, cost, LedgerEntry.VehiclePurchase); + return reply(CommandError.None, $"Acquistati {c.Count} × {def.NameIt}", created); + } + + public static CommandResult SellVehicle(World w, Company company, SellVehicleCommand c, Reply reply) + { + if (!c.Vehicle.IsValid || c.Vehicle.Value >= w.Vehicles.Count) return reply(CommandError.NotFound, "Veicolo inesistente"); + var v = w.Vehicles[c.Vehicle.Value]; + if (v.Owner != company.Id || v.Sold) return reply(CommandError.NotFound, "Veicolo inesistente"); + if (v.Train.IsValid) return reply(CommandError.NotAllowed, "Il veicolo fa parte di un treno: scomponilo prima"); + var value = ResaleValue(w, v); + v.Sold = true; + v.Depot = DepotId.None; + w.Money.Transfer(Account.External, Account.Of(company.Id), value, LedgerEntry.VehicleSale); + return reply(CommandError.None, $"Venduto per {value}"); + } + + /// Valore di rivendita: prezzo × (1 − età/vita, minimo 10 %) × condizione media. + public static Money ResaleValue(World w, Vehicle v) + { + double ageYears = (w.Clock.Day - v.BoughtDay) / (double)w.Calendar.DaysPerYear; + double residual = Math.Max(w.Data.Balance.Finance.BookValueFloor, 1 - ageYears / v.Def.LifeYears); + double condition = v.Components.Length == 0 ? 1 : v.Components.Average() / 100; + return new Money(v.Def.Price) * (residual * condition); + } + + public static CommandResult ComposeTrain(World w, Company company, ComposeTrainCommand c, Reply reply) + { + var ops = w.Data.Construction.Operations; + if (c.Vehicles.Count == 0 || c.Vehicles.Count > ops.MaxVehiclesPerTrain) return reply(CommandError.InvalidArgument, $"Da 1 a {ops.MaxVehiclesPerTrain} veicoli"); + if (!c.Depot.IsValid || c.Depot.Value >= w.Network.Depots.Count || w.Network.Depots[c.Depot.Value].Owner != company.Id) + return reply(CommandError.NotFound, "Deposito inesistente"); + if (c.Vehicles.Distinct().Count() != c.Vehicles.Count) return reply(CommandError.InvalidArgument, "Veicoli ripetuti"); + foreach (var id in c.Vehicles) + { + if (!id.IsValid || id.Value >= w.Vehicles.Count) return reply(CommandError.NotFound, "Veicolo inesistente"); + var v = w.Vehicles[id.Value]; + if (v.Owner != company.Id || v.Sold) return reply(CommandError.NotFound, "Veicolo inesistente"); + if (v.Train.IsValid || v.Depot != c.Depot) return reply(CommandError.NotAllowed, $"{v.Def.NameIt} non è libero in questo deposito"); + } + if (!c.Vehicles.Any(id => w.Vehicles[id.Value].Def.Kind == VehicleKind.Locomotive)) + return reply(CommandError.InvalidArgument, "Serve almeno una locomotiva"); + var depot = w.Network.Depots[c.Depot.Value]; + var train = new Train + { + Id = new TrainId(w.Trains.Count), + Owner = company.Id, + Name = c.Name ?? $"Treno {w.Trains.Count(t => t.Owner == company.Id) + 1}", + HomeDepot = c.Depot, + AtNode = depot.Node, + }; + foreach (var id in c.Vehicles) + { + train.Vehicles.Add(id); + var v = w.Vehicles[id.Value]; + v.Train = train.Id; + v.Depot = DepotId.None; + } + RecomputeTrain(w, train); + w.Trains.Add(train); + w.NextIds.Train = w.Trains.Count; + w.LineGraphs.Touch(); + return reply(CommandError.None, $"{train.Name} composto: {train.LengthM:F0} m, {train.EmptyMassT:F0} t, {train.MaxSpeedKmh:F0} km/h", train.Id.Value); + } + + /// Ricalcola le caratteristiche fisiche del treno dalla composizione. + public static void RecomputeTrain(World w, Train t) + { + var cx = w.Data.Construction.Physics.CxByKind; + double mass = 0, locoMass = 0, power = 0, te = 0, length = 0, drag = 0, vmax = double.MaxValue; + bool electric = false; + int locos = 0; + foreach (var id in t.Vehicles) + { + var d = w.Vehicles[id.Value].Def; + mass += d.MassT; + length += d.LengthM; + vmax = Math.Min(vmax, d.MaxSpeedKmh); + drag += cx[d.Kind.ToString().ToLowerInvariant()]; + if (d.Kind != VehicleKind.Locomotive) continue; + locos++; + locoMass += d.MassT; + power += d.PowerKw; + te += d.TractiveEffortKn; + if (d.Traction is { } tr && w.Data.Eras.Tractions.First(x => x.Id == tr).NeedsElectrification) electric = true; + } + t.EmptyMassT = mass; + t.LocoMassT = locoMass; + t.PowerKw = power; + t.TractiveKn = te; + t.LengthM = length; + t.Cx = drag; + t.MaxSpeedKmh = vmax == double.MaxValue ? 0 : vmax; + t.NeedsElectrification = electric; + t.Locomotives = locos; + } + + public static CommandResult CreateLine(World w, Company company, CreateLineCommand c, Reply reply) + { + var error = ValidateStops(w, company, c.Stops); + if (error is not null) return reply(CommandError.InvalidArgument, error); + var line = new Line + { + Id = new LineId(w.Lines.Count), + Owner = company.Id, + Name = string.IsNullOrWhiteSpace(c.Name) ? $"Linea {w.Lines.Count(l => l.Owner == company.Id) + 1}" : c.Name, + Color = c.Color, + }; + line.Stops.AddRange(c.Stops); + w.Lines.Add(line); + w.NextIds.Line = w.Lines.Count; + w.LineGraphs.Touch(); + return reply(CommandError.None, $"{line.Name} creata con {line.Stops.Count} fermate", line.Id.Value); + } + + public static CommandResult EditLine(World w, Company company, EditLineCommand c, Reply reply) + { + if (!c.Line.IsValid || c.Line.Value >= w.Lines.Count || w.Lines[c.Line.Value].Owner != company.Id || w.Lines[c.Line.Value].Removed) + return reply(CommandError.NotFound, "Linea inesistente"); + var error = ValidateStops(w, company, c.Stops); + if (error is not null) return reply(CommandError.InvalidArgument, error); + var line = w.Lines[c.Line.Value]; + line.Stops.Clear(); + line.Stops.AddRange(c.Stops); + if (c.Name is not null) line.Name = c.Name; + foreach (var t in w.Trains.Where(t => t.Line == line.Id && t.StopIndex >= line.Stops.Count)) t.StopIndex = 0; + w.LineGraphs.Touch(); + return reply(CommandError.None, $"{line.Name} aggiornata"); + } + + private static string? ValidateStops(World w, Company company, IReadOnlyList stops) + { + if (stops.Count < 2) return "Una linea ha almeno due fermate"; + foreach (var s in stops) + { + if (!s.Station.IsValid || s.Station.Value >= w.Network.Stations.Count) return "Stazione inesistente"; + var st = w.Network.Stations[s.Station.Value]; + if (st.Owner != company.Id || w.Network.Nodes[st.Node.Value].Station != st.Id) return "Stazione inesistente"; + if (s.MaxWaitDays < 0 || s.MaxWaitDays > 60) return "Attesa massima tra 0 e 60 giorni"; + } + return null; + } + + public static CommandResult AssignTrain(World w, Company company, AssignTrainCommand c, Reply reply) + { + if (!TryTrain(w, c.Train, company, out var train)) return reply(CommandError.NotFound, "Treno inesistente"); + if (c.Line.IsValid && (c.Line.Value >= w.Lines.Count || w.Lines[c.Line.Value].Owner != company.Id || w.Lines[c.Line.Value].Removed)) + return reply(CommandError.NotFound, "Linea inesistente"); + train.Line = c.Line; + train.StopIndex = 0; + train.GoingToDepot = DepotId.None; + if (train.State == TrainState.NoRoute) train.State = TrainState.Waiting; + w.LineGraphs.Touch(); + return reply(CommandError.None, c.Line.IsValid ? $"{train.Name} assegnato a {w.Lines[c.Line.Value].Name}" : $"{train.Name} tolto dal servizio"); + } + + public static CommandResult SendToDepot(World w, Company company, SendToDepotCommand c, Reply reply) + { + if (!TryTrain(w, c.Train, company, out var train)) return reply(CommandError.NotFound, "Treno inesistente"); + if (!c.Depot.IsValid || c.Depot.Value >= w.Network.Depots.Count || w.Network.Depots[c.Depot.Value].Owner != company.Id) + return reply(CommandError.NotFound, "Deposito inesistente"); + train.GoingToDepot = c.Depot; + train.Line = LineId.None; + if (train.State == TrainState.NoRoute) train.State = TrainState.Waiting; + w.LineGraphs.Touch(); + return reply(CommandError.None, $"{train.Name} diretto al deposito"); + } + + /// Ricalcola il bacino di una stazione (industrie, città, hub entro il raggio). + public static void UpdateCatchment(World w, Station s) + { + double km = w.Data.Construction.Stations.CatchmentKm; + s.Industries.Clear(); + s.Towns.Clear(); + s.Hubs.Clear(); + if (w.Network.Nodes[s.Node.Value].Station != s.Id) return; + foreach (var i in w.Industries) + { + if (!i.Closed && Vec2.Distance(i.Position, s.Position) <= km * 1000) s.Industries.Add(i.Id); + } + foreach (var t in w.Towns) + { + if (w.TownEdgeDistanceKm(t, s.Position) <= km) s.Towns.Add(t.Id); + } + foreach (var h in w.Hubs) + { + if (Vec2.Distance(h.Position, s.Position) <= km * 1000) s.Hubs.Add(h.Id); + } + } + + private static string DefaultName(World w, Vec2 p, string kind) + { + if (w.Towns.Count == 0) return kind; + var town = w.Towns.MinBy(t => w.TownEdgeDistanceKm(t, p))!; + string name = $"{kind} di {town.Name}"; + int n = 2; + while (w.Network.Stations.Any(s => s.Name == name) || w.Network.Depots.Any(d => d.Name == name)) name = $"{kind} di {town.Name} {n++}"; + return name; + } + + private static bool InsideMap(World w, Vec2 p) => p.X >= 0 && p.Y >= 0 && p.X < w.Terrain.WidthM && p.Y < w.Terrain.HeightM; + + private static bool TryEdge(World w, EdgeId id, Company company, out TrackEdge edge) + { + edge = null!; + if (!id.IsValid || id.Value >= w.Network.Edges.Count) return false; + edge = w.Network.Edges[id.Value]; + return edge.Owner == company.Id; + } + + private static bool TryTrain(World w, TrainId id, Company company, out Train train) + { + train = null!; + if (!id.IsValid || id.Value >= w.Trains.Count) return false; + train = w.Trains[id.Value]; + return train.Owner == company.Id && !train.Removed; + } +} diff --git a/src/ViaFerrea.Core/Simulation/SystemPipeline.cs b/src/ViaFerrea.Core/Simulation/SystemPipeline.cs index 94952fc..6b0cfe7 100644 --- a/src/ViaFerrea.Core/Simulation/SystemPipeline.cs +++ b/src/ViaFerrea.Core/Simulation/SystemPipeline.cs @@ -24,6 +24,9 @@ public sealed class SystemPipeline(IReadOnlyList systems) [ new ClockSystem(), new CommandSystem(), + new ConstructionSystem(), + new TrainSystem(), + new StationSystem(), new LocalTransportSystem(), new DemandSystem(), new EmploymentSystem(), diff --git a/src/ViaFerrea.Core/Simulation/Systems/ConstructionSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/ConstructionSystem.cs new file mode 100644 index 0000000..c065cc7 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/ConstructionSystem.cs @@ -0,0 +1,193 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Rail; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// 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. +/// +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); + } + + /// Squadre disponibili per una compagnia secondo il livello. + 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)); + } + } + + /// Fattore di velocità dovuto alla condizione di binario e strutture (8.3). + 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; + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs index dba0f16..ba8f8ad 100644 --- a/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs +++ b/src/ViaFerrea.Core/Simulation/Systems/FinanceSystem.cs @@ -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 } } + /// Costi d'esercizio giornalieri: veicoli posseduti, binari di stazione, depositi. + 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); + } + } + + /// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo. + 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]); + } + /// Rata mensile costante (alla francese) per il residuo e i mesi restanti. public static Money MonthlyPayment(Money remaining, double annualRate, int monthsLeft) { diff --git a/src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs new file mode 100644 index 0000000..2a1ae3e --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/StationSystem.cs @@ -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; + +/// +/// 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. +/// +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); + } + } + + /// Un'industria è servita se sta nel bacino di una stazione fermata di una linea con treni. + 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; + } + } + + /// + /// 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. + /// + 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 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; + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/StationWork.cs b/src/ViaFerrea.Core/Simulation/Systems/StationWork.cs new file mode 100644 index 0000000..3e00c4f --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/StationWork.cs @@ -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; + +/// +/// 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. +/// +public static class StationWork +{ + /// Fermata della linea che il treno sta servendo in questa stazione, se coincide. + 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))); + } + + /// Unità movimentate per tick (media tra carri e carrozze del treno). + 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); + } + } + + /// Assegna al pacchetto il prossimo tratto verso la destinazione; false se irraggiungibile. + 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; + } + + /// + /// 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. + /// + 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 + + /// Carica i pacchetti in attesa che viaggiano sulla linea del treno; restituisce le unità caricate. + 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; + } +} diff --git a/src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs b/src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs new file mode 100644 index 0000000..11c4dc9 --- /dev/null +++ b/src/ViaFerrea.Core/Simulation/Systems/TrainSystem.cs @@ -0,0 +1,590 @@ +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Data; +using ViaFerrea.Core.Rail; + +namespace ViaFerrea.Core.Simulation.Systems; + +/// +/// 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. +/// +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 + + /// Calcola il percorso verso la prossima destinazione del treno fermo in un nodo. + 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; + } + } + + /// Libera le risorse superate dalla coda. + 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; + } + } + } + + /// Libera immediatamente tutto (treno rimosso o rientrato in deposito). + 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 + + /// Distanza dalla testa alla fine dell'autorizzazione al movimento. + 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 + + /// Indice dell'ultima sezione di blocco dell'arco. + public static int LastBlock(TrackEdge e) => e.Signals.Count; + + /// Fine (progressiva nel verso di marcia) della sezione j. + 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]; + } + + /// Sezione che contiene la progressiva pos (nel verso di marcia). + 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; + } +} diff --git a/src/ViaFerrea.Core/Simulation/World.cs b/src/ViaFerrea.Core/Simulation/World.cs index c547f81..65a4929 100644 --- a/src/ViaFerrea.Core/Simulation/World.cs +++ b/src/ViaFerrea.Core/Simulation/World.cs @@ -3,6 +3,7 @@ using ViaFerrea.Core.Common; using ViaFerrea.Core.Data; using ViaFerrea.Core.Economy; using ViaFerrea.Core.Map; +using ViaFerrea.Core.Rail; using ViaFerrea.Core.Time; namespace ViaFerrea.Core.Simulation; @@ -56,6 +57,18 @@ public sealed class World public List Companies { get; } = []; public List Commutes { get; } = []; + /// Rete ferroviaria di tutte le compagnie. + public RailNetwork Network { get; } = new(); + public List Vehicles { get; } = []; + public List Trains { get; } = []; + public List Lines { get; } = []; + + /// Ricerca dei percorsi (buffer riutilizzati, non salvati). + public Pathfinder Pathfinder { get; } = new(); + + /// Grafo delle linee per compagnia (cache, non salvata). + public LineGraphCache LineGraphs { get; } = new(); + public Market Market { get; } public MoneyLedger Money { get; } public GoodsCounters Goods { get; } @@ -141,6 +154,20 @@ public sealed class World public long TotalStock(int good) { long sum = 0; + foreach (var s in Network.Stations) + { + foreach (var p in s.Waiting) + { + if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units; + } + } + foreach (var tr in Trains) + { + foreach (var p in tr.Cargo) + { + if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units; + } + } foreach (var t in Towns) sum += t.Stock[good]; foreach (var ind in Industries) { diff --git a/tests/ViaFerrea.Tests/Rail/RailFixture.cs b/tests/ViaFerrea.Tests/Rail/RailFixture.cs new file mode 100644 index 0000000..7a945e6 --- /dev/null +++ b/tests/ViaFerrea.Tests/Rail/RailFixture.cs @@ -0,0 +1,81 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Rail; +using ViaFerrea.Core.Simulation; +using ViaFerrea.Core.Simulation.Scenarios; +using ViaFerrea.Tests.Harness; +using ViaFerrea.Tests.Scenarios; + +namespace ViaFerrea.Tests.Rail; + +/// Mondo con comandi di comodo per i test ferroviari. +public sealed class RailFixture +{ + public World W { get; } + public LoadedScenario? Scenario { get; } + public CompanyId Me => W.Player.Id; + + public RailFixture(World w, LoadedScenario? scenario = null) + { + W = w; + Scenario = scenario; + } + + public static RailFixture Valdoria() { var s = ScenarioHelper.Load("valdoria"); return new RailFixture(s.World, s); } + + public static Vec2 K(double x, double y) => new(x * 1000, y * 1000); + + /// Esegue il comando nel prossimo tick e ne restituisce l'esito. + public CommandResult Do(GameCommand c, CompanyId? issuer = null) + { + W.Enqueue(c with { Issuer = issuer ?? Me }); + W.RunTicks(1); + return W.DrainResults().Last(); + } + + public int Ok(GameCommand c, CompanyId? issuer = null) + { + var r = Do(c, issuer); + Assert.True(r.Ok, $"{c.Type}: {r.Error} {r.Message}"); + return r.Created.Length > 0 ? r.Created[0] : -1; + } + + /// Esegue giorni finché la condizione è vera (o scade il limite). + public bool RunUntil(Func condition, int maxDays) + { + for (int d = 0; d < maxDays * 8; d++) + { + if (condition()) return true; + W.RunTicks(W.Calendar.TicksPerDay / 8); + } + return condition(); + } + + /// Compra veicoli e compone un treno nel deposito. + public int Train(int depot, string loco, int locos, string car, int cars, string name) + { + var ids = new List(); + ids.AddRange(W_Buy(loco, depot, locos)); + if (cars > 0) ids.AddRange(W_Buy(car, depot, cars)); + return Ok(new ComposeTrainCommand(new DepotId(depot), ids, name)); + } + + private IEnumerable W_Buy(string type, int depot, int count) => + Do(new BuyVehicleCommand(type, new DepotId(depot), count)).Created.Select(i => new VehicleId(i)); + + /// + /// Rete merci di Valdoria: stazione delle miniere, stazione dell'acciaieria, deposito e + /// tracciato per il valico; restituisce (miniera, acciaieria, deposito). + /// + public (int Mine, int Mill, int Depot) BuildFreightNetwork(bool waitForConstruction = true) + { + int mine = Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna")); + int mill = Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria")); + int depot = Ok(new BuildDepotCommand(K(2.6, 4.4), "small", "Deposito Rocca Bruna")); + Ok(new BuildTrackCommand(Scenario!.Route("valico", Me).Polyline, AllowTunnels: false)); + Ok(new BuildTrackCommand(new[] { K(2.6, 4.4), K(2.92, 4.95) })); + if (waitForConstruction) + Assert.True(RunUntil(() => W.Network.Edges.All(e => e.State == EdgeState.Active), 400), "cantieri completati"); + return (mine, mill, depot); + } +} diff --git a/tests/ViaFerrea.Tests/Rail/RailNetworkTests.cs b/tests/ViaFerrea.Tests/Rail/RailNetworkTests.cs new file mode 100644 index 0000000..39141d0 --- /dev/null +++ b/tests/ViaFerrea.Tests/Rail/RailNetworkTests.cs @@ -0,0 +1,127 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Rail; +using ViaFerrea.Core.Simulation.Systems; +using ViaFerrea.Tests.Harness; +using static ViaFerrea.Tests.Rail.RailFixture; + +namespace ViaFerrea.Tests.Rail; + +public static class RailNetworkTests +{ + [Test(Description = "Il tracciato del valico si completa nei giorni previsti dal piano e il costo è addebitato")] + public static void TrackIsBuiltInPlannedDays() + { + var f = Valdoria(); + var cash = f.W.Player.Cash; + var r = f.Do(new BuildTrackCommand(f.Scenario!.Route("valico", f.Me).Polyline, AllowTunnels: false)); + Assert.True(r.Ok, r.Message); + var edge = f.W.Network.Edges[r.Created[0]]; + var project = f.W.Network.Projects[r.Created[3]]; + Assert.Equal(EdgeState.UnderConstruction, edge.State); + Assert.True(f.W.Player.Cash < cash, "costo addebitato"); + f.RunUntil(() => edge.State == EdgeState.Active, 400); + Assert.Equal(EdgeState.Active, edge.State); + Assert.Approx(project.TotalDays, project.ProgressDays, 1.0, "giorni di cantiere"); + Assert.Equal(0L, f.W.MoneyBalanceSum()); + } + + [Test(Description = "Le squadre limitano i cantieri contemporanei: con due squadre il terzo progetto aspetta")] + public static void CrewsLimitConcurrentProjects() + { + var f = Valdoria(); + f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.3), K(14.3, 7.3) })); + f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.6), K(14.3, 7.6) })); + f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.9), K(14.3, 7.9) })); + f.W.RunDays(2); + var projects = f.W.Network.Projects; + Assert.Equal(2, ConstructionSystem.Crews(f.W, f.W.Player)); + Assert.True(projects[0].Crew >= 0 && projects[1].Crew >= 0); + Assert.Equal(-1, projects[2].Crew, "terzo progetto in attesa"); + Assert.True(f.RunUntil(() => projects.All(p => p.Done), 200)); + Assert.True(projects[2].StartedDay >= projects[0].StartedDay + projects[0].TotalDays - 1); + } + + [Test] + public static void AttachingToTrackSplitsTheEdge() + { + var f = Valdoria(); + int main = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) })); + f.Ok(new BuildTrackCommand(new[] { K(12.5, 9.53), K(12.5, 11.0) })); + var net = f.W.Network; + Assert.Equal(3, net.Edges.Count); + var junction = net.Nodes[net.Edges[main].B.Value]; + Assert.Equal(3, junction.Edges.Count, "scambio con tre archi"); + Assert.Approx(12500, junction.Position.X, 13); + Assert.Approx(3000, net.Edges[main].Length + net.Edges[1].Length, 1e-6, "le due metà sommano la lunghezza originale"); + Assert.True(f.RunUntil(() => net.Edges.All(e => e.State == EdgeState.Active), 100), "anche la metà nuova finisce col cantiere"); + } + + [Test(Description = "Attraversare il binario di un'altra compagnia richiede un cavalcavia automatico")] + public static void CrossingForeignTrackBuildsAnOverpass() + { + var f = Valdoria(); + var rival = f.W.Companies.First(c => !c.IsPlayer).Id; + f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }), rival); + var r = f.Do(new BuildTrackCommand(new[] { K(12.5, 8.8), K(12.5, 10.2) })); + Assert.True(r.Ok, r.Message); + var edge = f.W.Network.Edges[r.Created[0]]; + Assert.True(edge.LengthOf(WorkKind.Bridge) > 0, "cavalcavia"); + int k = Enumerable.Range(0, edge.S.Length).MinBy(i => Math.Abs(edge.Y[i] - 9500)); + double otherH = f.W.Network.Edges[0].HeightAt(1500); + Assert.True(edge.H[k] >= otherH + f.W.Data.Construction.Rules.OverpassClearanceM - 0.5, "franco sul binario altrui"); + // incrociare a raso il proprio binario è vietato + var own = f.Do(new BuildTrackCommand(new[] { K(13.5, 9.0), K(13.5, 10.0) }), rival); + Assert.Equal(CommandError.InvalidTrack, own.Error); + } + + [Test] + public static void InvalidRequestsAreRejectedWithoutSideEffects() + { + var f = Valdoria(); + var cash = f.W.Player.Cash; + Assert.Equal(CommandError.InvalidTrack, f.Do(new BuildTrackCommand(f.Scenario!.Route("diretto", f.Me).Polyline, AllowTunnels: false)).Error); + Assert.Equal(CommandError.NotAllowed, f.Do(new BuildStationCommand(K(13.6, 4.6), 2)).Error, "stazione dentro la città"); + Assert.Equal(CommandError.InvalidArgument, f.Do(new BuildDepotCommand(K(5, 5), "huge")).Error); + Assert.Equal(CommandError.NotFound, f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(3))).Error); + Assert.Equal(cash, f.W.Player.Cash); + Assert.Equal(0, f.W.Network.Edges.Count); + f.W.Money.Transfer(ViaFerrea.Core.Economy.Account.Of(f.Me), ViaFerrea.Core.Economy.Account.External, f.W.Player.Cash, ViaFerrea.Core.Economy.LedgerEntry.Other); + Assert.Equal(CommandError.InsufficientFunds, f.Do(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) })).Error); + } + + [Test] + public static void StationsHaveCatchmentsAndDemolitionRefunds() + { + var f = Valdoria(); + int mill = f.Ok(new BuildStationCommand(K(10.6, 5.4), 3, "Acciaieria")); + var st = f.W.Network.Stations[mill]; + Assert.True(st.Industries.Any(i => f.W.Industries[i.Value].Def.Id == "steel_mill")); + Assert.True(st.Towns.Count == 0, "Valdoria è oltre il bacino di 2 km"); + int track = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) })); + var before = f.W.Player.Cash; + Assert.True(f.Do(new DemolishCommand(DemolishTarget.Edge, track)).Ok); + Assert.True(f.W.Player.Cash > before, "rimborso del 10 %"); + Assert.True(f.Do(new DemolishCommand(DemolishTarget.Station, mill)).Ok); + Assert.Equal(0L, f.W.MoneyBalanceSum()); + } + + [Test] + public static void SignalsSplitBlocksAndRenewalRestoresCondition() + { + var f = Valdoria(); + int track = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) })); + f.RunUntil(() => f.W.Network.Edges[track].State == EdgeState.Active, 50); + Assert.True(f.Do(new PlaceSignalCommand(new EdgeId(track), 1500)).Ok); + var e = f.W.Network.Edges[track]; + Assert.Equal(2, e.BlocksForward.Length); + Assert.Approx(1500, TrainSystem.BlockEnd(e, true, 0), 1e-9); + Assert.Approx(1500, TrainSystem.BlockEnd(e, false, 0), 1e-9); + e.Condition = 40; + Assert.Approx(0.6, ConstructionSystem.ConditionFactor(f.W, e), 1e-12); + Assert.True(f.Do(new RenewTrackCommand(new EdgeId(track))).Ok); + Assert.Equal(EdgeState.Closed, e.State); + f.RunUntil(() => e.State == EdgeState.Active, 50); + Assert.Equal(100.0, e.Condition); + } +} diff --git a/tests/ViaFerrea.Tests/Rail/TrainTests.cs b/tests/ViaFerrea.Tests/Rail/TrainTests.cs new file mode 100644 index 0000000..0cd268d --- /dev/null +++ b/tests/ViaFerrea.Tests/Rail/TrainTests.cs @@ -0,0 +1,94 @@ +using ViaFerrea.Core.Commands; +using ViaFerrea.Core.Common; +using ViaFerrea.Core.Economy; +using ViaFerrea.Core.Persistence; +using ViaFerrea.Core.Rail; +using ViaFerrea.Tests.Harness; +using static ViaFerrea.Tests.Rail.RailFixture; + +namespace ViaFerrea.Tests.Rail; + +public static class TrainTests +{ + private static (RailFixture F, Train Train, int Line) FreightLine(int wagons = 5) + { + var f = Valdoria(); + var (mine, mill, depot) = f.BuildFreightNetwork(); + int tr = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", wagons, "Treno 12"); + int line = f.Ok(new CreateLineCommand("Linea 3, carbone", "#e0a526", + new[] { new LineStop(new StationId(mine), WaitFull: true, MaxWaitDays: 2), new LineStop(new StationId(mill)) })); + f.Ok(new AssignTrainCommand(new TrainId(tr), new LineId(line))); + return (f, f.W.Trains[tr], line); + } + + [Test(Description = "La linea merci porta minerale e carbone all'acciaieria e il vettore incassa le tariffe")] + public static void FreightLineDeliversAndEarns() + { + var (f, t, _) = FreightLine(); + var steel = f.W.Industries.First(i => i.Def.Id == "steel_mill"); + long revenueBefore = f.W.Player.YearEntries[(int)LedgerEntry.FreightRevenue]; + f.W.RunDays(60); + Assert.True(t.Odometer > 50_000, $"il treno ha viaggiato ({t.Odometer / 1000:F1} km)"); + Assert.True(steel.InputStock.All(s => s > 0), "l'acciaieria riceve minerale e carbone"); + Assert.True(f.W.Player.YearEntries[(int)LedgerEntry.FreightRevenue] > revenueBefore, "tariffe incassate"); + Assert.True(steel.Served, "industria servita"); + Assert.Equal(0L, f.W.MoneyBalanceSum()); + for (int g = 0; g < f.W.Data.GoodCount; g++) + Assert.Equal(f.W.Goods.ExpectedStock(g), f.W.TotalStock(g), $"merce {f.W.Data.Goods[g].Id}"); + } + + [Test(Description = "Due treni in versi opposti sullo stesso binario semplice si incrociano in stazione senza stallo")] + public static void OpposingTrainsOnSingleTrackDoNotDeadlock() + { + var (f, t1, line) = FreightLine(); + int depot = f.W.Network.Depots[0].Id.Value; + int tr2 = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 5, "Treno 13"); + var t2 = f.W.Trains[tr2]; + // il secondo parte più tardi: i due si troveranno in versi opposti + f.W.RunDays(3); + f.Ok(new AssignTrainCommand(new TrainId(tr2), new LineId(line))); + f.W.RunDays(120); + Assert.True(t1.Odometer > 150_000 && t2.Odometer > 150_000, $"entrambi viaggiano: {t1.Odometer / 1000:F0} e {t2.Odometer / 1000:F0} km"); + foreach (var e in f.W.Network.Edges) Assert.True(e.LockCount <= 2); + Assert.False(f.W.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal))); + } + + [Test(Description = "Un treno troppo pesante per la salita resta fermo (Stalled) e genera un avviso")] + public static void OverloadedTrainStallsOnTheGrade() + { + var f = Valdoria(); + var (mine, mill, depot) = f.BuildFreightNetwork(); + int tr = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 20, "Treno pesante"); + // carica forzata: 20 tramogge piene di minerale (contabilizzate come prodotte) + var t = f.W.Trains[tr]; + int ore = f.W.Data.GoodIndex("iron_ore"); + var st = f.W.Network.Stations[mine]; + st.Waiting.Add(new Packet { Id = f.W.NextIds.Packet++, Kind = PacketKind.Freight, Good = ore, Units = 400, Origin = st.Id, Destination = new StationId(mill), HopLine = LineId.None, Contract = -1, ExpiresTick = long.MaxValue }); + f.W.Goods.Produced[ore] += 400; + int line = f.Ok(new CreateLineCommand("Pesante", "#b3573e", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) })); + for (int i = 0; i < st.Waiting.Count; i++) { var p = st.Waiting[i]; p.HopLine = new LineId(line); p.HopEnd = new StationId(mill); st.Waiting[i] = p; } + f.Ok(new AssignTrainCommand(new TrainId(tr), new LineId(line))); + Assert.True(f.RunUntil(() => t.State == TrainState.Stalled, 60), $"stato {t.State}"); + Assert.True(f.W.Events.Recent.Any(e => e.Text.Contains("non supera la salita", StringComparison.Ordinal))); + } + + [Test(Description = "Determinismo e salvataggio con treni in movimento")] + public static void TrainsAreDeterministicAndSurviveSaveLoad() + { + var (a, ta, _) = FreightLine(); + a.W.RunDays(17); + a.W.RunTicks(77); // a metà strada, fuori dal confine del giorno + var b = SaveFile.Load(TestData.Data, SaveFile.Save(a.W, "test")); + Assert.Equal(StateHasher.Compute(a.W), StateHasher.Compute(b)); + a.W.RunDays(40); + b.RunDays(40); + Assert.Equal(a.W.LastStateHash, b.LastStateHash); + Assert.Approx(ta.Odometer, b.Trains[ta.Id.Value].Odometer, 1e-9); + + var (c, _, _) = FreightLine(); + c.W.RunDays(17); + c.W.RunTicks(77); + c.W.RunDays(40); + Assert.Equal(a.W.LastStateHash, c.W.LastStateHash, "due esecuzioni identiche"); + } +}