- Protocollo: riepilogo di manutenzione nei record (blocco 1), RequestDetail, MaintenanceCard, WorkshopRegister, EmploymentReport con depositi, motivi e convenzioni, MaintenanceAlert. - Server: dettagli su richiesta, avvisi dalla manutenzione, registro dopo le convenzioni. - Client: pannelli Officine (cartella di manutenzione, Registro officina, scorta di ricambi, avvisi, mappa di calore) e Impieghi (Registro degli impieghi con convenzioni); schede di treno, industria e città aggiornate; pilota automatico con le nuove schermate. - ADR 0010, PROTOCOL, ARCHITECTURE e STATE aggiornati; 102 test verdi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
363 lines
15 KiB
C#
363 lines
15 KiB
C#
using ViaFerrea.Core.Common;
|
|
using ViaFerrea.Core.Data;
|
|
using ViaFerrea.Core.Map;
|
|
using ViaFerrea.Core.Rail;
|
|
using ViaFerrea.Core.Time;
|
|
using ViaFerrea.Protocol.Messages;
|
|
|
|
namespace ViaFerrea.Protocol.Client;
|
|
|
|
/// <summary>
|
|
/// Copia locale del mondo costruita dai messaggi del server: terreno a chunk, entità, rete dei
|
|
/// binari (con gli stessi id del server) e moto dei treni. Non simula nulla: serve a disegnare,
|
|
/// a interpolare i treni e a calcolare le anteprime con le classi di Core (il server ricalcola).
|
|
/// </summary>
|
|
public sealed class ClientWorld(GameData data)
|
|
{
|
|
public GameData Data { get; } = data;
|
|
public WorldSummary? Summary { get; private set; }
|
|
public Terrain? Terrain { get; private set; }
|
|
public TerrainSampler? Sampler { get; private set; }
|
|
public RailNetwork Network { get; private set; } = new();
|
|
public ulong SessionId { get; private set; }
|
|
|
|
public Dictionary<int, CompanyInfo> Companies { get; } = [];
|
|
public Dictionary<int, TownInfo> Towns { get; } = [];
|
|
public Dictionary<int, IndustryInfo> Industries { get; } = [];
|
|
public Dictionary<int, HubInfo> Hubs { get; } = [];
|
|
public Dictionary<int, StationInfo> Stations { get; } = [];
|
|
public Dictionary<int, DepotInfo> Depots { get; } = [];
|
|
public Dictionary<int, LineInfo> Lines { get; } = [];
|
|
public Dictionary<int, VehicleInfo> Vehicles { get; } = [];
|
|
public Dictionary<int, TrainInfo> Trains { get; } = [];
|
|
public Dictionary<int, EdgeInfo> Edges { get; } = [];
|
|
public Dictionary<int, TrainMotion> Motions { get; } = [];
|
|
public HashSet<(int Cx, int Cy)> Chunks { get; } = [];
|
|
|
|
public DailyDigest? LastDigest { get; private set; }
|
|
|
|
/// <summary>Dettagli ricevuti su richiesta (F4): cartelle dei treni, registri delle officine, registro degli impieghi.</summary>
|
|
public Dictionary<int, MaintenanceCard> Cards { get; } = [];
|
|
public Dictionary<int, WorkshopRegister> Workshops { get; } = [];
|
|
public EmploymentReport? Employment { get; private set; }
|
|
|
|
/// <summary>Ultimi avvisi di manutenzione, dal più recente.</summary>
|
|
public List<MaintenanceAlert> Alerts { get; } = [];
|
|
private const int AlertCapacity = 50;
|
|
|
|
/// <summary>Contatore dei dettagli ricevuti (per aggiornare i pannelli).</summary>
|
|
public int DetailVersion { get; private set; }
|
|
public long Tick { get; private set; }
|
|
public byte Speed { get; private set; }
|
|
|
|
/// <summary>Contatori di modifica per il disegno (terreno, binari, entità).</summary>
|
|
public int TerrainVersion { get; private set; }
|
|
public int TrackVersion { get; private set; }
|
|
public int EntityVersion { get; private set; }
|
|
|
|
public CompanyId Company => Summary is null ? CompanyId.None : new CompanyId(Summary.CompanyId);
|
|
|
|
public Calendar? Calendar { get; private set; }
|
|
|
|
public int Year => Calendar is null ? 0 : Calendar.StartYear + (int)(Tick / Calendar.TicksPerDay / Calendar.DaysPerYear);
|
|
|
|
/// <summary>Applica un messaggio del server; restituisce false se non riguarda lo stato.</summary>
|
|
public bool Apply(IMessage message)
|
|
{
|
|
switch (message)
|
|
{
|
|
case Welcome m: Reset(m); return true;
|
|
case MapChunk m: ApplyChunk(m); return true;
|
|
case EntitySnapshot m:
|
|
ClearEntities();
|
|
ApplyEntities(m.Entities, m.Tick);
|
|
return true;
|
|
case EntityDelta m:
|
|
ApplyEntities(m.Changed, m.Tick);
|
|
foreach (var (type, id) in m.Removed) Remove(type, id);
|
|
EntityVersion++;
|
|
return true;
|
|
case TrackWorks m: ApplyTrack(m); return true;
|
|
case TrainMotion m:
|
|
Motions[m.TrainId] = m;
|
|
Tick = Math.Max(Tick, m.Tick);
|
|
return true;
|
|
case DailyDigest m:
|
|
LastDigest = m;
|
|
Tick = Math.Max(Tick, m.Tick);
|
|
Speed = m.Speed;
|
|
return true;
|
|
case Pong m:
|
|
Tick = Math.Max(Tick, (long)m.ServerTick);
|
|
return true;
|
|
case MaintenanceCard m:
|
|
Cards[m.Train] = m;
|
|
DetailVersion++;
|
|
return true;
|
|
case WorkshopRegister m:
|
|
Workshops[m.Depot] = m;
|
|
DetailVersion++;
|
|
return true;
|
|
case EmploymentReport m:
|
|
Employment = m;
|
|
DetailVersion++;
|
|
return true;
|
|
case MaintenanceAlert m:
|
|
Alerts.Insert(0, m);
|
|
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
|
|
DetailVersion++;
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private void Reset(Welcome m)
|
|
{
|
|
Cards.Clear();
|
|
Workshops.Clear();
|
|
Employment = null;
|
|
Alerts.Clear();
|
|
Summary = m.Summary;
|
|
SessionId = m.SessionId;
|
|
Tick = m.Summary.Tick;
|
|
Speed = m.Summary.Speed;
|
|
Calendar = new Calendar(Data.Balance.Time, m.Summary.StartYear);
|
|
Terrain = new Terrain(m.Summary.WidthCells, m.Summary.HeightCells, m.Summary.CellSizeM, m.Summary.ChunkCells);
|
|
Sampler = new TerrainSampler(Terrain);
|
|
Chunks.Clear();
|
|
Network = new RailNetwork();
|
|
Edges.Clear();
|
|
ClearEntities();
|
|
LastDigest = null;
|
|
TerrainVersion++;
|
|
TrackVersion++;
|
|
}
|
|
|
|
private void ClearEntities()
|
|
{
|
|
Companies.Clear(); Towns.Clear(); Industries.Clear(); Hubs.Clear(); Stations.Clear(); Depots.Clear();
|
|
Lines.Clear(); Vehicles.Clear(); Trains.Clear(); Motions.Clear();
|
|
EntityVersion++;
|
|
}
|
|
|
|
private void ApplyChunk(MapChunk m)
|
|
{
|
|
if (Terrain is null) return;
|
|
int x0 = m.Cx * Terrain.ChunkCells, y0 = m.Cy * Terrain.ChunkCells;
|
|
if (x0 < 0 || y0 < 0 || x0 + m.Width > Terrain.Width || y0 + m.Height > Terrain.Height) throw new ProtocolException("chunk fuori dalla mappa");
|
|
for (int y = 0; y < m.Height; y++)
|
|
{
|
|
int dst = (y0 + y) * Terrain.Width + x0;
|
|
m.Heights.AsSpan(y * m.Width, m.Width).CopyTo(Terrain.Heights.AsSpan(dst));
|
|
m.Types.AsSpan(y * m.Width, m.Width).CopyTo(Terrain.Types.AsSpan(dst));
|
|
m.RiverWidth.AsSpan(y * m.Width, m.Width).CopyTo(Terrain.RiverWidth.AsSpan(dst));
|
|
}
|
|
Chunks.Add((m.Cx, m.Cy));
|
|
TerrainVersion++;
|
|
}
|
|
|
|
private void ApplyEntities(EntityLists e, long tick)
|
|
{
|
|
Tick = Math.Max(Tick, tick);
|
|
foreach (var x in e.Companies) Companies[x.Id] = x;
|
|
foreach (var x in e.Towns) Towns[x.Id] = x;
|
|
foreach (var x in e.Industries) Industries[x.Id] = x;
|
|
foreach (var x in e.Hubs) Hubs[x.Id] = x;
|
|
foreach (var x in e.Lines) Lines[x.Id] = x;
|
|
foreach (var x in e.Vehicles) Vehicles[x.Id] = x;
|
|
foreach (var x in e.Trains) Trains[x.Id] = x;
|
|
bool network = e.Nodes.Count + e.Stations.Count + e.Depots.Count > 0;
|
|
foreach (var n in e.Nodes) SetNode(n);
|
|
foreach (var s in e.Stations)
|
|
{
|
|
Stations[s.Id] = s;
|
|
SetStation(s);
|
|
}
|
|
foreach (var d in e.Depots)
|
|
{
|
|
Depots[d.Id] = d;
|
|
SetDepot(d);
|
|
}
|
|
if (network) Network.Touch();
|
|
EntityVersion++;
|
|
}
|
|
|
|
private void Remove(EntityType type, int id)
|
|
{
|
|
switch (type)
|
|
{
|
|
case EntityType.Company: Companies.Remove(id); break;
|
|
case EntityType.Town: Towns.Remove(id); break;
|
|
case EntityType.Industry: Industries.Remove(id); break;
|
|
case EntityType.Hub: Hubs.Remove(id); break;
|
|
case EntityType.Line: Lines.Remove(id); break;
|
|
case EntityType.Vehicle: Vehicles.Remove(id); break;
|
|
case EntityType.Train:
|
|
Trains.Remove(id);
|
|
Motions.Remove(id);
|
|
break;
|
|
case EntityType.Node:
|
|
if (id >= 0 && id < Network.Nodes.Count) Network.Nodes[id].Removed = true;
|
|
Network.Touch();
|
|
break;
|
|
case EntityType.Station:
|
|
Stations.Remove(id);
|
|
if (id >= 0 && id < Network.Stations.Count) Network.Stations[id] = PlaceholderStation(id);
|
|
Network.Touch();
|
|
break;
|
|
case EntityType.Depot:
|
|
Depots.Remove(id);
|
|
if (id >= 0 && id < Network.Depots.Count) Network.Depots[id] = PlaceholderDepot(id);
|
|
Network.Touch();
|
|
break;
|
|
case EntityType.Edge:
|
|
RemoveEdge(id);
|
|
break;
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ rete
|
|
|
|
private void SetNode(NodeInfo n)
|
|
{
|
|
while (Network.Nodes.Count <= n.Id)
|
|
Network.Nodes.Add(new TrackNode { Id = new NodeId(Network.Nodes.Count), Position = default, HeightM = 0, Removed = true });
|
|
var node = new TrackNode
|
|
{
|
|
Id = new NodeId(n.Id), Position = n.Position, HeightM = n.HeightM, Owner = new CompanyId(n.Owner),
|
|
Station = new StationId(n.Station), Depot = new DepotId(n.Depot),
|
|
};
|
|
foreach (int e in n.Edges) node.AddEdge(new EdgeId(e));
|
|
Network.Nodes[n.Id] = node;
|
|
}
|
|
|
|
private void SetStation(StationInfo s)
|
|
{
|
|
while (Network.Stations.Count <= s.Id) Network.Stations.Add(PlaceholderStation(Network.Stations.Count));
|
|
Network.Stations[s.Id] = new Station
|
|
{
|
|
Id = new StationId(s.Id), Owner = new CompanyId(s.Owner), Name = s.Name, Node = new NodeId(s.Node), Position = s.Position, Platforms = s.Platforms,
|
|
};
|
|
}
|
|
|
|
private void SetDepot(DepotInfo d)
|
|
{
|
|
while (Network.Depots.Count <= d.Id) Network.Depots.Add(PlaceholderDepot(Network.Depots.Count));
|
|
Network.Depots[d.Id] = new Depot { Id = new DepotId(d.Id), Owner = new CompanyId(d.Owner), Name = d.Name, Node = new NodeId(d.Node), Position = d.Position, Size = d.Size };
|
|
}
|
|
|
|
private static Station PlaceholderStation(int id) =>
|
|
new() { Id = new StationId(id), Owner = CompanyId.None, Name = "", Node = NodeId.None, Position = default, Platforms = 0 };
|
|
|
|
private static Depot PlaceholderDepot(int id) =>
|
|
new() { Id = new DepotId(id), Owner = CompanyId.None, Name = "", Node = NodeId.None, Position = default, Size = "" };
|
|
|
|
private void ApplyTrack(TrackWorks m)
|
|
{
|
|
foreach (var e in m.Edges)
|
|
{
|
|
Edges[e.Id] = e;
|
|
while (Network.Edges.Count <= e.Id) Network.Edges.Add(PlaceholderEdge(Network.Edges.Count));
|
|
var edge = new TrackEdge
|
|
{
|
|
Id = new EdgeId(e.Id), A = new NodeId(e.A), B = new NodeId(e.B), Owner = new CompanyId(e.Owner), TrackClass = e.TrackClass,
|
|
DoubleTrack = e.DoubleTrack, Electrified = e.Electrified, State = (EdgeState)e.State,
|
|
S = e.S, X = e.X, Y = e.Y, H = e.H, Ground = e.Ground, Kinds = e.Kinds.Select(k => (WorkKind)k).ToArray(), SpeedLimitKmh = e.SpeedLimitKmh,
|
|
Condition = e.Condition, StructureCondition = e.StructureCondition,
|
|
};
|
|
edge.Signals.AddRange(e.Signals);
|
|
Network.Edges[e.Id] = edge;
|
|
}
|
|
foreach (int id in m.Removed) RemoveEdge(id);
|
|
Network.Touch();
|
|
TrackVersion++;
|
|
}
|
|
|
|
private void RemoveEdge(int id)
|
|
{
|
|
Edges.Remove(id);
|
|
if (id >= 0 && id < Network.Edges.Count) Network.Edges[id] = PlaceholderEdge(id);
|
|
Network.Touch();
|
|
TrackVersion++;
|
|
}
|
|
|
|
private static TrackEdge PlaceholderEdge(int id) => new()
|
|
{
|
|
Id = new EdgeId(id), A = NodeId.None, B = NodeId.None, Owner = CompanyId.None, TrackClass = 0, DoubleTrack = false, Electrified = false,
|
|
State = EdgeState.Demolished, S = [0, 1], X = [0, 0], Y = [0, 0], H = [0, 0], Ground = [0, 0], Kinds = [WorkKind.Natural, WorkKind.Natural],
|
|
SpeedLimitKmh = [0, 0],
|
|
};
|
|
|
|
// ------------------------------------------------------------------ anteprime e treni
|
|
|
|
/// <summary>Distanza dal bordo dell'abitato più vicino, come <c>World.TownEdgeDistanceKm</c>.</summary>
|
|
public double NearestTownEdgeKm(Vec2 p)
|
|
{
|
|
if (Towns.Count == 0 || Terrain is null) return double.MaxValue;
|
|
double best = double.MaxValue;
|
|
foreach (var t in Towns.Values) best = Math.Min(best, Math.Max(0, (Vec2.Distance(t.Position, p) - t.RadiusCells * Terrain.CellSizeM) / 1000.0));
|
|
return best;
|
|
}
|
|
|
|
/// <summary>Ingressi del pianificatore per l'anteprima di un binario (stesso codice del server).</summary>
|
|
public TrackPreviewInputs PreviewInputs()
|
|
{
|
|
if (Summary is null || Sampler is null) throw new InvalidOperationException("Nessuna partita");
|
|
return new TrackPreviewInputs
|
|
{
|
|
Data = Data,
|
|
Sampler = Sampler,
|
|
Network = Network,
|
|
Year = Year,
|
|
CostMultiplier = Summary.CostMultiplier,
|
|
NearestTownEdgeKm = NearestTownEdgeKm,
|
|
};
|
|
}
|
|
|
|
/// <summary>Anteprima di un binario della compagnia della sessione.</summary>
|
|
public TrackPlan PreviewTrack(Core.Commands.BuildTrackCommand command) => TrackPreview.Prepare(PreviewInputs(), Company, command).Plan;
|
|
|
|
/// <summary>Punto alla distanza d lungo i tratti di un moto (estremi inclusi).</summary>
|
|
public Vec2? PointAlong(TrainMotion motion, double d)
|
|
{
|
|
if (motion.Segments.Count == 0) return null;
|
|
double acc = 0;
|
|
for (int i = 0; i < motion.Segments.Count; i++)
|
|
{
|
|
var seg = motion.Segments[i];
|
|
if (seg.Edge < 0 || seg.Edge >= Network.Edges.Count) return null;
|
|
double len = seg.Length;
|
|
if (d <= acc + len || i == motion.Segments.Count - 1)
|
|
{
|
|
double t = len <= 0 ? 0 : Math.Clamp((d - acc) / len, 0, 1);
|
|
return Network.Edges[seg.Edge].PointAt(seg.FromS + (seg.ToS - seg.FromS) * t);
|
|
}
|
|
acc += len;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>Lunghezza totale dei tratti di un moto.</summary>
|
|
public static double TotalLength(TrainMotion motion)
|
|
{
|
|
double sum = 0;
|
|
foreach (var s in motion.Segments) sum += s.Length;
|
|
return sum;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Testa del treno interpolata: avanza dalla posizione inviata alla velocità inviata per i
|
|
/// secondi di orologio dei treni trascorsi, senza superare il tratto prenotato.
|
|
/// </summary>
|
|
public Vec2? TrainHead(int trainId, double elapsedTrainSeconds = 0) =>
|
|
Motions.TryGetValue(trainId, out var m) ? TrainHead(m, elapsedTrainSeconds) : null;
|
|
|
|
/// <summary>Testa interpolata a partire da un moto qualsiasi.</summary>
|
|
public Vec2? TrainHead(TrainMotion m, double elapsedTrainSeconds)
|
|
{
|
|
double d = Math.Min(m.HeadDistance + m.Speed * Math.Max(0, elapsedTrainSeconds), TotalLength(m));
|
|
return PointAlong(m, d);
|
|
}
|
|
}
|