Files
Rail_Enterprise/src/ViaFerrea.Server/GameHost.cs
T
Claude 7879ac502d F5: manutenzione delle industrie, livelli, borsa e scalate, agenti IA
- Sezione 11: usura e recupero degli impianti, fermi e incidenti, ricambi e macchinari come
  domanda esplicita (treno, trasporto locale, trasbordo nel bacino), revisione e ammodernamento,
  acquisto delle industrie dal livello 3, conguaglio mensile con il proprietario (ADR 0011).
- Livelli della compagnia con soglie ritarate e ritaratura economica misurata con le IA.
- Sezione 12.2–12.3: libro dei soci, prezzo con sentiment, quotazione, riacquisto, dividendi,
  controllo e fusione (comando 39), offerte pubbliche con difese, esiti per difficoltà,
  aste delle IA fallite, nuovi concorrenti, fine partita e Cronaca finale (ADR 0012).
- Sezione 12.1: agenti IA con candidati, Dijkstra sulle celle, TrackPreview e ROI, tre
  personalità, linee dei ricambi, rimedio agli stalli, borsa (ADR 0013).
- Salvataggio versione 3, protocollo (messaggi 126–128, blocchi di estensione), server,
  simulate --trace-ai; test di 14.5 su IA e borsa e accettazione F5 (120 test).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
2026-10-12 10:36:31 +00:00

714 lines
30 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Server;
/// <summary>
/// Ospita la partita: il mondo appartiene al thread del ciclo di gioco, che esegue i tick con un
/// accumulatore, applica i messaggi delle sessioni (coda concorrente drenata a inizio giro) e
/// pubblica verso i client snapshot, delta, opere, moto dei treni e resoconti giornalieri.
/// Se i tick non stanno nel budget la velocità effettiva si dimezza e il resoconto segnala «slow».
/// </summary>
public sealed class GameHost : IDisposable
{
public static readonly byte[] Speeds = [0, 1, 2, 4, 8];
private const long ResumeWindowMs = 120_000;
private const long MotionIntervalMs = 100;
private const int TrackBatchBytes = 1024 * 1024;
private readonly ServerConfig _config;
private readonly GameData _data;
private readonly ILogger _log;
private readonly SaveStore _saves;
private readonly ConcurrentQueue<Action> _inbox = new();
private readonly Dictionary<ulong, Session> _sessions = [];
private readonly Dictionary<uint, (Session Session, uint ClientSeq)> _pending = [];
private readonly List<EventInfo> _dayEvents = [];
private readonly Stopwatch _clock = Stopwatch.StartNew();
private World _world;
private Thread? _thread;
private volatile bool _stop;
private byte _speed = 1;
private double _effectiveSpeed = 1;
private bool _slow;
private uint _serverSeq;
private long _lastMotionMs;
private long _lastAutosaveMs;
private long _lastHeartbeatMs;
private double _tickMsEma;
private bool _publishDirty;
private bool _dailyDue;
private bool _monthlyDue;
private ulong _lastTerrainHash;
private FileStream? _record;
// istantanee per /metrics (lette da altri thread)
private volatile int _sessionCount;
private volatile int _trainCount;
private volatile int _packetCount;
private volatile int _contractCount;
private long _tickMsBits;
private long _ticks;
public string GameVersion { get; } = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<System.Reflection.AssemblyInformationalVersionAttribute>(typeof(GameHost).Assembly)?.InformationalVersion?.Split('+')[0] ?? "0.0.0";
public GameHost(ServerConfig config, GameData data, ILogger log, World? world = null)
{
_config = config;
_data = data;
_log = log;
_saves = new SaveStore(config.SavesDir, GameVersion);
_world = world ?? InitialWorld();
_lastTerrainHash = _world.Terrain.ComputeHash();
if (config.RecordPath is { Length: > 0 } path)
{
// registro dei comandi: si apre con un salvataggio di partenza accanto
_record = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
Protocol.CommandLogFile.WriteHeader(_record);
Core.Persistence.SaveFile.SaveToFile(_world, path + ".start.vfsave", GameVersion);
_world.CommandLog = [];
_log.LogInformation("Registro dei comandi in {Path}", path);
}
}
public SaveStore Saves => _saves;
public long NowMs => _clock.ElapsedMilliseconds;
public bool Healthy => _thread is { IsAlive: true } && NowMs - Interlocked.Read(ref _lastHeartbeatMs) < 5000;
public double TickMs => BitConverter.Int64BitsToDouble(Interlocked.Read(ref _tickMsBits));
public byte Speed => Volatile.Read(ref _speed);
private World InitialWorld()
{
string? latest = _saves.LatestAutosave();
if (latest is not null)
{
try
{
var w = _saves.Load(_data, latest);
_log.LogInformation("Partita ripresa dal salvataggio automatico {Save} ({Date})", latest, w.Clock.Date.ToString());
return w;
}
catch (Exception e)
{
_log.LogWarning(e, "Salvataggio automatico {Save} illeggibile: nuova partita", latest);
}
}
var settings = new NewGameSettings { Seed = _config.Seed, SizeKm = _config.MapSizeKm, DifficultyId = _config.Difficulty };
var world = WorldFactory.Create(_data, settings);
_log.LogInformation("Nuova partita: seme {Seed}, mappa {Size} km, difficoltà {Difficulty}", settings.Seed, settings.SizeKm, settings.DifficultyId);
return world;
}
public void Start()
{
_lastAutosaveMs = NowMs;
Interlocked.Exchange(ref _lastHeartbeatMs, NowMs);
_thread = new Thread(Run) { IsBackground = true, Name = "GameLoop" };
_thread.Start();
}
public void Dispose()
{
_stop = true;
_thread?.Join(5000);
_record?.Dispose();
}
/// <summary>Esegue un'azione sul thread del ciclo di gioco.</summary>
public void Post(Action action) => _inbox.Enqueue(action);
/// <summary>Esegue una funzione sul thread del ciclo di gioco e ne attende il risultato.</summary>
public Task<T> InvokeAsync<T>(Func<World, T> f)
{
var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
Post(() =>
{
try
{
tcs.SetResult(f(_world));
}
catch (Exception e)
{
tcs.SetException(e);
}
});
return tcs.Task;
}
// ------------------------------------------------------------------ sessioni
/// <summary>Valida l'Hello e apre (o riprende) una sessione; il Welcome è il primo messaggio in coda.</summary>
public Task<(Session? Session, Reject? Reject)> OpenSessionAsync(Hello hello) => InvokeAsync<(Session?, Reject?)>(w =>
{
if (hello.ProtocolVersion != Frame.ProtocolVersion)
return (null, new Reject { Code = RejectCode.ProtocolVersion, Reason = $"Versione del protocollo {hello.ProtocolVersion}, il server usa la {Frame.ProtocolVersion}" });
if (_config.Token.Length > 0 && !FixedTimeEquals(hello.Token, _config.Token))
return (null, new Reject { Code = RejectCode.BadToken, Reason = "Token errato" });
if (hello.DataHash != 0 && hello.DataHash != _data.Hash)
return (null, new Reject { Code = RejectCode.DataMismatch, Reason = $"Dati di gioco diversi da quelli del server ({_data.Hash:x16})" });
if (hello.ResumeSessionId != 0 && _sessions.TryGetValue(hello.ResumeSessionId, out var old) && !old.Connected)
{
old.Attach();
old.Send(Welcome(old));
_log.LogInformation("Sessione {Session} ripresa", old.Id);
UpdateSessionCount();
return (old, null);
}
if (_sessions.Values.Count(s => s.Connected) >= _config.MaxSessions)
return (null, new Reject { Code = RejectCode.ServerFull, Reason = "Server pieno" });
ulong id;
do id = BitConverter.ToUInt64(RandomNumberGenerator.GetBytes(8));
while (id == 0 || _sessions.ContainsKey(id));
// in F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009)
var session = new Session(id, w.Player.Id);
session.Attach();
_sessions[id] = session;
session.Send(Welcome(session));
_log.LogInformation("Sessione {Session} aperta (client {Client})", id, hello.ClientVersion);
UpdateSessionCount();
return (session, null);
});
public void Receive(Session session, IMessage message) => Post(() => Handle(session, message));
public void Detach(Session session) => Post(() =>
{
session.MarkDisconnected(NowMs);
_log.LogInformation("Sessione {Session} disconnessa", session.Id);
UpdateSessionCount();
});
private static bool FixedTimeEquals(string a, string b) =>
CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(a), Encoding.UTF8.GetBytes(b));
private void UpdateSessionCount() => _sessionCount = _sessions.Values.Count(s => s.Connected);
private Welcome Welcome(Session s) => new()
{
SessionId = s.Id,
Summary = Projection.Summary(_world, _world.Companies[s.Company.Value], _speed),
DataHash = _data.Hash,
Difficulty = _world.Difficulty.Id,
};
private void Handle(Session s, IMessage message)
{
if (!s.Connected) return;
switch (message)
{
case Ping m:
s.Send(new Pong { Nonce = m.Nonce, ServerTick = (ulong)_world.Clock.Tick });
break;
case Subscribe m:
s.Viewport = m;
SendChunks(s);
foreach (var key in s.MotionSent.Keys.ToList()) s.MotionSent[key] = (-1, 255);
break;
case CommandMessage m:
uint seq = ++_serverSeq;
_pending[seq] = (s, m.Seq);
_world.Enqueue(m.Command with { Issuer = s.Company, Seq = seq });
break;
case SetSpeed m:
_speed = Speeds.Contains(m.Speed) ? m.Speed : (byte)1;
_effectiveSpeed = Math.Max(1, (int)_speed);
_slow = false;
_log.LogInformation("Velocità {Speed}×", _speed);
break;
case RequestDetail m:
SendDetail(s, m);
break;
case ListSaves:
s.Send(new SaveList { Saves = _saves.List() });
break;
case Save m:
SaveNow(m.Name.Length > 0 ? m.Name : "partita");
s.Send(new SaveList { Saves = _saves.List() });
break;
case Load m:
try
{
ReplaceWorld(_saves.Load(_data, m.SaveId), $"caricato {m.SaveId}");
}
catch (Exception e)
{
_log.LogWarning(e, "Caricamento di {Save} fallito", m.SaveId);
s.Send(Notice($"Caricamento non riuscito: {e.Message}"));
}
break;
case NewGame m:
try
{
var preset = _data.DifficultyPreset(m.DifficultyPreset.Length > 0 ? m.DifficultyPreset : _config.Difficulty);
var settings = new NewGameSettings
{
Seed = m.Seed,
SizeKm = m.SizeKm > 0 ? m.SizeKm : _config.MapSizeKm,
StartYear = m.StartYear > 0 ? m.StartYear : null,
DifficultyId = preset.Id,
DifficultyOverride = m.Overrides.Count > 0 ? DifficultyOverrides.Apply(preset, m.Overrides) : null,
Endless = m.EndlessFlags == 0 ? EndlessFlags.Default : (EndlessFlags)m.EndlessFlags,
};
ReplaceWorld(WorldFactory.Create(_data, settings), $"nuova partita, seme {settings.Seed}");
}
catch (Exception e)
{
_log.LogWarning(e, "Nuova partita rifiutata");
s.Send(Notice($"Nuova partita non creata: {e.Message}"));
}
break;
}
}
private static Notification Notice(string text) => new()
{
Event = new EventInfo { Severity = (byte)EventSeverity.Warning, Text = text },
};
public Protocol.Messages.SaveInfo SaveNow(string name)
{
var info = _saves.Save(_world, name);
_log.LogInformation("Salvataggio {Save} ({Bytes} byte)", info.SaveId, info.SizeBytes);
return info;
}
private void ReplaceWorld(World world, string why)
{
_world = world;
_pending.Clear();
_dayEvents.Clear();
_lastTerrainHash = world.Terrain.ComputeHash();
foreach (var s in _sessions.Values)
{
s.ResetCaches();
if (s.Connected) s.Send(Welcome(s));
}
_log.LogInformation("Mondo sostituito: {Why}", why);
}
// ------------------------------------------------------------------ ciclo
private void Run()
{
double due = 0;
long last = Stopwatch.GetTimestamp();
while (!_stop)
{
long now = Stopwatch.GetTimestamp();
double elapsedMs = Stopwatch.GetElapsedTime(last, now).TotalMilliseconds;
last = now;
try
{
while (_inbox.TryDequeue(out var action)) action();
if (_speed > 0)
{
due += elapsedMs * _effectiveSpeed / _config.TickMs;
due = Math.Min(due, 4 * _effectiveSpeed);
}
else
{
due = 0;
}
long budgetEnd = Stopwatch.GetTimestamp() + (long)(Stopwatch.Frequency * _config.TickMs / 1000.0);
while (due >= 1 && !_stop)
{
RunTick();
due -= 1;
if (Stopwatch.GetTimestamp() > budgetEnd) break;
}
AdjustSpeed();
Publish();
Autosave();
}
catch (Exception e)
{
_log.LogError(e, "Errore nel ciclo di gioco");
}
Interlocked.Exchange(ref _lastHeartbeatMs, NowMs);
double untilNext = _speed == 0 ? 10 : (1 - due) * _config.TickMs / _effectiveSpeed;
if (untilNext >= 2) Thread.Sleep((int)Math.Min(untilNext - 1, 10));
else Thread.Yield();
}
}
private void RunTick()
{
var w = _world;
bool newDay = w.Clock.IsNewDay;
bool newMonth = w.Clock.IsNewMonth;
long start = Stopwatch.GetTimestamp();
w.Tick();
double ms = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
_tickMsEma = _tickMsEma == 0 ? ms : _tickMsEma * 0.98 + ms * 0.02;
Interlocked.Exchange(ref _tickMsBits, BitConverter.DoubleToInt64Bits(_tickMsEma));
Interlocked.Increment(ref _ticks);
if (_record is not null && w.CommandLog is { Count: > 0 } log)
{
foreach (var (tick, command) in log) Protocol.CommandLogFile.Append(_record, tick, command);
log.Clear();
_record.Flush();
}
foreach (var r in w.DrainResults())
{
if (r.Ok) _publishDirty = true;
if (!_pending.Remove(r.Seq, out var p)) continue;
p.Session.Send(new CommandResultMessage
{
Seq = p.ClientSeq, Type = (ushort)r.Type, Error = (ushort)r.Error, Message = r.Message, Created = r.Created, Tick = r.Tick,
});
// le convenzioni cambiano il Registro degli impieghi: lo si rimanda subito
if (r.Ok && r.Type is CommandType.AcceptAgreement or CommandType.RejectAgreement)
p.Session.Send(Projection.Employment(w, p.Session.Company));
}
foreach (var a in w.Alerts)
{
var alert = new MaintenanceAlert
{
Train = a.Train.Value, Depot = a.Depot.Value, Component = a.Component, Condition = (float)a.Condition, DueDays = a.DueDays, Text = a.Text,
};
foreach (var s in _sessions.Values)
{
if (s.Connected && s.Company == a.Company) s.Send(alert);
}
}
w.Alerts.Clear();
foreach (var e in w.Events.Drain())
{
var info = Projection.Event(e);
_dayEvents.Add(info);
if (e.Severity == EventSeverity.Info) continue;
foreach (var s in _sessions.Values)
{
if (s.Connected && (!e.Company.IsValid || e.Company == s.Company)) s.Send(new Notification { Event = info });
}
}
if (newDay) _dailyDue = true;
if (newMonth) _monthlyDue = true;
}
/// <summary>Budget: se i tick costano più del tempo disponibile si dimezza la velocità effettiva.</summary>
private void AdjustSpeed()
{
if (_speed == 0 || _tickMsEma <= 0) return;
double budget = _config.TickMs;
bool wasSlow = _slow;
if (_tickMsEma * _effectiveSpeed > budget * 0.9 && _effectiveSpeed > 1)
{
_effectiveSpeed = Math.Max(1, _effectiveSpeed / 2);
}
else if (_effectiveSpeed < _speed && _tickMsEma * _effectiveSpeed * 2 < budget * 0.5)
{
_effectiveSpeed = Math.Min(_speed, _effectiveSpeed * 2);
}
_slow = _effectiveSpeed < _speed || _tickMsEma > budget;
if (_slow && !wasSlow) _log.LogWarning("Tick medio {TickMs:F2} ms: velocità effettiva ridotta a {Speed}× su {Requested}×", _tickMsEma, _effectiveSpeed, _speed);
else if (!_slow && wasSlow) _log.LogInformation("Velocità di nuovo a {Speed}×", _speed);
}
private void Autosave()
{
if (_config.AutosaveMinutes <= 0 || NowMs - _lastAutosaveMs < _config.AutosaveMinutes * 60_000L) return;
_lastAutosaveMs = NowMs;
try
{
var info = _saves.Autosave(_world);
_log.LogInformation("Salvataggio automatico {Save}", info.SaveId);
}
catch (Exception e)
{
_log.LogError(e, "Salvataggio automatico fallito");
}
}
// ------------------------------------------------------------------ pubblicazione
private void Publish()
{
long now = NowMs;
foreach (var s in _sessions.Values)
{
if (s.Connected && s.NeedsFullState) SendFullState(s);
}
if (_dailyDue)
{
_dailyDue = false;
PublishDaily();
_publishDirty = true;
}
if (_publishDirty)
{
_publishDirty = false;
PublishDeltas();
}
if (now - _lastMotionMs >= MotionIntervalMs)
{
_lastMotionMs = now;
PublishMotion();
}
foreach (var s in _sessions.Values.Where(s => !s.Connected && now - s.DisconnectedAtMs > ResumeWindowMs).ToList())
{
_sessions.Remove(s.Id);
foreach (var key in _pending.Where(p => p.Value.Session == s).Select(p => p.Key).ToList()) _pending.Remove(key);
}
}
private void SendFullState(Session s)
{
s.ResetCaches();
s.NeedsFullState = false;
var entities = Projection.Entities(_world);
s.Send(new EntitySnapshot { Tick = _world.Clock.Tick, Entities = entities });
foreach (var (key, hash, _) in Records(entities)) s.EntityHashes[key] = hash;
var edges = new List<EdgeInfo>();
foreach (var e in _world.Network.Edges)
{
if (e.State == Core.Rail.EdgeState.Demolished) continue;
var info = Projection.Edge(_world, e);
edges.Add(info);
s.EdgeHashes[e.Id.Value] = Projection.Hash(info);
}
SendTrack(s, edges, []);
SendChunks(s);
}
/// <summary>TrackWorks in lotti sotto il megabyte (il frame massimo è 4 MB).</summary>
private static void SendTrack(Session s, List<EdgeInfo> edges, List<int> removed)
{
var batch = new TrackWorks { Removed = removed };
long bytes = 0;
foreach (var e in edges)
{
long size = 64 + e.S.Length * 49L + e.Signals.Length * 8L;
if (batch.Edges.Count > 0 && bytes + size > TrackBatchBytes)
{
s.Send(batch);
batch = new TrackWorks();
bytes = 0;
}
batch.Edges.Add(e);
bytes += size;
}
if (batch.Edges.Count > 0 || batch.Removed.Count > 0) s.Send(batch);
}
/// <summary>Chunk del viewport (con un chunk di margine) non ancora inviati.</summary>
private void SendChunks(Session s)
{
if (s.Viewport is not { } v) return;
var t = _world.Terrain;
int cs = t.ChunkCells;
int cx0 = Math.Max(0, Math.Min(v.X0, v.X1) / cs - 1), cy0 = Math.Max(0, Math.Min(v.Y0, v.Y1) / cs - 1);
int cx1 = Math.Min(t.ChunksX - 1, Math.Max(v.X0, v.X1) / cs + 1), cy1 = Math.Min(t.ChunksY - 1, Math.Max(v.Y0, v.Y1) / cs + 1);
for (int cy = cy0; cy <= cy1; cy++)
{
for (int cx = cx0; cx <= cx1; cx++)
{
if (!s.SentChunks.Add((cx, cy))) continue;
s.ChunkHashes[(cx, cy)] = Projection.ChunkHash(_world, cx, cy);
s.Send(Projection.Chunk(_world, cx, cy));
}
}
}
private static IEnumerable<((EntityType, int) Key, ulong Hash, IWritable Record)> Records(EntityLists e)
{
foreach (var x in e.Companies) yield return ((EntityType.Company, x.Id), Projection.Hash(x), x);
foreach (var x in e.Towns) yield return ((EntityType.Town, x.Id), Projection.Hash(x), x);
foreach (var x in e.Industries) yield return ((EntityType.Industry, x.Id), Projection.Hash(x), x);
foreach (var x in e.Hubs) yield return ((EntityType.Hub, x.Id), Projection.Hash(x), x);
foreach (var x in e.Nodes) yield return ((EntityType.Node, x.Id), Projection.Hash(x), x);
foreach (var x in e.Stations) yield return ((EntityType.Station, x.Id), Projection.Hash(x), x);
foreach (var x in e.Depots) yield return ((EntityType.Depot, x.Id), Projection.Hash(x), x);
foreach (var x in e.Lines) yield return ((EntityType.Line, x.Id), Projection.Hash(x), x);
foreach (var x in e.Vehicles) yield return ((EntityType.Vehicle, x.Id), Projection.Hash(x), x);
foreach (var x in e.Trains) yield return ((EntityType.Train, x.Id), Projection.Hash(x), x);
}
private void PublishDeltas()
{
var connected = _sessions.Values.Where(s => s.Connected && !s.NeedsFullState).ToList();
if (connected.Count == 0) return;
var records = Records(Projection.Entities(_world)).ToList();
var present = records.Select(r => r.Key).ToHashSet();
var edges = new List<(int Id, ulong Hash, EdgeInfo Info)>();
foreach (var e in _world.Network.Edges)
{
if (e.State == Core.Rail.EdgeState.Demolished) continue;
var info = Projection.Edge(_world, e);
edges.Add((e.Id.Value, Projection.Hash(info), info));
}
var liveEdges = edges.Select(e => e.Id).ToHashSet();
foreach (var s in connected)
{
var changed = new EntityLists();
foreach (var (key, hash, record) in records)
{
if (s.EntityHashes.TryGetValue(key, out ulong old) && old == hash) continue;
s.EntityHashes[key] = hash;
Add(changed, record);
}
var removed = s.EntityHashes.Keys.Where(k => !present.Contains(k)).OrderBy(k => k.Type).ThenBy(k => k.Id).ToList();
foreach (var k in removed) s.EntityHashes.Remove(k);
if (changed.TotalCount > 0 || removed.Count > 0)
s.Send(new EntityDelta { Tick = _world.Clock.Tick, Changed = changed, Removed = removed });
var changedEdges = new List<EdgeInfo>();
foreach (var (id, hash, info) in edges)
{
if (s.EdgeHashes.TryGetValue(id, out ulong old) && old == hash) continue;
s.EdgeHashes[id] = hash;
changedEdges.Add(info);
}
var removedEdges = s.EdgeHashes.Keys.Where(id => !liveEdges.Contains(id)).OrderBy(id => id).ToList();
foreach (int id in removedEdges) s.EdgeHashes.Remove(id);
if (changedEdges.Count > 0 || removedEdges.Count > 0) SendTrack(s, changedEdges, removedEdges);
}
}
private static void Add(EntityLists lists, IWritable record)
{
switch (record)
{
case CompanyInfo x: lists.Companies.Add(x); break;
case TownInfo x: lists.Towns.Add(x); break;
case IndustryInfo x: lists.Industries.Add(x); break;
case HubInfo x: lists.Hubs.Add(x); break;
case NodeInfo x: lists.Nodes.Add(x); break;
case StationInfo x: lists.Stations.Add(x); break;
case DepotInfo x: lists.Depots.Add(x); break;
case LineInfo x: lists.Lines.Add(x); break;
case VehicleInfo x: lists.Vehicles.Add(x); break;
case TrainInfo x: lists.Trains.Add(x); break;
}
}
private void PublishDaily()
{
var w = _world;
_trainCount = w.Trains.Count(t => !t.Removed);
_packetCount = w.Network.Stations.Sum(s => s.Waiting.Count) + w.Trains.Sum(t => t.Cargo.Count);
_contractCount = w.Commutes.Count;
// il terreno cambia quando le città si allargano o le industrie nascono e chiudono
ulong terrain = w.Terrain.ComputeHash();
bool terrainChanged = terrain != _lastTerrainHash;
_lastTerrainHash = terrain;
foreach (var s in _sessions.Values)
{
if (!s.Connected || s.NeedsFullState) continue;
var company = w.Companies[s.Company.Value];
var events = _dayEvents.Where(e => e.Company < 0 || e.Company == s.Company.Value).ToList();
s.Send(Projection.Digest(w, company, events, _slow, _speed, (float)_tickMsEma));
if (terrainChanged)
{
foreach (var key in s.SentChunks.OrderBy(k => k.Cy).ThenBy(k => k.Cx))
{
ulong h = Projection.ChunkHash(w, key.Cx, key.Cy);
if (s.ChunkHashes.TryGetValue(key, out ulong old) && old == h) continue;
s.ChunkHashes[key] = h;
s.Send(Projection.Chunk(w, key.Cx, key.Cy));
}
}
if (_monthlyDue) s.Send(Projection.Employment(w, s.Company));
// listino di borsa del giorno (12.2) e, a fine partita, la Cronaca finale una volta per sessione
s.Send(Projection.Tape(w, s.Company));
if (w.GameOver is not null && !s.ChronicleSent)
{
s.Send(Projection.Chronicle(w));
s.ChronicleSent = true;
}
}
_monthlyDue = false;
_dayEvents.Clear();
}
/// <summary>Dettagli su richiesta: cartella di manutenzione, registro officina, registro degli impieghi.</summary>
private void SendDetail(Session s, RequestDetail m)
{
var w = _world;
switch (m.Kind)
{
case DetailKind.TrainCard:
if (m.Target >= 0 && m.Target < w.Trains.Count && w.Trains[m.Target] is { Removed: false } t && t.Owner == s.Company)
s.Send(Projection.Card(w, t));
break;
case DetailKind.Workshop:
if (m.Target >= 0 && m.Target < w.Network.Depots.Count && w.Network.Depots[m.Target] is { } d && d.Owner == s.Company && w.Network.IsAlive(d))
s.Send(Projection.Workshop(w, d));
break;
case DetailKind.Employment:
s.Send(Projection.Employment(w, s.Company));
break;
case DetailKind.Company:
if (m.Target >= 0 && m.Target < w.Companies.Count) s.Send(Projection.CompanyCard(w, w.Companies[m.Target]));
break;
case DetailKind.Industry:
if (m.Target >= 0 && m.Target < w.Industries.Count && !w.Industries[m.Target].Closed)
s.Send(Projection.IndustryCard(w, w.Industries[m.Target]));
break;
case DetailKind.Chronicle:
s.Send(Projection.Chronicle(w));
break;
}
}
private void PublishMotion()
{
var w = _world;
var sessions = _sessions.Values.Where(s => s.Connected && !s.NeedsFullState && s.Viewport is not null).ToList();
if (sessions.Count == 0) return;
double cell = w.Terrain.CellSizeM, margin = w.Terrain.ChunkCells * cell;
var motions = new List<(TrainMotion Motion, Vec2 Head)>();
foreach (var t in w.Trains)
{
var m = Projection.Motion(w, t);
var head = Projection.HeadPoint(w, t);
if (m is not null && head is { } h) motions.Add((m, h));
}
foreach (var s in sessions)
{
var v = s.Viewport!;
double x0 = Math.Min(v.X0, v.X1) * cell - margin, x1 = (Math.Max(v.X0, v.X1) + 1) * cell + margin;
double y0 = Math.Min(v.Y0, v.Y1) * cell - margin, y1 = (Math.Max(v.Y0, v.Y1) + 1) * cell + margin;
foreach (var (m, head) in motions)
{
if (head.X < x0 || head.X > x1 || head.Y < y0 || head.Y > y1) continue;
bool moving = m.Speed > 0;
if (!moving && s.MotionSent.TryGetValue(m.TrainId, out var last) && last.State == m.State && last.Tick >= 0) continue;
if (s.SendDroppable(m)) s.MotionSent[m.TrainId] = (m.Tick, m.State);
}
}
}
// ------------------------------------------------------------------ metriche
/// <summary>Metriche in formato Prometheus (testo).</summary>
public string Metrics()
{
var sb = new StringBuilder();
void Gauge(string name, string help, double value)
{
sb.Append("# HELP ").Append(name).Append(' ').Append(help).Append('\n');
sb.Append("# TYPE ").Append(name).Append(" gauge\n");
sb.Append(name).Append(' ').Append(value.ToString("0.######", CultureInfo.InvariantCulture)).Append('\n');
}
Gauge("tick_ms", "Durata media di un tick in millisecondi", TickMs);
Gauge("trains", "Treni in servizio", _trainCount);
Gauge("packets", "Pacchetti di merci e passeggeri", _packetCount);
Gauge("contracts", "Contratti di pendolarismo", _contractCount);
Gauge("sessions", "Sessioni collegate", _sessionCount);
Gauge("ticks_total", "Tick eseguiti dall'avvio", Interlocked.Read(ref _ticks));
Gauge("speed", "Velocità richiesta", _speed);
return sb.ToString();
}
}