using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Panels;
using RailEnterprise.Client.Tutorial;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
///
/// Schermata iniziale e di connessione (immagine di riferimento 09): a sinistra la mappa decorativa
/// con il titolo, a destra «Dove gira il motore di gioco?» con le due strade (server locale figlio
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione e protocollo,
/// sistema, tempo di attività, tick al secondo, latenza, client collegati), le partite salvate sul
/// server e i pulsanti per riprendere o iniziare. All'apertura la schermata avvia il server locale o
/// verifica il server in rete ricordato, con una sessione di prova che legge lo stato e l'elenco dei
/// salvataggi; «Connetti e riprendi» la passa alla partita (e se non c'è ancora la apre). Nessuna
/// logica di gioco: carica, nuova partita ed elenco sono richieste al server (Load, NewGame,
/// ListSaves). Caricare o creare una partita sostituisce il mondo per tutti: si chiede conferma. Sotto i
/// pulsanti la casella «Mostra il tutorial» (attiva alla prima partita) vale per la partita che si apre, e
/// «Tutorial» apre una partita locale di prova sempre nuova, separata da quella del giocatore (ADR 0023).
///
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private const double SavesRefreshS = 5;
private const double WelcomeTimeoutS = 30;
/// Metadato della riga «Partita in corso» nell'elenco dei salvataggi.
private const string CurrentGame = "";
private readonly GameData _data;
private readonly bool _remember, _autoStart;
private GameSession? _handover;
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400", SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly CheckBox _rememberBox = new() { Text = T("Ricorda questo server"), ButtonPressed = true };
private readonly Button _probe = new() { Text = T("Verifica connessione"), CustomMinimumSize = new Vector2(0, 40) };
private readonly VBoxContainer _remoteFields = new();
private readonly Button _localCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Button _remoteCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly ColorRect _dot = new() { CustomMinimumSize = new Vector2(12, 12), SizeFlagsVertical = SizeFlags.ShrinkCenter };
private readonly Label _stateTitle = UiTheme.Text("", 16, bold: true);
/// Stato del server in tre colonne per due righe, didascalia sopra il valore (immagine 09).
private readonly GridContainer _stateGrid = new() { Columns = 3 };
private readonly List<(Label Caption, Label Value)> _stateCells = [];
/// Partite salvate in tre colonne: nome, data di gioco, quanto tempo fa.
private readonly Tree _saves = new()
{
Columns = 3, HideRoot = true, SelectMode = Tree.SelectModeEnum.Row, CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill,
};
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
private readonly CheckBox _showTutorial = new() { Text = T("Mostra il tutorial") };
private readonly Button _tutorial = new() { Text = T("Tutorial") };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly ConfirmationDialog _confirm = new() { Title = T("Sostituire la partita?"), DialogAutowrap = true, MinSize = new Vector2I(520, 0) };
private Action? _onConfirm;
private GameSession? _session;
private bool _busy, _local, _closed, _resumeAfterConnect;
private double _sinceSaves = double.MaxValue;
private SaveList? _shownSaves;
/// Riga scelta nell'elenco, per id del salvataggio (CurrentGame per la partita in corso): l'elenco si riordina a ogni aggiornamento.
private string _selectedSave = CurrentGame;
private Action? _awaitingWelcome;
private double _waiting;
/// Stato del server mostrato e istante in cui è arrivato: il tempo di attività avanza da lì.
private ServerInfo? _infoSeen;
private double _infoAt;
/// La sessione di prova diventa la partita: la schermata non la chiude più.
public event Action? PlayRequested;
public event Action? LanguageChanged;
/// Apre il pannello delle impostazioni audio.
public event Action? AudioRequested;
/// Pulsante «Tutorial»: Main apre la partita di prova del tutorial.
public event Action? TutorialRequested;
/// Casella «Mostra il tutorial» per la partita che si apre.
public bool ShowTutorial => _showTutorial.ButtonPressed;
/// Origine della partita per la voce del tutorial: il server locale o l'indirizzo del server in rete.
public string GameScope => _local ? "local" : "remote_" + _address.Text.Trim();
/// Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.
/// Avvia subito il server locale o verifica il server ricordato (falso nel collaudo).
/// Sessione di prova di una schermata precedente (cambio di lingua): la si riprende così com'è.
public ConnectScreen(GameData data, bool remember = true, bool autoStart = true, GameSession? handover = null)
{
_data = data;
_remember = remember;
_autoStart = autoStart;
_handover = handover;
}
/// Stato e salvataggi sono arrivati dal server (serve al collaudo).
public bool Loaded => _session?.World.Server is not null && _shownSaves is not null;
public override void _Ready()
{
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var split = new HBoxContainer();
split.SetAnchorsPreset(LayoutPreset.FullRect);
split.AddThemeConstantOverride("separation", 0);
AddChild(split);
// sinistra: mappa decorativa con il titolo
var left = new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 1.1f, ClipContents = true };
var backdrop = new ConnectBackdrop();
backdrop.SetAnchorsPreset(LayoutPreset.FullRect);
left.AddChild(backdrop);
// titolo in basso a sinistra, sopra il velo della mappa
var brand = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
brand.AnchorLeft = 0;
brand.AnchorRight = 1;
brand.AnchorTop = 1;
brand.AnchorBottom = 1;
brand.OffsetLeft = 56;
brand.OffsetRight = -56;
brand.OffsetTop = -280;
brand.OffsetBottom = -56;
brand.AddThemeConstantOverride("separation", 6);
brand.AddChild(UiTheme.TitleLabel("RAIL ENTERPRISE", 76, Palette.AmberLight));
brand.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 20, Palette.Text));
brand.AddChild(UiTheme.Text($"{T("Versione del gioco")} {ClientVersion}", 13, Palette.TextSecondary));
left.AddChild(brand);
split.AddChild(left);
// destra: dove gira il motore
var right = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 0.9f };
right.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 40));
split.AddChild(right);
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
right.AddChild(scroll);
var col = PanelKit.Column(14);
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
col.SizeFlagsVertical = SizeFlags.ExpandFill;
scroll.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Dove gira il motore di gioco?"), 38));
var lead = UiTheme.Text(T("Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso."), 14, Palette.TextSecondary);
lead.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(lead);
var modes = PanelKit.Row(12);
var group = new ButtonGroup();
ModeCard(_localCard, group, T("Gioca in locale"), T("Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui."));
ModeCard(_remoteCard, group, T("Connetti a un server"), T("Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa."));
_localCard.Pressed += () => SetMode(local: true, start: true);
_remoteCard.Pressed += () => SetMode(local: false, start: true);
modes.AddChild(_localCard);
modes.AddChild(_remoteCard);
col.AddChild(modes);
// indirizzo e token del server in rete
_remoteFields.AddThemeConstantOverride("separation", 8);
var fields = PanelKit.Row(10);
var addressCol = PanelKit.Column(4);
addressCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
addressCol.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
addressCol.AddChild(_address);
var tokenCol = PanelKit.Column(4);
tokenCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
tokenCol.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
tokenCol.AddChild(_token);
fields.AddChild(addressCol);
fields.AddChild(tokenCol);
_remoteFields.AddChild(fields);
var probeRow = PanelKit.Row(10);
_rememberBox.SizeFlagsHorizontal = SizeFlags.ExpandFill;
probeRow.AddChild(_rememberBox);
_probe.Pressed += SubmitRemote;
probeRow.AddChild(_probe);
_remoteFields.AddChild(probeRow);
_token.TextSubmitted += _ => SubmitRemote();
col.AddChild(_remoteFields);
// stato del server
var state = new PanelContainer();
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
var stateCol = PanelKit.Column(12);
var stateHead = PanelKit.Row(10);
stateHead.AddChild(_dot);
stateHead.AddChild(_stateTitle);
stateCol.AddChild(stateHead);
_stateGrid.AddThemeConstantOverride("h_separation", 24);
_stateGrid.AddThemeConstantOverride("v_separation", 12);
for (int i = 0; i < 6; i++)
{
var cell = PanelKit.Column(2);
cell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
var caption = UiTheme.Text("", 12, Palette.TextSecondary);
var value = UiTheme.Text("", 14, bold: true);
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
cell.AddChild(caption);
cell.AddChild(value);
_stateGrid.AddChild(cell);
_stateCells.Add((caption, value));
}
stateCol.AddChild(_stateGrid);
state.AddChild(stateCol);
col.AddChild(state);
// partite salvate sul server: nome, data di gioco, quanto tempo fa
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
_saves.SetColumnExpand(0, true);
_saves.SetColumnExpandRatio(0, 3);
_saves.SetColumnExpand(1, true);
_saves.SetColumnExpandRatio(1, 2);
_saves.SetColumnExpand(2, true);
_saves.SetColumnExpandRatio(2, 1);
_saves.ItemSelected += () =>
{
if (_saves.GetSelected() is { } item) _selectedSave = item.GetMetadata(0).AsString();
};
_saves.ItemActivated += Resume;
col.AddChild(_saves);
var actions = PanelKit.Row(10);
_resume.CustomMinimumSize = new Vector2(0, 48);
_resume.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_resume.Pressed += Resume;
actions.AddChild(_resume);
_newGame.CustomMinimumSize = new Vector2(0, 48);
_newGame.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_newGame.Pressed += NewGameOnServer;
actions.AddChild(_newGame);
col.AddChild(actions);
var tutorialRow = PanelKit.Row(10);
_showTutorial.ButtonPressed = !TutorialSettings.Played;
_showTutorial.TooltipText = T("Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1");
_showTutorial.SizeFlagsHorizontal = SizeFlags.ExpandFill;
tutorialRow.AddChild(_showTutorial);
_tutorial.TooltipText = T("Nuova partita locale di prova con il tutorial dal primo passo: la tua partita locale resta com'è");
_tutorial.CustomMinimumSize = new Vector2(160, 40);
_tutorial.Pressed += () =>
{
if (_busy) return;
// da qui la schermata non avvia né riprende altro: Main apre la partita di prova
_busy = true;
_tutorial.Disabled = true;
TutorialRequested?.Invoke();
};
tutorialRow.AddChild(_tutorial);
col.AddChild(tutorialRow);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
// piede: lingua, audio, uscita, avviso sulla cifratura
var foot = PanelKit.Row(8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
foot.AddChild(b);
}
var audio = new Button { Text = T("Audio") };
audio.Pressed += () => AudioRequested?.Invoke();
foot.AddChild(audio);
foot.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(100, 0) };
quit.Pressed += () => GetTree().Quit();
foot.AddChild(quit);
col.AddChild(foot);
var notice = UiTheme.Text(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://)."), 12, Palette.TextSecondary);
notice.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(notice);
// conferma prima di sostituire la partita sul server
_confirm.OkButtonText = T("Sostituisci la partita");
_confirm.CancelButtonText = T("Annulla");
_confirm.Confirmed += () =>
{
var action = _onConfirm;
_onConfirm = null;
action?.Invoke();
};
_confirm.Canceled += () => _onConfirm = null;
AddChild(_confirm);
bool remote = false;
if (_remember)
{
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
}
}
if (_handover is not null)
{
// cambio di lingua: la sessione di prova (e il suo server locale) passa a questa schermata
var session = _handover;
_handover = null;
SetMode(local: session.LocalServer is not null, start: false);
Attach(session);
}
else
{
// all'apertura si avvia la strada scelta l'ultima volta, come nell'immagine 09
SetMode(local: !remote, start: _autoStart);
}
ShowState();
}
private static void ModeCard(Button card, ButtonGroup group, string title, string text)
{
card.ButtonGroup = group;
card.AddThemeStyleboxOverride("normal", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
card.AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.AmberDark, 10, 0));
card.AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("hover_pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("disabled", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
var margin = new MarginContainer { MouseFilter = MouseFilterEnum.Ignore };
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (var side in new[] { "left", "right", "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 16);
var col = PanelKit.Column(6);
col.MouseFilter = MouseFilterEnum.Ignore;
var t = UiTheme.Text(title, 17, Palette.AmberLight, bold: true);
var d = UiTheme.Text(text, 12, Palette.TextSecondary);
d.AutowrapMode = TextServer.AutowrapMode.WordSmart;
t.MouseFilter = d.MouseFilter = MouseFilterEnum.Ignore;
col.AddChild(t);
col.AddChild(d);
margin.AddChild(col);
card.AddChild(margin);
}
private static string ClientVersion =>
typeof(ConnectScreen).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
// ------------------------------------------------------------------ modalità e sessione di prova
/// La sessione di prova è della strada scelta: server locale figlio del gioco o server in rete.
private bool SessionMatchesMode => _session is not null && (_session.LocalServer is not null) == _local;
///
/// Cambia strada. La sessione dell'altra strada si chiude (e con lei il server locale), così
/// «Connetti e riprendi» non apre mai la partita della strada non scelta. Con start si avvia il
/// server locale o si verifica il server in rete indicato.
///
private void SetMode(bool local, bool start)
{
_local = local;
_localCard.SetPressedNoSignal(local);
_remoteCard.SetPressedNoSignal(!local);
_remoteFields.Visible = !local;
if (_session is not null && !SessionMatchesMode)
{
_ = Release();
SetStatus("");
}
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "mode", local ? "local" : "remote");
cfg.Save(SettingsPath);
}
if (start && _session is null && !_busy)
{
if (local) _ = StartLocal();
else if (_address.Text.Trim().Length > 0) SubmitRemote();
}
ShowState();
}
/// Avvia il server locale figlio del gioco e apre la sessione di prova.
private async Task StartLocal()
{
if (_busy) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
_resumeAfterConnect = false;
SetStatus(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), error: true);
return;
}
await Release();
_busy = true;
SetStatus(T("Avvio del server locale…"));
ShowState();
var launcher = new LocalServerLauncher();
try
{
int port = await launcher.StartAsync(server, ProjectSettings.GlobalizePath("user://server"), TimeSpan.FromSeconds(60));
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
session.LocalServer = launcher;
_busy = false;
if (!Adopt(session, local: true)) return;
SetStatus("");
}
catch (Exception e)
{
launcher.Dispose();
_busy = false;
_resumeAfterConnect = false;
if (!_closed) SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
}
if (!_closed) ShowState();
}
private void SubmitRemote()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
_resumeAfterConnect = false;
SetStatus(T("Indica l'indirizzo del server"), error: true);
return;
}
string url = address.Contains("://") ? address : $"ws://{address}";
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
_resumeAfterConnect = false;
SetStatus(T("Indirizzo non valido"), error: true);
return;
}
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", _rememberBox.ButtonPressed ? address : "");
cfg.SetValue("server", "token", _rememberBox.ButtonPressed ? _token.Text : "");
cfg.Save(SettingsPath);
}
_ = ProbeRemote(uri, _token.Text);
}
/// Collega la sessione di prova a un server in rete (dal pulsante o dal collaudo).
public async Task ProbeRemote(Uri uri, string token)
{
if (_busy) return;
SetMode(local: false, start: false);
await Release();
_busy = true;
SetStatus(T("Collegamento in corso…"));
ShowState();
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var session = await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token);
_busy = false;
if (!Adopt(session, local: false)) return;
SetStatus("");
}
catch (Exception e)
{
_busy = false;
_resumeAfterConnect = false;
if (!_closed) SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
}
if (!_closed) ShowState();
}
///
/// Prende la sessione appena aperta, se la schermata è ancora aperta e sulla stessa strada;
/// altrimenti la chiude (con il suo server locale). Con «Connetti e riprendi» in attesa si entra
/// subito in partita.
///
private bool Adopt(GameSession session, bool local)
{
if (_closed || _local != local)
{
_resumeAfterConnect = false;
_ = session.DisposeAsync();
return false;
}
Attach(session);
if (_resumeAfterConnect)
{
_resumeAfterConnect = false;
Play();
return false;
}
return true;
}
private void Attach(GameSession session)
{
_session = session;
_shownSaves = null;
_sinceSaves = double.MaxValue;
_session.MessageApplied += OnMessage;
}
/// Chiude la sessione di prova (e il server locale, se è suo).
private async Task Release()
{
var s = _session;
_session = null;
_shownSaves = null;
_awaitingWelcome = null;
if (s is null) return;
s.MessageApplied -= OnMessage;
await s.DisposeAsync();
}
/// Consegna la sessione di prova a chi la chiede (Main: partita, cambio di lingua, chiusura del gioco).
public GameSession? TakeSession()
{
var s = _session;
if (s is not null) s.MessageApplied -= OnMessage;
_session = null;
_awaitingWelcome = null;
return s;
}
public override void _ExitTree()
{
// una connessione ancora in corso si chiude da sola quando arriva (Adopt)
_closed = true;
if (_session is not null) _ = Release();
}
private void OnMessage(IMessage m) => _awaitingWelcome?.Invoke(m);
public override void _Process(double delta)
{
if (_session is null) return;
_session.Poll();
if (_session is null) return; // Play durante Poll: la sessione è passata alla partita
if (!_session.IsOpen)
{
SetStatus(T("Il server ha chiuso la connessione"), error: true);
_ = Release();
ShowState();
return;
}
_sinceSaves += delta;
if (_awaitingWelcome is not null && (_waiting += delta) > WelcomeTimeoutS)
{
_awaitingWelcome = null;
SetStatus(T("Il server non ha risposto"), error: true);
}
if (_sinceSaves >= SavesRefreshS && _awaitingWelcome is null)
{
_sinceSaves = 0;
_session.Send(new ListSaves());
}
if (!ReferenceEquals(_session.World.Saves, _shownSaves)) ShowSaves();
ShowState();
}
// ------------------------------------------------------------------ azioni
private void Resume()
{
if (_busy || _awaitingWelcome is not null) return;
if (_session is null)
{
// nessuna sessione ancora: «Connetti e riprendi» apre la strada scelta ed entra in partita
_resumeAfterConnect = true;
if (_local) _ = StartLocal();
else SubmitRemote();
return;
}
if (!SessionMatchesMode) return;
string id = _selectedSave;
var save = _shownSaves?.Saves.FirstOrDefault(s => s.SaveId == id);
if (id == CurrentGame || save is null)
{
Play();
return;
}
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso."),
CurrentGameText(), save.Name, ConnectedText()), () =>
{
if (_session is null || _awaitingWelcome is not null) return;
SetStatus($"{T("Caricamento di")} {save.Name}…");
AwaitWelcome();
_session.Send(new Load { SaveId = id });
});
}
private void NewGameOnServer()
{
if (_session is null || _awaitingWelcome is not null || !SessionMatchesMode) return;
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso."),
CurrentGameText(), ConnectedText()), () =>
{
if (_session is null || _awaitingWelcome is not null) return;
var summary = _session.World.Summary;
SetStatus(T("Creazione della nuova partita sul server…"));
AwaitWelcome();
// il seme lo sceglie il client: la generazione resta deterministica sul server
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
});
}
private void Confirm(string text, Action action)
{
_onConfirm = action;
_confirm.DialogText = text;
_confirm.PopupCentered();
}
private string CurrentGameText()
{
var summary = _session?.World.Summary;
return summary is null ? "—" : $"{summary.CompanyName}, {summary.Date}";
}
private string ConnectedText()
{
var info = _session?.World.Server;
return info is null ? "?" : info.Sessions.ToString();
}
/// Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.
private void AwaitWelcome()
{
_awaitingWelcome = m =>
{
if (m is Welcome)
{
_awaitingWelcome = null;
Play();
}
else if (m is Notification { Event.Day: < 0 } note)
{
// caricamento o creazione rifiutati: l'avviso del server ha il giorno −1; gli eventi
// del mondo (giorno della partita) arrivano anche qui e non interrompono l'attesa
_awaitingWelcome = null;
SetStatus(note.Event.Text, error: true);
}
};
_waiting = 0;
}
private void Play()
{
var s = TakeSession();
if (s is not null) PlayRequested?.Invoke(s);
}
// ------------------------------------------------------------------ stato
public void SetStatus(string text, bool error = false)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", error ? Palette.Danger : Palette.TextSecondary);
}
private void ShowState()
{
var info = _session?.World.Server;
var summary = _session?.World.Summary;
double now = Time.GetTicksMsec() / 1000.0;
if (!ReferenceEquals(info, _infoSeen))
{
_infoSeen = info;
_infoAt = now;
}
string title;
Color dot;
if (_busy)
{
title = _local ? T("Avvio del server locale…") : T("Collegamento in corso…");
dot = Palette.Amber;
}
else if (_session is not null)
{
title = $"{T("Server raggiungibile")} · {_session.ServerLabel}";
dot = Palette.Ok;
}
else
{
title = _local ? T("Server locale spento: «Connetti e riprendi» lo avvia") : T("Non collegato");
dot = Palette.TextSecondary;
}
_stateTitle.Text = title;
_dot.Color = dot;
var cells = new (string, string)[]
{
(T("Versione"), info is null ? "—" : $"{info.Version}, {T("protocollo")} {Frame.ProtocolVersion}"),
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds + (long)(now - _infoAt))),
(T("Simulazione"), info is null || info.TickMs <= 0 ? "—" : $"{Fmt.Number(1000 / info.TickMs, 0)} {T("tick al secondo")}" + (summary is null ? "" : $" · {summary.Date}")),
(T("Latenza"), _session is null || _session.LatencyMs <= 0 ? "—" : $"{Fmt.Number(_session.LatencyMs, 0)} ms"),
(T("Client collegati"), info is null ? "—" : $"{info.Sessions} / {info.MaxSessions}"),
};
for (int i = 0; i < cells.Length && i < _stateCells.Count; i++)
{
_stateCells[i].Caption.Text = cells[i].Item1;
_stateCells[i].Value.Text = cells[i].Item2;
}
bool ready = SessionMatchesMode && !_busy && _awaitingWelcome is null;
// senza sessione «Connetti e riprendi» apre la connessione; «Nuova partita» vuole il server collegato
_resume.Disabled = _busy || _awaitingWelcome is not null || (_session is not null && !ready);
_newGame.Disabled = !ready;
_probe.Disabled = _busy;
_tutorial.Disabled = _busy;
_localCard.Disabled = _busy;
_remoteCard.Disabled = _busy;
}
/// Elenco ricostruito a ogni aggiornamento: la riga scelta si ritrova per id, non per posizione.
private void ShowSaves()
{
var w = _session!.World;
_shownSaves = w.Saves;
_saves.Clear();
var root = _saves.CreateItem();
var current = _saves.CreateItem(root);
current.SetText(0, $"{T("Partita in corso")} · {w.Summary?.CompanyName ?? ""}");
current.SetText(1, w.Summary?.Date ?? "");
current.SetText(2, T("in corso"));
current.SetMetadata(0, CurrentGame);
current.SetCustomColor(2, Palette.Ok);
TreeItem selected = current;
double now = Time.GetUnixTimeFromSystem();
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs).ThenBy(s => s.SaveId, StringComparer.Ordinal))
{
var item = _saves.CreateItem(root);
item.SetText(0, s.Autosave ? $"{s.Name} ({T("automatico")})" : s.Name);
item.SetText(1, s.GameDate);
item.SetText(2, Ago(now - s.SavedUnixMs / 1000.0));
item.SetMetadata(0, s.SaveId);
for (int c = 1; c < 3; c++) item.SetCustomColor(c, Palette.TextSecondary);
if (s.SaveId == _selectedSave) selected = item;
}
// salvataggio scelto sparito dall'elenco: si torna alla partita in corso
_selectedSave = selected.GetMetadata(0).AsString();
selected.Select(0);
}
private static string Uptime(long seconds)
{
if (seconds < 3600) return $"{Math.Max(1, seconds / 60)} min";
if (seconds < 86_400) return $"{seconds / 3600} h {seconds % 3600 / 60} min";
return $"{seconds / 86_400} {T("giorni")} {seconds % 86_400 / 3600} h";
}
private static string Ago(double seconds)
{
if (seconds < 90) return T("adesso");
if (seconds < 3600) return $"{(int)(seconds / 60)} {T("minuti fa")}";
if (seconds < 86_400) return $"{(int)(seconds / 3600)} {T("ore fa")}";
return $"{(int)(seconds / 86_400)} {T("giorni fa")}";
}
}
///
/// Mappa decorativa della schermata iniziale: pianura, un fiume, una linea a doppio binario con
/// stazioni e i tetti dei paesi, disegnati in codice con la palette della mappa (immagine 05) e
/// velati verso il basso per il titolo. Solo grafica: nessun dato di gioco.
///
public partial class ConnectBackdrop : Control
{
public override void _Draw()
{
var size = Size;
DrawRect(new Rect2(Vector2.Zero, size), Palette.Plain);
// colline e boschi a macchie, posizioni fisse in frazioni della superficie
foreach (var (x, y, r, c) in new[] { (0.15f, 0.2f, 0.16f, Palette.Hill), (0.7f, 0.15f, 0.2f, Palette.Highland), (0.85f, 0.55f, 0.14f, Palette.Undergrowth),
(0.3f, 0.6f, 0.12f, Palette.Undergrowth), (0.55f, 0.35f, 0.07f, Palette.Canopy), (0.1f, 0.45f, 0.06f, Palette.Canopy), (0.62f, 0.72f, 0.05f, Palette.Canopy) })
DrawCircle(new Vector2(x * size.X, y * size.Y), r * Math.Max(size.X, size.Y), c);
// fiume
var river = new Vector2[] { new(0.62f, 0f), new(0.58f, 0.18f), new(0.66f, 0.36f), new(0.6f, 0.55f), new(0.7f, 0.78f), new(0.66f, 1f) };
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Banks, 30, true);
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Water, 20, true);
// linea ferroviaria: massicciata, traversine, rotaie
var rail = new Vector2[] { new(-0.05f, 0.42f), new(0.25f, 0.38f), new(0.48f, 0.44f), new(0.75f, 0.4f), new(1.05f, 0.3f) };
var pts = rail.Select(p => p * size).ToArray();
DrawPolyline(pts, Palette.Ballast, 16, true);
for (int i = 0; i < pts.Length - 1; i++)
{
var a = pts[i];
var b = pts[i + 1];
var dir = (b - a).Normalized();
var n = new Vector2(-dir.Y, dir.X) * 7;
for (float t = 0; t < a.DistanceTo(b); t += 9)
{
var p = a + dir * t;
DrawLine(p - n, p + n, Palette.Sleepers, 3);
}
}
foreach (float off in new[] { -3.5f, 3.5f })
DrawPolyline(pts.Select((p, i) => p + Normal(pts, i) * off).ToArray(), Palette.Rails, 1.5f, true);
// stazioni e paesi
foreach (var (x, y) in new[] { (0.25f, 0.38f), (0.75f, 0.4f) })
{
var c = new Vector2(x * size.X, y * size.Y);
DrawRect(new Rect2(c - new Vector2(22, 26), new Vector2(44, 14)), Palette.Panel);
for (int k = 0; k < 9; k++)
{
var roof = c + new Vector2((k % 3 - 1) * 26 + (k * 7 % 5), 28 + k / 3 * 20);
DrawRect(new Rect2(roof, new Vector2(16, 12)), k % 4 == 0 ? Palette.IndustrialRoof : Palette.TileRoof);
}
}
// velo verso il basso per leggere il titolo
var veil = new Color[] { Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.92f), Palette.WithAlpha(Palette.AppBackground, 0.92f) };
DrawPolygon([new Vector2(0, size.Y * 0.35f), new Vector2(size.X, size.Y * 0.35f), new Vector2(size.X, size.Y), new Vector2(0, size.Y)], veil);
}
private static Vector2 Normal(Vector2[] pts, int i)
{
var dir = (pts[Math.Min(i + 1, pts.Length - 1)] - pts[Math.Max(i - 1, 0)]).Normalized();
return new Vector2(-dir.Y, dir.X);
}
public override void _Notification(int what)
{
if (what == NotificationResized) QueueRedraw();
}
}