F3: protocollo binario completo, server con WebSocket e immagine Docker

- Protocol: SpanWriter/SpanReader, frame [u32][u16][payload], tutti i messaggi
  dei due versi con byte di estensione, codec di tutti i 38 comandi, test di
  round-trip, troncamento e corruzione.
- Comandi delle fasi successive con formato definitivo (NotImplemented).
- ClientWorld e ProtocolClient condivisi da client Godot e test: copia del
  terreno a chunk, entità, rete con gli stessi id, moto dei treni.
- TrackPreview estratto dai comandi: anteprima del client e piano del server
  con lo stesso codice; stazioni e depositi demoliti esclusi dagli agganci.
- Server: GameLoop con accumulatore e velocità effettiva, sessioni con coda
  a due classi e ripresa, delta per hash, TrackWorks a lotti, moto dei treni
  nel viewport, resoconti giornalieri, /health, /metrics, /api/saves,
  autosave a rotazione, log JSON, --local e --healthcheck.
- Docker: Dockerfile, compose, modello Unraid; build senza rete.
- viaferrea-tools smoke: collaudo end-to-end contro un server in esecuzione.

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-02 00:14:13 +00:00
1 parent ac9414a03d
commit 5a318e6528
36 files changed
+4940 -62

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# Contesto della build Docker: solo sorgenti e dati del server.
**/bin/
**/obj/
.git/
.godot/
client/
docker/data/
reference/
out/
artifacts/
saves/
*.vfsave
+18
View File
@@ -0,0 +1,18 @@
# Immagine del server di Via Ferrea (guida, sezione 14.4).
# Build dalla radice del repository: docker build -f docker/Dockerfile -t via-ferrea-server .
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish src/ViaFerrea.Server -c Release -o /app -p:VfServerOnly=true
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
# l'immagine .NET 10 è Ubuntu 24.04: useradd al posto di adduser (ADR 0009)
RUN useradd --system --user-group --no-create-home --shell /usr/sbin/nologin vf && mkdir -p /data && chown vf /data
USER vf
ENV VF_PORT=7400 VF_DATA_DIR=/data ASPNETCORE_URLS=http://0.0.0.0:7400 ASPNETCORE_HTTP_PORTS=
EXPOSE 7400
VOLUME /data
HEALTHCHECK --interval=30s --timeout=5s CMD ["dotnet","ViaFerrea.Server.dll","--healthcheck"]
ENTRYPOINT ["dotnet","ViaFerrea.Server.dll"]
+16
View File
@@ -0,0 +1,16 @@
# Server di Via Ferrea con docker compose (dalla cartella docker/: docker compose up -d).
services:
via-ferrea:
image: via-ferrea-server:latest
build:
context: ..
dockerfile: docker/Dockerfile
container_name: via-ferrea
ports:
- "7400:7400"
volumes:
- ./data:/data
environment:
VF_TOKEN: "${VF_TOKEN:-cambiami}"
VF_DIFFICULTY: "${VF_DIFFICULTY:-imprenditore}"
restart: unless-stopped
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0"?>
<!-- Modello per Unraid (Docker › Add Container › Template): server di Via Ferrea dal registry Gitea. -->
<Container version="2">
<Name>via-ferrea</Name>
<Repository>gitea.lan:3000/utente/via-ferrea-server:latest</Repository>
<Registry>http://gitea.lan:3000/utente/-/packages/container/via-ferrea-server</Registry>
<Network>bridge</Network>
<Shell>bash</Shell>
<Privileged>false</Privileged>
<Overview>Server autorevole di Via Ferrea, gestionale ferroviario dall'alto. I client si collegano via WebSocket su ws://[IP]:7400/ws con il token indicato; i salvataggi stanno nella cartella dei dati.</Overview>
<Category>GameServers:</Category>
<WebUI>http://[IP]:[PORT:7400]/health</WebUI>
<Icon/>
<Config Name="Porta del gioco" Target="7400" Default="7400" Mode="tcp" Description="WebSocket /ws e API HTTP (/health, /metrics, /api/saves)" Type="Port" Display="always" Required="true" Mask="false">7400</Config>
<Config Name="Dati" Target="/data" Default="/mnt/user/appdata/via-ferrea" Mode="rw" Description="Salvataggi e salvataggi automatici" Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/via-ferrea</Config>
<Config Name="Token" Target="VF_TOKEN" Default="" Mode="" Description="Token richiesto ai client nell'Hello" Type="Variable" Display="always" Required="true" Mask="true"/>
<Config Name="Difficoltà" Target="VF_DIFFICULTY" Default="imprenditore" Mode="" Description="Preset di difficoltà della nuova partita (vedi data/difficulty.json)" Type="Variable" Display="always" Required="false" Mask="false">imprenditore</Config>
</Container>
@@ -104,12 +104,3 @@ public sealed record SetIndustryPolicyCommand(IndustryId Industry, Economy.Indus
{
public override CommandType Type => CommandType.SetIndustryPolicy;
}
/// <summary>
/// Comando non ancora implementato nella fase corrente: viaggia nel protocollo e riceve
/// l'esito NotImplemented. Permette al protocollo di essere completo fin da subito.
/// </summary>
public sealed record PendingCommand(CommandType Kind, byte[] Payload) : GameCommand
{
public override CommandType Type => Kind;
}
@@ -0,0 +1,135 @@
using ViaFerrea.Core.Common;
namespace ViaFerrea.Core.Commands;
// Comandi delle fasi F4–F7: il formato è già definitivo (protocollo stabile), l'esecuzione
// risponde NotImplemented finché il sistema corrispondente non esiste.
/// <summary>Ambito di una politica di manutenzione.</summary>
public enum MaintenanceScope : byte { Company = 0, Line = 1, Train = 2 }
/// <summary>Marca o smarca un treno come riserva in deposito (10.3).</summary>
public sealed record SetReserveCommand(TrainId Train, bool Reserve) : GameCommand
{
public override CommandType Type => CommandType.SetReserve;
}
/// <summary>Politica di manutenzione (id di <c>maintenance.json</c>: economy, standard, thorough).</summary>
public sealed record SetMaintenancePolicyCommand(MaintenanceScope Scope, int Target, string Policy) : GameCommand
{
public override CommandType Type => CommandType.SetMaintenancePolicy;
}
/// <summary>Programma un intervento (id di <c>maintenance.json</c>: inspection, service, overhaul).</summary>
public sealed record ScheduleServiceCommand(TrainId Train, string Intervention) : GameCommand
{
public override CommandType Type => CommandType.ScheduleService;
}
/// <summary>Ordina ricambi per un deposito (domanda esplicita sul grafo delle linee).</summary>
public sealed record OrderPartsCommand(DepotId Depot, int Quantity) : GameCommand
{
public override CommandType Type => CommandType.OrderParts;
}
/// <summary>Accetta una convenzione di pendolarismo proposta da un'industria.</summary>
public sealed record AcceptAgreementCommand(AgreementId Agreement) : GameCommand
{
public override CommandType Type => CommandType.AcceptAgreement;
}
/// <summary>Rifiuta una convenzione di pendolarismo.</summary>
public sealed record RejectAgreementCommand(AgreementId Agreement) : GameCommand
{
public override CommandType Type => CommandType.RejectAgreement;
}
/// <summary>Compra merce al prezzo locale in una stazione (commercio, livello 2).</summary>
public sealed record BuyGoodsCommand(StationId Station, string Good, int Units, Money MaxUnitPrice) : GameCommand
{
public override CommandType Type => CommandType.BuyGoods;
}
/// <summary>Vende merce della compagnia al prezzo locale in una stazione.</summary>
public sealed record SellGoodsCommand(StationId Station, string Good, int Units, Money MinUnitPrice) : GameCommand
{
public override CommandType Type => CommandType.SellGoods;
}
/// <summary>Offerta d'acquisto di un'industria.</summary>
public sealed record BuyIndustryCommand(IndustryId Industry, Money Offer) : GameCommand
{
public override CommandType Type => CommandType.BuyIndustry;
}
/// <summary>Fermo programmato (revisione) di un'industria posseduta.</summary>
public sealed record OverhaulIndustryCommand(IndustryId Industry) : GameCommand
{
public override CommandType Type => CommandType.OverhaulIndustry;
}
/// <summary>Ammodernamento di livello di un'industria posseduta.</summary>
public sealed record UpgradeIndustryCommand(IndustryId Industry) : GameCommand
{
public override CommandType Type => CommandType.UpgradeIndustry;
}
/// <summary>Quotazione in borsa: quota del capitale offerta.</summary>
public sealed record IpoCommand(double FloatShare) : GameCommand
{
public override CommandType Type => CommandType.Ipo;
}
/// <summary>Acquisto di azioni di una compagnia quotata.</summary>
public sealed record BuySharesCommand(CompanyId Company, long Shares, Money MaxPrice) : GameCommand
{
public override CommandType Type => CommandType.BuyShares;
}
/// <summary>Vendita di azioni possedute.</summary>
public sealed record SellSharesCommand(CompanyId Company, long Shares, Money MinPrice) : GameCommand
{
public override CommandType Type => CommandType.SellShares;
}
/// <summary>Dividendo per azione.</summary>
public sealed record PayDividendCommand(Money PerShare) : GameCommand
{
public override CommandType Type => CommandType.PayDividend;
}
/// <summary>Offerta pubblica di acquisto sulle azioni di una compagnia.</summary>
public sealed record LaunchBidCommand(CompanyId Target, Money PricePerShare, double TargetShare) : GameCommand
{
public override CommandType Type => CommandType.LaunchBid;
}
/// <summary>Risposta a un'offerta pubblica (azionisti del bersaglio).</summary>
public sealed record RespondBidCommand(BidId Bid, bool Accept) : GameCommand
{
public override CommandType Type => CommandType.RespondBid;
}
/// <summary>Acquisto della concessione di una regione.</summary>
public sealed record BuyConcessionCommand(RegionId Region) : GameCommand
{
public override CommandType Type => CommandType.BuyConcession;
}
/// <summary>Accettazione di un contratto (data/contracts.json).</summary>
public sealed record AcceptContractCommand(ContractId Contract) : GameCommand
{
public override CommandType Type => CommandType.AcceptContract;
}
/// <summary>Finanziamento di un progetto di ricerca.</summary>
public sealed record FundResearchCommand(string Project, Money Amount) : GameCommand
{
public override CommandType Type => CommandType.FundResearch;
}
/// <summary>Delega di una regione a un direttore (modalità holding) con obiettivo e budget annuo.</summary>
public sealed record DelegateRegionCommand(RegionId Region, string Objective, Money Budget) : GameCommand
{
public override CommandType Type => CommandType.DelegateRegion;
}
@@ -0,0 +1,53 @@
namespace ViaFerrea.Core.Data;
/// <summary>
/// Difficoltà «Personalizzata»: ritocchi di un preset per nome di campo (camelCase, come in
/// <c>difficulty.json</c>). Gli enum si indicano con il loro valore numerico.
/// </summary>
public static class DifficultyOverrides
{
public static readonly string[] Keys =
[
"initialCapital", "initialCredit", "baseInterestRate", "constructionCostMultiplier", "tariffMultiplier", "wearMultiplier",
"marketVolatilityMultiplier", "aiCompetitors", "aiCapitalMultiplier", "aiCostDiscount", "playerTakeover", "takeoverRansomYears",
"bankruptcyDays", "publicFromStart", "playerShareAtStart", "ironman", "depletion",
];
/// <summary>Applica i ritocchi; una chiave sconosciuta o un valore fuori limite solleva ArgumentException.</summary>
public static DifficultyDef Apply(DifficultyDef preset, IEnumerable<(string Key, double Value)> overrides)
{
var d = preset;
foreach (var (key, value) in overrides)
{
if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentException($"Valore non valido per {key}");
d = key switch
{
"initialCapital" => d with { InitialCapital = NonNegativeLong(key, value) },
"initialCredit" => d with { InitialCredit = NonNegativeLong(key, value) },
"baseInterestRate" => d with { BaseInterestRate = Range(key, value, 0, 1) },
"constructionCostMultiplier" => d with { ConstructionCostMultiplier = Range(key, value, 0.1, 10) },
"tariffMultiplier" => d with { TariffMultiplier = Range(key, value, 0.1, 10) },
"wearMultiplier" => d with { WearMultiplier = Range(key, value, 0, 10) },
"marketVolatilityMultiplier" => d with { MarketVolatilityMultiplier = Range(key, value, 0, 10) },
"aiCompetitors" => d with { AiCompetitors = (int)Range(key, value, 0, 8) },
"aiCapitalMultiplier" => d with { AiCapitalMultiplier = Range(key, value, 0, 10) },
"aiCostDiscount" => d with { AiCostDiscount = Range(key, value, 0, 0.9) },
"playerTakeover" => d with { PlayerTakeover = (TakeoverRule)(int)Range(key, value, 0, 2) },
"takeoverRansomYears" => d with { TakeoverRansomYears = (int)Range(key, value, 0, 50) },
"bankruptcyDays" => d with { BankruptcyDays = (int)Range(key, value, 1, 3600) },
"publicFromStart" => d with { PublicFromStart = value != 0 },
"playerShareAtStart" => d with { PlayerShareAtStart = Range(key, value, 0, 1) },
"ironman" => d with { Ironman = (IronmanRule)(int)Range(key, value, 0, 2) },
"depletion" => d with { Depletion = (DepletionRate)(int)Range(key, value, 0, 2) },
_ => throw new ArgumentException($"Campo di difficoltà sconosciuto: {key}"),
};
}
return d;
}
private static double Range(string key, double v, double min, double max) =>
v < min || v > max ? throw new ArgumentException($"{key} fuori dai limiti ({min}–{max})") : v;
private static long NonNegativeLong(string key, double v) =>
v < 0 || v > 1e17 ? throw new ArgumentException($"{key} fuori dai limiti") : (long)v;
}
+10 -4
View File
@@ -33,6 +33,12 @@ public sealed class RailNetwork
public void Touch() => Version++;
/// <summary>Vero se la stazione non è stata demolita (il suo nodo la indica ancora).</summary>
public bool IsAlive(Station s) => s.Node.IsValid && s.Node.Value < Nodes.Count && Nodes[s.Node.Value].Station == s.Id;
/// <summary>Vero se il deposito non è stato demolito.</summary>
public bool IsAlive(Depot d) => d.Node.IsValid && d.Node.Value < Nodes.Count && Nodes[d.Node.Value].Depot == d.Id;
public TrackNode AddNode(Vec2 position, double heightM, CompanyId owner)
{
var node = new TrackNode { Id = new NodeId(Nodes.Count), Position = position, HeightM = heightM, Owner = owner };
@@ -145,12 +151,12 @@ public sealed class RailNetwork
// stazioni e depositi: tutta l'area aggancia al nodo
foreach (var s in Stations)
{
if (s.Owner == company && Vec2.Distance(s.Position, p) <= stationRadiusM)
if (s.Owner == company && IsAlive(s) && 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)
if (d.Owner == company && IsAlive(d) && 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;
@@ -238,7 +244,7 @@ public sealed class RailNetwork
foreign = false;
foreach (var s in net.Stations)
{
if (Vec2.Distance(s.Position, p) > r) continue;
if (!net.IsAlive(s) || Vec2.Distance(s.Position, p) > r) continue;
if (Vec2.Distance(p, start) <= r || Vec2.Distance(p, end) <= r)
{
if (s.Owner == company) continue;
@@ -248,7 +254,7 @@ public sealed class RailNetwork
}
foreach (var d in net.Depots)
{
if (Vec2.Distance(d.Position, p) > r) continue;
if (!net.IsAlive(d) || 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;
+65
View File
@@ -0,0 +1,65 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Map;
namespace ViaFerrea.Core.Rail;
/// <summary>
/// Ciò che serve al pianificatore oltre al comando: dati, terreno, rete, anno e costi. Il server
/// lo ricava dal mondo, il client dalla propria copia (terreno ricevuto a chunk, rete da
/// TrackWorks): stesso codice, stesso risultato.
/// </summary>
public sealed class TrackPreviewInputs
{
public required GameData Data { get; init; }
public required TerrainSampler Sampler { get; init; }
public required RailNetwork Network { get; init; }
public required int Year { get; init; }
public required double CostMultiplier { get; init; }
public required Func<Vec2, double> NearestTownEdgeKm { get; init; }
}
/// <summary>Anteprima di un binario: aggancio delle estremità, attraversamenti, profilo, opere e costo.</summary>
public static class TrackPreview
{
public static TrackPlanContext Context(TrackPreviewInputs inputs, ITrackObstacles? obstacles) => new()
{
Data = inputs.Data,
Sampler = inputs.Sampler,
Year = inputs.Year,
CostMultiplier = inputs.CostMultiplier,
Obstacles = obstacles,
NearestTownEdgeKm = inputs.NearestTownEdgeKm,
};
/// <summary>
/// Prepara il piano come farebbe il comando: aggancia le estremità a nodi e archi esistenti e
/// considera gli attraversamenti.
/// </summary>
public static (TrackPlan Plan, AttachPoint Start, AttachPoint End) Prepare(TrackPreviewInputs inputs, CompanyId company, BuildTrackCommand c)
{
var sp = inputs.Data.Construction.Stations;
var net = inputs.Network;
var start = net.FindAttach(c.Polyline[0], company, sp.SnapM, sp.AreaRadiusM);
var end = net.FindAttach(c.Polyline[^1], company, 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,
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(Context(inputs, obstacles), request), start, end);
}
}
@@ -12,46 +12,28 @@ public static class RailCommandHandlers
{
public delegate CommandResult Reply(CommandError error, string message, params int[] created);
/// <summary>Contesto del pianificatore per una compagnia (difficoltà e sconto IA inclusi).</summary>
public static TrackPlanContext PlanContext(World w, Company company, ITrackObstacles? obstacles = null) => new()
/// <summary>Moltiplicatore dei costi di costruzione di una compagnia (difficoltà e sconto IA).</summary>
public static double CostMultiplier(World w, Company company) =>
w.Difficulty.ConstructionCostMultiplier * (company.IsPlayer ? 1.0 : 1.0 - w.Difficulty.AiCostDiscount);
/// <summary>Ingressi dell'anteprima ricavati dal mondo autorevole.</summary>
public static TrackPreviewInputs PreviewInputs(World w, Company company) => new()
{
Data = w.Data,
Sampler = w.Sampler,
Network = w.Network,
Year = w.Clock.Year,
CostMultiplier = w.Difficulty.ConstructionCostMultiplier * (company.IsPlayer ? 1.0 : 1.0 - w.Difficulty.AiCostDiscount),
Obstacles = obstacles,
CostMultiplier = CostMultiplier(w, company),
NearestTownEdgeKm = p => w.Towns.Count == 0 ? double.MaxValue : w.Towns.Min(t => w.TownEdgeDistanceKm(t, p)),
};
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>Contesto del pianificatore per una compagnia (difficoltà e sconto IA inclusi).</summary>
public static TrackPlanContext PlanContext(World w, Company company, ITrackObstacles? obstacles = null) =>
TrackPreview.Context(PreviewInputs(w, company), obstacles);
/// <summary>Prepara il piano di un binario come farebbe il comando (stesso codice dell'anteprima del client).</summary>
public static (TrackPlan Plan, AttachPoint Start, AttachPoint End) PreparePlan(World w, Company company, BuildTrackCommand c) =>
TrackPreview.Prepare(PreviewInputs(w, company), company.Id, c);
public static CommandResult BuildTrack(World w, Company company, BuildTrackCommand c, Reply reply)
{
@@ -111,8 +93,8 @@ public static class RailCommandHandlers
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))
if (w.Network.Stations.Any(s => w.Network.IsAlive(s) && Vec2.Distance(s.Position, c.Position) < sp.AreaRadiusM * 2)
|| w.Network.Depots.Any(d => w.Network.IsAlive(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)
@@ -123,7 +105,7 @@ public static class RailCommandHandlers
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));
* CostMultiplier(w, company);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}");
var node = attach.Node.IsValid ? w.Network.Nodes[attach.Node.Value]
@@ -161,15 +143,15 @@ public static class RailCommandHandlers
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))
if (w.Network.Stations.Any(s => w.Network.IsAlive(s) && Vec2.Distance(s.Position, c.Position) < sp.AreaRadiusM * 2)
|| w.Network.Depots.Any(d => w.Network.IsAlive(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));
var cost = new Money(baseCost) * CostMultiplier(w, company);
if (company.Cash < cost) return reply(CommandError.InsufficientFunds, $"Servono {cost}");
var node = attach.Node.IsValid ? w.Network.Nodes[attach.Node.Value]
@@ -23,7 +23,10 @@ public sealed class StationSystem : ISimSystem
var net = w.Network;
if (ctx.IsNewMonth || ctx.Day == 0)
{
foreach (var s in net.Stations) RailCommandHandlers.UpdateCatchment(w, s);
foreach (var s in net.Stations)
{
if (net.IsAlive(s)) RailCommandHandlers.UpdateCatchment(w, s);
}
}
foreach (var s in net.Stations)
{
+2 -1
View File
@@ -3,8 +3,9 @@
<!-- Motore di simulazione deterministico: nessuna dipendenza oltre la BCL. -->
<PropertyGroup>
<TargetFrameworks>net10.0;net8.0</TargetFrameworks>
<!-- Immagine del server: solo net10.0, così la build non scarica il targeting pack net8.0 (ADR 0009). -->
<TargetFrameworks Condition="'$(VfServerOnly)' == 'true'">net10.0</TargetFrameworks>
<RootNamespace>ViaFerrea.Core</RootNamespace>
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
</Project>
@@ -0,0 +1,329 @@
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; }
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;
default:
return false;
}
}
private void Reset(Welcome m)
{
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);
}
}
@@ -0,0 +1,152 @@
using System.Net.WebSockets;
using System.Threading.Channels;
using ViaFerrea.Core.Commands;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Protocol.Client;
/// <summary>Il server ha rifiutato la sessione.</summary>
public sealed class SessionRejectedException(Reject reject) : Exception($"{reject.Code}: {reject.Reason}")
{
public Reject Reject { get; } = reject;
}
/// <summary>
/// Connessione WebSocket al server: un frame per messaggio binario, ricezione su un task dedicato
/// con coda dei messaggi, invii serializzati. Usata dal client Godot e dai test di integrazione.
/// </summary>
public sealed class ProtocolClient : IAsyncDisposable
{
private readonly ClientWebSocket _socket;
private readonly Channel<IMessage> _incoming = Channel.CreateUnbounded<IMessage>(new UnboundedChannelOptions { SingleReader = false, SingleWriter = true });
private readonly SemaphoreSlim _sendLock = new(1, 1);
private readonly CancellationTokenSource _cts = new();
private Task? _receiveLoop;
private uint _seq;
public Exception? Fault { get; private set; }
public bool IsOpen => _socket.State == WebSocketState.Open;
private ProtocolClient(ClientWebSocket socket) => _socket = socket;
public static async Task<ProtocolClient> ConnectAsync(Uri uri, CancellationToken ct = default)
{
var socket = new ClientWebSocket();
await socket.ConnectAsync(uri, ct).ConfigureAwait(false);
var client = new ProtocolClient(socket);
client._receiveLoop = Task.Run(client.ReceiveLoopAsync);
return client;
}
/// <summary>Hello → Welcome; un Reject diventa <see cref="SessionRejectedException"/>.</summary>
public async Task<Welcome> HandshakeAsync(Hello hello, CancellationToken ct = default)
{
await SendAsync(hello, ct).ConfigureAwait(false);
var reply = await ReceiveAsync(ct).ConfigureAwait(false);
return reply switch
{
Welcome w => w,
Reject r => throw new SessionRejectedException(r),
_ => throw new ProtocolException($"risposta inattesa all'Hello: {reply.Id}"),
};
}
public async Task SendAsync(IMessage message, CancellationToken ct = default)
{
byte[] frame = Frame.Encode(message);
await _sendLock.WaitAsync(ct).ConfigureAwait(false);
try
{
await _socket.SendAsync(frame, WebSocketMessageType.Binary, true, ct).ConfigureAwait(false);
}
finally
{
_sendLock.Release();
}
}
/// <summary>Invia un comando con un nuovo numero di sequenza e lo restituisce.</summary>
public async Task<uint> SendCommandAsync(GameCommand command, CancellationToken ct = default)
{
uint seq = Interlocked.Increment(ref _seq);
await SendAsync(new CommandMessage { Seq = seq, Command = command }, ct).ConfigureAwait(false);
return seq;
}
public async Task<IMessage> ReceiveAsync(CancellationToken ct = default)
{
try
{
return await _incoming.Reader.ReadAsync(ct).ConfigureAwait(false);
}
catch (ChannelClosedException) when (Fault is not null)
{
throw new ProtocolException($"connessione chiusa: {Fault.Message}");
}
}
/// <summary>Per il ciclo di disegno: prende un messaggio se ce n'è uno pronto.</summary>
public bool TryReceive(out IMessage message) => _incoming.Reader.TryRead(out message!);
private async Task ReceiveLoopAsync()
{
var buffer = new byte[64 * 1024];
var frame = new MemoryStream();
try
{
while (!_cts.IsCancellationRequested && _socket.State == WebSocketState.Open)
{
var result = await _socket.ReceiveAsync(buffer, _cts.Token).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close) break;
frame.Write(buffer, 0, result.Count);
if (frame.Length > Frame.MaxFrameBytes) throw new ProtocolException("frame oltre 4 MB");
if (!result.EndOfMessage) continue;
var message = Frame.Decode(frame.GetBuffer().AsSpan(0, (int)frame.Length));
frame.SetLength(0);
await _incoming.Writer.WriteAsync(message, _cts.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
Fault = e;
}
finally
{
_incoming.Writer.TryComplete(Fault);
}
}
public async ValueTask DisposeAsync()
{
try
{
if (_socket.State == WebSocketState.Open)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "fine", timeout.Token).ConfigureAwait(false);
}
}
catch (Exception)
{
// il server può aver già chiuso
}
_cts.Cancel();
if (_receiveLoop is not null)
{
try
{
await _receiveLoop.ConfigureAwait(false);
}
catch (Exception)
{
}
}
_socket.Dispose();
_cts.Dispose();
_sendLock.Dispose();
}
}
+268
View File
@@ -0,0 +1,268 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Protocol;
/// <summary>
/// Codifica del payload dei comandi (Command.type = <see cref="CommandType"/>). I campi seguono
/// l'ordine dei parametri dei record di Core; i campi futuri si aggiungono in coda dopo il byte
/// di estensione. Issuer non viaggia: lo assegna il server in base alla sessione.
/// </summary>
public static class CommandCodec
{
public static void Write(ref SpanWriter w, GameCommand command)
{
switch (command)
{
case BuildTrackCommand c:
w.Count(c.Polyline.Count);
foreach (var p in c.Polyline) w.Vec2(p);
w.F64(c.HeightOffsetM);
w.Bool(c.AllowBridges);
w.Bool(c.AllowTunnels);
w.String(c.TrackClass);
w.Bool(c.DoubleTrack);
w.Bool(c.Electrified);
w.I64(c.ExpectedCostCents);
break;
case RenewTrackCommand c: w.I32(c.Edge.Value); break;
case UpgradeTrackCommand c:
w.I32(c.Edge.Value);
w.String(c.TrackClass);
w.Bool(c.DoubleTrack);
w.Bool(c.Electrified);
break;
case DemolishCommand c:
w.U8((byte)c.Target);
w.I32(c.Id);
break;
case BuildStationCommand c:
w.Vec2(c.Position);
w.I32(c.Platforms);
OptionalString(ref w, c.Name);
break;
case BuildDepotCommand c:
w.Vec2(c.Position);
w.String(c.Size);
OptionalString(ref w, c.Name);
break;
case PlaceSignalCommand c:
w.I32(c.Edge.Value);
w.F64(c.PositionM);
break;
case BuyVehicleCommand c:
w.String(c.VehicleType);
w.I32(c.Depot.Value);
w.I32(c.Count);
break;
case SellVehicleCommand c: w.I32(c.Vehicle.Value); break;
case ComposeTrainCommand c:
w.I32(c.Depot.Value);
w.Count(c.Vehicles.Count);
foreach (var v in c.Vehicles) w.I32(v.Value);
OptionalString(ref w, c.Name);
break;
case CreateLineCommand c:
w.String(c.Name);
w.String(c.Color);
Stops(ref w, c.Stops);
break;
case EditLineCommand c:
w.I32(c.Line.Value);
Stops(ref w, c.Stops);
OptionalString(ref w, c.Name);
break;
case AssignTrainCommand c:
w.I32(c.Train.Value);
w.I32(c.Line.Value);
break;
case SendToDepotCommand c:
w.I32(c.Train.Value);
w.I32(c.Depot.Value);
break;
case SetReserveCommand c:
w.I32(c.Train.Value);
w.Bool(c.Reserve);
break;
case SetMaintenancePolicyCommand c:
w.U8((byte)c.Scope);
w.I32(c.Target);
w.String(c.Policy);
break;
case ScheduleServiceCommand c:
w.I32(c.Train.Value);
w.String(c.Intervention);
break;
case OrderPartsCommand c:
w.I32(c.Depot.Value);
w.I32(c.Quantity);
break;
case TakeLoanCommand c: w.Money(c.Amount); break;
case RepayLoanCommand c:
w.I32(c.Loan.Value);
w.Money(c.Amount);
break;
case AcceptAgreementCommand c: w.I32(c.Agreement.Value); break;
case RejectAgreementCommand c: w.I32(c.Agreement.Value); break;
case BuyGoodsCommand c:
w.I32(c.Station.Value);
w.String(c.Good);
w.I32(c.Units);
w.Money(c.MaxUnitPrice);
break;
case SellGoodsCommand c:
w.I32(c.Station.Value);
w.String(c.Good);
w.I32(c.Units);
w.Money(c.MinUnitPrice);
break;
case BuyIndustryCommand c:
w.I32(c.Industry.Value);
w.Money(c.Offer);
break;
case SetIndustryPolicyCommand c:
w.I32(c.Industry.Value);
w.U8((byte)c.Budget);
break;
case OverhaulIndustryCommand c: w.I32(c.Industry.Value); break;
case UpgradeIndustryCommand c: w.I32(c.Industry.Value); break;
case IpoCommand c: w.F64(c.FloatShare); break;
case BuySharesCommand c:
w.I32(c.Company.Value);
w.I64(c.Shares);
w.Money(c.MaxPrice);
break;
case SellSharesCommand c:
w.I32(c.Company.Value);
w.I64(c.Shares);
w.Money(c.MinPrice);
break;
case PayDividendCommand c: w.Money(c.PerShare); break;
case LaunchBidCommand c:
w.I32(c.Target.Value);
w.Money(c.PricePerShare);
w.F64(c.TargetShare);
break;
case RespondBidCommand c:
w.I32(c.Bid.Value);
w.Bool(c.Accept);
break;
case BuyConcessionCommand c: w.I32(c.Region.Value); break;
case AcceptContractCommand c: w.I32(c.Contract.Value); break;
case FundResearchCommand c:
w.String(c.Project);
w.Money(c.Amount);
break;
case DelegateRegionCommand c:
w.I32(c.Region.Value);
w.String(c.Objective);
w.Money(c.Budget);
break;
default:
throw new ProtocolException($"comando senza codifica: {command.Type}");
}
w.Flags(0);
}
public static GameCommand Read(CommandType type, ref SpanReader r)
{
GameCommand c = type switch
{
CommandType.BuildTrack => ReadBuildTrack(ref r),
CommandType.RenewTrack => new RenewTrackCommand(new EdgeId(r.I32())),
CommandType.UpgradeTrack => new UpgradeTrackCommand(new EdgeId(r.I32()), r.String(), r.Bool(), r.Bool()),
CommandType.Demolish => new DemolishCommand(Enum<DemolishTarget>(r.U8(), 3), r.I32()),
CommandType.BuildStation => new BuildStationCommand(r.Vec2(), r.I32(), OptionalString(ref r)),
CommandType.BuildDepot => new BuildDepotCommand(r.Vec2(), r.String(), OptionalString(ref r)),
CommandType.PlaceSignal => new PlaceSignalCommand(new EdgeId(r.I32()), r.F64()),
CommandType.BuyVehicle => new BuyVehicleCommand(r.String(), new DepotId(r.I32()), r.I32()),
CommandType.SellVehicle => new SellVehicleCommand(new VehicleId(r.I32())),
CommandType.ComposeTrain => ReadCompose(ref r),
CommandType.CreateLine => new CreateLineCommand(r.String(), r.String(), Stops(ref r)),
CommandType.EditLine => new EditLineCommand(new LineId(r.I32()), Stops(ref r), OptionalString(ref r)),
CommandType.AssignTrain => new AssignTrainCommand(new TrainId(r.I32()), new LineId(r.I32())),
CommandType.SendToDepot => new SendToDepotCommand(new TrainId(r.I32()), new DepotId(r.I32())),
CommandType.SetReserve => new SetReserveCommand(new TrainId(r.I32()), r.Bool()),
CommandType.SetMaintenancePolicy => new SetMaintenancePolicyCommand(Enum<MaintenanceScope>(r.U8(), 2), r.I32(), r.String()),
CommandType.ScheduleService => new ScheduleServiceCommand(new TrainId(r.I32()), r.String()),
CommandType.OrderParts => new OrderPartsCommand(new DepotId(r.I32()), r.I32()),
CommandType.TakeLoan => new TakeLoanCommand(r.Money()),
CommandType.RepayLoan => new RepayLoanCommand(new LoanId(r.I32()), r.Money()),
CommandType.AcceptAgreement => new AcceptAgreementCommand(new AgreementId(r.I32())),
CommandType.RejectAgreement => new RejectAgreementCommand(new AgreementId(r.I32())),
CommandType.BuyGoods => new BuyGoodsCommand(new StationId(r.I32()), r.String(), r.I32(), r.Money()),
CommandType.SellGoods => new SellGoodsCommand(new StationId(r.I32()), r.String(), r.I32(), r.Money()),
CommandType.BuyIndustry => new BuyIndustryCommand(new IndustryId(r.I32()), r.Money()),
CommandType.SetIndustryPolicy => new SetIndustryPolicyCommand(new IndustryId(r.I32()), Enum<IndustryBudget>(r.U8(), 2)),
CommandType.OverhaulIndustry => new OverhaulIndustryCommand(new IndustryId(r.I32())),
CommandType.UpgradeIndustry => new UpgradeIndustryCommand(new IndustryId(r.I32())),
CommandType.Ipo => new IpoCommand(r.F64()),
CommandType.BuyShares => new BuySharesCommand(new CompanyId(r.I32()), r.I64(), r.Money()),
CommandType.SellShares => new SellSharesCommand(new CompanyId(r.I32()), r.I64(), r.Money()),
CommandType.PayDividend => new PayDividendCommand(r.Money()),
CommandType.LaunchBid => new LaunchBidCommand(new CompanyId(r.I32()), r.Money(), r.F64()),
CommandType.RespondBid => new RespondBidCommand(new BidId(r.I32()), r.Bool()),
CommandType.BuyConcession => new BuyConcessionCommand(new RegionId(r.I32())),
CommandType.AcceptContract => new AcceptContractCommand(new ContractId(r.I32())),
CommandType.FundResearch => new FundResearchCommand(r.String(), r.Money()),
CommandType.DelegateRegion => new DelegateRegionCommand(new RegionId(r.I32()), r.String(), r.Money()),
_ => throw new ProtocolException($"tipo di comando sconosciuto: {(ushort)type}"),
};
r.Flags();
return c;
}
private static BuildTrackCommand ReadBuildTrack(ref SpanReader r)
{
int n = r.Count();
var polyline = new Vec2[n];
for (int i = 0; i < n; i++) polyline[i] = r.Vec2();
return new BuildTrackCommand(polyline, r.F64(), r.Bool(), r.Bool(), r.String(), r.Bool(), r.Bool(), r.I64());
}
private static ComposeTrainCommand ReadCompose(ref SpanReader r)
{
var depot = new DepotId(r.I32());
int n = r.Count();
var vehicles = new VehicleId[n];
for (int i = 0; i < n; i++) vehicles[i] = new VehicleId(r.I32());
return new ComposeTrainCommand(depot, vehicles, OptionalString(ref r));
}
private static void Stops(ref SpanWriter w, IReadOnlyList<LineStop> stops)
{
w.Count(stops.Count);
foreach (var s in stops)
{
w.I32(s.Station.Value);
w.Bool(s.Load);
w.Bool(s.Unload);
w.Bool(s.WaitFull);
w.I32(s.MaxWaitDays);
}
}
private static LineStop[] Stops(ref SpanReader r)
{
int n = r.Count();
var stops = new LineStop[n];
for (int i = 0; i < n; i++) stops[i] = new LineStop(new StationId(r.I32()), r.Bool(), r.Bool(), r.Bool(), r.I32());
return stops;
}
private static void OptionalString(ref SpanWriter w, string? s)
{
w.Bool(s is not null);
if (s is not null) w.String(s);
}
private static string? OptionalString(ref SpanReader r) => r.Bool() ? r.String() : null;
private static T Enum<T>(byte value, byte max) where T : struct, System.Enum
{
if (value > max) throw new ProtocolException($"{typeof(T).Name} non valido: {value}");
return (T)(object)value;
}
}
+51
View File
@@ -0,0 +1,51 @@
using System.Buffers.Binary;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Protocol;
/// <summary>
/// Frame <c>[u32 length][u16 messageId][payload]</c>, little endian; length conta messageId e
/// payload. Un messaggio WebSocket binario contiene esattamente un frame.
/// </summary>
public static class Frame
{
public const int HeaderSize = 6;
public const int MaxFrameBytes = 4 * 1024 * 1024;
public const int MaxLength = MaxFrameBytes - 4;
/// <summary>Versione del protocollo: cresce solo per modifiche incompatibili.</summary>
public const ushort ProtocolVersion = 1;
public static byte[] Encode(IMessage message)
{
var w = new SpanWriter(256);
w.U32(0);
w.U16((ushort)message.Id);
message.Write(ref w);
int length = w.Length - 4;
if (length > MaxLength) throw new ProtocolException($"frame troppo grande: {w.Length} byte");
w.PatchU32(0, (uint)length);
return w.ToArray();
}
/// <summary>Lunghezza totale del frame che inizia in data, se l'intestazione è completa.</summary>
public static bool TryReadLength(ReadOnlySpan<byte> data, out int frameBytes)
{
frameBytes = 0;
if (data.Length < 4) return false;
uint length = BinaryPrimitives.ReadUInt32LittleEndian(data);
if (length < 2 || length > MaxLength) throw new ProtocolException($"lunghezza del frame non valida: {length}");
frameBytes = (int)length + 4;
return true;
}
public static IMessage Decode(ReadOnlySpan<byte> frame)
{
if (frame.Length < HeaderSize) throw new ProtocolException("frame troppo corto");
uint length = BinaryPrimitives.ReadUInt32LittleEndian(frame);
if (length > MaxLength || length + 4 != frame.Length) throw new ProtocolException($"lunghezza del frame incoerente: {length} su {frame.Length} byte");
var id = (MessageId)BinaryPrimitives.ReadUInt16LittleEndian(frame[4..]);
var r = new SpanReader(frame[HeaderSize..]);
return MessageCodec.Read(id, ref r);
}
}
+40
View File
@@ -0,0 +1,40 @@
namespace ViaFerrea.Protocol;
/// <summary>Identificativi stabili dei messaggi (PROTOCOL.md): 1–99 dal client, 101–199 dal server.</summary>
public enum MessageId : ushort
{
Hello = 1,
Ping = 2,
Subscribe = 3,
Command = 4,
SetSpeed = 5,
ListSaves = 6,
Save = 7,
Load = 8,
NewGame = 9,
Welcome = 101,
Reject = 102,
Pong = 103,
MapChunk = 110,
EntitySnapshot = 111,
EntityDelta = 112,
TrackWorks = 113,
TrainMotion = 114,
DailyDigest = 120,
MaintenanceAlert = 121,
EmploymentReport = 122,
MarketTape = 123,
CommandResult = 130,
Notification = 131,
Newspaper = 132,
SaveList = 133,
}
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
public interface IMessage
{
MessageId Id { get; }
void Write(ref SpanWriter w);
}
@@ -0,0 +1,223 @@
using ViaFerrea.Core.Commands;
namespace ViaFerrea.Protocol.Messages;
/// <summary>Apertura della sessione: versione, token, sessione da riprendere (0 = nuova) e hash dei dati del client.</summary>
public sealed class Hello : IMessage
{
public MessageId Id => MessageId.Hello;
public ushort ProtocolVersion { get; init; } = Frame.ProtocolVersion;
public string ClientVersion { get; init; } = "";
public string Token { get; init; } = "";
public ulong ResumeSessionId { get; init; }
/// <summary>Hash dei dati del client (0 = non verificare).</summary>
public ulong DataHash { get; init; }
public void Write(ref SpanWriter w)
{
w.U16(ProtocolVersion);
w.String(ClientVersion);
w.String(Token);
w.U64(ResumeSessionId);
w.U64(DataHash);
w.Flags(0);
}
public static Hello Read(ref SpanReader r)
{
var m = new Hello { ProtocolVersion = r.U16(), ClientVersion = r.String(), Token = r.String(), ResumeSessionId = r.U64(), DataHash = r.U64() };
r.Flags();
return m;
}
}
public sealed class Ping : IMessage
{
public MessageId Id => MessageId.Ping;
public ulong Nonce { get; init; }
public void Write(ref SpanWriter w)
{
w.U64(Nonce);
w.Flags(0);
}
public static Ping Read(ref SpanReader r)
{
var m = new Ping { Nonce = r.U64() };
r.Flags();
return m;
}
}
/// <summary>Area di interesse in celle (estremi inclusi) e livello di dettaglio (0 pieno, 1 medio, 2 lontano).</summary>
public sealed class Subscribe : IMessage
{
public MessageId Id => MessageId.Subscribe;
public int X0 { get; init; }
public int Y0 { get; init; }
public int X1 { get; init; }
public int Y1 { get; init; }
public byte Lod { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(X0);
w.I32(Y0);
w.I32(X1);
w.I32(Y1);
w.U8(Lod);
w.Flags(0);
}
public static Subscribe Read(ref SpanReader r)
{
var m = new Subscribe { X0 = r.I32(), Y0 = r.I32(), X1 = r.I32(), Y1 = r.I32(), Lod = r.U8() };
r.Flags();
return m;
}
}
/// <summary>Comando di gioco con il numero di sequenza del client; il payload segue <see cref="CommandCodec"/>.</summary>
public sealed class CommandMessage : IMessage
{
public MessageId Id => MessageId.Command;
public uint Seq { get; init; }
public required GameCommand Command { get; init; }
public void Write(ref SpanWriter w)
{
w.U32(Seq);
w.U16((ushort)Command.Type);
// payload con lunghezza: un lettore vecchio può saltarlo anche se il comando cresce
var inner = new SpanWriter(64);
CommandCodec.Write(ref inner, Command);
w.Bytes(inner.Written);
w.Flags(0);
}
public static CommandMessage Read(ref SpanReader r)
{
uint seq = r.U32();
var type = (CommandType)r.U16();
byte[] payload = r.Bytes();
var inner = new SpanReader(payload);
var command = CommandCodec.Read(type, ref inner) with { Seq = seq };
r.Flags();
return new CommandMessage { Seq = seq, Command = command };
}
}
/// <summary>Velocità della simulazione: 0 (pausa), 1, 2, 4, 8.</summary>
public sealed class SetSpeed : IMessage
{
public MessageId Id => MessageId.SetSpeed;
public byte Speed { get; init; }
public void Write(ref SpanWriter w)
{
w.U8(Speed);
w.Flags(0);
}
public static SetSpeed Read(ref SpanReader r)
{
var m = new SetSpeed { Speed = r.U8() };
r.Flags();
return m;
}
}
public sealed class ListSaves : IMessage
{
public MessageId Id => MessageId.ListSaves;
public void Write(ref SpanWriter w) => w.Flags(0);
public static ListSaves Read(ref SpanReader r)
{
r.Flags();
return new ListSaves();
}
}
public sealed class Save : IMessage
{
public MessageId Id => MessageId.Save;
public string Name { get; init; } = "";
public void Write(ref SpanWriter w)
{
w.String(Name);
w.Flags(0);
}
public static Save Read(ref SpanReader r)
{
var m = new Save { Name = r.String() };
r.Flags();
return m;
}
}
public sealed class Load : IMessage
{
public MessageId Id => MessageId.Load;
public string SaveId { get; init; } = "";
public void Write(ref SpanWriter w)
{
w.String(SaveId);
w.Flags(0);
}
public static Load Read(ref SpanReader r)
{
var m = new Load { SaveId = r.String() };
r.Flags();
return m;
}
}
/// <summary>Nuova partita: seme, lato della mappa (km), anno d'inizio (0 = predefinito), difficoltà, ritocchi e opzioni del gioco infinito.</summary>
public sealed class NewGame : IMessage
{
public MessageId Id => MessageId.NewGame;
public ulong Seed { get; init; }
public int SizeKm { get; init; }
public int StartYear { get; init; }
public string DifficultyPreset { get; init; } = "";
/// <summary>Ritocchi della difficoltà «Personalizzata»: nome del campo (camelCase) e valore.</summary>
public List<(string Key, double Value)> Overrides { get; init; } = [];
public uint EndlessFlags { get; init; }
public void Write(ref SpanWriter w)
{
w.U64(Seed);
w.I32(SizeKm);
w.I32(StartYear);
w.String(DifficultyPreset);
w.Count(Overrides.Count);
foreach (var (key, value) in Overrides)
{
w.String(key);
w.F64(value);
}
w.U32(EndlessFlags);
w.Flags(0);
}
public static NewGame Read(ref SpanReader r)
{
ulong seed = r.U64();
int size = r.I32();
int year = r.I32();
string preset = r.String();
int n = r.Count();
var overrides = new List<(string, double)>(n);
for (int i = 0; i < n; i++) overrides.Add((r.String(), r.F64()));
var m = new NewGame { Seed = seed, SizeKm = size, StartYear = year, DifficultyPreset = preset, Overrides = overrides, EndlessFlags = r.U32() };
r.Flags();
return m;
}
}
@@ -0,0 +1,35 @@
namespace ViaFerrea.Protocol.Messages;
/// <summary>Decodifica per id: l'unico punto in cui un id diventa un tipo.</summary>
public static class MessageCodec
{
public static IMessage Read(MessageId id, ref SpanReader r) => id switch
{
MessageId.Hello => Hello.Read(ref r),
MessageId.Ping => Ping.Read(ref r),
MessageId.Subscribe => Subscribe.Read(ref r),
MessageId.Command => CommandMessage.Read(ref r),
MessageId.SetSpeed => SetSpeed.Read(ref r),
MessageId.ListSaves => ListSaves.Read(ref r),
MessageId.Save => Save.Read(ref r),
MessageId.Load => Load.Read(ref r),
MessageId.NewGame => NewGame.Read(ref r),
MessageId.Welcome => Welcome.Read(ref r),
MessageId.Reject => Reject.Read(ref r),
MessageId.Pong => Pong.Read(ref r),
MessageId.MapChunk => MapChunk.Read(ref r),
MessageId.EntitySnapshot => EntitySnapshot.Read(ref r),
MessageId.EntityDelta => EntityDelta.Read(ref r),
MessageId.TrackWorks => TrackWorks.Read(ref r),
MessageId.TrainMotion => TrainMotion.Read(ref r),
MessageId.DailyDigest => DailyDigest.Read(ref r),
MessageId.MaintenanceAlert => MaintenanceAlert.Read(ref r),
MessageId.EmploymentReport => EmploymentReport.Read(ref r),
MessageId.MarketTape => MarketTape.Read(ref r),
MessageId.CommandResult => CommandResultMessage.Read(ref r),
MessageId.Notification => Notification.Read(ref r),
MessageId.Newspaper => Newspaper.Read(ref r),
MessageId.SaveList => SaveList.Read(ref r),
_ => throw new ProtocolException($"messaggio sconosciuto: {(ushort)id}"),
};
}
+447
View File
@@ -0,0 +1,447 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Protocol.Messages;
// Record delle entità inviati al client. Ogni record ha Write/Read e un byte di estensione finale.
/// <summary>Record serializzabile (entità, archi, eventi).</summary>
public interface IWritable
{
void Write(ref SpanWriter w);
}
/// <summary>Tipo di entità nei riferimenti e nelle rimozioni.</summary>
public enum EntityType : byte { Company = 0, Town = 1, Industry = 2, Hub = 3, Node = 4, Station = 5, Depot = 6, Line = 7, Vehicle = 8, Train = 9, Edge = 10 }
public sealed class WorldSummary : IWritable
{
public ulong Seed { get; init; }
public int SizeKm { get; init; }
public int StartYear { get; init; }
public long Tick { get; init; }
public string Date { get; init; } = "";
public int CompanyId { get; init; }
public string CompanyName { get; init; } = "";
public string RegionId { get; init; } = "";
public int WidthCells { get; init; }
public int HeightCells { get; init; }
public double CellSizeM { get; init; }
public int ChunkCells { get; init; }
public byte Speed { get; init; }
public ulong TerrainHash { get; init; }
/// <summary>Moltiplicatore dei costi di costruzione della compagnia (difficoltà), per le anteprime.</summary>
public double CostMultiplier { get; init; } = 1;
public void Write(ref SpanWriter w)
{
w.U64(Seed); w.I32(SizeKm); w.I32(StartYear); w.I64(Tick); w.String(Date);
w.I32(CompanyId); w.String(CompanyName); w.String(RegionId);
w.I32(WidthCells); w.I32(HeightCells); w.F64(CellSizeM); w.I32(ChunkCells);
w.U8(Speed); w.U64(TerrainHash); w.F64(CostMultiplier);
w.Flags(0);
}
public static WorldSummary Read(ref SpanReader r)
{
var m = new WorldSummary
{
Seed = r.U64(), SizeKm = r.I32(), StartYear = r.I32(), Tick = r.I64(), Date = r.String(),
CompanyId = r.I32(), CompanyName = r.String(), RegionId = r.String(),
WidthCells = r.I32(), HeightCells = r.I32(), CellSizeM = r.F64(), ChunkCells = r.I32(),
Speed = r.U8(), TerrainHash = r.U64(), CostMultiplier = r.F64(),
};
r.Flags();
return m;
}
}
public sealed class CompanyInfo : IWritable
{
public int Id { get; init; }
public string Name { get; init; } = "";
public string Color { get; init; } = "";
public bool IsPlayer { get; init; }
public Money Cash { get; init; }
public Money NetWorth { get; init; }
public string Rating { get; init; } = "";
public byte Tier { get; init; }
public bool Bankrupt { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Name); w.String(Color); w.Bool(IsPlayer); w.Money(Cash); w.Money(NetWorth);
w.String(Rating); w.U8(Tier); w.Bool(Bankrupt);
w.Flags(0);
}
public static CompanyInfo Read(ref SpanReader r)
{
var m = new CompanyInfo
{
Id = r.I32(), Name = r.String(), Color = r.String(), IsPlayer = r.Bool(), Cash = r.Money(), NetWorth = r.Money(),
Rating = r.String(), Tier = r.U8(), Bankrupt = r.Bool(),
};
r.Flags();
return m;
}
}
public sealed class TownInfo : IWritable
{
public int Id { get; init; }
public string Name { get; init; } = "";
public Vec2 Position { get; init; }
public int Population { get; init; }
public double RadiusCells { get; init; }
public float Satisfaction { get; init; }
public int Services { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Name); w.Vec2(Position); w.I32(Population); w.F64(RadiusCells); w.F32(Satisfaction); w.I32(Services);
w.Flags(0);
}
public static TownInfo Read(ref SpanReader r)
{
var m = new TownInfo { Id = r.I32(), Name = r.String(), Position = r.Vec2(), Population = r.I32(), RadiusCells = r.F64(), Satisfaction = r.F32(), Services = r.I32() };
r.Flags();
return m;
}
}
public sealed class IndustryInfo : IWritable
{
public int Id { get; init; }
public string Type { get; init; } = "";
public string Name { get; init; } = "";
public Vec2 Position { get; init; }
public int FootprintCells { get; init; }
public int Level { get; init; }
public bool Closed { get; init; }
public float Efficiency { get; init; }
public float Condition { get; init; }
public int Owner { get; init; } = -1;
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Type); w.String(Name); w.Vec2(Position); w.I32(FootprintCells); w.I32(Level); w.Bool(Closed);
w.F32(Efficiency); w.F32(Condition); w.I32(Owner);
w.Flags(0);
}
public static IndustryInfo Read(ref SpanReader r)
{
var m = new IndustryInfo
{
Id = r.I32(), Type = r.String(), Name = r.String(), Position = r.Vec2(), FootprintCells = r.I32(), Level = r.I32(), Closed = r.Bool(),
Efficiency = r.F32(), Condition = r.F32(), Owner = r.I32(),
};
r.Flags();
return m;
}
}
public sealed class HubInfo : IWritable
{
public int Id { get; init; }
public string Kind { get; init; } = "";
public string Name { get; init; } = "";
public Vec2 Position { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.String(Kind); w.String(Name); w.Vec2(Position);
w.Flags(0);
}
public static HubInfo Read(ref SpanReader r)
{
var m = new HubInfo { Id = r.I32(), Kind = r.String(), Name = r.String(), Position = r.Vec2() };
r.Flags();
return m;
}
}
public sealed class NodeInfo : IWritable
{
public int Id { get; init; }
public Vec2 Position { get; init; }
public double HeightM { get; init; }
public int Owner { get; init; } = -1;
public int Station { get; init; } = -1;
public int Depot { get; init; } = -1;
public int[] Edges { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Id); w.Vec2(Position); w.F64(HeightM); w.I32(Owner); w.I32(Station); w.I32(Depot);
w.Count(Edges.Length);
foreach (int e in Edges) w.I32(e);
w.Flags(0);
}
public static NodeInfo Read(ref SpanReader r)
{
int id = r.I32();
var pos = r.Vec2();
double h = r.F64();
int owner = r.I32(), station = r.I32(), depot = r.I32();
var edges = new int[r.Count()];
for (int i = 0; i < edges.Length; i++) edges[i] = r.I32();
r.Flags();
return new NodeInfo { Id = id, Position = pos, HeightM = h, Owner = owner, Station = station, Depot = depot, Edges = edges };
}
}
public sealed class StationInfo : IWritable
{
public int Id { get; init; }
public int Owner { get; init; }
public string Name { get; init; } = "";
public int Node { get; init; }
public Vec2 Position { get; init; }
public int Platforms { get; init; }
public int WaitingUnits { get; init; }
public int[] Industries { get; init; } = [];
public int[] Towns { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Id); w.I32(Owner); w.String(Name); w.I32(Node); w.Vec2(Position); w.I32(Platforms); w.I32(WaitingUnits);
w.Count(Industries.Length);
foreach (int i in Industries) w.I32(i);
w.Count(Towns.Length);
foreach (int t in Towns) w.I32(t);
w.Flags(0);
}
public static StationInfo Read(ref SpanReader r)
{
int id = r.I32(), owner = r.I32();
string name = r.String();
int node = r.I32();
var pos = r.Vec2();
int platforms = r.I32(), waiting = r.I32();
var industries = new int[r.Count()];
for (int i = 0; i < industries.Length; i++) industries[i] = r.I32();
var towns = new int[r.Count()];
for (int i = 0; i < towns.Length; i++) towns[i] = r.I32();
r.Flags();
return new StationInfo { Id = id, Owner = owner, Name = name, Node = node, Position = pos, Platforms = platforms, WaitingUnits = waiting, Industries = industries, Towns = towns };
}
}
public sealed class DepotInfo : IWritable
{
public int Id { get; init; }
public int Owner { get; init; }
public string Name { get; init; } = "";
public int Node { get; init; }
public Vec2 Position { get; init; }
public string Size { get; init; } = "";
public void Write(ref SpanWriter w)
{
w.I32(Id); w.I32(Owner); w.String(Name); w.I32(Node); w.Vec2(Position); w.String(Size);
w.Flags(0);
}
public static DepotInfo Read(ref SpanReader r)
{
var m = new DepotInfo { Id = r.I32(), Owner = r.I32(), Name = r.String(), Node = r.I32(), Position = r.Vec2(), Size = r.String() };
r.Flags();
return m;
}
}
public sealed class LineInfo : IWritable
{
public int Id { get; init; }
public int Owner { get; init; }
public string Name { get; init; } = "";
public string Color { get; init; } = "";
public LineStop[] Stops { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Id); w.I32(Owner); w.String(Name); w.String(Color);
w.Count(Stops.Length);
foreach (var s in Stops)
{
w.I32(s.Station.Value); w.Bool(s.Load); w.Bool(s.Unload); w.Bool(s.WaitFull); w.I32(s.MaxWaitDays);
}
w.Flags(0);
}
public static LineInfo Read(ref SpanReader r)
{
int id = r.I32(), owner = r.I32();
string name = r.String(), color = r.String();
var stops = new LineStop[r.Count()];
for (int i = 0; i < stops.Length; i++) stops[i] = new LineStop(new StationId(r.I32()), r.Bool(), r.Bool(), r.Bool(), r.I32());
r.Flags();
return new LineInfo { Id = id, Owner = owner, Name = name, Color = color, Stops = stops };
}
}
public sealed class VehicleInfo : IWritable
{
public int Id { get; init; }
public int Owner { get; init; }
public string Type { get; init; } = "";
public int Depot { get; init; } = -1;
public int Train { get; init; } = -1;
public float Condition { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Id); w.I32(Owner); w.String(Type); w.I32(Depot); w.I32(Train); w.F32(Condition);
w.Flags(0);
}
public static VehicleInfo Read(ref SpanReader r)
{
var m = new VehicleInfo { Id = r.I32(), Owner = r.I32(), Type = r.String(), Depot = r.I32(), Train = r.I32(), Condition = r.F32() };
r.Flags();
return m;
}
}
public sealed class TrainInfo : IWritable
{
public int Id { get; init; }
public int Owner { get; init; }
public string Name { get; init; } = "";
public int Line { get; init; } = -1;
public byte State { get; init; }
public int[] Vehicles { get; init; } = [];
public float MaxSpeedKmh { get; init; }
public float LengthM { get; init; }
public int Load { get; init; }
public int Capacity { get; init; }
public int Depot { get; init; } = -1;
public void Write(ref SpanWriter w)
{
w.I32(Id); w.I32(Owner); w.String(Name); w.I32(Line); w.U8(State);
w.Count(Vehicles.Length);
foreach (int v in Vehicles) w.I32(v);
w.F32(MaxSpeedKmh); w.F32(LengthM); w.I32(Load); w.I32(Capacity); w.I32(Depot);
w.Flags(0);
}
public static TrainInfo Read(ref SpanReader r)
{
int id = r.I32(), owner = r.I32();
string name = r.String();
int line = r.I32();
byte state = r.U8();
var vehicles = new int[r.Count()];
for (int i = 0; i < vehicles.Length; i++) vehicles[i] = r.I32();
var m = new TrainInfo
{
Id = id, Owner = owner, Name = name, Line = line, State = state, Vehicles = vehicles,
MaxSpeedKmh = r.F32(), LengthM = r.F32(), Load = r.I32(), Capacity = r.I32(), Depot = r.I32(),
};
r.Flags();
return m;
}
}
/// <summary>Arco di binario con i campioni del profilo (TrackWorks): precisione piena per le anteprime del client.</summary>
public sealed class EdgeInfo : IWritable
{
public int Id { get; init; }
public int Owner { get; init; }
public int A { get; init; }
public int B { get; init; }
public byte TrackClass { get; init; }
public bool DoubleTrack { get; init; }
public bool Electrified { get; init; }
public byte State { get; init; }
public float Condition { get; init; }
public float StructureCondition { get; init; }
/// <summary>Avanzamento del cantiere 0–1 (1 = completato).</summary>
public float Progress { get; init; } = 1;
public double[] S { get; init; } = [];
public double[] X { get; init; } = [];
public double[] Y { get; init; } = [];
public double[] H { get; init; } = [];
public double[] Ground { get; init; } = [];
public byte[] Kinds { get; init; } = [];
public double[] SpeedLimitKmh { get; init; } = [];
public double[] Signals { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Id); w.I32(Owner); w.I32(A); w.I32(B); w.U8(TrackClass); w.Bool(DoubleTrack); w.Bool(Electrified); w.U8(State);
w.F32(Condition); w.F32(StructureCondition); w.F32(Progress);
int n = S.Length;
w.Count(n);
for (int i = 0; i < n; i++)
{
w.F64(S[i]); w.F64(X[i]); w.F64(Y[i]); w.F64(H[i]); w.F64(Ground[i]); w.U8(Kinds[i]); w.F64(SpeedLimitKmh[i]);
}
w.Count(Signals.Length);
foreach (double s in Signals) w.F64(s);
w.Flags(0);
}
public static EdgeInfo Read(ref SpanReader r)
{
int id = r.I32(), owner = r.I32(), a = r.I32(), b = r.I32();
byte cls = r.U8();
bool dbl = r.Bool(), el = r.Bool();
byte state = r.U8();
float cond = r.F32(), sc = r.F32(), progress = r.F32();
int n = r.Count();
var s = new double[n]; var x = new double[n]; var y = new double[n]; var h = new double[n]; var g = new double[n];
var k = new byte[n]; var v = new double[n];
for (int i = 0; i < n; i++)
{
s[i] = r.F64(); x[i] = r.F64(); y[i] = r.F64(); h[i] = r.F64(); g[i] = r.F64(); k[i] = r.U8(); v[i] = r.F64();
}
var signals = new double[r.Count()];
for (int i = 0; i < signals.Length; i++) signals[i] = r.F64();
r.Flags();
return new EdgeInfo
{
Id = id, Owner = owner, A = a, B = b, TrackClass = cls, DoubleTrack = dbl, Electrified = el, State = state,
Condition = cond, StructureCondition = sc, Progress = progress, S = s, X = x, Y = y, H = h, Ground = g, Kinds = k,
SpeedLimitKmh = v, Signals = signals,
};
}
}
/// <summary>Evento della simulazione (notifiche, ticker, resoconto giornaliero).</summary>
public sealed class EventInfo : IWritable
{
public long Day { get; init; }
public byte Kind { get; init; }
public byte Severity { get; init; }
public string Text { get; init; } = "";
public byte Entity { get; init; }
public int EntityIndex { get; init; } = -1;
public int Company { get; init; } = -1;
public void Write(ref SpanWriter w)
{
w.I64(Day); w.U8(Kind); w.U8(Severity); w.String(Text); w.U8(Entity); w.I32(EntityIndex); w.I32(Company);
w.Flags(0);
}
public static EventInfo Read(ref SpanReader r)
{
var m = new EventInfo { Day = r.I64(), Kind = r.U8(), Severity = r.U8(), Text = r.String(), Entity = r.U8(), EntityIndex = r.I32(), Company = r.I32() };
r.Flags();
return m;
}
}
/// <summary>Tratto di moto di un treno: arco percorso nel verso indicato tra due progressive.</summary>
public readonly record struct MotionSegment(int Edge, bool Forward, double FromS, double ToS)
{
public double Length => Math.Abs(ToS - FromS);
}
@@ -0,0 +1,660 @@
using System.IO.Compression;
using ViaFerrea.Core.Common;
namespace ViaFerrea.Protocol.Messages;
/// <summary>Codici di <see cref="Reject"/>.</summary>
public enum RejectCode : ushort { ProtocolVersion = 1, BadToken = 2, DataMismatch = 3, ServerFull = 4, NoGame = 5 }
public sealed class Welcome : IMessage
{
public MessageId Id => MessageId.Welcome;
public ulong SessionId { get; init; }
public required WorldSummary Summary { get; init; }
public ulong DataHash { get; init; }
public string Difficulty { get; init; } = "";
public void Write(ref SpanWriter w)
{
w.U64(SessionId);
Summary.Write(ref w);
w.U64(DataHash);
w.String(Difficulty);
w.Flags(0);
}
public static Welcome Read(ref SpanReader r)
{
var m = new Welcome { SessionId = r.U64(), Summary = WorldSummary.Read(ref r), DataHash = r.U64(), Difficulty = r.String() };
r.Flags();
return m;
}
}
public sealed class Reject : IMessage
{
public MessageId Id => MessageId.Reject;
public RejectCode Code { get; init; }
public string Reason { get; init; } = "";
public void Write(ref SpanWriter w)
{
w.U16((ushort)Code);
w.String(Reason);
w.Flags(0);
}
public static Reject Read(ref SpanReader r)
{
var m = new Reject { Code = (RejectCode)r.U16(), Reason = r.String() };
r.Flags();
return m;
}
}
public sealed class Pong : IMessage
{
public MessageId Id => MessageId.Pong;
public ulong Nonce { get; init; }
public ulong ServerTick { get; init; }
public void Write(ref SpanWriter w)
{
w.U64(Nonce);
w.U64(ServerTick);
w.Flags(0);
}
public static Pong Read(ref SpanReader r)
{
var m = new Pong { Nonce = r.U64(), ServerTick = r.U64() };
r.Flags();
return m;
}
}
/// <summary>
/// Un chunk del terreno: altezze (dm), tipi di cella e larghezza dei fiumi, compressi con Brotli.
/// I chunk di bordo possono essere più piccoli di ChunkCells.
/// </summary>
public sealed class MapChunk : IMessage
{
public MessageId Id => MessageId.MapChunk;
public int Cx { get; init; }
public int Cy { get; init; }
public int Width { get; init; }
public int Height { get; init; }
public ushort[] Heights { get; init; } = [];
public byte[] Types { get; init; } = [];
public byte[] RiverWidth { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Cx); w.I32(Cy); w.I32(Width); w.I32(Height);
int n = Width * Height;
if (Heights.Length != n || Types.Length != n || RiverWidth.Length != n) throw new ProtocolException("chunk incoerente");
var raw = new byte[n * 4];
for (int i = 0; i < n; i++)
{
raw[2 * i] = (byte)Heights[i];
raw[2 * i + 1] = (byte)(Heights[i] >> 8);
}
Types.CopyTo(raw, 2 * n);
RiverWidth.CopyTo(raw, 3 * n);
var packed = new byte[BrotliEncoder.GetMaxCompressedLength(raw.Length)];
if (!BrotliEncoder.TryCompress(raw, packed, out int written, quality: 4, window: 22)) throw new ProtocolException("compressione del chunk fallita");
w.U8(1); // compressione: 1 = Brotli
w.Bytes(packed.AsSpan(0, written));
w.Flags(0);
}
public static MapChunk Read(ref SpanReader r)
{
int cx = r.I32(), cy = r.I32(), width = r.I32(), height = r.I32();
if (width <= 0 || height <= 0 || width > 1024 || height > 1024) throw new ProtocolException("dimensioni del chunk non valide");
int n = width * height;
byte compression = r.U8();
byte[] packed = r.Bytes();
var raw = new byte[n * 4];
if (compression == 1)
{
if (!BrotliDecoder.TryDecompress(packed, raw, out int written) || written != raw.Length) throw new ProtocolException("chunk corrotto");
}
else if (compression == 0 && packed.Length == raw.Length) packed.CopyTo(raw, 0);
else throw new ProtocolException($"compressione sconosciuta: {compression}");
var heights = new ushort[n];
for (int i = 0; i < n; i++) heights[i] = (ushort)(raw[2 * i] | raw[2 * i + 1] << 8);
r.Flags();
return new MapChunk
{
Cx = cx, Cy = cy, Width = width, Height = height, Heights = heights,
Types = raw.AsSpan(2 * n, n).ToArray(), RiverWidth = raw.AsSpan(3 * n, n).ToArray(),
};
}
}
/// <summary>Liste di entità comuni a snapshot e delta.</summary>
public sealed class EntityLists
{
public List<CompanyInfo> Companies { get; init; } = [];
public List<TownInfo> Towns { get; init; } = [];
public List<IndustryInfo> Industries { get; init; } = [];
public List<HubInfo> Hubs { get; init; } = [];
public List<NodeInfo> Nodes { get; init; } = [];
public List<StationInfo> Stations { get; init; } = [];
public List<DepotInfo> Depots { get; init; } = [];
public List<LineInfo> Lines { get; init; } = [];
public List<VehicleInfo> Vehicles { get; init; } = [];
public List<TrainInfo> Trains { get; init; } = [];
public int TotalCount => Companies.Count + Towns.Count + Industries.Count + Hubs.Count + Nodes.Count + Stations.Count + Depots.Count + Lines.Count + Vehicles.Count + Trains.Count;
public void Write(ref SpanWriter w)
{
w.Count(Companies.Count); foreach (var x in Companies) x.Write(ref w);
w.Count(Towns.Count); foreach (var x in Towns) x.Write(ref w);
w.Count(Industries.Count); foreach (var x in Industries) x.Write(ref w);
w.Count(Hubs.Count); foreach (var x in Hubs) x.Write(ref w);
w.Count(Nodes.Count); foreach (var x in Nodes) x.Write(ref w);
w.Count(Stations.Count); foreach (var x in Stations) x.Write(ref w);
w.Count(Depots.Count); foreach (var x in Depots) x.Write(ref w);
w.Count(Lines.Count); foreach (var x in Lines) x.Write(ref w);
w.Count(Vehicles.Count); foreach (var x in Vehicles) x.Write(ref w);
w.Count(Trains.Count); foreach (var x in Trains) x.Write(ref w);
}
public static EntityLists Read(ref SpanReader r)
{
var m = new EntityLists();
for (int n = r.Count(), i = 0; i < n; i++) m.Companies.Add(CompanyInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Towns.Add(TownInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Industries.Add(IndustryInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Hubs.Add(HubInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Nodes.Add(NodeInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Stations.Add(StationInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Depots.Add(DepotInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Lines.Add(LineInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Vehicles.Add(VehicleInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Trains.Add(TrainInfo.Read(ref r));
return m;
}
}
/// <summary>Stato completo delle entità (all'ingresso e dopo un caricamento).</summary>
public sealed class EntitySnapshot : IMessage
{
public MessageId Id => MessageId.EntitySnapshot;
public long Tick { get; init; }
public required EntityLists Entities { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Tick);
Entities.Write(ref w);
w.Flags(0);
}
public static EntitySnapshot Read(ref SpanReader r)
{
var m = new EntitySnapshot { Tick = r.I64(), Entities = EntityLists.Read(ref r) };
r.Flags();
return m;
}
}
/// <summary>Entità nuove o cambiate dall'ultimo invio e quelle rimosse.</summary>
public sealed class EntityDelta : IMessage
{
public MessageId Id => MessageId.EntityDelta;
public long Tick { get; init; }
public required EntityLists Changed { get; init; }
public List<(EntityType Type, int Id)> Removed { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I64(Tick);
Changed.Write(ref w);
w.Count(Removed.Count);
foreach (var (type, id) in Removed)
{
w.U8((byte)type);
w.I32(id);
}
w.Flags(0);
}
public static EntityDelta Read(ref SpanReader r)
{
long tick = r.I64();
var changed = EntityLists.Read(ref r);
int n = r.Count();
var removed = new List<(EntityType, int)>(n);
for (int i = 0; i < n; i++) removed.Add(((EntityType)r.U8(), r.I32()));
r.Flags();
return new EntityDelta { Tick = tick, Changed = changed, Removed = removed };
}
}
/// <summary>Archi di binario nuovi o cambiati (opere, cantiere, condizione, segnali) e archi demoliti.</summary>
public sealed class TrackWorks : IMessage
{
public MessageId Id => MessageId.TrackWorks;
public List<EdgeInfo> Edges { get; init; } = [];
public List<int> Removed { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.Count(Edges.Count);
foreach (var e in Edges) e.Write(ref w);
w.Count(Removed.Count);
foreach (int id in Removed) w.I32(id);
w.Flags(0);
}
public static TrackWorks Read(ref SpanReader r)
{
var m = new TrackWorks();
for (int n = r.Count(), i = 0; i < n; i++) m.Edges.Add(EdgeInfo.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Removed.Add(r.I32());
r.Flags();
return m;
}
}
/// <summary>
/// Moto di un treno: tratti dalla coda alla testa e oltre (percorso prenotato), la distanza della
/// testa lungo i tratti e la velocità; il client interpola avanzando la testa a velocità costante.
/// </summary>
public sealed class TrainMotion : IMessage
{
public MessageId Id => MessageId.TrainMotion;
public int TrainId { get; init; }
public long Tick { get; init; }
public byte State { get; init; }
public float Condition { get; init; }
/// <summary>Velocità in m/s di orologio dei treni.</summary>
public float Speed { get; init; }
public float LengthM { get; init; }
public double HeadDistance { get; init; }
public List<MotionSegment> Segments { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(TrainId); w.I64(Tick); w.U8(State); w.F32(Condition); w.F32(Speed); w.F32(LengthM); w.F64(HeadDistance);
w.Count(Segments.Count);
foreach (var s in Segments)
{
w.I32(s.Edge); w.Bool(s.Forward); w.F64(s.FromS); w.F64(s.ToS);
}
w.Flags(0);
}
public static TrainMotion Read(ref SpanReader r)
{
int id = r.I32();
long tick = r.I64();
byte state = r.U8();
float cond = r.F32(), speed = r.F32(), length = r.F32();
double head = r.F64();
int n = r.Count();
var segs = new List<MotionSegment>(n);
for (int i = 0; i < n; i++) segs.Add(new MotionSegment(r.I32(), r.Bool(), r.F64(), r.F64()));
r.Flags();
return new TrainMotion { TrainId = id, Tick = tick, State = state, Condition = cond, Speed = speed, LengthM = length, HeadDistance = head, Segments = segs };
}
}
/// <summary>Resoconto giornaliero: data, conti della compagnia, prezzi, eventi del giorno, hash di stato.</summary>
public sealed class DailyDigest : IMessage
{
public MessageId Id => MessageId.DailyDigest;
public long Day { get; init; }
public long Tick { get; init; }
public string Date { get; init; } = "";
public Money Cash { get; init; }
public Money NetWorth { get; init; }
public string Rating { get; init; } = "";
public List<Money> Prices { get; init; } = [];
public List<EventInfo> Events { get; init; } = [];
public ulong StateHash { get; init; }
public bool Slow { get; init; }
public byte Speed { get; init; }
public float TickMs { get; init; }
public void Write(ref SpanWriter w)
{
w.I64(Day); w.I64(Tick); w.String(Date); w.Money(Cash); w.Money(NetWorth); w.String(Rating);
w.Count(Prices.Count);
foreach (var p in Prices) w.Money(p);
w.Count(Events.Count);
foreach (var e in Events) e.Write(ref w);
w.U64(StateHash); w.Bool(Slow); w.U8(Speed); w.F32(TickMs);
w.Flags(0);
}
public static DailyDigest Read(ref SpanReader r)
{
long day = r.I64(), tick = r.I64();
string date = r.String();
var cash = r.Money();
var worth = r.Money();
string rating = r.String();
var prices = new List<Money>();
for (int n = r.Count(), i = 0; i < n; i++) prices.Add(r.Money());
var events = new List<EventInfo>();
for (int n = r.Count(), i = 0; i < n; i++) events.Add(EventInfo.Read(ref r));
var m = new DailyDigest
{
Day = day, Tick = tick, Date = date, Cash = cash, NetWorth = worth, Rating = rating, Prices = prices, Events = events,
StateHash = r.U64(), Slow = r.Bool(), Speed = r.U8(), TickMs = r.F32(),
};
r.Flags();
return m;
}
}
/// <summary>Avviso di manutenzione di un treno o di un deposito (F4).</summary>
public sealed class MaintenanceAlert : IMessage
{
public MessageId Id => MessageId.MaintenanceAlert;
public int Train { get; init; } = -1;
public int Depot { get; init; } = -1;
public string Component { get; init; } = "";
public float Condition { get; init; }
public int DueDays { get; init; }
public string Text { get; init; } = "";
public void Write(ref SpanWriter w)
{
w.I32(Train); w.I32(Depot); w.String(Component); w.F32(Condition); w.I32(DueDays); w.String(Text);
w.Flags(0);
}
public static MaintenanceAlert Read(ref SpanReader r)
{
var m = new MaintenanceAlert { Train = r.I32(), Depot = r.I32(), Component = r.String(), Condition = r.F32(), DueDays = r.I32(), Text = r.String() };
r.Flags();
return m;
}
}
/// <summary>Provenienza dei lavoratori di un posto di lavoro (Registro degli impieghi).</summary>
public sealed class EmploymentSource
{
public int Town { get; init; }
public int HomeStation { get; init; } = -1;
/// <summary>Prima linea del percorso (−1 = a piedi).</summary>
public int Line { get; init; } = -1;
public byte Category { get; init; }
public int Headcount { get; init; }
public float Coverage { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Town); w.I32(HomeStation); w.I32(Line); w.U8(Category); w.I32(Headcount); w.F32(Coverage);
w.Flags(0);
}
public static EmploymentSource Read(ref SpanReader r)
{
var m = new EmploymentSource { Town = r.I32(), HomeStation = r.I32(), Line = r.I32(), Category = r.U8(), Headcount = r.I32(), Coverage = r.F32() };
r.Flags();
return m;
}
}
public sealed class EmploymentRow
{
public int Industry { get; init; }
public int JobsWorkers { get; init; }
public int JobsStaff { get; init; }
public float WorkersPresent { get; init; }
public float StaffPresent { get; init; }
public string Reason { get; init; } = "";
public List<EmploymentSource> Sources { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I32(Industry); w.I32(JobsWorkers); w.I32(JobsStaff); w.F32(WorkersPresent); w.F32(StaffPresent); w.String(Reason);
w.Count(Sources.Count);
foreach (var s in Sources) s.Write(ref w);
w.Flags(0);
}
public static EmploymentRow Read(ref SpanReader r)
{
int ind = r.I32(), jw = r.I32(), js = r.I32();
float wp = r.F32(), sp = r.F32();
string reason = r.String();
var sources = new List<EmploymentSource>();
for (int n = r.Count(), i = 0; i < n; i++) sources.Add(EmploymentSource.Read(ref r));
r.Flags();
return new EmploymentRow { Industry = ind, JobsWorkers = jw, JobsStaff = js, WorkersPresent = wp, StaffPresent = sp, Reason = reason, Sources = sources };
}
}
/// <summary>Resoconto mensile del pendolarismo della compagnia.</summary>
public sealed class EmploymentReport : IMessage
{
public MessageId Id => MessageId.EmploymentReport;
public long Day { get; init; }
public List<EmploymentRow> Rows { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I64(Day);
w.Count(Rows.Count);
foreach (var row in Rows) row.Write(ref w);
w.Flags(0);
}
public static EmploymentReport Read(ref SpanReader r)
{
var m = new EmploymentReport { Day = r.I64() };
for (int n = r.Count(), i = 0; i < n; i++) m.Rows.Add(EmploymentRow.Read(ref r));
r.Flags();
return m;
}
}
public sealed class SharePrice
{
public int Company { get; init; }
public Money Price { get; init; }
public float Change { get; init; }
public bool Listed { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Company); w.Money(Price); w.F32(Change); w.Bool(Listed);
w.Flags(0);
}
public static SharePrice Read(ref SpanReader r)
{
var m = new SharePrice { Company = r.I32(), Price = r.Money(), Change = r.F32(), Listed = r.Bool() };
r.Flags();
return m;
}
}
public sealed class BidInfo
{
public int Bid { get; init; }
public int Bidder { get; init; }
public int Target { get; init; }
public Money PricePerShare { get; init; }
public double TargetShare { get; init; }
public long ExpiresDay { get; init; }
public void Write(ref SpanWriter w)
{
w.I32(Bid); w.I32(Bidder); w.I32(Target); w.Money(PricePerShare); w.F64(TargetShare); w.I64(ExpiresDay);
w.Flags(0);
}
public static BidInfo Read(ref SpanReader r)
{
var m = new BidInfo { Bid = r.I32(), Bidder = r.I32(), Target = r.I32(), PricePerShare = r.Money(), TargetShare = r.F64(), ExpiresDay = r.I64() };
r.Flags();
return m;
}
}
/// <summary>Listino giornaliero della borsa e offerte pubbliche in corso (F5).</summary>
public sealed class MarketTape : IMessage
{
public MessageId Id => MessageId.MarketTape;
public long Day { get; init; }
public List<SharePrice> Shares { get; init; } = [];
public List<BidInfo> Bids { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I64(Day);
w.Count(Shares.Count);
foreach (var s in Shares) s.Write(ref w);
w.Count(Bids.Count);
foreach (var b in Bids) b.Write(ref w);
w.Flags(0);
}
public static MarketTape Read(ref SpanReader r)
{
var m = new MarketTape { Day = r.I64() };
for (int n = r.Count(), i = 0; i < n; i++) m.Shares.Add(SharePrice.Read(ref r));
for (int n = r.Count(), i = 0; i < n; i++) m.Bids.Add(BidInfo.Read(ref r));
r.Flags();
return m;
}
}
/// <summary>Esito di un comando, con il numero di sequenza del client e gli id creati.</summary>
public sealed class CommandResultMessage : IMessage
{
public MessageId Id => MessageId.CommandResult;
public uint Seq { get; init; }
public ushort Type { get; init; }
public ushort Error { get; init; }
public string Message { get; init; } = "";
public int[] Created { get; init; } = [];
public long Tick { get; init; }
public bool Ok => Error == 0;
public void Write(ref SpanWriter w)
{
w.U32(Seq); w.U16(Type); w.U16(Error); w.String(Message);
w.Count(Created.Length);
foreach (int c in Created) w.I32(c);
w.I64(Tick);
w.Flags(0);
}
public static CommandResultMessage Read(ref SpanReader r)
{
uint seq = r.U32();
ushort type = r.U16(), error = r.U16();
string message = r.String();
var created = new int[r.Count()];
for (int i = 0; i < created.Length; i++) created[i] = r.I32();
var m = new CommandResultMessage { Seq = seq, Type = type, Error = error, Message = message, Created = created, Tick = r.I64() };
r.Flags();
return m;
}
}
/// <summary>Notifica immediata (evento rilevante per la compagnia della sessione).</summary>
public sealed class Notification : IMessage
{
public MessageId Id => MessageId.Notification;
public required EventInfo Event { get; init; }
public void Write(ref SpanWriter w)
{
Event.Write(ref w);
w.Flags(0);
}
public static Notification Read(ref SpanReader r)
{
var m = new Notification { Event = EventInfo.Read(ref r) };
r.Flags();
return m;
}
}
/// <summary>La «Cronaca» mensile.</summary>
public sealed class Newspaper : IMessage
{
public MessageId Id => MessageId.Newspaper;
public long Day { get; init; }
public string Title { get; init; } = "";
public List<(string Headline, string Body)> Articles { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.I64(Day);
w.String(Title);
w.Count(Articles.Count);
foreach (var (h, b) in Articles)
{
w.String(h);
w.String(b);
}
w.Flags(0);
}
public static Newspaper Read(ref SpanReader r)
{
var m = new Newspaper { Day = r.I64(), Title = r.String() };
for (int n = r.Count(), i = 0; i < n; i++) m.Articles.Add((r.String(), r.String()));
r.Flags();
return m;
}
}
public sealed class SaveInfo
{
public string SaveId { get; init; } = "";
public string Name { get; init; } = "";
public string GameDate { get; init; } = "";
public long SizeBytes { get; init; }
public long SavedUnixMs { get; init; }
public bool Autosave { get; init; }
public void Write(ref SpanWriter w)
{
w.String(SaveId); w.String(Name); w.String(GameDate); w.I64(SizeBytes); w.I64(SavedUnixMs); w.Bool(Autosave);
w.Flags(0);
}
public static SaveInfo Read(ref SpanReader r)
{
var m = new SaveInfo { SaveId = r.String(), Name = r.String(), GameDate = r.String(), SizeBytes = r.I64(), SavedUnixMs = r.I64(), Autosave = r.Bool() };
r.Flags();
return m;
}
}
/// <summary>Risposta a ListSaves e a Save (salvataggi disponibili sul server).</summary>
public sealed class SaveList : IMessage
{
public MessageId Id => MessageId.SaveList;
public List<SaveInfo> Saves { get; init; } = [];
public void Write(ref SpanWriter w)
{
w.Count(Saves.Count);
foreach (var s in Saves) s.Write(ref w);
w.Flags(0);
}
public static SaveList Read(ref SpanReader r)
{
var m = new SaveList();
for (int n = r.Count(), i = 0; i < n; i++) m.Saves.Add(SaveInfo.Read(ref r));
r.Flags();
return m;
}
}
+86
View File
@@ -0,0 +1,86 @@
using System.Buffers.Binary;
using System.Text;
using ViaFerrea.Core.Common;
namespace ViaFerrea.Protocol;
/// <summary>Errore di decodifica: frame troncato, valore fuori dai limiti o messaggio sconosciuto.</summary>
public sealed class ProtocolException(string message) : Exception(message);
/// <summary>Lettore binario little endian con controllo dei limiti (vedi <see cref="SpanWriter"/>).</summary>
public ref struct SpanReader(ReadOnlySpan<byte> data)
{
private readonly ReadOnlySpan<byte> _data = data;
private int _position;
/// <summary>Limite di sicurezza per i conteggi delle liste.</summary>
public const int MaxCount = 4 * 1024 * 1024;
public readonly int Remaining => _data.Length - _position;
public readonly int Position => _position;
private ReadOnlySpan<byte> Take(int n)
{
if (n < 0 || _position + n > _data.Length) throw new ProtocolException("messaggio troncato");
var span = _data.Slice(_position, n);
_position += n;
return span;
}
public bool Bool()
{
byte b = U8();
return b switch
{
0 => false,
1 => true,
_ => throw new ProtocolException($"booleano non valido: {b}"),
};
}
public byte U8() => Take(1)[0];
public ushort U16() => BinaryPrimitives.ReadUInt16LittleEndian(Take(2));
public uint U32() => BinaryPrimitives.ReadUInt32LittleEndian(Take(4));
public ulong U64() => BinaryPrimitives.ReadUInt64LittleEndian(Take(8));
public short I16() => BinaryPrimitives.ReadInt16LittleEndian(Take(2));
public int I32() => BinaryPrimitives.ReadInt32LittleEndian(Take(4));
public long I64() => BinaryPrimitives.ReadInt64LittleEndian(Take(8));
public float F32() => BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(Take(4)));
public double F64() => BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(Take(8)));
public ulong VarUInt()
{
ulong result = 0;
for (int shift = 0; shift < 64; shift += 7)
{
byte b = U8();
result |= (ulong)(b & 0x7F) << shift;
if ((b & 0x80) == 0) return result;
}
throw new ProtocolException("varuint troppo lungo");
}
/// <summary>Conteggio di una lista, entro <see cref="MaxCount"/> e i byte residui.</summary>
public int Count()
{
ulong n = VarUInt();
if (n > MaxCount || n > (ulong)Math.Max(0, Remaining) * 8 + 8) throw new ProtocolException($"conteggio non plausibile: {n}");
return (int)n;
}
public string String()
{
int n = Count();
return Encoding.UTF8.GetString(Take(n));
}
public byte[] Bytes() => Take(Count()).ToArray();
public Money Money() => new(I64());
public Vec2 Vec2() => new(F64(), F64());
/// <summary>Byte di estensione: assente nei messaggi più vecchi (vale 0).</summary>
public byte Flags() => Remaining > 0 ? U8() : (byte)0;
}
+107
View File
@@ -0,0 +1,107 @@
using System.Buffers.Binary;
using System.Text;
using ViaFerrea.Core.Common;
namespace ViaFerrea.Protocol;
/// <summary>
/// Scrittore binario little endian su un buffer che cresce. Le lunghezze e i conteggi sono
/// varuint (LEB128), le stringhe UTF-8 con lunghezza in byte. Nessuna reflection.
/// </summary>
public ref struct SpanWriter
{
private byte[] _buffer;
private int _position;
public SpanWriter(int capacity)
{
_buffer = new byte[Math.Max(16, capacity)];
_position = 0;
}
public SpanWriter(byte[] buffer)
{
_buffer = buffer;
_position = 0;
}
public readonly int Length => _position;
public readonly ReadOnlySpan<byte> Written => _buffer.AsSpan(0, _position);
public readonly byte[] ToArray() => _buffer.AsSpan(0, _position).ToArray();
/// <summary>Riserva n byte e restituisce lo spazio da riempire.</summary>
public Span<byte> Reserve(int n)
{
Ensure(n);
var span = _buffer.AsSpan(_position, n);
_position += n;
return span;
}
/// <summary>Riscrive un u32 in una posizione già scritta (lunghezze dei frame).</summary>
public readonly void PatchU32(int offset, uint value) => BinaryPrimitives.WriteUInt32LittleEndian(_buffer.AsSpan(offset, 4), value);
private void Ensure(int n)
{
if (_position + n <= _buffer.Length) return;
int size = Math.Max(_buffer.Length * 2, _position + n);
Array.Resize(ref _buffer, size);
}
public void Bool(bool v) => U8(v ? (byte)1 : (byte)0);
public void U8(byte v)
{
Ensure(1);
_buffer[_position++] = v;
}
public void U16(ushort v) => BinaryPrimitives.WriteUInt16LittleEndian(Reserve(2), v);
public void U32(uint v) => BinaryPrimitives.WriteUInt32LittleEndian(Reserve(4), v);
public void U64(ulong v) => BinaryPrimitives.WriteUInt64LittleEndian(Reserve(8), v);
public void I16(short v) => BinaryPrimitives.WriteInt16LittleEndian(Reserve(2), v);
public void I32(int v) => BinaryPrimitives.WriteInt32LittleEndian(Reserve(4), v);
public void I64(long v) => BinaryPrimitives.WriteInt64LittleEndian(Reserve(8), v);
public void F32(float v) => BinaryPrimitives.WriteInt32LittleEndian(Reserve(4), BitConverter.SingleToInt32Bits(v));
public void F64(double v) => BinaryPrimitives.WriteInt64LittleEndian(Reserve(8), BitConverter.DoubleToInt64Bits(v));
public void VarUInt(ulong v)
{
while (v >= 0x80)
{
U8((byte)(v | 0x80));
v >>= 7;
}
U8((byte)v);
}
/// <summary>Conteggio di una lista (varuint).</summary>
public void Count(int n) => VarUInt((ulong)n);
public void String(string? s)
{
s ??= "";
int n = Encoding.UTF8.GetByteCount(s);
Count(n);
Encoding.UTF8.GetBytes(s, Reserve(n));
}
public void Bytes(ReadOnlySpan<byte> bytes)
{
Count(bytes.Length);
bytes.CopyTo(Reserve(bytes.Length));
}
public void Money(Money m) => I64(m.Cents);
public void Vec2(Vec2 v)
{
F64(v.X);
F64(v.Y);
}
/// <summary>Byte di estensione in coda al messaggio: i campi futuri seguono i bit impostati.</summary>
public void Flags(byte flags) => U8(flags);
}
@@ -3,8 +3,9 @@
<!-- Frame binari del protocollo WebSocket, condivisi da server e client. -->
<PropertyGroup>
<TargetFrameworks>net10.0;net8.0</TargetFrameworks>
<!-- Immagine del server: solo net10.0, così la build non scarica il targeting pack net8.0 (ADR 0009). -->
<TargetFrameworks Condition="'$(VfServerOnly)' == 'true'">net10.0</TargetFrameworks>
<RootNamespace>ViaFerrea.Protocol</RootNamespace>
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
<ItemGroup>
+667
View File
@@ -0,0 +1,667 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
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;
// 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();
}
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 => _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);
}
/// <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 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);
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,
});
}
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(EmploymentReport(w, s.Company));
}
_monthlyDue = false;
_dayEvents.Clear();
}
/// <summary>Registro degli impieghi della compagnia: posti serviti dai suoi treni e provenienze.</summary>
private static EmploymentReport EmploymentReport(World w, CompanyId company)
{
var report = new EmploymentReport { Day = w.Clock.Day };
foreach (var ind in w.Industries)
{
if (ind.Closed) continue;
var sources = new List<EmploymentSource>();
foreach (var c in w.Commutes)
{
if (c.Walking || c.Carrier != company || c.Workplace.Kind != Core.Economy.WorkplaceKind.Industry || c.Workplace.Index != ind.Id.Value) continue;
sources.Add(new EmploymentSource
{
Town = c.Town.Value, HomeStation = c.HomeStation.Value, Line = c.Route.Count > 0 ? c.Route[0].Value : -1,
Category = (byte)c.Category, Headcount = c.Headcount, Coverage = (float)c.Coverage,
});
}
if (sources.Count == 0) continue;
report.Rows.Add(new EmploymentRow
{
Industry = ind.Id.Value, JobsWorkers = ind.JobsWorkers, JobsStaff = ind.JobsStaff,
WorkersPresent = (float)ind.WorkersPresent, StaffPresent = (float)ind.StaffPresent, Sources = sources,
});
}
return report;
}
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();
}
}
+104 -6
View File
@@ -1,17 +1,115 @@
using System.Net.Http;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Simulation;
using ProtocolSaveInfo = ViaFerrea.Protocol.Messages.SaveInfo;
namespace ViaFerrea.Server;
/// <summary>
/// Punto d'ingresso del server autorevole. In F0 espone solo /health; il ciclo di gioco,
/// le sessioni WebSocket e le API dei salvataggi arrivano in F3.
/// Server autorevole di Via Ferrea: Kestrel con WebSocket su /ws, API HTTP (/health, /metrics,
/// /api/saves), ciclo di gioco su un thread dedicato, log JSON su stdout.
/// </summary>
public static class ServerProgram
{
public static int Main(string[] args)
{
var builder = WebApplication.CreateSlimBuilder(args);
var app = builder.Build();
app.MapGet("/health", () => Results.Text("ok"));
app.Run();
var config = ServerConfig.From(args, Environment.GetEnvironmentVariables());
if (config.HealthCheck) return HealthCheck(config);
using var app = Build(config, args);
app.Start();
if (config.Local)
{
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses;
int port = new Uri(addresses.First()).Port;
Console.Out.WriteLine($"LISTENING {port}");
Console.Out.Flush();
}
app.WaitForShutdown();
return 0;
}
/// <summary>Costruisce l'applicazione; i test la avviano in processo su una porta casuale.</summary>
public static WebApplication Build(ServerConfig config, string[]? args = null, World? world = null, GameData? data = null)
{
var builder = WebApplication.CreateSlimBuilder(args ?? []);
builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole(o =>
{
o.IncludeScopes = false;
o.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
o.UseUtcTimestamp = true;
o.JsonWriterOptions = new System.Text.Json.JsonWriterOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
});
builder.Logging.SetMinimumLevel(Enum.TryParse<LogLevel>(config.LogLevel, true, out var level) ? level : LogLevel.Information);
builder.WebHost.UseUrls(config.Local ? "http://127.0.0.1:0" : $"http://0.0.0.0:{config.Port}");
builder.Services.AddSingleton<HostHolder>();
builder.Services.ConfigureHttpJsonOptions(o =>
{
o.SerializerOptions.TypeInfoResolverChain.Insert(0, ServerJsonContext.Default);
o.SerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
});
var app = builder.Build();
var log = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("ViaFerrea.Server");
data ??= GameData.LoadDefault();
log.LogInformation("Dati caricati: hash {Hash:x16}", data.Hash);
var host = new GameHost(config, data, log, world);
app.Lifetime.ApplicationStarted.Register(host.Start);
app.Lifetime.ApplicationStopping.Register(host.Dispose);
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) });
app.Map("/ws", context => SessionEndpoint.HandleAsync(context, host, log));
app.MapGet("/health", () => host.Healthy ? Results.Text("ok") : Results.Text("ciclo di gioco fermo", statusCode: 503));
app.MapGet("/metrics", () => Results.Text(host.Metrics(), "text/plain; version=0.0.4"));
app.MapGet("/api/saves", () => Results.Json(host.Saves.List().Select(SaveDto.From).ToList(), Json.ListSaveDto));
app.MapGet("/api/saves/{id}", (string id) =>
host.Saves.Exists(id) ? Results.File(host.Saves.PathOf(id), "application/octet-stream", Path.GetFileName(host.Saves.PathOf(id))) : Results.NotFound());
app.MapPost("/api/saves", async (string? name) =>
{
var info = await host.InvokeAsync(_ => host.SaveNow(string.IsNullOrWhiteSpace(name) ? "partita" : name));
return Results.Json(SaveDto.From(info), Json.SaveDto, statusCode: StatusCodes.Status201Created);
});
app.Services.GetRequiredService<HostHolder>().Host = host;
return app;
}
private static readonly ServerJsonContext Json = new(new System.Text.Json.JsonSerializerOptions
{
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
});
private static int HealthCheck(ServerConfig config)
{
try
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(4) };
var response = http.GetAsync($"http://127.0.0.1:{config.Port}/health").GetAwaiter().GetResult();
return response.IsSuccessStatusCode ? 0 : 1;
}
catch (Exception)
{
return 1;
}
}
}
/// <summary>Riferimento al GameHost per i test in processo.</summary>
public sealed class HostHolder
{
public GameHost? Host { get; set; }
}
/// <summary>Descrizione di un salvataggio nell'API HTTP.</summary>
public sealed record SaveDto(string Id, string Name, string GameDate, long SizeBytes, long SavedUnixMs, bool Autosave)
{
public static SaveDto From(ProtocolSaveInfo s) => new(s.SaveId, s.Name, s.GameDate, s.SizeBytes, s.SavedUnixMs, s.Autosave);
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
[JsonSerializable(typeof(SaveDto))]
[JsonSerializable(typeof(List<SaveDto>))]
internal sealed partial class ServerJsonContext : JsonSerializerContext;
+256
View File
@@ -0,0 +1,256 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Server;
/// <summary>
/// Proiezione del mondo autorevole nei record del protocollo. Gira sul thread del ciclo di gioco:
/// legge il mondo, non lo modifica.
/// </summary>
public static class Projection
{
public static WorldSummary Summary(World w, Company company, byte speed) => new()
{
Seed = w.Settings.Seed,
SizeKm = w.Settings.SizeKm,
StartYear = w.Settings.StartYear,
Tick = w.Clock.Tick,
Date = w.Clock.Date.ToString(),
CompanyId = company.Id.Value,
CompanyName = company.Name,
RegionId = w.Settings.RegionId,
WidthCells = w.Terrain.Width,
HeightCells = w.Terrain.Height,
CellSizeM = w.Terrain.CellSizeM,
ChunkCells = w.Terrain.ChunkCells,
Speed = speed,
TerrainHash = w.Terrain.ComputeHash(),
CostMultiplier = RailCommandHandlers.CostMultiplier(w, company),
};
public static MapChunk Chunk(World w, int cx, int cy)
{
var t = w.Terrain;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int width = Math.Min(t.ChunkCells, t.Width - x0), height = Math.Min(t.ChunkCells, t.Height - y0);
var heights = new ushort[width * height];
var types = new byte[width * height];
var river = new byte[width * height];
for (int y = 0; y < height; y++)
{
int src = (y0 + y) * t.Width + x0;
t.Heights.AsSpan(src, width).CopyTo(heights.AsSpan(y * width));
t.Types.AsSpan(src, width).CopyTo(types.AsSpan(y * width));
t.RiverWidth.AsSpan(src, width).CopyTo(river.AsSpan(y * width));
}
return new MapChunk { Cx = cx, Cy = cy, Width = width, Height = height, Heights = heights, Types = types, RiverWidth = river };
}
/// <summary>Hash del contenuto di un chunk (per rimandarlo quando l'abitato o un'industria cambia il terreno).</summary>
public static ulong ChunkHash(World w, int cx, int cy)
{
var t = w.Terrain;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int width = Math.Min(t.ChunkCells, t.Width - x0), height = Math.Min(t.ChunkCells, t.Height - y0);
ulong h = 0;
for (int y = 0; y < height; y++)
{
int src = (y0 + y) * t.Width + x0;
h = XxHash64.Hash(t.Types.AsSpan(src, width), h);
h = XxHash64.Hash(System.Runtime.InteropServices.MemoryMarshal.AsBytes(t.Heights.AsSpan(src, width)), h);
}
return h;
}
/// <summary>Tutte le entità visibili a una compagnia (in F3: tutte).</summary>
public static EntityLists Entities(World w)
{
var net = w.Network;
var e = new EntityLists();
foreach (var c in w.Companies)
{
e.Companies.Add(new CompanyInfo
{
Id = c.Id.Value, Name = c.Name, Color = c.Color, IsPlayer = c.IsPlayer, Cash = c.Cash, NetWorth = c.NetWorth,
Rating = c.Rating.ToString(), Tier = (byte)c.Tier, Bankrupt = c.Bankrupt,
});
}
foreach (var t in w.Towns)
{
e.Towns.Add(new TownInfo
{
Id = t.Id.Value, Name = t.Name, Position = t.Position, Population = t.Population, RadiusCells = t.RadiusCells,
Satisfaction = (float)t.OverallSatisfaction, Services = t.Services,
});
}
foreach (var i in w.Industries)
{
e.Industries.Add(new IndustryInfo
{
Id = i.Id.Value, Type = i.Def.Id, Name = i.Name, Position = i.Position, FootprintCells = i.FootprintCells, Level = i.Level,
Closed = i.Closed, Efficiency = (float)i.Efficiency, Condition = (float)i.Condition, Owner = i.Owner.IsValid ? i.Owner.Value : -1,
});
}
foreach (var h in w.Hubs)
e.Hubs.Add(new HubInfo { Id = h.Id.Value, Kind = h.Kind.ToString().ToLowerInvariant(), Name = h.Name, Position = h.Position });
foreach (var n in net.Nodes)
{
if (n.Removed) continue;
e.Nodes.Add(new NodeInfo
{
Id = n.Id.Value, Position = n.Position, HeightM = n.HeightM, Owner = n.Owner.Value, Station = n.Station.Value, Depot = n.Depot.Value,
Edges = n.Edges.Select(x => x.Value).ToArray(),
});
}
foreach (var s in net.Stations)
{
if (!net.IsAlive(s)) continue;
int waiting = 0;
foreach (var p in s.Waiting) waiting += p.Units;
e.Stations.Add(new StationInfo
{
Id = s.Id.Value, Owner = s.Owner.Value, Name = s.Name, Node = s.Node.Value, Position = s.Position, Platforms = s.Platforms,
WaitingUnits = waiting, Industries = s.Industries.Select(x => x.Value).ToArray(), Towns = s.Towns.Select(x => x.Value).ToArray(),
});
}
foreach (var d in net.Depots)
{
if (!net.IsAlive(d)) continue;
e.Depots.Add(new DepotInfo { Id = d.Id.Value, Owner = d.Owner.Value, Name = d.Name, Node = d.Node.Value, Position = d.Position, Size = d.Size });
}
foreach (var l in w.Lines)
{
if (l.Removed) continue;
e.Lines.Add(new LineInfo { Id = l.Id.Value, Owner = l.Owner.Value, Name = l.Name, Color = l.Color, Stops = l.Stops.ToArray() });
}
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
double cond = v.Components.Length == 0 ? 100 : v.Components.Min();
e.Vehicles.Add(new VehicleInfo { Id = v.Id.Value, Owner = v.Owner.Value, Type = v.Def.Id, Depot = v.Depot.Value, Train = v.Train.Value, Condition = (float)cond });
}
foreach (var t in w.Trains)
{
if (t.Removed) continue;
int load = 0, capacity = 0;
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
load += v.Load + v.Pax;
capacity += (v.Def.Capacity ?? 0) + (v.Def.PaxCapacity ?? 0);
}
var atDepot = t.AtNode.IsValid ? net.Nodes[t.AtNode.Value].Depot : DepotId.None;
e.Trains.Add(new TrainInfo
{
Id = t.Id.Value, Owner = t.Owner.Value, Name = t.Name, Line = t.Line.Value, State = (byte)t.State,
Vehicles = t.Vehicles.Select(x => x.Value).ToArray(), MaxSpeedKmh = (float)t.MaxSpeedKmh, LengthM = (float)t.LengthM,
Load = load, Capacity = capacity, Depot = atDepot.Value,
});
}
return e;
}
public static EdgeInfo Edge(World w, TrackEdge e)
{
float progress = 1;
if (e.Project >= 0 && e.Project < w.Network.Projects.Count)
{
var p = w.Network.Projects[e.Project];
if (!p.Done) progress = (float)Math.Clamp(p.ProgressDays / Math.Max(1, p.TotalDays), 0, 1);
}
return new EdgeInfo
{
Id = e.Id.Value, Owner = e.Owner.Value, A = e.A.Value, B = e.B.Value, TrackClass = (byte)e.TrackClass, DoubleTrack = e.DoubleTrack,
Electrified = e.Electrified, State = (byte)e.State, Condition = (float)e.Condition, StructureCondition = (float)e.StructureCondition,
Progress = progress, S = e.S, X = e.X, Y = e.Y, H = e.H, Ground = e.Ground, Kinds = e.Kinds.Select(k => (byte)k).ToArray(),
SpeedLimitKmh = e.SpeedLimitKmh, Signals = e.Signals.ToArray(),
};
}
/// <summary>
/// Moto di un treno: i passi del percorso dalla coda (testa meno lunghezza) fino al tratto
/// prenotato, con la distanza della testa misurata dal primo passo incluso.
/// </summary>
public static TrainMotion? Motion(World w, Train t)
{
if (t.Removed || t.Route.Count == 0 || t.State == TrainState.InDepot) return null;
var net = w.Network;
int index = Math.Clamp(t.RouteIndex, 0, t.Route.Count - 1);
double headInStep = Math.Min(t.StepPos, net.Edges[t.Route[index].Edge.Value].Length);
// risale fino al passo che contiene la coda
int first = index;
double behind = t.LengthM - headInStep;
while (behind > 0 && first > 0)
{
first--;
behind -= net.Edges[t.Route[first].Edge.Value].Length;
}
int last = Math.Clamp(Math.Max(index, t.ReservedStep), index, t.Route.Count - 1);
var segments = new List<MotionSegment>(last - first + 1);
double head = 0;
for (int i = first; i <= last; i++)
{
var step = t.Route[i];
double len = net.Edges[step.Edge.Value].Length;
segments.Add(step.Forward ? new MotionSegment(step.Edge.Value, true, 0, len) : new MotionSegment(step.Edge.Value, false, len, 0));
if (i < index) head += len;
}
head += headInStep;
double cond = 100;
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
foreach (double c in v.Components) cond = Math.Min(cond, c);
}
return new TrainMotion
{
TrainId = t.Id.Value, Tick = w.Clock.Tick, State = (byte)t.State, Condition = (float)cond, Speed = (float)t.Speed,
LengthM = (float)t.LengthM, HeadDistance = head, Segments = segments,
};
}
/// <summary>Punto della testa del treno sul server (riferimento dei test di coerenza).</summary>
public static Vec2? HeadPoint(World w, Train t)
{
if (t.Route.Count == 0) return t.AtNode.IsValid ? w.Network.Nodes[t.AtNode.Value].Position : null;
int index = Math.Clamp(t.RouteIndex, 0, t.Route.Count - 1);
var step = t.Route[index];
var edge = w.Network.Edges[step.Edge.Value];
double s = Math.Min(t.StepPos, edge.Length);
return edge.PointAt(step.Forward ? s : edge.Length - s);
}
public static EventInfo Event(GameEvent e) => new()
{
Day = e.Day, Kind = (byte)e.Kind, Severity = (byte)e.Severity, Text = e.Text, Entity = (byte)e.Entity, EntityIndex = e.EntityIndex,
Company = e.Company.IsValid ? e.Company.Value : -1,
};
public static DailyDigest Digest(World w, Company company, List<EventInfo> events, bool slow, byte speed, float tickMs) => new()
{
Day = w.Clock.Day,
Tick = w.Clock.Tick,
Date = w.Clock.Date.ToString(),
Cash = company.Cash,
NetWorth = company.NetWorth,
Rating = company.Rating.ToString(),
Prices = w.Market.GlobalPrice.Select(p => Money.FromCentsRounded(p)).ToList(),
Events = events,
StateHash = w.LastStateHash,
Slow = slow,
Speed = speed,
TickMs = tickMs,
};
/// <summary>Hash di un record serializzato (per i delta per sessione).</summary>
public static ulong Hash(IWritable record)
{
var w = new SpanWriter(128);
record.Write(ref w);
return XxHash64.Hash(w.Written);
}
}
+95
View File
@@ -0,0 +1,95 @@
using System.Globalization;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ProtocolSaveInfo = ViaFerrea.Protocol.Messages.SaveInfo;
namespace ViaFerrea.Server;
/// <summary>
/// Salvataggi in <c>$VF_DATA_DIR/saves</c>: file <c>.vfsave</c>; i salvataggi automatici ruotano
/// sugli ultimi cinque. L'id di un salvataggio è il nome del file senza estensione.
/// </summary>
public sealed class SaveStore(string directory, string gameVersion)
{
public const string Extension = ".vfsave";
public const string AutosavePrefix = "autosave-";
public const int AutosaveKeep = 5;
public string Directory { get; } = directory;
public string PathOf(string id) => System.IO.Path.Combine(Directory, SaveFile.SafeFileName(id) + Extension);
public bool Exists(string id) => File.Exists(PathOf(id));
public ProtocolSaveInfo Save(World w, string name)
{
System.IO.Directory.CreateDirectory(Directory);
string stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
string id = $"{SaveFile.SafeFileName(name)}-{stamp}";
return Write(w, id);
}
/// <summary>Salvataggio automatico con rotazione.</summary>
public ProtocolSaveInfo Autosave(World w)
{
System.IO.Directory.CreateDirectory(Directory);
string stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss-fff", CultureInfo.InvariantCulture);
var info = Write(w, AutosavePrefix + stamp);
var old = List().Where(s => s.Autosave).OrderByDescending(s => s.SavedUnixMs).ThenByDescending(s => s.SaveId, StringComparer.Ordinal).Skip(AutosaveKeep);
foreach (var s in old) File.Delete(PathOf(s.SaveId));
return info;
}
private ProtocolSaveInfo Write(World w, string id)
{
string path = PathOf(id);
string temp = path + ".tmp";
SaveFile.SaveToFile(w, temp, gameVersion);
File.Move(temp, path, overwrite: true);
return Describe(path) ?? throw new IOException($"Salvataggio illeggibile: {path}");
}
public World Load(GameData data, string id) => SaveFile.LoadFromFile(data, PathOf(id));
public List<ProtocolSaveInfo> List()
{
if (!System.IO.Directory.Exists(Directory)) return [];
var list = new List<ProtocolSaveInfo>();
foreach (string path in System.IO.Directory.GetFiles(Directory, "*" + Extension))
{
var info = Describe(path);
if (info is not null) list.Add(info);
}
list.Sort((a, b) => b.SavedUnixMs != a.SavedUnixMs ? b.SavedUnixMs.CompareTo(a.SavedUnixMs) : string.CompareOrdinal(a.SaveId, b.SaveId));
return list;
}
/// <summary>Il salvataggio automatico più recente, se c'è (ripresa dopo un riavvio del container).</summary>
public string? LatestAutosave() => List().FirstOrDefault(s => s.Autosave)?.SaveId;
private static ProtocolSaveInfo? Describe(string path)
{
try
{
var file = new FileInfo(path);
byte[] head = new byte[Math.Min(file.Length, 4096)];
using (var f = File.OpenRead(path)) f.ReadExactly(head);
var info = SaveFile.ReadInfo(head);
string id = System.IO.Path.GetFileNameWithoutExtension(path);
return new ProtocolSaveInfo
{
SaveId = id,
Name = info.CompanyName,
GameDate = info.Date,
SizeBytes = file.Length,
SavedUnixMs = new DateTimeOffset(file.LastWriteTimeUtc).ToUnixTimeMilliseconds(),
Autosave = id.StartsWith(AutosavePrefix, StringComparison.Ordinal),
};
}
catch (Exception)
{
return null;
}
}
}
+57
View File
@@ -0,0 +1,57 @@
using System.Collections;
namespace ViaFerrea.Server;
/// <summary>
/// Configurazione del server dalle variabili d'ambiente (sezione 14.2) e dagli argomenti
/// <c>--local</c>, <c>--healthcheck</c>, <c>--token</c>, <c>--port</c>, <c>--data</c>.
/// </summary>
public sealed class ServerConfig
{
public int Port { get; init; } = 7400;
public string Token { get; init; } = "";
public string DataDir { get; init; } = "/data";
public int TickMs { get; init; } = 50;
public int AutosaveMinutes { get; init; } = 10;
public ulong Seed { get; init; } = 1;
public int MapSizeKm { get; init; } = 128;
public string Difficulty { get; init; } = "imprenditore";
public string LogLevel { get; init; } = "Information";
/// <summary>Processo locale figlio del client: porta casuale su 127.0.0.1, stampa «LISTENING porta».</summary>
public bool Local { get; init; }
public bool HealthCheck { get; init; }
/// <summary>Numero massimo di sessioni contemporanee.</summary>
public int MaxSessions { get; init; } = 16;
public string SavesDir => Path.Combine(DataDir, "saves");
public static ServerConfig From(string[] args, IDictionary environment)
{
string? Env(string name) => environment[name] as string is { Length: > 0 } v ? v : null;
string? Arg(string name)
{
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] == name) return args[i + 1];
}
return null;
}
bool local = args.Contains("--local");
string dataDir = Arg("--data") ?? Env("VF_DATA_DIR")
?? (local ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ViaFerrea") : "/data");
return new ServerConfig
{
Local = local,
HealthCheck = args.Contains("--healthcheck"),
Port = int.TryParse(Arg("--port") ?? Env("VF_PORT"), out int port) ? port : 7400,
Token = Arg("--token") ?? Env("VF_TOKEN") ?? "",
DataDir = dataDir,
TickMs = int.TryParse(Env("VF_TICK_MS"), out int tick) && tick > 0 ? tick : 50,
AutosaveMinutes = int.TryParse(Env("VF_AUTOSAVE_MIN"), out int auto) ? auto : 10,
Seed = ulong.TryParse(Env("VF_SEED"), out ulong seed) ? seed : 1,
MapSizeKm = int.TryParse(Env("VF_MAP_SIZE"), out int size) ? size : 128,
Difficulty = Env("VF_DIFFICULTY") ?? "imprenditore",
LogLevel = Env("VF_LOG_LEVEL") ?? "Information",
};
}
}
+114
View File
@@ -0,0 +1,114 @@
using System.Net.WebSockets;
using System.Threading.Channels;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Server;
/// <summary>
/// Sessione di un client. La coda d'invio ha due classi: i messaggi affidabili (chunk, entità,
/// esiti, resoconti) non si scartano mai; i moti dei treni si scartano quando la coda supera la
/// soglia (backpressure). Se gli affidabili superano il limite la sessione si chiude: il client
/// può riprenderla con il proprio sessionId.
/// </summary>
public sealed class Session
{
public const long DroppableLimitBytes = 256 * 1024;
public const long ReliableLimitBytes = 64L * 1024 * 1024;
public ulong Id { get; }
public CompanyId Company { get; }
private Channel<byte[]> _queue = Channel.CreateUnbounded<byte[]>(new UnboundedChannelOptions { SingleReader = true });
private long _pendingBytes;
public bool Connected { get; private set; }
public long DisconnectedAtMs { get; private set; }
public long DroppedMotions { get; private set; }
public long SentBytes => Interlocked.Read(ref _sentBytes);
private long _sentBytes;
// ---- stato posseduto dal ciclo di gioco
public Subscribe? Viewport { get; set; }
public HashSet<(int Cx, int Cy)> SentChunks { get; } = [];
public Dictionary<(int Cx, int Cy), ulong> ChunkHashes { get; } = [];
public Dictionary<(EntityType Type, int Id), ulong> EntityHashes { get; } = [];
public Dictionary<int, ulong> EdgeHashes { get; } = [];
public Dictionary<int, (long Tick, byte State)> MotionSent { get; } = [];
public bool NeedsFullState { get; set; } = true;
public Session(ulong id, CompanyId company)
{
Id = id;
Company = company;
}
/// <summary>Riaggancio a un nuovo socket (ripresa): coda nuova, stato da rimandare per intero.</summary>
public void Attach()
{
_queue.Writer.TryComplete();
_queue = Channel.CreateUnbounded<byte[]>(new UnboundedChannelOptions { SingleReader = true });
Interlocked.Exchange(ref _pendingBytes, 0);
Connected = true;
ResetCaches();
}
public void ResetCaches()
{
SentChunks.Clear();
ChunkHashes.Clear();
EntityHashes.Clear();
EdgeHashes.Clear();
MotionSent.Clear();
NeedsFullState = true;
}
public void MarkDisconnected(long nowMs)
{
Connected = false;
DisconnectedAtMs = nowMs;
_queue.Writer.TryComplete();
}
/// <summary>Accoda un messaggio affidabile; false se la sessione va chiusa per backlog.</summary>
public bool Send(IMessage message)
{
if (!Connected) return false;
byte[] frame = Frame.Encode(message);
long pending = Interlocked.Add(ref _pendingBytes, frame.Length);
if (pending > ReliableLimitBytes)
{
_queue.Writer.TryComplete(new IOException("coda d'invio oltre il limite"));
return false;
}
return _queue.Writer.TryWrite(frame);
}
/// <summary>Accoda un messaggio scartabile (moto dei treni) se la coda è sotto soglia.</summary>
public bool SendDroppable(IMessage message)
{
if (!Connected) return false;
if (Interlocked.Read(ref _pendingBytes) > DroppableLimitBytes)
{
DroppedMotions++;
return false;
}
return Send(message);
}
/// <summary>Svuota la coda sul socket finché la sessione resta aperta.</summary>
public async Task SendLoopAsync(WebSocket socket, CancellationToken ct)
{
var reader = _queue.Reader;
while (await reader.WaitToReadAsync(ct).ConfigureAwait(false))
{
while (reader.TryRead(out var frame))
{
await socket.SendAsync(frame, WebSocketMessageType.Binary, true, ct).ConfigureAwait(false);
Interlocked.Add(ref _pendingBytes, -frame.Length);
Interlocked.Add(ref _sentBytes, frame.Length);
}
}
}
}
+123
View File
@@ -0,0 +1,123 @@
using System.Net.WebSockets;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Server;
/// <summary>
/// Endpoint WebSocket <c>/ws</c>: il primo frame dev'essere un Hello (entro 10 s); poi un task
/// riceve i frame e li passa al ciclo di gioco, un altro svuota la coda d'invio della sessione.
/// </summary>
public static class SessionEndpoint
{
private static readonly TimeSpan HelloTimeout = TimeSpan.FromSeconds(10);
public static async Task HandleAsync(HttpContext context, GameHost host, ILogger log)
{
if (!context.WebSockets.IsWebSocketRequest)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("Serve una connessione WebSocket");
return;
}
using var socket = await context.WebSockets.AcceptWebSocketAsync();
var buffer = new MemoryStream();
IMessage? first;
using (var helloTimeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted))
{
helloTimeout.CancelAfter(HelloTimeout);
try
{
first = await ReceiveAsync(socket, buffer, helloTimeout.Token);
}
catch (Exception e) when (e is OperationCanceledException or ProtocolException or WebSocketException)
{
await CloseAsync(socket, WebSocketCloseStatus.PolicyViolation, "Hello mancante o non valido");
return;
}
}
if (first is not Hello hello)
{
await CloseAsync(socket, WebSocketCloseStatus.PolicyViolation, "Il primo messaggio dev'essere Hello");
return;
}
var (session, reject) = await host.OpenSessionAsync(hello);
if (session is null)
{
await socket.SendAsync(Frame.Encode(reject!), WebSocketMessageType.Binary, true, context.RequestAborted);
await CloseAsync(socket, WebSocketCloseStatus.PolicyViolation, reject!.Reason);
log.LogInformation("Sessione rifiutata: {Code} {Reason}", reject.Code, reject.Reason);
return;
}
using var cts = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
var sending = session.SendLoopAsync(socket, cts.Token);
var status = WebSocketCloseStatus.NormalClosure;
string reason = "fine";
try
{
while (socket.State == WebSocketState.Open && !cts.IsCancellationRequested)
{
var message = await ReceiveAsync(socket, buffer, cts.Token);
if (message is null) break;
host.Receive(session, message);
}
}
catch (ProtocolException e)
{
status = e.Message.Contains("4 MB", StringComparison.Ordinal) ? WebSocketCloseStatus.MessageTooBig : WebSocketCloseStatus.InvalidPayloadData;
reason = e.Message;
log.LogWarning("Sessione {Session}: {Error}", session.Id, e.Message);
}
catch (Exception e) when (e is OperationCanceledException or WebSocketException)
{
}
finally
{
host.Detach(session);
cts.Cancel();
try
{
await sending;
}
catch (Exception)
{
// invio interrotto con la connessione
}
await CloseAsync(socket, status, reason);
}
}
/// <summary>Riceve un frame completo (anche frammentato in più parti); null alla chiusura.</summary>
private static async Task<IMessage?> ReceiveAsync(WebSocket socket, MemoryStream buffer, CancellationToken ct)
{
buffer.SetLength(0);
var chunk = new byte[16 * 1024];
while (true)
{
var result = await socket.ReceiveAsync(chunk, ct);
if (result.MessageType == WebSocketMessageType.Close) return null;
if (result.MessageType != WebSocketMessageType.Binary) throw new ProtocolException("solo messaggi binari");
buffer.Write(chunk, 0, result.Count);
if (buffer.Length > Frame.MaxFrameBytes) throw new ProtocolException("frame oltre 4 MB");
if (result.EndOfMessage) return Frame.Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length));
}
}
private static async Task CloseAsync(WebSocket socket, WebSocketCloseStatus status, string reason)
{
try
{
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
string text = reason.Length > 100 ? reason[..100] : reason;
await socket.CloseAsync(status, text, timeout.Token);
}
}
catch (Exception)
{
// il client se n'è già andato
}
}
}
@@ -0,0 +1,213 @@
using System.Diagnostics;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Tools.Commands;
/// <summary>
/// smoke: collaudo di un server in esecuzione (locale o in Docker) con un client vero. Trova un
/// fiume, costruisce due stazioni, un deposito e un binario con ponte usando l'anteprima del
/// client come costo atteso (il server rifiuta se differisce), compra un treno, lo mette in linea
/// e verifica che la posizione interpolata dal client coincida con quella inviata dal server
/// (scarto &lt; 1 cella sui tratti a velocità costante).
/// </summary>
public sealed class SmokeCommand : IToolCommand
{
public string Name => "smoke";
public string Usage => "smoke --url ws://127.0.0.1:7400/ws [--token <t>] [--timeout 600]";
public int Run(CommandLine args)
{
string url = args.String("url", "ws://127.0.0.1:7400/ws");
string token = args.String("token", "");
int timeout = args.Int("timeout", 600);
args.EnsureAllUsed();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeout));
try
{
return RunAsync(new Uri(url), token, cts.Token).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
Console.Error.WriteLine("smoke: tempo scaduto");
return 1;
}
}
private sealed class Session(ProtocolClient connection, ClientWorld world)
{
public ProtocolClient Connection { get; } = connection;
public ClientWorld World { get; } = world;
public Dictionary<uint, CommandResultMessage> Results { get; } = [];
public List<TrainMotion> Motions { get; } = [];
public async Task Until(Func<bool> condition, CancellationToken ct)
{
while (!condition())
{
var m = await Connection.ReceiveAsync(ct);
if (m is CommandResultMessage r) Results[r.Seq] = r;
if (m is TrainMotion tm) Motions.Add(tm);
World.Apply(m);
}
}
public async Task<CommandResultMessage> Do(GameCommand c, CancellationToken ct)
{
uint seq = await Connection.SendCommandAsync(c, ct);
await Until(() => Results.ContainsKey(seq), ct);
return Results[seq];
}
}
private static async Task<int> RunAsync(Uri url, string token, CancellationToken ct)
{
var data = GameData.LoadDefault();
var clock = Stopwatch.StartNew();
await using var connection = await ProtocolClient.ConnectAsync(url, ct);
var welcome = await connection.HandshakeAsync(new Hello { ClientVersion = "smoke", Token = token, DataHash = data.Hash }, ct);
var s = new Session(connection, new ClientWorld(data));
var w = s.World;
w.Apply(welcome);
var summary = welcome.Summary;
Console.WriteLine($"smoke: sessione {welcome.SessionId:x}, mappa {summary.SizeKm} km, {summary.Date}");
await connection.SendAsync(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 }, ct);
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
await s.Until(() => w.Chunks.Count == chunks && w.Companies.Count > 0, ct);
Console.WriteLine($" terreno ricevuto: {chunks} chunk, hash {w.Terrain!.ComputeHash():x16} (server {summary.TerrainHash:x16})");
if (w.Terrain.ComputeHash() != summary.TerrainHash) return Fail("terreno diverso da quello del server");
// capitale: un prestito per stazioni, deposito, binario e treno (il più grande concesso)
for (long lire = 400_000; lire >= 25_000; lire /= 2)
{
var loan = await s.Do(new TakeLoanCommand(Money.FromLire(lire)), ct);
if (!loan.Ok) continue;
Console.WriteLine($" prestito di {Money.FromLire(lire)}");
break;
}
await s.Until(() => w.Companies.TryGetValue(summary.CompanyId, out var c) && c.Cash.Cents > 0, ct);
var site = FindBridgeSite(w);
if (site is null) return Fail("nessun attraversamento di fiume adatto trovato");
var (a, b, depotAt) = site.Value;
Console.WriteLine($" sito: da ({a.X / 1000:F2}, {a.Y / 1000:F2}) a ({b.X / 1000:F2}, {b.Y / 1000:F2}) km");
var sa = await s.Do(new BuildStationCommand(a, 2, "Smoke Ovest"), ct);
var sb = await s.Do(new BuildStationCommand(b, 2, "Smoke Est"), ct);
var sd = await s.Do(new BuildDepotCommand(depotAt, "small", "Smoke Deposito"), ct);
if (!sa.Ok || !sb.Ok || !sd.Ok) return Fail($"stazioni: {sa.Message} / {sb.Message} / {sd.Message}");
await s.Until(() => w.Stations.ContainsKey(sb.Created[0]) && w.Depots.ContainsKey(sd.Created[0]), ct);
var main = new BuildTrackCommand([a, b]);
var preview = w.PreviewTrack(main);
if (!preview.Valid) return Fail("anteprima non valida: " + string.Join("; ", preview.Errors.Select(e => e.Message)));
var built = await s.Do(main with { ExpectedCostCents = preview.TotalCost.Cents }, ct);
if (!built.Ok) return Fail($"binario: {built.Message}");
Console.WriteLine($" binario: {preview.LengthM / 1000:F2} km, ponte {preview.LengthOf(WorkKind.Bridge):F0} m, {preview.TotalCost}, {preview.Days} giorni (anteprima = server)");
int edge = built.Created[0];
await s.Until(() => w.Edges.ContainsKey(edge), ct);
var info = w.Edges[edge];
for (int i = 0; i < info.S.Length; i++)
{
if (info.S.Length != preview.Samples.Count || info.H[i] != preview.Samples[i].TrackM) return Fail($"profilo diverso al campione {i}");
}
var spur = new BuildTrackCommand([depotAt, a]);
var spurPreview = w.PreviewTrack(spur);
var spurBuilt = await s.Do(spur with { ExpectedCostCents = spurPreview.Valid ? spurPreview.TotalCost.Cents : 0 }, ct);
if (!spurBuilt.Ok) return Fail($"raccordo del deposito: {spurBuilt.Message}");
await connection.SendAsync(new SetSpeed { Speed = 8 }, ct);
await s.Until(() => w.Edges.Values.All(e => e.State == (byte)EdgeState.Active), ct);
Console.WriteLine($" cantieri completati: {w.LastDigest?.Date} ({clock.Elapsed.TotalSeconds:F0} s)");
int depot = sd.Created[0];
var loco = await s.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1), ct);
var cars = await s.Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3), ct);
if (!loco.Ok || !cars.Ok) return Fail($"acquisto: {loco.Message} / {cars.Message}");
var train = await s.Do(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(cars.Created).Select(i => new VehicleId(i)).ToList(), "Treno di collaudo"), ct);
var line = await s.Do(new CreateLineCommand("Linea di collaudo", "#e0a526", [new LineStop(new StationId(sa.Created[0])), new LineStop(new StationId(sb.Created[0]))]), ct);
if (!train.Ok || !line.Ok) return Fail($"treno o linea: {train.Message} / {line.Message}");
int trainId = train.Created[0];
var assign = await s.Do(new AssignTrainCommand(new TrainId(trainId), new LineId(line.Created[0])), ct);
if (!assign.Ok) return Fail(assign.Message);
// a velocità 1 si confronta la posizione estrapolata dal client con quella del moto successivo
await connection.SendAsync(new SetSpeed { Speed = 1 }, ct);
var calendar = w.Calendar!;
int pairs = 0;
double worst = 0;
s.Motions.Clear();
await s.Until(() =>
{
var list = s.Motions.Where(m => m.TrainId == trainId).ToList();
pairs = 0;
worst = 0;
for (int i = 1; i < list.Count; i++)
{
var p = list[i - 1];
var q = list[i];
if (p.Speed < 1 || Math.Abs(p.Speed - q.Speed) > 0.05 || q.Tick <= p.Tick || q.Tick - p.Tick > 20) continue;
var predicted = w.TrainHead(p, (q.Tick - p.Tick) * calendar.TrainSecondsPerTick);
var actual = w.PointAlong(q, q.HeadDistance);
if (predicted is null || actual is null) continue;
worst = Math.Max(worst, Vec2.Distance(predicted.Value, actual.Value));
pairs++;
}
return pairs >= 5;
}, ct);
Console.WriteLine($" treno {trainId} in moto: {pairs} confronti, scarto massimo {worst:F2} m (limite {summary.CellSizeM:F0} m)");
await connection.SendAsync(new SetSpeed { Speed = 1 }, ct);
if (worst >= summary.CellSizeM) return Fail("posizione del treno incoerente");
Console.WriteLine($"smoke: ok in {clock.Elapsed.TotalSeconds:F0} s");
return 0;
}
private static int Fail(string why)
{
Console.Error.WriteLine($"smoke: FALLITO — {why}");
return 1;
}
/// <summary>
/// Cerca un attraversamento di fiume rettilineo di 1,5–2,5 km con estremità e deposito su
/// terreno libero e un'anteprima valida con ponte.
/// </summary>
private static (Vec2 A, Vec2 B, Vec2 Depot)? FindBridgeSite(ClientWorld w)
{
var t = w.Terrain!;
var rng = new Rng(7);
bool Free(Vec2 p)
{
if (p.X < 2000 || p.Y < 2000 || p.X > t.WidthM - 2000 || p.Y > t.HeightM - 2000) return false;
var (x, y) = t.CellAt(p);
return (CellType)t.Types[y * t.Width + x] is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill;
}
var rivers = new List<int>();
for (int i = 0; i < t.RiverWidth.Length; i++)
{
if (t.RiverWidth[i] > 0) rivers.Add(i);
}
if (rivers.Count == 0) return null;
for (int attempt = 0; attempt < 400; attempt++)
{
int cell = rivers[rng.NextInt(rivers.Count)];
var center = t.CellCenter(cell % t.Width, cell / t.Width);
double angle = rng.NextDouble(0, Math.PI);
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
double half = rng.NextDouble(750, 1250);
var a = center - dir * half;
var b = center + dir * half;
var depot = a - dir * 600;
if (!Free(a) || !Free(b) || !Free(depot)) continue;
var plan = w.PreviewTrack(new BuildTrackCommand([a, b]));
if (plan.Valid && plan.LengthOf(WorkKind.Bridge) > 0 && plan.Days <= 120) return (a, b, depot);
}
return null;
}
}
+1
View File
@@ -12,6 +12,7 @@ public static class ToolsProgram
new SimulateCommand(),
new ProfileCommand(),
new BenchCommand(),
new SmokeCommand(),
];
public static int Main(string[] args)
@@ -182,7 +182,7 @@ public static class EconomyTests
{
var w = TestWorlds.Small(108);
ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new PendingCommand(CommandType.BuildTrack, []) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new OverhaulIndustryCommand(new IndustryId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults();
@@ -0,0 +1,283 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Protocol;
public static class ProtocolTests
{
private static readonly Vec2 P = new(1234.5, 6789.25);
/// <summary>Un esemplare con campi non predefiniti per ogni messaggio del protocollo.</summary>
public static IEnumerable<IMessage> SampleMessages()
{
yield return new Hello { ClientVersion = "0.1.0", Token = "segreto", ResumeSessionId = 42, DataHash = 0xDEADBEEFUL };
yield return new Ping { Nonce = 7 };
yield return new Subscribe { X0 = -3, Y0 = 4, X1 = 300, Y1 = 200, Lod = 1 };
yield return new CommandMessage { Seq = 99, Command = new BuildStationCommand(P, 3, "Stazione Nord") };
yield return new SetSpeed { Speed = 4 };
yield return new ListSaves();
yield return new Save { Name = "partita è bella" };
yield return new Load { SaveId = "auto-0003" };
yield return new NewGame { Seed = 123, SizeKm = 128, StartYear = 1860, DifficultyPreset = "personalizzata", Overrides = [("wearMultiplier", 1.3), ("aiCompetitors", 2)], EndlessFlags = 0x7F };
yield return new Welcome
{
SessionId = 77,
Summary = new WorldSummary
{
Seed = 5, SizeKm = 64, StartYear = 1850, Tick = 1000, Date = "3 gennaio 1850", CompanyId = 0, CompanyName = "Società",
RegionId = "valdoria", WidthCells = 640, HeightCells = 640, CellSizeM = 100, ChunkCells = 64, Speed = 1, TerrainHash = 99,
},
DataHash = 12345,
Difficulty = "imprenditore",
};
yield return new Reject { Code = RejectCode.BadToken, Reason = "Token errato" };
yield return new Pong { Nonce = 7, ServerTick = 123456 };
yield return SampleChunk();
yield return new EntitySnapshot { Tick = 55, Entities = SampleEntities() };
yield return new EntityDelta { Tick = 56, Changed = SampleEntities(), Removed = [(EntityType.Train, 3), (EntityType.Station, 9)] };
yield return new TrackWorks { Edges = [SampleEdge()], Removed = [4, 5] };
yield return new TrainMotion
{
TrainId = 12, Tick = 999, State = 2, Condition = 87.5f, Speed = 13.4f, LengthM = 71, HeadDistance = 120.5,
Segments = [new MotionSegment(3, true, 10, 300), new MotionSegment(4, false, 500, 0)],
};
yield return new DailyDigest
{
Day = 31, Tick = 7440, Date = "1 febbraio 1850", Cash = new Money(123456789), NetWorth = new Money(-5), Rating = "BBB",
Prices = [new Money(3800), new Money(4200)], Events = [SampleEvent()], StateHash = 0xABCDEF, Slow = true, Speed = 2, TickMs = 0.84f,
};
yield return new MaintenanceAlert { Train = 12, Component = "brakes", Condition = 35, DueDays = 4, Text = "Treno 12: freni al 35 %" };
yield return new EmploymentReport
{
Day = 60,
Rows =
[
new EmploymentRow
{
Industry = 2, JobsWorkers = 40, JobsStaff = 2, WorkersPresent = 39.5f, StaffPresent = 2, Reason = "capacità delle carrozze insufficiente",
Sources = [new EmploymentSource { Town = 1, HomeStation = 3, Line = 1, Category = 0, Headcount = 28, Coverage = 0.97f }],
},
],
};
yield return new MarketTape
{
Day = 90,
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180 }],
};
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
yield return new Notification { Event = SampleEvent() };
yield return new Newspaper { Day = 30, Title = "La Cronaca di Valdoria", Articles = [("Nuova linea", "Inaugurata la linea per il valico."), ("Prezzi", "Il carbone sale.")] };
yield return new SaveList { Saves = [new SaveInfo { SaveId = "s1", Name = "Prima", GameDate = "1 marzo 1851", SizeBytes = 4096, SavedUnixMs = 1_700_000_000_000, Autosave = true }] };
}
private static EventInfo SampleEvent() => new()
{
Day = 31, Kind = 4, Severity = 2, Text = "Treno 12 è fermo da 20 giorni", Entity = 6, EntityIndex = 12, Company = 0,
};
private static MapChunk SampleChunk()
{
int w = 7, h = 5;
var heights = new ushort[w * h];
var types = new byte[w * h];
var river = new byte[w * h];
for (int i = 0; i < heights.Length; i++)
{
heights[i] = (ushort)(i * 997 % 65535);
types[i] = (byte)(i % 11);
river[i] = (byte)(i % 5);
}
return new MapChunk { Cx = 2, Cy = 3, Width = w, Height = h, Heights = heights, Types = types, RiverWidth = river };
}
private static EdgeInfo SampleEdge() => new()
{
Id = 4, Owner = 0, A = 1, B = 2, TrackClass = 1, DoubleTrack = true, Electrified = false, State = 1, Condition = 92, StructureCondition = 100, Progress = 0.4f,
S = [0, 25, 50], X = [0, 25, 50.5], Y = [10, 10, 11], H = [100, 101.25, 102.5], Ground = [100, 99, 103], Kinds = [0, 3, 1], SpeedLimitKmh = [60, 60, 45.5],
Signals = [12.5],
};
private static EntityLists SampleEntities() => new()
{
Companies = [new CompanyInfo { Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2 }],
Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }],
Industries = [new IndustryInfo { Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1 }],
Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }],
Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }],
Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }],
Depots = [new DepotInfo { Id = 0, Owner = 0, Name = "Deposito", Node = 5, Position = P, Size = "small" }],
Lines = [new LineInfo { Id = 0, Owner = 0, Name = "Linea 1", Color = "#e0a526", Stops = [new LineStop(new StationId(1)), new LineStop(new StationId(2), WaitFull: true, MaxWaitDays: 2)] }],
Vehicles = [new VehicleInfo { Id = 7, Owner = 0, Type = "wagon_hopper", Depot = -1, Train = 2, Condition = 99.5f }],
Trains = [new TrainInfo { Id = 2, Owner = 0, Name = "Treno 12", Line = 0, State = 3, Vehicles = [6, 7], MaxSpeedKmh = 60, LengthM = 27, Load = 20, Capacity = 20 }],
};
/// <summary>Un esemplare per ogni tipo di comando, con campi non predefiniti.</summary>
public static IEnumerable<GameCommand> SampleCommands()
{
yield return new BuildTrackCommand([P, P + new Vec2(1000, 0), P + new Vec2(2000, 500)], 1.5, false, true, "c100", true, true, 123456);
yield return new RenewTrackCommand(new EdgeId(3));
yield return new UpgradeTrackCommand(new EdgeId(3), "c160", true, true);
yield return new DemolishCommand(DemolishTarget.Signal, 8);
yield return new BuildStationCommand(P, 4);
yield return new BuildDepotCommand(P, "medium", "Officina");
yield return new PlaceSignalCommand(new EdgeId(2), 812.5);
yield return new BuyVehicleCommand("loco_steam_1850", new DepotId(1), 2);
yield return new SellVehicleCommand(new VehicleId(9));
yield return new ComposeTrainCommand(new DepotId(1), [new VehicleId(1), new VehicleId(2)], "Treno 1");
yield return new CreateLineCommand("Linea 1", "#4f7cac", [new LineStop(new StationId(1), true, false, true, 3), new LineStop(new StationId(2))]);
yield return new EditLineCommand(new LineId(1), [new LineStop(new StationId(2))]);
yield return new AssignTrainCommand(new TrainId(4), LineId.None);
yield return new SendToDepotCommand(new TrainId(4), new DepotId(0));
yield return new SetReserveCommand(new TrainId(4), true);
yield return new SetMaintenancePolicyCommand(MaintenanceScope.Line, 2, "thorough");
yield return new ScheduleServiceCommand(new TrainId(4), "overhaul");
yield return new OrderPartsCommand(new DepotId(1), 30);
yield return new TakeLoanCommand(Money.FromLire(50000));
yield return new RepayLoanCommand(new LoanId(1), new Money(999));
yield return new AcceptAgreementCommand(new AgreementId(5));
yield return new RejectAgreementCommand(new AgreementId(6));
yield return new BuyGoodsCommand(new StationId(1), "coal", 100, new Money(4000));
yield return new SellGoodsCommand(new StationId(2), "steel", 50, new Money(15000));
yield return new BuyIndustryCommand(new IndustryId(3), Money.FromLire(1_000_000));
yield return new SetIndustryPolicyCommand(new IndustryId(3), IndustryBudget.High);
yield return new OverhaulIndustryCommand(new IndustryId(3));
yield return new UpgradeIndustryCommand(new IndustryId(3));
yield return new IpoCommand(0.3);
yield return new BuySharesCommand(new CompanyId(2), 10_000, new Money(1500));
yield return new SellSharesCommand(new CompanyId(2), 5_000, new Money(1400));
yield return new PayDividendCommand(new Money(12));
yield return new LaunchBidCommand(new CompanyId(1), new Money(2000), 0.51);
yield return new RespondBidCommand(new BidId(1), false);
yield return new BuyConcessionCommand(new RegionId(2));
yield return new AcceptContractCommand(new ContractId(8));
yield return new FundResearchCommand("electric_traction", Money.FromLire(20000));
yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000));
}
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
public static void EveryMessageRoundTrips()
{
var seen = new HashSet<MessageId>();
foreach (var m in SampleMessages())
{
byte[] frame = Frame.Encode(m);
var decoded = Frame.Decode(frame);
Assert.Equal(m.GetType(), decoded.GetType());
Assert.Equal(m.Id, decoded.Id);
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(decoded)), $"{m.Id}: i byte ricodificati differiscono");
seen.Add(m.Id);
}
foreach (var id in Enum.GetValues<MessageId>()) Assert.True(seen.Contains(id), $"manca l'esemplare di {id}");
}
[Test(Description = "Ogni tipo di comando sopravvive al round-trip dentro un messaggio Command")]
public static void EveryCommandRoundTrips()
{
var seen = new HashSet<CommandType>();
foreach (var c in SampleCommands())
{
var message = new CommandMessage { Seq = 17, Command = c };
byte[] frame = Frame.Encode(message);
var decoded = (CommandMessage)Frame.Decode(frame);
Assert.Equal(c.GetType(), decoded.Command.GetType());
Assert.Equal(17u, decoded.Command.Seq);
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(decoded)), $"{c.Type}: i byte ricodificati differiscono");
seen.Add(c.Type);
}
foreach (var t in Enum.GetValues<CommandType>()) Assert.True(seen.Contains(t), $"manca l'esemplare del comando {t}");
}
[Test]
public static void FieldsSurviveTheRoundTrip()
{
var track = (BuildTrackCommand)((CommandMessage)Frame.Decode(Frame.Encode(new CommandMessage { Seq = 1, Command = SampleCommands().First() }))).Command;
Assert.Equal(3, track.Polyline.Count);
Assert.Equal(P, track.Polyline[0]);
Assert.Equal("c100", track.TrackClass);
Assert.True(track.DoubleTrack && track.Electrified && !track.AllowBridges);
Assert.Equal(123456L, track.ExpectedCostCents);
var chunk = (MapChunk)Frame.Decode(Frame.Encode(SampleChunk()));
Assert.True(chunk.Heights.AsSpan().SequenceEqual(SampleChunk().Heights));
Assert.True(chunk.RiverWidth.AsSpan().SequenceEqual(SampleChunk().RiverWidth));
var hello = (Hello)Frame.Decode(Frame.Encode(SampleMessages().OfType<Hello>().First()));
Assert.Equal(Frame.ProtocolVersion, hello.ProtocolVersion);
Assert.Equal("segreto", hello.Token);
var delta = (EntityDelta)Frame.Decode(Frame.Encode(SampleMessages().OfType<EntityDelta>().First()));
Assert.Equal((EntityType.Station, 9), delta.Removed[1]);
Assert.Equal("Treno 12", delta.Changed.Trains[0].Name);
Assert.True(delta.Changed.Lines[0].Stops[1].WaitFull);
}
[Test(Description = "Frame troncati o corrotti producono solo ProtocolException")]
public static void TruncatedAndCorruptedFramesFailCleanly()
{
var rng = new Rng(2024);
foreach (var m in SampleMessages())
{
byte[] frame = Frame.Encode(m);
for (int cut = 0; cut < frame.Length; cut += Math.Max(1, frame.Length / 17))
{
byte[] part = frame.AsSpan(0, cut).ToArray();
Assert.Throws<ProtocolException>(() => Frame.Decode(part), $"{m.Id} troncato a {cut}");
}
for (int k = 0; k < 40; k++)
{
byte[] bad = (byte[])frame.Clone();
int at = Frame.HeaderSize + rng.NextInt(Math.Max(1, bad.Length - Frame.HeaderSize));
if (at >= bad.Length) continue;
bad[at] ^= (byte)(1 + rng.NextInt(255));
try
{
Frame.Decode(bad);
}
catch (ProtocolException)
{
}
}
}
// un messaggio sconosciuto e una lunghezza incoerente
Assert.Throws<ProtocolException>(() => Frame.Decode([2, 0, 0, 0, 0xE7, 0x03]));
Assert.Throws<ProtocolException>(() => Frame.Decode([9, 0, 0, 0, 2, 0, 1]));
}
[Test(Description = "Un lettore ignora i byte di estensione che non conosce (campi futuri in coda)")]
public static void ReadersIgnoreUnknownTrailingFields()
{
byte[] frame = Frame.Encode(new Ping { Nonce = 5 });
byte[] longer = new byte[frame.Length + 3];
frame.CopyTo(longer, 0);
longer[frame.Length - 1] = 1; // flags: un blocco opzionale segue
longer[frame.Length] = 0xAA;
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(longer, (uint)(longer.Length - 4));
var ping = (Ping)Frame.Decode(longer);
Assert.Equal(5UL, ping.Nonce);
}
[Test]
public static void VarUIntAndStringsEncodeCompactly()
{
var w = new SpanWriter(8);
w.VarUInt(0);
w.VarUInt(127);
w.VarUInt(128);
w.VarUInt(ulong.MaxValue);
w.String("città");
var r = new SpanReader(w.ToArray());
Assert.Equal(0UL, r.VarUInt());
Assert.Equal(127UL, r.VarUInt());
Assert.Equal(128UL, r.VarUInt());
Assert.Equal(ulong.MaxValue, r.VarUInt());
Assert.Equal("città", r.String());
Assert.Equal(0, r.Remaining);
Assert.Equal(1 + 1 + 2 + 10 + 1 + 6, w.Length);
}
}
+272
View File
@@ -0,0 +1,272 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using ViaFerrea.Server;
using ViaFerrea.Tests.Harness;
using ViaFerrea.Tests.Scenarios;
namespace ViaFerrea.Tests.Server;
/// <summary>Server in processo su una porta casuale, con un client WebSocket vero.</summary>
public sealed class ServerFixture : IAsyncDisposable
{
public WebApplication App { get; }
public GameHost Host { get; }
public int Port { get; }
public string DataDir { get; }
public const string Token = "segreto-di-prova";
private ServerFixture(WebApplication app, string dataDir)
{
App = app;
DataDir = dataDir;
Host = app.Services.GetRequiredService<HostHolder>().Host!;
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses;
Port = new Uri(addresses.First()).Port;
}
public static ServerFixture Start(World world, int tickMs = 1)
{
string dir = Path.Combine(Path.GetTempPath(), "viaferrea-test-" + Path.GetRandomFileName());
var config = new ServerConfig { Local = true, Token = Token, TickMs = tickMs, AutosaveMinutes = 0, DataDir = dir, LogLevel = "Error" };
var app = ServerProgram.Build(config, [], world, TestData.Data);
app.Start();
return new ServerFixture(app, dir);
}
public Uri WebSocketUri => new($"ws://127.0.0.1:{Port}/ws");
public async ValueTask DisposeAsync()
{
await App.StopAsync();
await App.DisposeAsync();
try
{
Directory.Delete(DataDir, true);
}
catch (IOException)
{
}
}
}
/// <summary>Client di prova: applica i messaggi alla copia locale e raccoglie gli esiti dei comandi.</summary>
public sealed class TestClient : IAsyncDisposable
{
public ProtocolClient Connection { get; }
public ClientWorld World { get; } = new(TestData.Data);
public Dictionary<uint, CommandResultMessage> Results { get; } = [];
public List<IMessage> Received { get; } = [];
public Welcome Welcome { get; private set; } = null!;
private TestClient(ProtocolClient connection) => Connection = connection;
public static async Task<TestClient> ConnectAsync(ServerFixture server, ulong resume = 0)
{
var connection = await ProtocolClient.ConnectAsync(server.WebSocketUri);
var client = new TestClient(connection);
client.Welcome = await connection.HandshakeAsync(new Hello { ClientVersion = "test", Token = ServerFixture.Token, DataHash = TestData.Data.Hash, ResumeSessionId = resume });
client.World.Apply(client.Welcome);
return client;
}
/// <summary>Riceve e applica messaggi finché la condizione è vera.</summary>
public async Task<T> WaitFor<T>(Func<T?> condition, string what, int timeoutMs = 60_000) where T : class
{
using var cts = new CancellationTokenSource(timeoutMs);
while (true)
{
var value = condition();
if (value is not null) return value;
IMessage m;
try
{
m = await Connection.ReceiveAsync(cts.Token);
}
catch (OperationCanceledException)
{
throw new AssertionException($"tempo scaduto in attesa di: {what}");
}
Received.Add(m);
if (m is CommandResultMessage r) Results[r.Seq] = r;
World.Apply(m);
}
}
public Task<bool> WaitUntil(Func<bool> condition, string what, int timeoutMs = 60_000) =>
WaitFor(() => condition() ? (object)true : null, what, timeoutMs).ContinueWith(_ => true);
/// <summary>Invia un comando e ne attende l'esito.</summary>
public async Task<CommandResultMessage> Do(GameCommand command)
{
uint seq = await Connection.SendCommandAsync(command);
return await WaitFor(() => Results.GetValueOrDefault(seq), $"esito di {command.Type}");
}
public async Task<int> Ok(GameCommand command)
{
var r = await Do(command);
Assert.True(r.Ok, $"{command.Type}: {r.Error} {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
public Task SubscribeAll() => Connection.SendAsync(new Subscribe
{
X0 = 0, Y0 = 0, X1 = World.Summary!.WidthCells - 1, Y1 = World.Summary.HeightCells - 1,
});
public ValueTask DisposeAsync() => Connection.DisposeAsync();
}
public static class ServerTests
{
private static Vec2 K(double x, double y) => new(x * 1000, y * 1000);
[Test(Slow = true, Description = "Accettazione F3 (senza grafica): linea con ponte costruita via WebSocket, anteprima identica al server, treno in moto con posizione coerente")]
public static void BuildLineWithBridgeOverTheNetworkAndWatchTheTrain() => Run().GetAwaiter().GetResult();
private static async Task Run()
{
var scenario = ScenarioHelper.Load("valdoria");
await using var server = ServerFixture.Start(scenario.World);
await using var client = await TestClient.ConnectAsync(server);
var w = client.World;
Assert.Equal(160, w.Summary!.WidthCells);
await client.SubscribeAll();
int chunks = ((w.Summary.WidthCells + 63) / 64) * ((w.Summary.HeightCells + 63) / 64);
await client.WaitUntil(() => w.Chunks.Count == chunks && w.Towns.Count == 3, "terreno e entità");
// il terreno ricevuto è identico a quello del server
Assert.Equal(scenario.World.Terrain.ComputeHash(), w.Terrain!.ComputeHash());
int mine = await client.Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
int mill = await client.Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
int depot = await client.Ok(new BuildDepotCommand(K(2.6, 4.4), "small", "Deposito"));
await client.WaitUntil(() => w.Stations.ContainsKey(mill) && w.Depots.ContainsKey(depot), "stazioni nella copia locale");
// anteprima del client = piano del server (il server rifiuta un costo diverso)
var valico = new BuildTrackCommand(scenario.Route("valico", w.Company).Polyline, AllowTunnels: false);
var preview = w.PreviewTrack(valico);
Assert.True(preview.Valid, string.Join("; ", preview.Errors.Select(e => e.Message)));
Assert.True(preview.LengthOf(WorkKind.Bridge) > 0, "il tracciato passa il fiume su un ponte");
int edge = await client.Ok(valico with { ExpectedCostCents = preview.TotalCost.Cents });
await client.WaitUntil(() => w.Edges.ContainsKey(edge), "arco del valico");
var info = w.Edges[edge];
Assert.Equal(preview.Samples.Count, info.S.Length);
for (int i = 0; i < info.S.Length; i++)
{
Assert.Equal(preview.Samples[i].TrackM, info.H[i], $"quota del campione {i}");
Assert.Equal((byte)preview.Samples[i].Kind, info.Kinds[i], $"opera del campione {i}");
}
var spur = new BuildTrackCommand([K(2.6, 4.4), K(2.92, 4.95)]);
var spurPreview = w.PreviewTrack(spur);
Assert.True(spurPreview.Valid);
await client.Ok(spur with { ExpectedCostCents = spurPreview.TotalCost.Cents });
// un'anteprima sbagliata viene respinta
var wrong = await client.Do(new BuildTrackCommand([K(3.0, 1.0), K(4.0, 1.2)], ExpectedCostCents: 1));
Assert.Equal((ushort)CommandError.PreviewMismatch, wrong.Error);
await client.Connection.SendAsync(new SetSpeed { Speed = 8 });
await client.WaitUntil(() => w.Edges.Count >= 3 && w.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri completati", 120_000);
var loco = await client.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var wagons = await client.Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3));
Assert.True(loco.Ok && wagons.Ok);
int train = await client.Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
int line = await client.Ok(new CreateLineCommand("Linea 1", "#e0a526", [new LineStop(new StationId(mine)), new LineStop(new StationId(mill))]));
await client.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Speed > 5, "treno in moto", 120_000);
// in pausa: la posizione disegnata dal client coincide con quella del server
await client.Connection.SendAsync(new SetSpeed { Speed = 0 });
long tick;
Vec2? head;
while (true)
{
(tick, head) = await server.Host.InvokeAsync(world => (world.Clock.Tick, Projection.HeadPoint(world, world.Trains[train])));
await Task.Delay(60);
long again = await server.Host.InvokeAsync(world => world.Clock.Tick);
if (again == tick) break;
}
// in pausa il server rimanda i moti dei treni in marcia ogni 100 ms
await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Tick == tick, "moto all'ultimo tick", 10_000);
var drawn = w.TrainHead(train);
Assert.True(drawn is not null && head is not null);
double gap = Vec2.Distance(drawn!.Value, head!.Value);
Assert.True(gap < w.Summary.CellSizeM, $"scarto tra client e server {gap:F2} m");
Assert.True(gap < 0.01, $"scarto atteso nullo, misurato {gap:F4} m");
Assert.True(client.Received.OfType<DailyDigest>().Any(), "resoconti giornalieri ricevuti");
}
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();
private static async Task RunRejections()
{
await using var server = ServerFixture.Start(TestWorlds.Small(301), tickMs: 50);
async Task<RejectCode?> Try(Hello hello)
{
await using var c = await ProtocolClient.ConnectAsync(server.WebSocketUri);
try
{
await c.HandshakeAsync(hello);
return null;
}
catch (SessionRejectedException e)
{
return e.Reject.Code;
}
}
Assert.Equal(RejectCode.BadToken, await Try(new Hello { Token = "sbagliato" }));
Assert.Equal(RejectCode.DataMismatch, await Try(new Hello { Token = ServerFixture.Token, DataHash = 1 }));
Assert.Equal(RejectCode.ProtocolVersion, await Try(new Hello { Token = ServerFixture.Token, ProtocolVersion = 999 }));
Assert.Equal((RejectCode?)null, await Try(new Hello { Token = ServerFixture.Token }));
}
[Test(Description = "Ping, salvataggi, ripresa della sessione e API HTTP")]
public static void PingSavesResumeAndHttp() => RunMisc().GetAwaiter().GetResult();
private static async Task RunMisc()
{
await using var server = ServerFixture.Start(TestWorlds.Small(302), tickMs: 50);
ulong sessionId;
await using (var client = await TestClient.ConnectAsync(server))
{
sessionId = client.Welcome.SessionId;
await client.Connection.SendAsync(new Ping { Nonce = 41 });
var pong = await client.WaitFor(() => client.Received.OfType<Pong>().FirstOrDefault(), "pong");
Assert.Equal(41UL, pong.Nonce);
await client.Connection.SendAsync(new Save { Name = "prova rete" });
var list = await client.WaitFor(() => client.Received.OfType<SaveList>().FirstOrDefault(), "elenco dei salvataggi");
Assert.Equal(1, list.Saves.Count);
Assert.True(list.Saves[0].SaveId.StartsWith("prova_rete-", StringComparison.Ordinal), list.Saves[0].SaveId);
await client.WaitFor(() => client.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot");
}
// ripresa con lo stesso id: stessa sessione, stato rimandato per intero
await using (var again = await TestClient.ConnectAsync(server, resume: sessionId))
{
Assert.Equal(sessionId, again.Welcome.SessionId);
await again.WaitFor(() => again.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot dopo la ripresa");
}
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
Assert.Equal("ok", await http.GetStringAsync("/health"));
string metrics = await http.GetStringAsync("/metrics");
foreach (string name in new[] { "tick_ms", "trains", "packets", "contracts", "sessions" })
Assert.True(metrics.Contains($"\n{name} ", StringComparison.Ordinal), $"metrica {name}");
var posted = await http.PostAsync("/api/saves?name=da-http", null);
Assert.Equal(System.Net.HttpStatusCode.Created, posted.StatusCode);
string saves = await http.GetStringAsync("/api/saves");
Assert.True(saves.Contains("da-http", StringComparison.Ordinal), saves);
string id = saves.Split("\"id\":\"")[1].Split('"')[0];
var file = await http.GetByteArrayAsync($"/api/saves/{id}");
Assert.True(file.AsSpan(0, 4).SequenceEqual("VFSV"u8));
}
}