F2: pendolarismo su rotaia, carichi per linea, accettazione Valdoria e bench

- Abbinamento mensile dei pendolari sul LineGraph (60/90 minuti con i tratti a
  piedi, quote proporzionali ai lavoratori liberi, capacità residua delle
  linee), pacchetti giornalieri, coperture e scioglimento dei contratti.
- LineGraph con maschere dei carichi: merci, lavoratori e personale viaggiano
  solo su linee i cui treni li possono portare; durata dei giri con le soste
  di carico e scarico.
- Industria servita = merce ritirata o consegnata dal vettore.
- Parametri residui spostati in data/*.json.
- Test di accettazione F2 sullo scenario Valdoria con tre linee, test del
  pendolarismo (copertura > 0,9 in 60 giorni, capacità, scioglimento).
- viaferrea-tools bench: 2.000 treni, tick medio 0,84 ms.
- ADR 0007 e 0008, ARCHITECTURE e STATE aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-01 23:45:59 +00:00
1 parent 36631dbd09
commit ac9414a03d
27 files changed
+953 -84

No files matched your search

+12
View File
@@ -141,6 +141,8 @@ public sealed class TownGenParams
public required int MinPopulation { get; init; }
public required double RadiusBaseCells { get; init; }
public required double RadiusPerSqrtPop { get; init; }
/// <summary>Crescita minima del raggio (celle) prima di allargare l'abitato.</summary>
public required double RadiusHysteresisCells { get; init; }
}
public sealed class IndustryGenParams
@@ -185,6 +187,8 @@ public sealed class WorldMarketParams
public required double ShockMin { get; init; }
public required double ShockMax { get; init; }
public required double ShockDecayDays { get; init; }
/// <summary>Minimo della componente mondiale del prezzo, come frazione del prezzo base.</summary>
public required double PriceFloor { get; init; }
}
public sealed class LocalPriceBalance
@@ -229,6 +233,12 @@ public sealed class GrowthBalance
public sealed class TownBalance
{
/// <summary>Giorni in cui l'insoddisfazione «lavoro» si riduce di un fattore e.</summary>
public required int WorkDissatisfactionDecayDays { get; init; }
public required double DemandPriceFactorMin { get; init; }
public required double DemandPriceFactorMax { get; init; }
/// <summary>Soglia di popolazione annunciata nella cronaca.</summary>
public required int PopulationMilestone { get; init; }
public required double BaseGrowth { get; init; }
public required double SatisfactionWeight { get; init; }
public required double EmploymentWeight { get; init; }
@@ -272,6 +282,8 @@ public sealed class EmploymentBalance
public required int ReturnBoardDays { get; init; }
/// <summary>Copertura iniziale di un contratto su rotaia appena creato.</summary>
public required double RailStartCoverage { get; init; }
/// <summary>Quota della capacità stimata delle linee assegnabile ai contratti (margine per ritardi e soste).</summary>
public required double LineCapacityUtilization { get; init; }
}
public sealed class LocalTransportBalance
@@ -46,6 +46,10 @@ public sealed class OperationsParams
public required double LookaheadMarginM { get; init; }
public required int WaitWarningDays { get; init; }
public required int DefaultMaxWaitDays { get; init; }
/// <summary>Margine sui tempi di percorrenza stimati delle linee (accelerazioni e frenate).</summary>
public required double LineRunTimeMargin { get; init; }
/// <summary>Velocità assunta per stimare i tempi di una linea ancora senza treni.</summary>
public required double DefaultLineSpeedKmh { get; init; }
}
public sealed class ProfileParams
@@ -154,6 +158,10 @@ public sealed class StructureParams
public required double SpeedLimitBelow { get; init; }
public required double SpeedLimitFactor { get; init; }
public required double CloseBelow { get; init; }
/// <summary>Fattore di velocità sulle opere sotto la soglia di chiusura.</summary>
public required double ClosedSpeedFactor { get; init; }
/// <summary>Anni in cui un'opera oltre la vita utile perde tutta la condizione.</summary>
public required double AgingYearsToZero { get; init; }
}
public sealed class PhysicsParams
@@ -167,4 +175,6 @@ public sealed class PhysicsParams
public required double BrakingMs2 { get; init; }
public required double StallSpeedKmh { get; init; }
public required double StallSeconds { get; init; }
/// <summary>Massa di un passeggero con bagaglio (t).</summary>
public required double PassengerMassT { get; init; }
}
+1
View File
@@ -17,6 +17,7 @@ public static class DataValidator
// --- beni
Unique("goods.json", d.Goods.Select(g => g.Id), errors);
if (d.Goods.Count > Rail.LineGraph.MaxGoods) Err("goods.json", $"al massimo {Rail.LineGraph.MaxGoods} beni (maschera dei carichi delle linee)");
var goodIds = d.Goods.Select(g => g.Id).ToHashSet(StringComparer.Ordinal);
foreach (string required in new[] { "spare_parts", "machinery" })
{
+63 -12
View File
@@ -14,16 +14,38 @@ public sealed record Connection(StationId Destination, double Minutes, Hop[] Hop
/// <summary>
/// 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.
/// (stazione, linea) con penalità di cambio, limitato alle linee i cui treni possono portare
/// il carico richiesto (merce con carri adatti, lavoratori o personale con le carrozze della
/// classe). Ricostruito quando cambiano rete, linee o treni.
/// </summary>
public sealed class LineGraph
{
private readonly record struct Segment(int From, int To, LineId Line, double Minutes);
private readonly record struct Segment(int From, int To, LineId Line, double Minutes, ulong Carries);
private readonly Dictionary<int, List<Segment>> _out = new();
private readonly Dictionary<int, Dictionary<int, Connection>> _reach = new();
private readonly Dictionary<(int, ulong), Dictionary<int, Connection>> _reach = new();
private readonly double _transferMinutes;
/// <summary>Bit del carico «lavoratori» (i bit bassi sono i beni, uno per indice).</summary>
public const ulong WorkersCargo = 1UL << 62;
/// <summary>Bit del carico «personale qualificato».</summary>
public const ulong StaffCargo = 1UL << 63;
/// <summary>Numero massimo di beni rappresentabili nella maschera dei carichi.</summary>
public const int MaxGoods = 62;
public static ulong GoodCargo(int good) => 1UL << good;
public static ulong PaxCargo(Data.PaxClass cls) => cls == Data.PaxClass.Staff ? StaffCargo : WorkersCargo;
public static ulong CargoOf(in Packet p) => p.Kind switch
{
PacketKind.Freight => GoodCargo(p.Good),
PacketKind.Staff => StaffCargo,
_ => WorkersCargo,
};
/// <summary>Carichi che i treni di ogni linea possono portare.</summary>
public Dictionary<int, ulong> Carries { get; } = new();
public CompanyId Company { get; }
public int Version { get; }
@@ -38,16 +60,41 @@ public sealed class LineGraph
Company = company;
Version = version;
var ops = w.Data.Construction.Operations;
double dwell = w.Data.Construction.Stations.MinDwellMinutes;
_transferMinutes = dwell * 2;
var sp = w.Data.Construction.Stations;
_transferMinutes = sp.MinDwellMinutes * 2;
var net = w.Network;
var path = new List<RouteStep>();
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;
double speed = trains.Count > 0 ? trains.Min(t => t.MaxSpeedKmh) : ops.DefaultLineSpeedKmh;
bool electric = trains.Any(t => t.NeedsElectrification);
ulong carries = 0;
foreach (var t in trains)
{
foreach (var vid in t.Vehicles)
{
var def = w.Vehicles[vid.Value].Def;
if (def.Kind == Data.VehicleKind.Coach) carries |= PaxCargo(def.Class ?? Data.PaxClass.Worker);
else if (def.Kind == Data.VehicleKind.Wagon)
foreach (int g in def.GoodIndices) carries |= GoodCargo(g);
}
}
Carries[line.Id.Value] = carries;
// sosta stimata a ogni fermata: scarico e carico completi del treno più capiente
double dwell = sp.MinDwellMinutes;
foreach (var t in trains)
{
double units = 0, perMinute = 0;
foreach (var vid in t.Vehicles)
{
var def = w.Vehicles[vid.Value].Def;
if (def.Kind == Data.VehicleKind.Coach) { units += def.PaxCapacity ?? 0; perMinute += sp.PaxPerMinutePerCoach; }
else if (def.Kind == Data.VehicleKind.Wagon) { units += def.Capacity ?? 0; perMinute += sp.FreightUnitsPerMinutePerWagon; }
}
if (perMinute > 0) dwell = Math.Max(dwell, 2 * units / perMinute);
}
double cycle = 0;
bool complete = true;
for (int i = 0; i < line.Stops.Count; i++)
@@ -62,10 +109,10 @@ public sealed class LineGraph
}
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
double minutes = seconds / 60 * ops.LineRunTimeMargin + dwell;
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));
list.Add(new Segment(a.Id.Value, b.Id.Value, line.Id, minutes, carries));
}
if (!complete || cycle <= 0) continue;
CycleMinutes[line.Id.Value] = cycle;
@@ -89,10 +136,13 @@ public sealed class LineGraph
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));
}
/// <summary>Collegamenti migliori da una stazione verso tutte le stazioni raggiungibili.</summary>
public IReadOnlyDictionary<int, Connection> From(StationId origin)
/// <summary>
/// Collegamenti migliori da una stazione verso tutte le stazioni raggiungibili con linee i cui
/// treni portano il carico indicato (maschera: beni, <see cref="WorkersCargo"/>, <see cref="StaffCargo"/>).
/// </summary>
public IReadOnlyDictionary<int, Connection> From(StationId origin, ulong cargo)
{
if (_reach.TryGetValue(origin.Value, out var cached)) return cached;
if (_reach.TryGetValue((origin.Value, cargo), out var cached)) return cached;
var result = new Dictionary<int, Connection>();
// stato = (stazione, linea su cui si viaggia); linea −1 = a terra all'origine
var best = new Dictionary<(int, int), double>();
@@ -109,6 +159,7 @@ public sealed class LineGraph
if (!_out.TryGetValue(state.Station, out var segs)) continue;
foreach (var seg in segs)
{
if ((seg.Carries & cargo) == 0) continue;
double c = cost + seg.Minutes + (state.Line >= 0 && state.Line != seg.Line.Value ? _transferMinutes : 0);
var next = (seg.To, seg.Line.Value);
if (best.TryGetValue(next, out double old) && old <= c) continue;
@@ -117,7 +168,7 @@ public sealed class LineGraph
open.Enqueue(next, (c, seg.To, seg.Line.Value));
}
}
_reach[origin.Value] = result;
_reach[(origin.Value, cargo)] = result;
return result;
}
@@ -20,6 +20,9 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
/// <summary>Tick totali (Stopwatch) spesi per sistema quando Profile è attivo.</summary>
public long[] ElapsedTicks { get; } = new long[systems.Count];
/// <summary>Byte allocati per sistema quando Profile è attivo.</summary>
public long[] AllocatedBytes { get; } = new long[systems.Count];
public static SystemPipeline CreateDefault() => new(
[
new ClockSystem(),
@@ -46,9 +49,11 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
}
for (int i = 0; i < Systems.Count; i++)
{
long bytes = GC.GetAllocatedBytesForCurrentThread();
long start = Stopwatch.GetTimestamp();
Systems[i].Step(ctx);
ElapsedTicks[i] += Stopwatch.GetTimestamp() - start;
AllocatedBytes[i] += GC.GetAllocatedBytesForCurrentThread() - bytes;
}
}
@@ -58,6 +58,20 @@ public sealed class ConstructionSystem : ISimSystem
}
}
/// <summary>
/// Completa subito tutti i cantieri aperti. Solo per gli strumenti (banco di prova, collaudi):
/// in partita i cantieri avanzano con le squadre.
/// </summary>
public static void CompleteAllNow(World w)
{
foreach (var p in w.Network.Projects)
{
if (p.Done) continue;
p.ProgressDays = p.TotalDays;
Complete(w.Context, w, p);
}
}
private static int FreeCrew(RailNetwork net, CompanyId company, int crews)
{
for (int c = 0; c < crews; c++)
@@ -172,7 +186,7 @@ public sealed class ConstructionSystem : ISimSystem
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);
if (age > st.RenewalYears) e.StructureCondition -= 100.0 / (st.AgingYearsToZero * 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,
@@ -187,7 +201,7 @@ public sealed class ConstructionSystem : ISimSystem
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);
if (e.StructureCondition < st.CloseBelow) f = Math.Min(f, st.ClosedSpeedFactor);
return f;
}
}
@@ -56,7 +56,8 @@ public sealed class DemandSystem : ISimSystem
var def = w.Data.Goods[good];
if (def.Town is not { } td || def.Era > year || (td.UntilYear is { } until && year >= until)) return 0;
double ratio = w.Market.GlobalPrice[good] / def.BasePrice;
double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), 0.5, 1.5);
var tb = w.Data.Balance.Town;
double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), tb.DemandPriceFactorMin, tb.DemandPriceFactorMax);
return town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
}
}
@@ -1,14 +1,16 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Core.Simulation.Systems;
/// <summary>
/// Pendolarismo (guida, sezione 9). In F1 gestisce i servizi cittadini, i lavoratori in sede e i
/// contratti a piedi verso posti di lavoro entro il raggio pedonale; i contratti su rotaia
/// arrivano in F4 con il LineGraph. Ogni mese ricostruisce i contratti a piedi; ogni giorno
/// aggiorna presenze e coperture.
/// Pendolarismo (guida, sezione 9): servizi cittadini, lavoratori in sede, contratti a piedi entro
/// il raggio pedonale e contratti su rotaia sul grafo delle linee (entro 60 minuti di orologio dei
/// treni per i lavoratori, 90 per il personale, tratto a piedi compreso). Ogni mese ricostruisce i
/// contratti a piedi, verifica quelli su rotaia e ne crea di nuovi; ogni giorno genera i pacchetti
/// di passeggeri e aggiorna presenze e coperture.
/// </summary>
public sealed class EmploymentSystem : ISimSystem
{
@@ -17,8 +19,9 @@ public sealed class EmploymentSystem : ISimSystem
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
if (ctx.IsNewMonth) Rematch(ctx);
UpdatePresence(ctx);
if (ctx.IsNewMonth) Rematch(ctx);
GeneratePassengers(ctx);
}
/// <summary>Ricostruisce servizi cittadini e contratti a piedi.</summary>
@@ -30,6 +33,7 @@ public sealed class EmploymentSystem : ISimSystem
var eb = w.Data.Balance.Employment;
w.Commutes.RemoveAll(c => c.Walking);
ValidateRailContracts(ctx);
foreach (var town in w.Towns)
{
@@ -72,8 +76,8 @@ public sealed class EmploymentSystem : ISimSystem
if (nearby.Count == 0) continue;
nearby.Sort((a, b) => a.Km != b.Km ? a.Km.CompareTo(b.Km) : a.Town.Id.Value.CompareTo(b.Town.Id.Value));
int openWorkers = ind.JobsWorkers - (int)Math.Ceiling(OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare)) - ind.ContractedWorkers;
int openStaff = ind.JobsStaff - (int)Math.Ceiling(OnSite(ind.JobsStaff, ib.OnSiteStaffShare)) - ind.ContractedStaff;
int openWorkers = OpenJobs(ind.JobsWorkers, ib.OnSiteWorkerShare, ind.ContractedWorkers);
int openStaff = OpenJobs(ind.JobsStaff, ib.OnSiteStaffShare, ind.ContractedStaff);
foreach (var (km, town) in nearby)
{
if (openWorkers > 0)
@@ -100,6 +104,195 @@ public sealed class EmploymentSystem : ISimSystem
}
}
}
MatchRail(ctx);
}
/// <summary>
/// I contratti su rotaia restano validi se il percorso esiste ancora e la copertura non è
/// rimasta sotto la soglia troppo a lungo; altrimenti si sciolgono e la città se ne lamenta.
/// </summary>
private static void ValidateRailContracts(WorldContext ctx)
{
var w = ctx.World;
var eb = w.Data.Balance.Employment;
var tb = w.Data.Balance.Town;
for (int i = w.Commutes.Count - 1; i >= 0; i--)
{
var c = w.Commutes[i];
if (c.Walking) continue;
bool routeOk = c.HomeStation.IsValid && c.WorkStation.IsValid
&& w.LineGraphs.For(w, c.Carrier).From(c.HomeStation, LineGraph.PaxCargo(c.Category)).ContainsKey(c.WorkStation.Value);
bool coverageOk = c.LowCoverageDays < eb.DissolveDays;
if (routeOk && coverageOk) continue;
w.Commutes.RemoveAt(i);
var town = w.Towns[c.Town.Value];
town.WorkDissatisfaction = Math.Min(1, town.WorkDissatisfaction + tb.WorkSatisfactionPenalty);
w.Events.Add(new GameEvent(ctx.Day, EventKind.Employment, EventSeverity.Warning,
$"{c.Headcount} {(c.Category == PaxClass.Staff ? "tecnici" : "lavoratori")} di {town.Name} perdono il posto: " +
(routeOk ? "i treni non li portano al lavoro" : "il collegamento non esiste più"), EntityKind.Town, town.Id.Value, c.Carrier));
}
}
/// <summary>
/// Abbinamento su rotaia: per ogni posto scoperto, città con lavoratori liberi raggiungibili
/// entro il tempo massimo; in ordine di tempo di viaggio, senza superare la capacità residua
/// delle linee del percorso.
/// </summary>
private static void MatchRail(WorldContext ctx)
{
var w = ctx.World;
var eb = w.Data.Balance.Employment;
var tb = w.Data.Balance.Town;
var ib = w.Data.Balance.Industry;
var net = w.Network;
if (w.Lines.Count == 0) return;
// posti già occupati sulle linee per classe
var usedWorkers = new Dictionary<int, double>();
var usedStaff = new Dictionary<int, double>();
foreach (var c in w.Commutes)
{
if (c.Walking) continue;
var used = c.Category == PaxClass.Staff ? usedStaff : usedWorkers;
foreach (var l in c.Route) used[l.Value] = used.GetValueOrDefault(l.Value) + c.Headcount;
}
var candidates = new List<(double Minutes, Town Town, Station Home, Station Work, Connection Conn)>();
var quota = new Dictionary<int, int>();
foreach (var ind in w.Industries)
{
if (ind.Closed || ind.Level <= 0) continue;
int openWorkers = OpenJobs(ind.JobsWorkers, ib.OnSiteWorkerShare, ind.ContractedWorkers);
int openStaff = OpenJobs(ind.JobsStaff, ib.OnSiteStaffShare, ind.ContractedStaff);
if (openWorkers <= 0 && openStaff <= 0) continue;
foreach (PaxClass cls in new[] { PaxClass.Worker, PaxClass.Staff })
{
int open = cls == PaxClass.Staff ? openStaff : openWorkers;
if (open <= 0) continue;
double maxMinutes = cls == PaxClass.Staff ? eb.StaffMaxMinutes : eb.WorkerMaxMinutes;
candidates.Clear();
foreach (var work in net.Stations)
{
if (net.Nodes[work.Node.Value].Station != work.Id || !work.Industries.Contains(ind.Id)) continue;
var graph = w.LineGraphs.For(w, work.Owner);
double walkWork = Vec2.Distance(work.Position, ind.Position) / 1000 / eb.WalkSpeedKmh * 60;
foreach (var home in net.Stations)
{
if (home.Owner != work.Owner || home.Id == work.Id || net.Nodes[home.Node.Value].Station != home.Id) continue;
if (!graph.From(home.Id, LineGraph.PaxCargo(cls)).TryGetValue(work.Id.Value, out var conn)) continue;
foreach (var tid in home.Towns)
{
var town = w.Towns[tid.Value];
double walkHome = w.TownEdgeDistanceKm(town, home.Position) / eb.WalkSpeedKmh * 60;
double minutes = conn.Minutes + walkHome + walkWork;
if (minutes <= maxMinutes) candidates.Add((minutes, town, home, work, conn));
}
}
}
candidates.Sort((a, b) => a.Minutes != b.Minutes ? a.Minutes.CompareTo(b.Minutes)
: a.Town.Id.Value != b.Town.Id.Value ? a.Town.Id.Value.CompareTo(b.Town.Id.Value)
: a.Home.Id.Value != b.Home.Id.Value ? a.Home.Id.Value.CompareTo(b.Home.Id.Value)
: a.Work.Id.Value.CompareTo(b.Work.Id.Value));
// prima passata: quote proporzionali ai lavoratori liberi di ogni città; seconda: il resto
// in ordine di tempo di viaggio. Mai oltre la capacità residua delle linee del percorso.
quota.Clear();
int totalFree = 0;
foreach (var cand in candidates)
{
if (quota.ContainsKey(cand.Town.Id.Value)) continue;
int free = cls == PaxClass.Staff ? cand.Town.FreeStaff(tb) : cand.Town.FreeWorkers(tb);
quota[cand.Town.Id.Value] = free;
totalFree += free;
}
if (totalFree <= 0) continue;
int open0 = open;
foreach (var cand in candidates)
{
int townQuota = (int)Math.Ceiling((double)open0 * quota[cand.Town.Id.Value] / totalFree);
open -= Assign(w, ind, cls, cand, Math.Min(open, townQuota), usedWorkers, usedStaff, eb, tb);
}
foreach (var cand in candidates)
{
if (open <= 0) break;
open -= Assign(w, ind, cls, cand, open, usedWorkers, usedStaff, eb, tb);
}
}
}
}
/// <summary>Crea un contratto per al più <paramref name="limit"/> pendolari della città candidata.</summary>
private static int Assign(World w, Industry ind, PaxClass cls,
(double Minutes, Town Town, Station Home, Station Work, Connection Conn) cand, int limit,
Dictionary<int, double> usedWorkers, Dictionary<int, double> usedStaff, EmploymentBalance eb, TownBalance tb)
{
if (limit <= 0) return 0;
int free = cls == PaxClass.Staff ? cand.Town.FreeStaff(tb) : cand.Town.FreeWorkers(tb);
var graph = w.LineGraphs.For(w, cand.Work.Owner);
var used = cls == PaxClass.Staff ? usedStaff : usedWorkers;
double capacity = double.MaxValue;
foreach (var hop in cand.Conn.Hops)
{
if (!graph.DailyCapacity.TryGetValue(hop.Line.Value, out var cap)) { capacity = 0; break; }
double seats = (cls == PaxClass.Staff ? cap.Staff : cap.Workers) * eb.LineCapacityUtilization;
capacity = Math.Min(capacity, seats - used.GetValueOrDefault(hop.Line.Value));
}
int take = Math.Min(limit, Math.Min(free, (int)Math.Floor(Math.Max(0, capacity))));
if (take <= 0) return 0;
var contract = new CommuteContract
{
Id = new ContractId(w.NextIds.Contract++),
Town = cand.Town.Id,
Workplace = WorkplaceRef.Of(ind.Id),
Category = cls,
Headcount = take,
Carrier = cand.Work.Owner,
HomeStation = cand.Home.Id,
WorkStation = cand.Work.Id,
ExpectedMinutes = cand.Minutes,
Coverage = eb.RailStartCoverage,
};
foreach (var hop in cand.Conn.Hops)
{
if (!contract.Route.Contains(hop.Line)) contract.Route.Add(hop.Line);
used[hop.Line.Value] = used.GetValueOrDefault(hop.Line.Value) + take;
}
w.Commutes.Add(contract);
if (cls == PaxClass.Staff)
{
cand.Town.EmployedStaff += take;
ind.ContractedStaff += take;
}
else
{
cand.Town.EmployedWorkers += take;
ind.ContractedWorkers += take;
}
return take;
}
/// <summary>Ogni giorno ogni contratto su rotaia manda i suoi pendolari alla stazione di casa.</summary>
private static void GeneratePassengers(WorldContext ctx)
{
var w = ctx.World;
var eb = w.Data.Balance.Employment;
foreach (var c in w.Commutes)
{
if (c.Walking || !c.HomeStation.IsValid) continue;
var home = w.Network.Stations[c.HomeStation.Value];
var p = new Packet
{
Id = w.NextIds.Packet++,
Kind = c.Category == PaxClass.Staff ? PacketKind.Staff : PacketKind.Workers,
Good = -1,
Units = c.Headcount,
Origin = c.HomeStation,
Destination = c.WorkStation,
CreatedTick = ctx.Tick,
ExpiresTick = ctx.Tick + (long)eb.BoardDays * w.Calendar.TicksPerDay,
Contract = c.Id.Value,
};
if (StationWork.Route(w, home, ref p)) home.Waiting.Add(p);
}
}
private static void AddWalking(World w, Town town, Industry ind, PaxClass category, int headcount, double km, EmploymentBalance eb)
@@ -118,6 +311,10 @@ public sealed class EmploymentSystem : ISimSystem
/// <summary>Posti coperti da chi vive in sede (quota fissa dei posti, frazionaria).</summary>
public static double OnSite(int jobs, double share) => jobs * share;
/// <summary>Posti da coprire con i pendolari: la parte frazionaria scoperta conta come un posto intero.</summary>
public static int OpenJobs(int jobs, double share, int contracted) =>
Math.Max(0, (int)Math.Ceiling(jobs - OnSite(jobs, share) - contracted - 1e-9));
private static void UpdatePresence(WorldContext ctx)
{
var w = ctx.World;
@@ -130,15 +327,18 @@ public sealed class EmploymentSystem : ISimSystem
}
foreach (var c in w.Commutes)
{
// a piedi si arriva sempre; su rotaia contano i passeggeri consegnati (F4)
// a piedi si arriva sempre; su rotaia contano i pendolari consegnati, mediati su 30 giorni
// (i treni arrivano a ondate: il rapporto giornaliero non si tronca)
if (c.Walking) c.ArrivedToday = c.Headcount;
double ratio = c.Headcount > 0 ? Math.Min(1.0, (double)c.ArrivedToday / c.Headcount) : 0;
double ratio = c.Headcount > 0 ? (double)c.ArrivedToday / c.Headcount : 0;
c.Coverage = Ema.Step(c.Coverage, ratio, eb.CoverageEmaDays);
if (!c.Walking) c.LowCoverageDays = c.Coverage < eb.DissolveCoverage ? c.LowCoverageDays + 1 : 0;
double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
if (c.Workplace.Kind == WorkplaceKind.Industry)
{
var ind = w.Industries[c.Workplace.Index];
if (c.Category == PaxClass.Staff) ind.StaffPresent += c.ArrivedToday;
else ind.WorkersPresent += c.ArrivedToday;
if (c.Category == PaxClass.Staff) ind.StaffPresent += present;
else ind.WorkersPresent += present;
}
if (!c.Walking) c.ArrivedToday = 0;
}
@@ -55,7 +55,7 @@ public sealed class MarketSystem : ISimSystem
market.CapacityToday[g] = 0;
continue;
}
double pw = pb * Math.Max(0.05, 1 + Market.WorldFactor(m, volatility, years, market.Shock[g]));
double pw = pb * Math.Max(m.World.PriceFloor, 1 + Market.WorldFactor(m, volatility, years, market.Shock[g]));
double d = market.Demand[g].Sum;
double s = market.Supply[g].Sum;
double v = Math.Max(m.World.BaselinePerDay * market.Demand[g].Count, m.World.VolumeShare * (d + s) / 2);
@@ -25,7 +25,6 @@ public sealed class StationSystem : ISimSystem
{
foreach (var s in net.Stations) RailCommandHandlers.UpdateCatchment(w, s);
}
MarkServed(w, ctx.Day);
foreach (var s in net.Stations)
{
if (net.Nodes[s.Node.Value].Station != s.Id) continue;
@@ -39,32 +38,6 @@ public sealed class StationSystem : ISimSystem
}
}
/// <summary>Un'industria è servita se sta nel bacino di una stazione fermata di una linea con treni.</summary>
private static void MarkServed(World w, long day)
{
foreach (var s in w.Network.Stations)
{
if (!IsServedStation(w, s)) continue;
foreach (var id in s.Industries) w.Industries[id.Value].LastServedDay = day;
}
}
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)
@@ -116,8 +89,6 @@ public sealed class StationSystem : ISimSystem
{
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];
@@ -128,6 +99,8 @@ public sealed class StationSystem : ISimSystem
int good = outputs[o].GoodIndex;
int units = ind.OutputStock[o];
if (units <= 0) continue;
var reach = graph.From(s.Id, LineGraph.GoodCargo(good));
if (reach.Count == 0) continue;
var dest = BestDestination(w, s, reach, good);
if (dest is null) continue;
var p = new Packet
@@ -146,6 +119,7 @@ public sealed class StationSystem : ISimSystem
Contract = -1,
};
ind.OutputStock[o] = 0;
ind.LastServedDay = ctx.Day;
s.Waiting.Add(p);
w.Network.Stations[dest.Destination.Value].Incoming[good] += units;
var sale = Money.FromCentsRounded(units * w.Market.GlobalPrice[good]);
@@ -185,7 +185,7 @@ public static class StationWork
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;
if (!graph.From(from.Id, LineGraph.CargoOf(p)).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);
@@ -210,6 +210,7 @@ public static class StationWork
int take = Math.Min(units, Math.Max(0, free));
if (take <= 0) continue;
ind.InputStock[i] += take;
ind.LastServedDay = w.Clock.Day;
units -= take;
var cost = Money.FromCentsRounded(take * w.Market.GlobalPrice[good]);
w.Money.Transfer(Account.Of(ind.Id), Account.External, cost, LedgerEntry.Other);
@@ -67,7 +67,7 @@ public sealed class TownSystem : ISimSystem
double ratio = Math.Min(1.0, _catConsumed[c] / _catDemand[c]);
town.Satisfaction[c] = Ema.Step(town.Satisfaction[c], ratio, tb.SatisfactionEmaDays);
}
town.WorkDissatisfaction *= 1.0 - 1.0 / 90.0;
town.WorkDissatisfaction *= 1.0 - 1.0 / tb.WorkDissatisfactionDecayDays;
}
private static void Grow(WorldContext ctx, Town town)
@@ -86,8 +86,8 @@ public sealed class TownSystem : ISimSystem
town.LastGrowth = g;
int before = town.Population;
town.Population = Math.Clamp((int)Math.Round(town.Population * (1 + g)), 0, tb.MaxPopulation);
if (before < 10_000 && town.Population >= 10_000)
ctx.Emit(EventKind.Town, EventSeverity.Info, $"{town.Name} supera i 10.000 abitanti", EntityKind.Town, town.Id.Value);
if (before < tb.PopulationMilestone && town.Population >= tb.PopulationMilestone)
ctx.Emit(EventKind.Town, EventSeverity.Info, $"{town.Name} supera i {Money.GroupThousands((ulong)tb.PopulationMilestone)} abitanti", EntityKind.Town, town.Id.Value);
}
private static void Migrate(WorldContext ctx)
@@ -137,7 +137,7 @@ public sealed class TownSystem : ISimSystem
{
var tp = w.Data.Balance.Map.Towns;
double radius = tp.RadiusBaseCells + tp.RadiusPerSqrtPop * Math.Sqrt(town.Population);
if (radius <= town.RadiusCells + 0.25) return;
if (radius <= town.RadiusCells + tp.RadiusHysteresisCells) return;
town.RadiusCells = radius;
int r = (int)Math.Ceiling(radius);
bool changed = false;
@@ -583,7 +583,7 @@ public sealed class TrainSystem : ISimSystem
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
m += v.Load + v.Pax * 0.08;
m += v.Load + v.Pax * w.Data.Construction.Physics.PassengerMassT;
}
return m;
}
@@ -0,0 +1,262 @@
using System.Diagnostics;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
namespace ViaFerrea.Tools.Commands;
/// <summary>
/// bench: costruisce con i comandi del protocollo una rete di linee a doppio binario con segnali,
/// stazioni a quattro binari e un deposito per linea, vi mette N treni merci e misura il tempo
/// di tick (media, percentili, massimo) e la ripartizione per sistema. Obiettivo della guida
/// (sezione 15): tick medio ≤ 10 ms con 2.000 treni.
/// </summary>
public sealed class BenchCommand : IToolCommand
{
public string Name => "bench";
public string Usage => "bench --trains 2000 [--size 256] [--seed 1] [--stations 600] [--days 5] [--warmup 3] [--budget-ms 10]";
public int Run(CommandLine args)
{
int trainCount = args.Int("trains", 2000);
int size = args.Int("size", 256);
ulong seed = args.ULong("seed", 1);
int stationCount = args.Int("stations", 600);
int days = args.Int("days", 5);
int warmupDays = args.Int("warmup", 3);
double budgetMs = args.Double("budget-ms", 10);
args.EnsureAllUsed();
var data = GameData.LoadDefault();
var total = Stopwatch.StartNew();
var w = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size });
long createMs = total.ElapsedMilliseconds;
Console.WriteLine($"bench: mappa {size} km (seme {seed}) in {createMs} ms; {w.Industries.Count} industrie, {w.Towns.Count} città");
var me = w.Player.Id;
// cassa illimitata per il banco di prova (registrata come movimento esterno: gli invarianti reggono)
w.Money.Transfer(Account.External, Account.Of(me), new Money(1_000_000_000_000_00), LedgerEntry.Other);
var build = Stopwatch.StartNew();
var lines = BuildNetwork(w, me, stationCount / 2, seed);
ConstructionSystem.CompleteAllNow(w);
int signals = PlaceSignals(w, me);
int trains = BuyTrains(w, me, lines, trainCount);
var net = w.Network;
var edges = net.Edges.Where(e => e.State != EdgeState.Demolished).ToList();
int stations = net.Stations.Count(s => net.Nodes[s.Node.Value].Station == s.Id);
Console.WriteLine($" rete: {lines.Count} linee, {stations} stazioni, {edges.Count} archi ({edges.Sum(e => e.Length) / 1000:F0} km), " +
$"{signals} segnali, {trains} treni in {build.ElapsedMilliseconds} ms");
w.RunDays(warmupDays);
int ticks = days * w.Calendar.TicksPerDay;
var samples = new double[ticks];
w.Pipeline.Profile = true;
Array.Clear(w.Pipeline.ElapsedTicks);
Array.Clear(w.Pipeline.AllocatedBytes);
long gc0 = GC.CollectionCount(0);
long allocDay = 0, allocOther = 0;
for (int i = 0; i < ticks; i++)
{
bool dayTick = w.Clock.IsNewDay;
long before = GC.GetAllocatedBytesForCurrentThread();
long start = Stopwatch.GetTimestamp();
w.Tick();
samples[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
long bytes = GC.GetAllocatedBytesForCurrentThread() - before;
if (dayTick) allocDay += bytes;
else allocOther += bytes;
}
w.Pipeline.Profile = false;
var sorted = (double[])samples.Clone();
Array.Sort(sorted);
double avg = samples.Average();
int moving = w.Trains.Count(t => !t.Removed && t.State == TrainState.Moving);
int loading = w.Trains.Count(t => !t.Removed && t.State == TrainState.Loading);
int packets = w.Network.Stations.Sum(s => s.Waiting.Count) + w.Trains.Sum(t => t.Cargo.Count);
Console.WriteLine($" misura: {ticks} tick ({days} giorni dopo {warmupDays} di avvio); treni in moto {moving}, in stazione {loading}, pacchetti {packets}");
Console.WriteLine($" tick: media {avg:F2} ms, mediana {Pct(sorted, 0.5):F2}, p95 {Pct(sorted, 0.95):F2}, p99 {Pct(sorted, 0.99):F2}, max {sorted[^1]:F2} ms");
Console.WriteLine($" allocazioni: {allocOther / (double)(ticks - days) / 1024:F2} KB per tick ordinario, {allocDay / (double)days / 1024:F0} KB per cambio di giorno, GC gen0 {GC.CollectionCount(0) - gc0}");
for (int i = 0; i < w.Pipeline.Systems.Count; i++)
{
double ms = w.Pipeline.ElapsedTicks[i] * 1000.0 / Stopwatch.Frequency / ticks;
double kb = w.Pipeline.AllocatedBytes[i] / 1024.0 / ticks;
if (ms >= 0.005 || kb >= 0.01) Console.WriteLine($" {w.Pipeline.Systems[i].Name,-16} {ms,8:F3} ms/tick {kb,8:F2} KB/tick");
}
bool stalls = w.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal));
Console.WriteLine($" invarianti: denaro {(w.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}; avvisi di stallo: {(stalls ? "sì" : "no")}");
bool ok = avg <= budgetMs;
Console.WriteLine(ok ? $" esito: entro il budget di {budgetMs} ms" : $" esito: OLTRE il budget di {budgetMs} ms");
return ok ? 0 : 1;
}
private static double Pct(double[] sorted, double p) => sorted[Math.Min(sorted.Length - 1, (int)(p * sorted.Length))];
private sealed record BenchLine(int StationA, int StationB, int Depot);
private static CommandResult Do(World w, GameCommand c, CompanyId me)
{
w.Enqueue(c with { Issuer = me });
w.RunTicks(1);
return w.DrainResults().Last();
}
/// <summary>
/// Linee rettilinee di 6–10 km ancorate alle industrie, lontane tra loro, con stazioni a quattro
/// binari alle estremità e un deposito su una diramazione vicino alla prima stazione.
/// </summary>
private static List<BenchLine> BuildNetwork(World w, CompanyId me, int count, ulong seed)
{
var rng = new Rng(seed).Fork("bench");
var placed = new List<(Vec2 A, Vec2 B)>();
var result = new List<BenchLine>();
double margin = 3000, spacing = 1500;
double maxX = w.Terrain.WidthM - margin, maxY = w.Terrain.HeightM - margin;
for (int attempt = 0; result.Count < count && attempt < count * 30; attempt++)
{
var anchor = w.Industries[rng.NextInt(w.Industries.Count)].Position;
double angle = rng.NextDouble(0, 2 * Math.PI);
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
var a = anchor + dir.Perpendicular * rng.NextDouble(400, 1200);
var b = a + dir * rng.NextDouble(6000, 10000);
if (!Inside(a, margin, maxX, maxY) || !Inside(b, margin, maxX, maxY)) continue;
if (placed.Any(s => SegmentDistance(a, b, s.A, s.B) < spacing)) continue;
var junction = a + dir * 800;
var depotAt = junction + dir.Perpendicular * 350;
if (Water(w, a) || Water(w, b) || Water(w, depotAt)) continue;
var sa = Do(w, new BuildStationCommand(a, 4), me);
if (!sa.Ok) continue;
var sb = Do(w, new BuildStationCommand(b, 4), me);
if (!sb.Ok) { Do(w, new DemolishCommand(DemolishTarget.Station, sa.Created[0]), me); continue; }
var track = Do(w, new BuildTrackCommand([a, b], DoubleTrack: true), me);
if (!track.Ok)
{
Do(w, new DemolishCommand(DemolishTarget.Station, sb.Created[0]), me);
Do(w, new DemolishCommand(DemolishTarget.Station, sa.Created[0]), me);
continue;
}
var depot = Do(w, new BuildDepotCommand(depotAt, "small"), me);
var spur = depot.Ok ? Do(w, new BuildTrackCommand([depotAt, junction]), me) : depot;
if (!spur.Ok)
{
// linea senza deposito: i suoi treni nasceranno nel deposito di un'altra linea, non serve
if (depot.Ok) Do(w, new DemolishCommand(DemolishTarget.Depot, depot.Created[0]), me);
foreach (var e in track.Created) Do(w, new DemolishCommand(DemolishTarget.Edge, e), me);
Do(w, new DemolishCommand(DemolishTarget.Station, sb.Created[0]), me);
Do(w, new DemolishCommand(DemolishTarget.Station, sa.Created[0]), me);
continue;
}
placed.Add((a, b));
result.Add(new BenchLine(sa.Created[0], sb.Created[0], depot.Created[0]));
}
return result;
}
/// <summary>Segnali ogni 800 m sugli archi principali (non sulle diramazioni dei depositi).</summary>
private static int PlaceSignals(World w, CompanyId me)
{
const double every = 800;
int placed = 0;
foreach (var e in w.Network.Edges.ToList())
{
if (e.State != EdgeState.Active || e.Owner != me) continue;
if (w.Network.Nodes[e.A.Value].Depot.IsValid || w.Network.Nodes[e.B.Value].Depot.IsValid) continue;
for (double s = every; s < e.Length - every / 2; s += every)
{
w.Enqueue(new PlaceSignalCommand(e.Id, s) with { Issuer = me });
placed++;
}
}
w.RunTicks(1);
placed -= w.DrainResults().Count(r => !r.Ok);
return placed;
}
/// <summary>Compra locomotive e tramogge, compone i treni, crea una linea per tratta e li assegna.</summary>
private static int BuyTrains(World w, CompanyId me, List<BenchLine> lines, int count)
{
if (lines.Count == 0) return 0;
var perLine = new int[lines.Count];
for (int i = 0; i < count; i++) perLine[i % lines.Count]++;
for (int l = 0; l < lines.Count; l++)
{
for (int k = 0; k < perLine[l]; k++)
{
w.Enqueue(new BuyVehicleCommand("loco_steam_1850", new DepotId(lines[l].Depot), 1) with { Issuer = me });
w.Enqueue(new BuyVehicleCommand("wagon_hopper", new DepotId(lines[l].Depot), 4) with { Issuer = me });
}
}
w.RunTicks(1);
var bought = w.DrainResults();
int r = 0;
for (int l = 0; l < lines.Count; l++)
{
for (int k = 0; k < perLine[l]; k++)
{
var ids = bought[r].Created.Concat(bought[r + 1].Created).Select(i => new VehicleId(i)).ToList();
r += 2;
w.Enqueue(new ComposeTrainCommand(new DepotId(lines[l].Depot), ids) with { Issuer = me });
}
w.Enqueue(new CreateLineCommand($"Linea {l + 1}", "#e0a526",
[new LineStop(new StationId(lines[l].StationA)), new LineStop(new StationId(lines[l].StationB))]) with { Issuer = me });
}
w.RunTicks(1);
var composed = w.DrainResults();
int c = 0, trains = 0;
for (int l = 0; l < lines.Count; l++)
{
var trainIds = new List<int>();
for (int k = 0; k < perLine[l]; k++)
{
if (composed[c].Ok) trainIds.Add(composed[c].Created[0]);
c++;
}
var line = composed[c++];
if (!line.Ok) continue;
foreach (int t in trainIds)
{
w.Enqueue(new AssignTrainCommand(new TrainId(t), new LineId(line.Created[0])) with { Issuer = me });
trains++;
}
}
w.RunTicks(1);
trains -= w.DrainResults().Count(x => !x.Ok);
return trains;
}
private static bool Inside(Vec2 p, double margin, double maxX, double maxY) => p.X >= margin && p.Y >= margin && p.X <= maxX && p.Y <= maxY;
private static bool Water(World w, Vec2 p)
{
var (x, y) = w.Terrain.CellAt(p);
return w.Terrain.IsWater(x, y);
}
private static double SegmentDistance(Vec2 a, Vec2 b, Vec2 c, Vec2 d)
{
if (Intersects(a, b, c, d)) return 0;
return Math.Min(Math.Min(PointSegment(a, c, d), PointSegment(b, c, d)), Math.Min(PointSegment(c, a, b), PointSegment(d, a, b)));
}
private static bool Intersects(Vec2 a, Vec2 b, Vec2 c, Vec2 d)
{
double d1 = Vec2.Cross(b - a, c - a), d2 = Vec2.Cross(b - a, d - a);
double d3 = Vec2.Cross(d - c, a - c), d4 = Vec2.Cross(d - c, b - c);
return d1 * d2 < 0 && d3 * d4 < 0;
}
private static double PointSegment(Vec2 p, Vec2 a, Vec2 b)
{
var ab = b - a;
double len2 = Vec2.Dot(ab, ab);
double t = len2 <= 0 ? 0 : Math.Clamp(Vec2.Dot(p - a, ab) / len2, 0, 1);
return Vec2.Distance(p, a + ab * t);
}
}
+1
View File
@@ -11,6 +11,7 @@ public static class ToolsProgram
new GenMapCommand(),
new SimulateCommand(),
new ProfileCommand(),
new BenchCommand(),
];
public static int Main(string[] args)