F3: client Godot minimo, replay dei comandi e collaudi automatici
- Client Godot 4.7 .NET (Godot.NET.Sdk 4.7.2): menu, collegamento, partita locale con server figlio; mappa con terreno (fasce, ombreggiatura, rive curve con shader, curve di livello), opere, entità, alberi, treni interpolati con fumo; strumenti binari con profilo, stazione, deposito, segnali, demolizione; pannelli treni, linee, mercato, finanze, schede; barra superiore, minimappa, notiziario; italiano e inglese. - Pilota automatico del client e scripts/client-autopilot.sh: partita locale, linea con ponte, treni in moto e schermate (docs/screenshots). - Registro dei comandi del server (--record) e viaferrea-tools replay. - PROTOCOL.md normativo, ADR 0009, ARCHITECTURE, STATE e README aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
97 files changed
+5151
-96
No files matched your search
@@ -0,0 +1,142 @@
|
||||
using Godot;
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Protocol;
|
||||
using ViaFerrea.Protocol.Client;
|
||||
using ViaFerrea.Protocol.Messages;
|
||||
|
||||
namespace ViaFerrea.Client.Net;
|
||||
|
||||
/// <summary>
|
||||
/// Sessione di gioco del client: connessione, copia locale del mondo, esiti dei comandi e
|
||||
/// notifiche. I messaggi si applicano sul thread principale in <see cref="Poll"/>.
|
||||
/// </summary>
|
||||
public sealed class GameSession : IAsyncDisposable
|
||||
{
|
||||
private readonly Dictionary<uint, Action<CommandResultMessage>> _callbacks = [];
|
||||
private long _pingSentMs;
|
||||
private ulong _pingNonce;
|
||||
|
||||
public ProtocolClient Connection { get; }
|
||||
public ClientWorld World { get; }
|
||||
public string ServerLabel { get; }
|
||||
public LocalServerLauncher? LocalServer { get; set; }
|
||||
|
||||
/// <summary>Istante di arrivo (ms) dell'ultimo moto di ogni treno, per l'interpolazione.</summary>
|
||||
public Dictionary<int, long> MotionReceivedMs { get; } = [];
|
||||
|
||||
/// <summary>Ritardo di andata e ritorno dell'ultimo ping (ms).</summary>
|
||||
public double LatencyMs { get; private set; }
|
||||
|
||||
public event Action<IMessage>? MessageApplied;
|
||||
public event Action<EventInfo>? Notified;
|
||||
public event Action<CommandResultMessage>? CommandFailed;
|
||||
|
||||
private GameSession(ProtocolClient connection, ClientWorld world, string label)
|
||||
{
|
||||
Connection = connection;
|
||||
World = world;
|
||||
ServerLabel = label;
|
||||
}
|
||||
|
||||
public static async Task<GameSession> ConnectAsync(GameData data, Uri uri, string token, string label, CancellationToken ct = default)
|
||||
{
|
||||
var connection = await ProtocolClient.ConnectAsync(uri, ct);
|
||||
try
|
||||
{
|
||||
var welcome = await connection.HandshakeAsync(new Hello
|
||||
{
|
||||
ClientVersion = typeof(GameSession).Assembly.GetName().Version?.ToString() ?? "0",
|
||||
Token = token,
|
||||
DataHash = data.Hash,
|
||||
}, ct);
|
||||
var world = new ClientWorld(data);
|
||||
world.Apply(welcome);
|
||||
return new GameSession(connection, world, label);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await connection.DisposeAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsOpen => Connection.IsOpen;
|
||||
|
||||
/// <summary>Applica i messaggi arrivati (al massimo maxMessages per fotogramma).</summary>
|
||||
public int Poll(int maxMessages = 2000)
|
||||
{
|
||||
int n = 0;
|
||||
while (n < maxMessages && Connection.TryReceive(out var message))
|
||||
{
|
||||
n++;
|
||||
World.Apply(message);
|
||||
switch (message)
|
||||
{
|
||||
case CommandResultMessage r:
|
||||
if (_callbacks.Remove(r.Seq, out var callback)) callback(r);
|
||||
if (!r.Ok) CommandFailed?.Invoke(r);
|
||||
break;
|
||||
case TrainMotion motion:
|
||||
MotionReceivedMs[motion.TrainId] = (long)Time.GetTicksMsec();
|
||||
break;
|
||||
case Notification note:
|
||||
Notified?.Invoke(note.Event);
|
||||
break;
|
||||
case DailyDigest digest when RequestedSpeed == digest.Speed:
|
||||
RequestedSpeed = null;
|
||||
break;
|
||||
case Pong pong when pong.Nonce == _pingNonce:
|
||||
LatencyMs = (long)Time.GetTicksMsec() - _pingSentMs;
|
||||
break;
|
||||
}
|
||||
MessageApplied?.Invoke(message);
|
||||
}
|
||||
if ((long)Time.GetTicksMsec() - _pingSentMs > 2000) Ping();
|
||||
return n;
|
||||
}
|
||||
|
||||
private void Ping()
|
||||
{
|
||||
_pingSentMs = (long)Time.GetTicksMsec();
|
||||
_pingNonce++;
|
||||
Send(new Ping { Nonce = _pingNonce });
|
||||
}
|
||||
|
||||
public void Send(IMessage message) => _ = SendSafe(message);
|
||||
|
||||
private async Task SendSafe(IMessage message)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Connection.SendAsync(message);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
GD.PrintErr($"Invio non riuscito: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Invia un comando; la callback riceve l'esito sul thread principale.</summary>
|
||||
public void Command(GameCommand command, Action<CommandResultMessage>? onResult = null)
|
||||
{
|
||||
uint seq = Connection.ReserveSeq();
|
||||
if (onResult is not null) _callbacks[seq] = onResult;
|
||||
Send(new CommandMessage { Seq = seq, Command = command });
|
||||
}
|
||||
|
||||
/// <summary>Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).</summary>
|
||||
public byte? RequestedSpeed { get; private set; }
|
||||
|
||||
public void SetSpeed(byte speed)
|
||||
{
|
||||
RequestedSpeed = speed;
|
||||
Send(new SetSpeed { Speed = speed });
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Connection.DisposeAsync();
|
||||
LocalServer?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
uid://b8etsc0caa35g
|
||||
@@ -0,0 +1,94 @@
|
||||
using System.Diagnostics;
|
||||
using Godot;
|
||||
|
||||
namespace ViaFerrea.Client.Net;
|
||||
|
||||
/// <summary>
|
||||
/// Partita locale: avvia il server come processo figlio con <c>--local --token</c>, legge
|
||||
/// «LISTENING porta» dallo standard output e lo termina alla chiusura del client.
|
||||
/// </summary>
|
||||
public sealed class LocalServerLauncher : IDisposable
|
||||
{
|
||||
private Process? _process;
|
||||
|
||||
public int Port { get; private set; }
|
||||
public string Token { get; } = Guid.NewGuid().ToString("N");
|
||||
|
||||
/// <summary>Percorso del server: variabile VF_SERVER_PATH, cartella «server» accanto al gioco, build del repository.</summary>
|
||||
public static string? FindServer()
|
||||
{
|
||||
string? env = System.Environment.GetEnvironmentVariable("VF_SERVER_PATH");
|
||||
if (!string.IsNullOrWhiteSpace(env) && File.Exists(env)) return env;
|
||||
string exeDir = Path.GetDirectoryName(OS.GetExecutablePath()) ?? ".";
|
||||
foreach (string name in new[] { "ViaFerrea.Server.exe", "ViaFerrea.Server", "ViaFerrea.Server.dll" })
|
||||
{
|
||||
string candidate = Path.Combine(exeDir, "server", name);
|
||||
if (File.Exists(candidate)) return candidate;
|
||||
}
|
||||
// sviluppo: il progetto Godot sta in client/ViaFerrea.Client, il server in src/
|
||||
string project = ProjectSettings.GlobalizePath("res://");
|
||||
foreach (string config in new[] { "Release", "Debug" })
|
||||
{
|
||||
string candidate = Path.GetFullPath(Path.Combine(project, "..", "..", "src", "ViaFerrea.Server", "bin", config, "net10.0", "ViaFerrea.Server.dll"));
|
||||
if (File.Exists(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Avvia il server e attende la porta (al massimo timeout).</summary>
|
||||
public async Task<int> StartAsync(string serverPath, string dataDir, TimeSpan timeout)
|
||||
{
|
||||
bool dll = serverPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase);
|
||||
var info = new ProcessStartInfo
|
||||
{
|
||||
FileName = dll ? "dotnet" : serverPath,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
WorkingDirectory = Path.GetDirectoryName(serverPath) ?? ".",
|
||||
};
|
||||
if (dll) info.ArgumentList.Add(serverPath);
|
||||
info.ArgumentList.Add("--local");
|
||||
info.ArgumentList.Add("--token");
|
||||
info.ArgumentList.Add(Token);
|
||||
info.ArgumentList.Add("--data");
|
||||
info.ArgumentList.Add(dataDir);
|
||||
_process = Process.Start(info) ?? throw new InvalidOperationException("Server non avviato");
|
||||
_process.ErrorDataReceived += (_, e) => { if (e.Data is not null) GD.PrintErr("[server] " + e.Data); };
|
||||
_process.BeginErrorReadLine();
|
||||
|
||||
using var cts = new CancellationTokenSource(timeout);
|
||||
while (!cts.IsCancellationRequested)
|
||||
{
|
||||
string? line = await _process.StandardOutput.ReadLineAsync(cts.Token);
|
||||
if (line is null) break;
|
||||
if (line.StartsWith("LISTENING ", StringComparison.Ordinal) && int.TryParse(line.AsSpan(10), out int port))
|
||||
{
|
||||
Port = port;
|
||||
// il resto dell'output (log JSON) si scarta per non riempire il buffer
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
while (await _process.StandardOutput.ReadLineAsync() is not null)
|
||||
{
|
||||
}
|
||||
});
|
||||
return port;
|
||||
}
|
||||
}
|
||||
throw new TimeoutException("Il server locale non ha risposto");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_process is { HasExited: false }) _process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
}
|
||||
_process?.Dispose();
|
||||
_process = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
uid://cr4o72tey2gop
|
||||
Reference in new issue
Block a user