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; /// /// 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. /// 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; var dayElapsed = new long[w.Pipeline.Systems.Count]; var snapshot = new long[w.Pipeline.Systems.Count]; for (int i = 0; i < ticks; i++) { bool dayTick = w.Clock.IsNewDay; if (dayTick) Array.Copy(w.Pipeline.ElapsedTicks, snapshot, snapshot.Length); long before = GC.GetAllocatedBytesForCurrentThread(); long start = Stopwatch.GetTimestamp(); w.Tick(); samples[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds; if (dayTick) { for (int k = 0; k < snapshot.Length; k++) dayElapsed[k] += w.Pipeline.ElapsedTicks[k] - snapshot[k]; } 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; double dayMs = dayElapsed[i] * 1000.0 / Stopwatch.Frequency / days; if (ms >= 0.005 || kb >= 0.01 || dayMs >= 0.5) Console.WriteLine($" {w.Pipeline.Systems[i].Name,-16} {ms,8:F3} ms/tick {kb,8:F2} KB/tick {dayMs,8:F2} ms al cambio di giorno"); } 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(); } /// /// 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. /// private static List 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(); 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; } /// Segnali ogni 800 m sugli archi principali (non sulle diramazioni dei depositi). 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; } /// Compra locomotive e tramogge, compone i treni, crea una linea per tratta e li assegna. private static int BuyTrains(World w, CompanyId me, List 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(); 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); } }