F6: scheda industria e schermata di connessione definitive

La scheda dell'industria e la schermata di connessione si allineano alle
immagini di riferimento 07 e 09. I dati che mancavano li calcola il Core
con una funzione pura, e viaggiano in blocchi compatibili del protocollo.
Il formato dei salvataggi non cambia (ADR 0021).

- IndustryOutlook calcola la scheda in sola lettura:
  - fattori dell'efficienza e quello che la limita;
  - ingressi e uscite al mese, con giorni di scorta o di magazzino;
  - fornitori e clienti con prezzo, distanza e linea che li collega;
  - forza lavoro dai contratti dei pendolari;
  - punteggio di crescita del trimestre con le soglie;
  - prezzo medio, utile annuo, stazioni che la servono, sblocco
    dell'acquisto.
  IndustryMath.GrowthScore è ora l'unica formula del punteggio e la usa
  anche IndustrySystem: gli hash non cambiano. Nuovi parametri in
  balance.json, industry.outlook.
- Protocollo:
  - IndustryCard: blocco 1 IndustrySheetInfo;
  - Welcome: blocco 1 ServerInfo (versione, sistema, Docker, tempo di
    attività, passo del ciclo, client collegati);
  - ClientWorld conserva lo stato del server e l'elenco dei salvataggi.
- Client:
  - IndustryPanel a tutto schermo, con tre schede, il grafo della
    catena, impianti e crescita, e i comandi del proprietario;
  - ConnectScreen sostituisce MenuScreen: server locale o in rete,
    stato del server, partite salvate, «Connetti e riprendi» e «Nuova
    partita sul server» su una sessione di prova;
  - testi in strings.csv;
  - pilota automatico: schermate 19_scheda_industria e 20_connessione.
- Test:
  - IndustryOutlookTests;
  - scheda e stato del server via WebSocket;
  - campioni del protocollo con i blocchi nuovi.
  200 test, 181 senza i lenti.

Refs #42.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 14:04:28 +01:00
1 parent 7eec322202
commit 45462bf9ec
28 files changed
+2810 -329

No files matched your search

@@ -254,5 +254,28 @@ public partial class AutoPilot : Node
_game.OpenChronicle();
await Until(() => _game.ChronicleVisible, "cronaca", 30);
await Shot("15_cronaca", 30);
_game.CloseChronicle();
// F6, scheda dell'industria (immagine 07): un'industria di trasformazione vicino alla linea,
// con catena produttiva, forza lavoro e crescita
var processing = World.Industries.Values
.Where(i => !i.Closed && i.Level > 0 && World.Data.Industries.FirstOrDefault(d => d.Id == i.Type)?.Recipe.Inputs.Count > 0)
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).FirstOrDefault() ?? industry;
_game.OpenIndustry(processing.Id);
await Until(() => World.IndustryCards.TryGetValue(processing.Id, out var c) && c.Sheet is not null, "scheda completa dell'industria", 30);
_game.ScrollPanel(0);
await Shot("19_scheda_industria", 40);
// F6, schermata di connessione (immagine 09) sopra la partita: sessione di prova sul server
// locale con il suo stato e l'elenco dei salvataggi (uno appena fatto)
Session.Send(new Save { Name = "Collaudo" });
var launcher = Session.LocalServer ?? throw new InvalidOperationException("collaudo senza server locale");
var connect = new ConnectScreen(World.Data, remember: false);
_game.AddChild(connect);
await Frame();
await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token);
await Until(() => connect.Loaded, "stato del server e salvataggi", 30);
await Shot("20_connessione", 30);
connect.QueueFree();
}
}
+22 -37
View File
@@ -8,7 +8,7 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client;
/// <summary>
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra menu, collegamento e partita;
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra schermata di connessione e partita;
/// alla chiusura termina la sessione e l'eventuale server locale.
/// </summary>
public partial class Main : Node
@@ -56,12 +56,20 @@ public partial class Main : Node
AddChild(screen);
}
/// <summary>Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.</summary>
private void ShowMenu(string status = "")
{
var menu = new MenuScreen();
menu.LocalGame += StartLocal;
menu.ConnectToServer += ShowConnect;
menu.LanguageChanged += code =>
if (_data is null)
{
// senza dati non si può aprire nessuna sessione: resta solo il messaggio
var label = UiTheme.Text(status, 16, Palette.Danger);
label.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.Center);
Swap(label);
return;
}
var screen = new ConnectScreen(_data);
screen.PlayRequested += ShowGame;
screen.LanguageChanged += code =>
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
@@ -70,32 +78,11 @@ public partial class Main : Node
TranslationServer.SetLocale(code);
ShowMenu();
};
Swap(menu);
if (status.Length > 0) menu.SetStatus(status);
}
private void ShowConnect()
{
var screen = new ConnectScreen();
screen.Back += () => ShowMenu();
screen.ConnectRequested += async (uri, token, label) =>
{
if (_data is null) return;
screen.SetStatus(T("Collegamento in corso…"), busy: true);
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var session = await GameSession.ConnectAsync(_data, uri, token, label, cts.Token);
ShowGame(session);
}
catch (Exception e)
{
screen.SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", busy: false);
}
};
Swap(screen);
if (status.Length > 0) screen.SetStatus(status, error: true);
}
/// <summary>Collaudo: server locale da zero e subito in partita, senza la schermata di connessione.</summary>
private async void StartLocal()
{
if (_data is null) return;
@@ -105,13 +92,11 @@ public partial class Main : Node
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."));
return;
}
if (_screen is MenuScreen menu) menu.SetStatus(T("Avvio del server locale…"));
var launcher = new LocalServerLauncher();
try
{
string dataDir = ProjectSettings.GlobalizePath(_autopilot is null ? "user://server" : "user://autopilot-server");
// il collaudo parte sempre da una partita nuova
if (_autopilot is not null && Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
string dataDir = ProjectSettings.GlobalizePath("user://autopilot-server");
if (Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
int port = await launcher.StartAsync(server, dataDir, 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;
@@ -141,10 +126,10 @@ public partial class Main : Node
public override void _Notification(int what)
{
if (what == NotificationWMCloseRequest && _session is not null)
{
_session.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
_session = null;
}
if (what != NotificationWMCloseRequest) return;
// anche la sessione di prova della schermata di connessione chiude il suo server locale
var session = _session ?? (_screen as ConnectScreen)?.TakeSession();
_session = null;
session?.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
}
}
@@ -11,20 +11,35 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
/// Scheda dell'industria a tutto schermo (immagine di riferimento 07, sezione 11): in alto nome,
/// livello, proprietà, stazione che la serve, valore stimato e l'anello dell'efficienza con il
/// fattore che la limita; sotto tre schede (materie prime in ingresso, forza lavoro, produzione), il
/// grafo della catena produttiva con fornitori, città dei pendolari e clienti, e la scheda «Impianti
/// e crescita» con condizione, punteggio trimestrale e soglie, comandi del proprietario e storico dei
/// fermi. Tutti i numeri arrivano dal server nella scheda (IndustryCard, blocco 1: ADR 0021); il
/// pannello li chiede una volta al secondo e li mostra com'è.
/// </summary>
public partial class IndustryPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
private readonly OptionButton _chooser = new() { CustomMinimumSize = new Vector2(320, 44), FitToLongestItem = false };
private readonly List<int> _ids = [];
private readonly VBoxContainer _header = PanelKit.Column(8);
private readonly Label _title = UiTheme.TitleLabel("", 44);
private readonly Label _subtitle = UiTheme.Text("", 15, Palette.TextSecondary);
private readonly Label _ownerLine = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Label _valuation = UiTheme.Text("", 26, Palette.AmberLight, bold: true);
private readonly EfficiencyRing _ring = new();
private readonly Label _limit = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly VBoxContainer _notices = PanelKit.Column(6);
private readonly ScrollContainer _scroll = new() { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
private readonly VBoxContainer _inputs = PanelKit.Column(8);
private readonly VBoxContainer _workforce = PanelKit.Column(8);
private readonly VBoxContainer _production = PanelKit.Column(8);
private readonly ChainGraph _graph = new();
private readonly VBoxContainer _chainFooter = PanelKit.Column(8);
private readonly VBoxContainer _plants = PanelKit.Column(8);
private readonly VBoxContainer _controls = PanelKit.Column(8);
private readonly VBoxContainer _details = PanelKit.Column(6);
private readonly VBoxContainer _history = PanelKit.Column(4);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<Button> _budgetButtons = [];
private SpinBox? _partsOrder;
@@ -33,25 +48,106 @@ public partial class IndustryPanel : VBoxContainer
private int _entityVersion = -1, _detailVersion = -1;
private double _request, _sinceRefresh;
/// <summary>«Torna alla mappa».</summary>
public event Action? CloseRequested;
/// <summary>«Crea una linea verso questa industria»: strumento binari centrato sull'industria.</summary>
public event Action<int>? PlanLineRequested;
public IndustryPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Industrie"), 34));
var help = UiTheme.Text(T("Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(_list);
AddChild(PanelKit.Separator());
AddChild(_header);
AddChild(_controls);
AddChild(_details);
AddThemeConstantOverride("separation", 14);
SizeFlagsVertical = SizeFlags.ExpandFill;
// barra di navigazione: ritorno alla mappa e scelta dell'industria
var nav = PanelKit.Row(12);
var back = new Button { Text = "‹ " + T("Mappa"), CustomMinimumSize = new Vector2(120, 44) };
back.Pressed += () => CloseRequested?.Invoke();
nav.AddChild(back);
nav.AddChild(_chooser);
_chooser.ItemSelected += i => Select(_ids[(int)i]);
var hint = UiTheme.Text(T("Scheda dell'industria"), 13, Palette.TextSecondary);
hint.SizeFlagsVertical = SizeFlags.ShrinkCenter;
nav.AddChild(hint);
AddChild(nav);
// intestazione: nome, livello, proprietà, valore ed efficienza
var header = PanelKit.Row(24);
var titles = PanelKit.Column(2);
titles.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_title.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
titles.AddChild(_title);
titles.AddChild(_subtitle);
_ownerLine.AutowrapMode = TextServer.AutowrapMode.WordSmart;
titles.AddChild(_ownerLine);
header.AddChild(titles);
var value = PanelKit.Column(0);
value.SizeFlagsVertical = SizeFlags.ShrinkCenter;
var valueCaption = UiTheme.Text(T("Valore stimato"), 13, Palette.TextSecondary);
valueCaption.HorizontalAlignment = HorizontalAlignment.Right;
_valuation.HorizontalAlignment = HorizontalAlignment.Right;
value.AddChild(valueCaption);
value.AddChild(_valuation);
header.AddChild(value);
var ring = PanelKit.Column(2);
ring.AddChild(_ring);
_limit.HorizontalAlignment = HorizontalAlignment.Center;
_limit.CustomMinimumSize = new Vector2(150, 0);
_limit.AutowrapMode = TextServer.AutowrapMode.WordSmart;
ring.AddChild(_limit);
header.AddChild(ring);
AddChild(header);
AddChild(_notices);
// corpo scorrevole: tre schede, poi catena produttiva e impianti
AddChild(_scroll);
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 10);
_scroll.AddChild(margin);
var body = PanelKit.Column(18);
margin.AddChild(body);
var cards = PanelKit.Row(18);
cards.AddChild(Card(T("Materie prime in ingresso"), _inputs, 1));
cards.AddChild(Card(T("Forza lavoro"), _workforce, 1));
cards.AddChild(Card(T("Produzione"), _production, 1));
body.AddChild(cards);
var lower = PanelKit.Row(18);
var chain = PanelKit.Column(10);
var legend = PanelKit.Row(16);
foreach (var (text, color) in new[] { (T("merci su linea"), Palette.Amber), (T("lavoratori"), Palette.Workers), (T("personale"), Palette.Staff), (T("non collegato"), Palette.TextSecondary) })
legend.AddChild(UiTheme.Text("— " + text, 12, color));
chain.AddChild(legend);
_graph.IndustryClicked += Select;
chain.AddChild(_graph);
chain.AddChild(_chainFooter);
lower.AddChild(Card(T("Catena produttiva"), chain, 1.6f));
var plants = PanelKit.Column(10);
plants.AddChild(_plants);
plants.AddChild(_controls);
plants.AddChild(_history);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_list.ItemSelected += i => Select(_ids[(int)i]);
plants.AddChild(_status);
lower.AddChild(Card(T("Impianti e crescita"), plants, 1));
body.AddChild(lower);
RefreshList();
}
/// <summary>Scheda con titolo e contenuto, larga in proporzione al rapporto dato.</summary>
private static PanelContainer Card(string title, Control content, float ratio)
{
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 22));
var col = PanelKit.Column(12);
col.AddChild(UiTheme.Text(title, 19, bold: true));
col.AddChild(content);
card.AddChild(col);
return card;
}
/// <summary>Industria mostrata (−1 se nessuna).</summary>
public int Industry => _industry;
@@ -60,11 +156,19 @@ public partial class IndustryPanel : VBoxContainer
if (id == _industry) return;
_industry = id;
_status.Text = "";
_scroll.ScrollVertical = 0;
SyncSelection();
Request();
Refresh();
}
/// <summary>Scorre il corpo della scheda (0 in cima, 1 in fondo).</summary>
public void ScrollTo(double fraction)
{
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
private void Request()
{
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
@@ -98,10 +202,17 @@ public partial class IndustryPanel : VBoxContainer
if (w.EntityVersion != _entityVersion) RefreshList();
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
foreach (var c in _header.GetChildren()) c.QueueFree();
foreach (var c in _details.GetChildren()) c.QueueFree();
foreach (var box in new[] { _notices, _inputs, _workforce, _production, _chainFooter, _plants, _history })
foreach (var c in box.GetChildren()) c.QueueFree();
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
{
_title.Text = T("Industrie");
_subtitle.Text = T("Scegli un'industria nell'elenco in alto.");
_ownerLine.Text = "";
_valuation.Text = "";
_limit.Text = "";
_ring.Set(0, Palette.Amber);
_graph.Visible = false;
BuildControls(null);
return;
}
@@ -109,12 +220,24 @@ public partial class IndustryPanel : VBoxContainer
BuildHeader(w, ind, card);
BuildControls(ind);
UpdateControls(ind, card);
BuildDetails(w, ind, card);
var sheet = card?.Sheet;
if (card is null || sheet is null)
{
_graph.Visible = false;
foreach (var box in new[] { _inputs, _workforce, _production, _plants })
box.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
BuildInputs(w, sheet);
BuildWorkforce(w, sheet);
BuildProduction(w, card, sheet);
BuildChain(w, ind, card, sheet);
BuildPlants(w, ind, card, sheet);
}
// ------------------------------------------------------------------ elenco
/// <summary>Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
/// <summary>Selettore: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
private void RefreshList()
{
var w = _session.World;
@@ -126,7 +249,7 @@ public partial class IndustryPanel : VBoxContainer
if (!same)
{
_ids.Clear();
_list.Clear();
_chooser.Clear();
}
for (int n = 0; n < ordered.Count; n++)
{
@@ -137,13 +260,12 @@ public partial class IndustryPanel : VBoxContainer
if (!same)
{
_ids.Add(ind.Id);
_list.AddItem(text);
_chooser.AddItem(text, n);
}
else if (_list.GetItemText(n) != text)
else if (_chooser.GetItemText(n) != text)
{
_list.SetItemText(n, text);
_chooser.SetItemText(n, text);
}
_list.SetItemCustomFgColor(n, ind.Owner == me ? Palette.AmberLight : MaintenancePanel.ConditionColor((int)ind.Condition));
}
if (!same) SyncSelection();
}
@@ -151,175 +273,341 @@ public partial class IndustryPanel : VBoxContainer
private void SyncSelection()
{
int index = _ids.IndexOf(_industry);
if (index < 0)
{
_list.DeselectAll();
return;
}
if (!_list.IsSelected(index)) _list.Select(index);
_list.EnsureCurrentIsVisible();
if (index >= 0 && _chooser.Selected != index) _chooser.Select(index);
if (index < 0) _chooser.Select(-1);
}
// ------------------------------------------------------------------ scheda
// ------------------------------------------------------------------ intestazione
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
int me = w.Summary?.CompanyId ?? 0;
var title = UiTheme.TitleLabel(ind.Name, 30);
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_header.AddChild(title);
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
_header.AddChild(UiTheme.Text($"{def?.NameIt ?? ind.Type} · {T("livello")} {ind.Level}", 14, Palette.TextSecondary));
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
_header.AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
var sheet = card?.Sheet;
_title.Text = ind.Name;
string level = sheet is null ? $"{T("Livello")} {ind.Level}" : $"{T("Livello")} {sheet.Level} {T("di")} {sheet.MaxLevel}";
_subtitle.Text = $"{TypeName(w, ind.Type)} · {level}";
string owner = ind.Owner == me ? T("la tua compagnia") : ind.Owner < 0 ? T("proprietari privati") : Fmt.Company(w, ind.Owner);
string served = "";
if (sheet is not null)
{
var names = sheet.ServingStations.Select(s => w.Stations.TryGetValue(s, out var st) ? st.Name : $"#{s}").Take(3).ToList();
served = names.Count == 0
? " · " + T("nessuna stazione la serve")
: $" · {T("servita dalla stazione")} {string.Join(", ", names)}" +
(sheet.ServingLine >= 0 && w.Lines.TryGetValue(sheet.ServingLine, out var line) ? $" ({T("linea")} {line.Name})" : "");
}
_ownerLine.Text = $"{T("Proprietà")}: {owner}{served}";
_valuation.Text = card?.Valuation.ToString() ?? "—";
float e = sheet?.Efficiency ?? ind.Efficiency;
var limit = sheet is null ? IndustryLimit.None : (IndustryLimit)sheet.Limit;
_ring.Set(e, limit is IndustryLimit.None ? Palette.Ok : e < 0.35f ? Palette.Danger : Palette.Amber);
_limit.Text = sheet is null ? T("Efficienza") : $"{T("Efficienza")} · {LimitText(limit)}";
long today = Fmt.Today(w);
if (ind.StoppedUntilDay >= today)
_header.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
_notices.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
else if (ind.PendingWork != 0)
_header.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
_notices.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
if (ind.PartsShort)
_header.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
var stats = PanelKit.Row(8);
stats.AddChild(PanelKit.Stat(T("Condizione"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", MaintenancePanel.ConditionColor((int)ind.Condition))));
stats.AddChild(PanelKit.Stat(T("Resa impianti"), PanelKit.Value(card is null ? "—" : "×" + Fmt.Number(card.ConditionMultiplier, 2))));
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value(Fmt.Pct(ind.Efficiency, 0))));
_header.AddChild(stats);
var bar = new ProgressBar { MaxValue = 100, Value = ind.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
var color = MaintenancePanel.ConditionColor((int)ind.Condition);
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
_header.AddChild(bar);
var m = w.Data.Balance.IndustryMaintenance;
_header.AddChild(Wrapped($"{T("Sopra il")} {Fmt.Number(m.EfficiencyFullAbove, 0)}% {T("gli impianti rendono pieno; sotto calano fino a")} ×{Fmt.Number(m.EfficiencyAt20, 1)} {T("al 20% e si fermano più spesso.")}", 12, Palette.TextSecondary));
_notices.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
}
/// <summary>Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
// ------------------------------------------------------------------ tre schede
private void BuildInputs(ClientWorld w, IndustrySheetInfo s)
{
if (s.Inputs.Count == 0)
{
_inputs.AddChild(Wrapped(T("Non consuma materie prime: estrae, coltiva o raccoglie da sé."), 13, Palette.TextSecondary));
}
foreach (var f in s.Inputs)
{
string unit = Unit(w, f.Good);
_inputs.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
_inputs.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, f.Limiting ? Palette.Danger : Palette.Amber));
string days = f.Days < 0 ? "" : $" · {T("bastano per")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
_inputs.AddChild(UiTheme.Text($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
foreach (var p in f.Partners) _inputs.AddChild(PartnerLine(w, p, unit, supplier: true));
if (f.Partners.Count == 0) _inputs.AddChild(UiTheme.Text(T("Nessun fornitore nella regione"), 12, Palette.TextSecondary));
_inputs.AddChild(PanelKit.Separator());
}
if (s.Inputs.Count > 0)
_inputs.AddChild(PanelKit.Pair($"{T("Copertura degli ingressi")} ({s.CoverageWindowDays} {T("giorni")})", ColoredValue(Fmt.Pct(s.CovInput, 0), CoverageColor(s.CovInput))));
}
private void BuildWorkforce(ClientWorld w, IndustrySheetInfo s)
{
WorkforceBlock(w, s.Workers, s.CovWorkers, s.CoverageWindowDays, staff: false);
_workforce.AddChild(PanelKit.Separator());
WorkforceBlock(w, s.Staff, s.CovStaff, s.CoverageWindowDays, staff: true);
var limit = (IndustryLimit)s.Limit;
if (limit is IndustryLimit.Workers or IndustryLimit.Staff)
{
var wf = limit == IndustryLimit.Staff ? s.Staff : s.Workers;
string who = limit == IndustryLimit.Staff ? T("il personale qualificato") : T("i lavoratori");
_workforce.AddChild(UiTheme.Notice($"{T("Collo di bottiglia")}: {who}. {T("Mancano")} {wf.Missing} {T("persone: portale in treno dalle città vicine.")}"));
}
}
private void WorkforceBlock(ClientWorld w, WorkforceInfo f, float coverage30, int window, bool staff)
{
var color = staff ? Palette.Staff : Palette.Workers;
if (f.Jobs <= 0)
{
_workforce.AddChild(UiTheme.Text(staff ? T("Nessun posto per il personale") : T("Nessun posto per i lavoratori"), 13, Palette.TextSecondary));
return;
}
_workforce.AddChild(FlowHeader(staff ? T("Personale qualificato") : T("Lavoratori"), $"{Fmt.Number(f.Present, 0)} / {f.Jobs} {T("presenti")}", color));
_workforce.AddChild(Bar(f.Jobs <= 0 ? 0 : f.Present / f.Jobs, color));
string minutes = f.AverageMinutes < 0 ? "" : $" · {T("viaggio medio")} {Fmt.Number(f.AverageMinutes, 0)} min";
_workforce.AddChild(UiTheme.Text($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("al lavoro ora")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
if (f.Missing > 0)
{
string reason = EmploymentPanel.ReasonText(w, f.Reason, f.ReasonLine, staff);
_workforce.AddChild(Wrapped($"{T("Mancano")} {f.Missing}" + (reason.Length > 0 ? " · " + reason : ""), 12, Palette.Amber));
}
foreach (var src in f.Sources)
{
string town = w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}";
string via = src.Walking ? T("a piedi") : src.Line >= 0 && w.Lines.TryGetValue(src.Line, out var line) ? line.Name : Fmt.Company(w, src.Carrier);
string time = src.Walking || src.Minutes <= 0 ? "" : $" · {Fmt.Number(src.Minutes, 0)} min";
_workforce.AddChild(Wrapped($"• {src.Headcount} {T("da")} {town} · {via}{time} · {Fmt.Pct(src.Coverage, 0)}", 12, color));
}
if (f.SourceCount > f.Sources.Count)
_workforce.AddChild(UiTheme.Text($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
}
private void BuildProduction(ClientWorld w, IndustryCard card, IndustrySheetInfo s)
{
foreach (var f in s.Outputs)
{
string unit = Unit(w, f.Good);
_production.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
_production.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, Palette.Amber));
string full = f.Days < 0 ? "" : f.Days <= 0 ? " · " + T("magazzino pieno") : $" · {T("pieno tra")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
_production.AddChild(UiTheme.Text($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
foreach (var p in f.Partners) _production.AddChild(PartnerLine(w, p, unit, supplier: false));
if (f.Partners.Count == 0) _production.AddChild(UiTheme.Text(T("Nessun cliente nella regione"), 12, Palette.TextSecondary));
_production.AddChild(PanelKit.Separator());
}
if (s.Outputs.Count == 0) _production.AddChild(UiTheme.Text(T("Nessuna produzione"), 13, Palette.TextSecondary));
_production.AddChild(PanelKit.Pair(T("Magazzino"), PanelKit.Value($"{s.StorageDays} {T("giorni di produzione")}")));
_production.AddChild(PanelKit.Pair(T("Prezzo medio realizzato"), PanelKit.Value(s.AveragePrice < 0 ? "—" : Fmt.PricePrecise(s.AveragePrice))));
_production.AddChild(PanelKit.Pair(T("Utile annuo stimato"), ColoredValue(s.AnnualProfit.ToString(), s.AnnualProfit.Cents < 0 ? Palette.Danger : Palette.Text)));
_production.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
}
// ------------------------------------------------------------------ catena produttiva
private void BuildChain(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
{
var left = new List<ChainNode>();
foreach (var f in s.Inputs)
foreach (var p in f.Partners.Take(2))
left.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.Number(p.MonthlyUnits, 0)} {Unit(w, f.Good)}/{T("mese")}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
foreach (var (wf, staff) in new[] { (s.Workers, false), (s.Staff, true) })
foreach (var src in wf.Sources.Take(staff ? 1 : 2))
left.Add(new ChainNode(w.Towns.TryGetValue(src.Town, out var t) ? t.Name : $"#{src.Town}",
$"{src.Headcount} {(staff ? T("tecnici") : T("lavoratori"))}", staff ? ChainEdge.Staff : ChainEdge.Workers));
var right = new List<ChainNode>();
foreach (var f in s.Outputs)
foreach (var p in f.Partners.Take(3))
right.Add(new ChainNode(PartnerName(w, p), $"{GoodName(w, f.Good)} · {Fmt.PricePrecise(p.Price)}", p.Line >= 0 ? ChainEdge.Goods : ChainEdge.Unlinked, PartnerIndustry(p)));
string outputs = string.Join(", ", s.Outputs.Select(f => GoodName(w, f.Good)));
_graph.Set(left, new ChainNode(ind.Name, $"{T("Livello")} {s.Level} · {outputs}", ChainEdge.Goods), right);
_graph.Visible = true;
// azioni della catena: linea verso l'industria e offerta di acquisto
var actions = PanelKit.Row(10);
var plan = UiTheme.Primary(T("Crea una linea verso questa industria"));
plan.CustomMinimumSize = new Vector2(0, 44);
int id = ind.Id;
plan.Pressed += () => PlanLineRequested?.Invoke(id);
actions.AddChild(plan);
int me = w.Summary?.CompanyId ?? 0;
if (ind.Owner != me)
{
var buy = new Button { Text = T("Fai un'offerta di acquisto"), CustomMinimumSize = new Vector2(0, 44) };
buy.Disabled = !(s.ForSale && s.BuyUnlocked);
buy.Pressed += () => _session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), Result);
actions.AddChild(buy);
}
_chainFooter.AddChild(actions);
if (ind.Owner == me)
_chainFooter.AddChild(UiTheme.Text(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
else if (!s.ForSale)
_chainFooter.AddChild(UiTheme.Text($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 12, Palette.TextSecondary));
else if (!s.BuyUnlocked)
_chainFooter.AddChild(UiTheme.Text($"{T("Disponibile al livello")} «{Fmt.Tier(w, s.BuyTier)}» ({T("avanzamento")} {Fmt.Progress(s.BuyProgress)})", 12, Palette.TextSecondary));
else
_chainFooter.AddChild(UiTheme.Text($"{T("Prezzo chiesto dai proprietari")}: {card.Valuation}", 12, Palette.TextSecondary));
}
// ------------------------------------------------------------------ impianti e crescita
private void BuildPlants(ClientWorld w, IndustryInfo ind, IndustryCard card, IndustrySheetInfo s)
{
var condColor = MaintenancePanel.ConditionColor((int)ind.Condition);
_plants.AddChild(PanelKit.Pair(T("Condizione degli impianti"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", condColor)));
_plants.AddChild(Bar(ind.Condition / 100f, condColor));
_plants.AddChild(PanelKit.Pair(T("Moltiplicatore di resa"), PanelKit.Value("×" + Fmt.Number(card.ConditionMultiplier, 2))));
_plants.AddChild(UiTheme.Text($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
_plants.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
if (s.ProfitFactor < 1) _plants.AddChild(PanelKit.Pair(T("Fattore di redditività"), PanelKit.Value("×" + Fmt.Number(s.ProfitFactor, 2))));
if (s.ReserveFraction >= 0)
_plants.AddChild(PanelKit.Pair(T("Giacimento residuo"), ColoredValue(Fmt.Pct(s.ReserveFraction, 0), s.Depletion < 1 ? Palette.Amber : Palette.Text)));
if (s.EventCapacity < 1) _plants.AddChild(PanelKit.Pair(T("Capacità ridotta da un evento"), ColoredValue("×" + Fmt.Number(s.EventCapacity, 2), Palette.Amber)));
// crescita trimestrale: punteggio in corso, soglie, componenti
_plants.AddChild(PanelKit.Separator());
_plants.AddChild(FlowHeader(T("Punteggio di crescita"), $"{Fmt.Number(s.Score, 2)} · {T("giorno")} {s.QuarterDay} {T("di")} {s.QuarterDays}"));
var bar = new ScoreBar();
bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
_plants.AddChild(bar);
_plants.AddChild(UiTheme.Text($"{T("sotto")} {Fmt.Number(s.DowngradeThreshold, 2)} {T("perde un livello")} · {T("sopra")} {Fmt.Number(s.UpgradeThreshold, 2)} {T("per")} {s.UpgradeQuarters} {T("trimestri sale")} ({s.QuartersAbove}/{s.UpgradeQuarters})", 12, Palette.TextSecondary));
var g = w.Data.Balance.Growth;
_plants.AddChild(UiTheme.Text($"{T("spedito")} {Fmt.Pct(s.Shipped, 0)} ×{Fmt.Number(g.WeightShipped, 1)} · {T("copertura")} {Fmt.Pct(s.Coverage, 0)} ×{Fmt.Number(g.WeightCoverage, 1)} · {T("utile")} {Fmt.Pct(s.Profit, 0)} ×{Fmt.Number(g.WeightProfit, 1)}", 12, Palette.TextSecondary));
if (s.LastScore >= 0) _plants.AddChild(UiTheme.Text($"{T("ultimo trimestre")} {Fmt.Number(s.LastScore, 2)}", 12, Palette.TextSecondary));
if (!s.Served)
_plants.AddChild(Wrapped(T("Nessun vettore la serve: il livello resta fermo finché una linea non la collega."), 12, Palette.Amber));
else if (s.Level >= s.MaxLevel)
_plants.AddChild(UiTheme.Text(T("Livello massimo raggiunto"), 12, Palette.Ok));
int me = w.Summary?.CompanyId ?? 0;
if (ind.Owner == me)
{
_plants.AddChild(PanelKit.Separator());
_plants.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
_plants.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
_plants.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
_plants.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
_plants.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
_plants.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
_plants.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
}
_history.AddChild(PanelKit.Separator());
_history.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
if (card.Stops.Count == 0) _history.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
foreach (var stop in Enumerable.Reverse(card.Stops).Take(6))
_history.AddChild(UiTheme.Text($"{Fmt.Date(w, stop.Day)} · {StopName(stop.Kind)} · {stop.Days} {T("giorni")}", 13, stop.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary));
}
/// <summary>Comandi del proprietario: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
private void BuildControls(IndustryInfo? ind)
{
var key = ind is null ? (-1, -1) : (ind.Id, ind.Owner);
int me = _session.World.Summary?.CompanyId ?? 0;
var key = ind is null || ind.Owner != me ? (-1, -1) : (ind.Id, ind.Owner);
if (key == _controlsKey) return;
_controlsKey = key;
foreach (var c in _controls.GetChildren()) c.QueueFree();
_budgetButtons.Clear();
_partsOrder = null;
if (ind is null) return;
if (ind is null || ind.Owner != me) return;
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
int id = ind.Id;
if (ind.Owner == me)
_controls.AddChild(PanelKit.Separator());
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
var row = PanelKit.Row(6);
var group = new ButtonGroup();
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
{
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
var row = PanelKit.Row(6);
var group = new ButtonGroup();
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
{
var p = w.Data.Balance.IndustryMaintenance.For(budget);
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
_budgetButtons.Add(b);
row.AddChild(b);
}
_controls.AddChild(row);
var p = w.Data.Balance.IndustryMaintenance.For(budget);
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
_budgetButtons.Add(b);
row.AddChild(b);
}
_controls.AddChild(row);
var order = PanelKit.Row(6);
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
caption.MouseFilter = MouseFilterEnum.Pass;
order.AddChild(caption);
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
order.AddChild(_partsOrder);
var orderButton = new Button { Text = T("Ordina ricambi") };
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
order.AddChild(orderButton);
_controls.AddChild(order);
var order = PanelKit.Row(6);
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
caption.MouseFilter = MouseFilterEnum.Pass;
order.AddChild(caption);
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
order.AddChild(_partsOrder);
var orderButton = new Button { Text = T("Ordina ricambi") };
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
order.AddChild(orderButton);
_controls.AddChild(order);
var actions = PanelKit.Row(6);
var m = w.Data.Balance.IndustryMaintenance;
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(overhaul);
var upgrade = UiTheme.Primary(T("Ammoderna"));
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(upgrade);
_controls.AddChild(actions);
}
else if (ind.Owner < 0)
{
_controls.AddChild(UiTheme.Text(T("In vendita"), 14, bold: true));
var price = PanelKit.Value("—");
price.Name = "Price";
_controls.AddChild(PanelKit.Pair(T("Prezzo chiesto dai proprietari"), price));
var buy = UiTheme.Primary(T("Acquista"));
buy.Pressed += () =>
{
if (_session.World.IndustryCards.TryGetValue(id, out var c))
_session.Command(new BuyIndustryCommand(new IndustryId(id), c.Valuation), Result);
else
Request();
};
_controls.AddChild(buy);
if (Fmt.UnlockTier(w, u => u.BuyIndustry) is { } tier)
_controls.AddChild(Wrapped($"{T("L'acquisto di industrie si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
else
{
_controls.AddChild(Wrapped($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 13, Palette.TextSecondary));
}
var actions = PanelKit.Row(6);
var m = w.Data.Balance.IndustryMaintenance;
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(overhaul);
var upgrade = UiTheme.Primary(T("Ammoderna"));
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(upgrade);
_controls.AddChild(actions);
}
private void UpdateControls(IndustryInfo ind, IndustryCard? card)
{
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
if (_controls.FindChild("Price", true, false) is Label price) price.Text = card?.Valuation.ToString() ?? "—";
}
private void BuildDetails(ClientWorld w, IndustryInfo ind, IndustryCard? card)
// ------------------------------------------------------------------ pezzi
private static HBoxContainer FlowHeader(string name, string value, Color? color = null)
{
if (card is null)
{
_details.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
int me = w.Summary?.CompanyId ?? 0;
_details.AddChild(UiTheme.Text(T("Impianti"), 14, bold: true));
_details.AddChild(PanelKit.Pair(T("Usura al giorno"), PanelKit.Value("−" + Fmt.Number(card.WearPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Recupero al giorno"), PanelKit.Value("+" + Fmt.Number(card.RecoveryPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
_details.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
if (ind.Owner == me)
{
_details.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
_details.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
_details.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
_details.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
}
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Scorte"), 14, bold: true));
_details.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
_details.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
_details.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
_details.AddChild(UiTheme.Text($"{T("servono")} {card.MachineryRequired} {T("macchinari per il prossimo lavoro")}", 12, Palette.TextSecondary));
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
if (card.Stops.Count == 0) _details.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
foreach (var s in Enumerable.Reverse(card.Stops).Take(8))
{
var l = UiTheme.Text($"{Fmt.Date(w, s.Day)} · {StopName(s.Kind)} · {s.Days} {T("giorni")}", 13, s.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary);
_details.AddChild(l);
}
var row = PanelKit.Row(8);
var l = UiTheme.Text(name, 15, color, bold: true);
l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
row.AddChild(l);
row.AddChild(UiTheme.Text(value, 14, bold: true));
return row;
}
private static ProgressBar Bar(float fraction, Color color)
{
var bar = new ProgressBar { MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
return bar;
}
private static Control PartnerLine(ClientWorld w, ChainPartnerInfo p, string unit, bool supplier)
{
string link = p.Line >= 0 && w.Lines.TryGetValue(p.Line, out var line)
? $"{T("linea")} {line.Name}"
: $"{T("non collegata")} · {Fmt.Number(p.DistanceKm, 1)} km";
string amount = (ChainPartnerKind)p.Kind == ChainPartnerKind.Hub ? "" : $" · {Fmt.Number(p.MonthlyUnits, 0)} {unit}/{T("mese")}";
string text = $"{(supplier ? "←" : "→")} {PartnerName(w, p)}{amount} · {Fmt.PricePrecise(p.Price)} · {link}";
return Wrapped(text, 12, p.Line >= 0 ? Palette.AmberLight : Palette.TextSecondary);
}
private static string PartnerName(ClientWorld w, ChainPartnerInfo p) => (ChainPartnerKind)p.Kind switch
{
ChainPartnerKind.Industry => w.Industries.TryGetValue(p.Target, out var i) ? i.Name : $"#{p.Target}",
ChainPartnerKind.Hub => w.Hubs.TryGetValue(p.Target, out var h) ? h.Name : $"#{p.Target}",
_ => w.Towns.TryGetValue(p.Target, out var t) ? t.Name : $"#{p.Target}",
};
private static int PartnerIndustry(ChainPartnerInfo p) => (ChainPartnerKind)p.Kind == ChainPartnerKind.Industry ? p.Target : -1;
private static bool English => TranslationServer.GetLocale().StartsWith("en");
private static string GoodName(ClientWorld w, int good) =>
good >= 0 && good < w.Data.Goods.Count ? (English ? w.Data.Goods[good].NameEn : w.Data.Goods[good].NameIt) : $"#{good}";
private static string Unit(ClientWorld w, int good) => good >= 0 && good < w.Data.Goods.Count ? w.Data.Goods[good].Unit : "";
private static string TypeName(ClientWorld w, string type)
{
var def = w.Data.Industries.FirstOrDefault(d => d.Id == type);
return def is null ? type : English ? def.NameEn : def.NameIt;
}
private static Color CoverageColor(float coverage) => coverage >= 0.9f ? Palette.Ok : coverage >= 0.5f ? Palette.Amber : Palette.Danger;
private static Control StockRow(string caption, int have, int target, Color color)
{
var row = PanelKit.Row(8);
@@ -335,6 +623,21 @@ public partial class IndustryPanel : VBoxContainer
// ------------------------------------------------------------------ testi
/// <summary>Fattore che limita l'efficienza (IndustryLimit) nella lingua dell'interfaccia.</summary>
public static string LimitText(IndustryLimit limit) => limit switch
{
IndustryLimit.None => T("a piena capacità"),
IndustryLimit.Inputs => T("limitata dalle materie prime"),
IndustryLimit.Workers => T("limitata dai lavoratori"),
IndustryLimit.Staff => T("limitata dal personale"),
IndustryLimit.Profit => T("limitata dalla redditività"),
IndustryLimit.Condition => T("limitata dagli impianti"),
IndustryLimit.Depletion => T("limitata dal giacimento"),
IndustryLimit.Event => T("limitata da un evento"),
IndustryLimit.Stopped => T("ferma"),
_ => T("inattiva"),
};
public static string StopName(byte kind) => kind switch
{
1 => T("Guasto"),
@@ -0,0 +1,185 @@
using Godot;
using RailEnterprise.Client.App;
namespace RailEnterprise.Client.Panels;
/// <summary>Anello dell'efficienza (immagine 07, in alto a destra): arco ambra sulla percentuale.</summary>
public partial class EfficiencyRing : Control
{
private float _value;
private Color _color = Palette.Amber;
public EfficiencyRing() => CustomMinimumSize = new Vector2(112, 112);
public void Set(float value, Color color)
{
_value = Math.Clamp(value, 0, 1);
_color = color;
QueueRedraw();
}
public override void _Draw()
{
var c = Size / 2;
float r = Math.Min(Size.X, Size.Y) / 2 - 8;
DrawArc(c, r, 0, Mathf.Tau, 64, Palette.Inner, 10, true);
if (_value > 0) DrawArc(c, r, -Mathf.Pi / 2, -Mathf.Pi / 2 + Mathf.Tau * _value, 64, _color, 10, true);
string text = Fmt.Pct(_value, 0);
var font = UiTheme.BodyBold;
const int size = 24;
var s = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
DrawString(font, new Vector2(c.X - s.X / 2, c.Y + s.Y / 4), text, HorizontalAlignment.Left, -1, size, Palette.Text);
}
}
/// <summary>
/// Barra del punteggio di crescita: il riempimento è il punteggio del trimestre in corso, le tacche
/// sono le soglie di declassamento (rossa) e di promozione (verde), la lineetta l'ultimo trimestre.
/// </summary>
public partial class ScoreBar : Control
{
private float _score, _last = -1, _down, _up;
public ScoreBar() => CustomMinimumSize = new Vector2(0, 26);
public void Set(float score, float last, float down, float up)
{
(_score, _last, _down, _up) = (Math.Clamp(score, 0, 1), last, down, up);
QueueRedraw();
}
public override void _Draw()
{
float h = 12, y = 7, w = Size.X;
DrawRect(new Rect2(0, y, w, h), Palette.Inner);
var fill = _score >= _up ? Palette.Ok : _score < _down ? Palette.Danger : Palette.Amber;
DrawRect(new Rect2(0, y, w * _score, h), fill);
DrawLine(new Vector2(w * _down, 2), new Vector2(w * _down, y + h + 5), Palette.Danger, 2);
DrawLine(new Vector2(w * _up, 2), new Vector2(w * _up, y + h + 5), Palette.Ok, 2);
if (_last >= 0) DrawLine(new Vector2(w * Math.Clamp(_last, 0, 1), y - 3), new Vector2(w * Math.Clamp(_last, 0, 1), y + h + 3), Palette.Text, 2);
}
}
/// <summary>Come si disegna un collegamento della catena produttiva (legenda dell'immagine 07).</summary>
public enum ChainEdge
{
/// <summary>Merci su una linea della compagnia: linea piena ambra.</summary>
Goods,
/// <summary>Lavoratori pendolari: tratteggio blu.</summary>
Workers,
/// <summary>Personale qualificato: puntinato azzurro.</summary>
Staff,
/// <summary>Partner possibile ma non collegato: tratteggio grigio.</summary>
Unlinked,
}
/// <summary>Nodo del grafo: titolo, riga secondaria, stile del collegamento, industria da aprire (−1 se nessuna).</summary>
public sealed record ChainNode(string Title, string Subtitle, ChainEdge Edge, int Industry = -1);
/// <summary>
/// Grafo della catena produttiva: fornitori e città dei pendolari a sinistra, l'industria al centro,
/// clienti a destra. I nodi delle industrie si aprono con un clic.
/// </summary>
public partial class ChainGraph : Control
{
private const float NodeW = 210, NodeH = 50, Gap = 10;
private readonly List<(Rect2 Rect, ChainNode Node)> _hits = [];
private List<ChainNode> _left = [], _right = [];
private ChainNode? _center;
public event Action<int>? IndustryClicked;
public ChainGraph()
{
CustomMinimumSize = new Vector2(0, 260);
MouseFilter = MouseFilterEnum.Stop;
}
public void Set(List<ChainNode> left, ChainNode center, List<ChainNode> right)
{
(_left, _center, _right) = (left, center, right);
int rows = Math.Max(3, Math.Max(left.Count, right.Count));
CustomMinimumSize = new Vector2(0, rows * (NodeH + Gap) + 10);
QueueRedraw();
}
public override void _Draw()
{
_hits.Clear();
if (_center is null) return;
float w = Size.X, h = Size.Y;
float nodeW = Math.Min(NodeW, (w - 80) / 3);
var centerRect = new Rect2(w / 2 - nodeW / 2, h / 2 - NodeH * 0.7f, nodeW, NodeH * 1.4f);
var leftRects = Column(_left, 0, nodeW, h);
var rightRects = Column(_right, w - nodeW, nodeW, h);
for (int i = 0; i < _left.Count; i++)
Edge(new Vector2(leftRects[i].End.X, leftRects[i].GetCenter().Y), new Vector2(centerRect.Position.X, centerRect.GetCenter().Y), _left[i].Edge);
for (int i = 0; i < _right.Count; i++)
Edge(new Vector2(centerRect.End.X, centerRect.GetCenter().Y), new Vector2(rightRects[i].Position.X, rightRects[i].GetCenter().Y), _right[i].Edge);
for (int i = 0; i < _left.Count; i++) Node(leftRects[i], _left[i], false);
for (int i = 0; i < _right.Count; i++) Node(rightRects[i], _right[i], false);
Node(centerRect, _center, true);
}
private static List<Rect2> Column(List<ChainNode> nodes, float x, float width, float height)
{
float total = nodes.Count * NodeH + Math.Max(0, nodes.Count - 1) * Gap;
float y = (height - total) / 2;
var rects = new List<Rect2>(nodes.Count);
foreach (var _ in nodes)
{
rects.Add(new Rect2(x, y, width, NodeH));
y += NodeH + Gap;
}
return rects;
}
private void Edge(Vector2 from, Vector2 to, ChainEdge edge)
{
switch (edge)
{
case ChainEdge.Goods:
DrawLine(from, to, Palette.Amber, 3, true);
break;
case ChainEdge.Workers:
DrawDashedLine(from, to, Palette.Workers, 2.5f, 10);
break;
case ChainEdge.Staff:
DrawDashedLine(from, to, Palette.Staff, 2.5f, 3);
break;
default:
DrawDashedLine(from, to, Palette.Border, 2, 8);
break;
}
}
private void Node(Rect2 rect, ChainNode node, bool center)
{
var border = center ? Palette.Amber : node.Edge switch
{
ChainEdge.Goods => Palette.AmberDark,
ChainEdge.Workers => Palette.Workers,
ChainEdge.Staff => Palette.Staff,
_ => Palette.Border,
};
DrawStyleBox(UiTheme.Box(center ? Palette.AmberDark : Palette.Inner, border, 8, 0), rect);
var font = UiTheme.BodyBold;
float width = rect.Size.X - 16;
DrawString(font, rect.Position + new Vector2(8, center ? 26 : 20), node.Title, HorizontalAlignment.Left, width, center ? 16 : 14,
center ? Palette.AmberLight : Palette.Text);
DrawString(UiTheme.Body, rect.Position + new Vector2(8, center ? 48 : 39), node.Subtitle, HorizontalAlignment.Left, width, 12, Palette.TextSecondary);
if (node.Industry >= 0) _hits.Add((rect, node));
}
public override void _GuiInput(InputEvent e)
{
if (e is not InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } click) return;
foreach (var (rect, node) in _hits)
{
if (!rect.HasPoint(click.Position)) continue;
IndustryClicked?.Invoke(node.Industry);
AcceptEvent();
return;
}
}
}
@@ -1,23 +1,66 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Panels;
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;
/// <summary>
/// Collegamento a un server (immagine 09 non fornita: palette e componenti dell'immagine 05).
/// Ricorda indirizzo e token in user://settings.cfg.
/// 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, sistema, tempo di
/// attività, tick al secondo, latenza, client collegati), le partite salvate sul server e i
/// pulsanti per riprendere o iniziare. La schermata apre una sessione di prova per leggere lo stato
/// e l'elenco dei salvataggi; «Connetti e riprendi» la passa alla partita. Nessuna logica di gioco:
/// carica, nuova partita ed elenco sono richieste al server (Load, NewGame, ListSaves).
/// </summary>
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400" };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server") };
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Button _connect = UiTheme.Primary(T("Collegati"));
private const double SavesRefreshS = 5;
private const double WelcomeTimeoutS = 30;
private readonly GameData _data;
private readonly bool _remember;
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);
private readonly GridContainer _stateRows = new() { Columns = 2 };
private readonly ItemList _saves = new() { CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill };
private readonly List<string> _saveIds = [];
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private GameSession? _session;
private bool _busy, _local;
private double _sinceSaves = double.MaxValue;
private SaveList? _shownSaves;
private Action<IMessage>? _awaitingWelcome;
private double _waiting;
public event Action<Uri, string, string>? ConnectRequested;
public event Action? Back;
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
public event Action<GameSession>? PlayRequested;
public event Action<string>? LanguageChanged;
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
public ConnectScreen(GameData data, bool remember = true)
{
_data = data;
_remember = remember;
}
/// <summary>Stato e salvataggi sono arrivati dal server (serve al collaudo).</summary>
public bool Loaded => _session?.World.Server is not null && _shownSaves is not null;
public override void _Ready()
{
@@ -27,67 +70,539 @@ public partial class ConnectScreen : Control
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var panel = new PanelContainer { CustomMinimumSize = new Vector2(480, 0) };
center.AddChild(panel);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
panel.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Collegati a un server"), 40));
col.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
col.AddChild(_address);
col.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
col.AddChild(_token);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 10);
_connect.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_connect.Pressed += Submit;
row.AddChild(_connect);
var back = new Button { Text = T("Indietro") };
back.Pressed += () => Back?.Invoke();
row.AddChild(back);
col.AddChild(row);
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: false);
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(10);
var stateHead = PanelKit.Row(10);
stateHead.AddChild(_dot);
stateHead.AddChild(_stateTitle);
stateCol.AddChild(stateHead);
_stateRows.AddThemeConstantOverride("h_separation", 24);
_stateRows.AddThemeConstantOverride("v_separation", 6);
stateCol.AddChild(_stateRows);
state.AddChild(stateCol);
col.AddChild(state);
// partite salvate sul server
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
_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);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
col.AddChild(UiTheme.Notice(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).")));
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
// piede: lingua, uscita, avviso sulla cifratura
var foot = PanelKit.Row(8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
foot.AddChild(b);
}
_token.TextSubmitted += _ => Submit();
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);
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";
}
}
SetMode(local: !remote, start: false);
ShowState();
}
public void SetStatus(string text, bool busy)
private static void ModeCard(Button card, ButtonGroup group, string title, string text)
{
_status.Text = text;
_connect.Disabled = busy;
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));
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 void Submit()
private static string ClientVersion =>
typeof(ConnectScreen).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
// ------------------------------------------------------------------ modalità e sessione di prova
private void SetMode(bool local, bool start)
{
_local = local;
_localCard.SetPressedNoSignal(local);
_remoteCard.SetPressedNoSignal(!local);
_remoteFields.Visible = !local;
if (start && local && (_session is null || _session.LocalServer is null)) _ = StartLocal();
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "mode", local ? "local" : "remote");
cfg.Save(SettingsPath);
}
ShowState();
}
/// <summary>Avvia il server locale figlio del gioco e apre la sessione di prova.</summary>
private async Task StartLocal()
{
if (_busy) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
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;
Attach(session);
}
catch (Exception e)
{
launcher.Dispose();
SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
}
private void SubmitRemote()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
SetStatus(T("Indica l'indirizzo del server"), 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))
{
SetStatus(T("Indirizzo non valido"), false);
SetStatus(T("Indirizzo non valido"), error: true);
return;
}
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", address);
cfg.SetValue("server", "token", _token.Text);
cfg.Save(SettingsPath);
ConnectRequested?.Invoke(uri, _token.Text, uri.Host);
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);
}
/// <summary>Collega la sessione di prova a un server in rete (dal pulsante o dal collaudo).</summary>
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));
Attach(await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token));
SetStatus("");
}
catch (Exception e)
{
SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
}
_busy = false;
ShowState();
}
private void Attach(GameSession session)
{
_session = session;
_shownSaves = null;
_sinceSaves = double.MaxValue;
_session.MessageApplied += OnMessage;
}
/// <summary>Chiude la sessione di prova (e il server locale, se è suo).</summary>
private async Task Release()
{
var s = _session;
_session = null;
_shownSaves = null;
_awaitingWelcome = null;
if (s is null) return;
s.MessageApplied -= OnMessage;
await s.DisposeAsync();
}
/// <summary>Consegna la sessione di prova a chi la chiede (Main, alla chiusura del gioco).</summary>
public GameSession? TakeSession()
{
var s = _session;
if (s is not null) s.MessageApplied -= OnMessage;
_session = null;
return s;
}
public override void _ExitTree()
{
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.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 (_session is null || _awaitingWelcome is not null) return;
int index = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
if (index <= 0 || index > _saveIds.Count)
{
Play();
return;
}
string id = _saveIds[index - 1];
SetStatus($"{T("Caricamento di")} {_saves.GetItemText(index)}…");
AwaitWelcome();
_session.Send(new Load { SaveId = id });
}
private void NewGameOnServer()
{
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 });
}
/// <summary>Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.</summary>
private void AwaitWelcome()
{
_awaitingWelcome = m =>
{
if (m is Welcome)
{
_awaitingWelcome = null;
Play();
}
else if (m is Notification { Event.Severity: >= (byte)EventSeverity.Warning } note)
{
// caricamento o creazione rifiutati: il server risponde con un avviso
_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;
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("Collegato a")} {_session.ServerLabel}";
dot = Palette.Ok;
}
else
{
title = _local ? T("Server locale spento: scegli «Gioca in locale» per avviarlo") : T("Non collegato");
dot = Palette.TextSecondary;
}
_stateTitle.Text = title;
_dot.Color = dot;
var rows = new List<(string, string)>
{
(T("Versione"), info is null ? "—" : $"{info.Version} · {T("dati compatibili")}"),
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds)),
(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}"),
};
if (_stateRows.GetChildCount() != rows.Count * 2)
{
foreach (var c in _stateRows.GetChildren()) c.QueueFree();
foreach (var (caption, _) in rows)
{
_stateRows.AddChild(UiTheme.Text(caption, 13, Palette.TextSecondary));
_stateRows.AddChild(UiTheme.Text("", 13, bold: true));
}
}
for (int i = 0; i < rows.Count; i++)
{
((Label)_stateRows.GetChild(i * 2)).Text = rows[i].Item1;
((Label)_stateRows.GetChild(i * 2 + 1)).Text = rows[i].Item2;
}
bool ready = _session is not null && !_busy && _awaitingWelcome is null;
_resume.Disabled = !ready;
_newGame.Disabled = !ready;
_probe.Disabled = _busy;
}
private void ShowSaves()
{
var w = _session!.World;
_shownSaves = w.Saves;
int selected = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
_saves.Clear();
_saveIds.Clear();
string company = w.Summary?.CompanyName ?? "";
_saves.AddItem($"{T("Partita in corso")} · {company} · {w.Summary?.Date ?? ""}");
double now = Time.GetUnixTimeFromSystem();
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs))
{
_saveIds.Add(s.SaveId);
string kind = s.Autosave ? $" ({T("automatico")})" : "";
_saves.AddItem($"{s.Name}{kind} · {s.GameDate} · {Ago(now - s.SavedUnixMs / 1000.0)}");
}
_saves.Select(Math.Clamp(selected, 0, _saves.ItemCount - 1));
}
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")}";
}
}
/// <summary>
/// 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.
/// </summary>
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();
}
}
@@ -98,7 +98,7 @@ public partial class GameScreen : Node
_maintenance?.SelectDepot(depot);
}
/// <summary>Apre il pannello Industrie sull'industria indicata (scheda del proprietario).</summary>
/// <summary>Apre la scheda dell'industria a tutto schermo (immagine 07) sull'industria indicata.</summary>
public void OpenIndustry(int industry)
{
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
@@ -142,6 +142,17 @@ public partial class GameScreen : Node
}
}
/// <summary>Dalla scheda dell'industria: strumento binari con la mappa centrata sull'industria da collegare.</summary>
private void PlanLineToIndustry(int industry)
{
_toolbar.Select(Tool.Track);
if (_session.World.Industries.TryGetValue(industry, out var ind))
{
_map.CenterOn(MapScale.V(ind.Position));
_map.SetZoom(0.3f);
}
}
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
public void OpenChronicle()
{
@@ -161,6 +172,11 @@ public partial class GameScreen : Node
/// <summary>Scorre il pannello laterale (0 = in cima, 1 = in fondo).</summary>
public void ScrollPanel(double fraction)
{
if (_industryPanel is not null)
{
_industryPanel.ScrollTo(fraction);
return;
}
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
@@ -411,7 +427,7 @@ public partial class GameScreen : Node
_climb = null;
_finance = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance;
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance or Tool.Industries;
_full.Visible = full;
if (_mapArea is not null) _mapArea.Visible = !full;
if (_side is not null) _side.Visible = !full;
@@ -465,7 +481,11 @@ public partial class GameScreen : Node
panel = new EmploymentPanel(_session);
break;
case Tool.Industries:
panel = _industryPanel = new IndustryPanel(_session);
_industryPanel = new IndustryPanel(_session);
_industryPanel.CloseRequested += () => _toolbar.Select(Tool.None);
_industryPanel.PlanLineRequested += PlanLineToIndustry;
_full.AddChild(_industryPanel);
panel = NewInfoPanel();
break;
case Tool.Companies:
_companies = new CompaniesPanel(_session);
@@ -791,7 +811,8 @@ public partial class GameScreen : Node
_chronicleScreen = screen;
}
private void CloseChronicle()
/// <summary>Chiude la Cronaca se è aperta.</summary>
public void CloseChronicle()
{
_chronicleScreen?.QueueFree();
_chronicleScreen = null;
@@ -1,56 +0,0 @@
using Godot;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>Menu iniziale: partita locale (server figlio), collegamento a un server, lingua, uscita.</summary>
public partial class MenuScreen : Control
{
public event Action? LocalGame;
public event Action? ConnectToServer;
public event Action<string>? LanguageChanged;
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
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 center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var col = new VBoxContainer { CustomMinimumSize = new Vector2(440, 0) };
col.AddThemeConstantOverride("separation", 14);
center.AddChild(col);
col.AddChild(UiTheme.TitleLabel("Rail Enterprise", 96));
col.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 18, Palette.TextSecondary));
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 20) });
var local = UiTheme.Primary(T("Partita locale"));
local.CustomMinimumSize = new Vector2(0, 48);
local.Pressed += () => LocalGame?.Invoke();
col.AddChild(local);
var remote = new Button { Text = T("Collegati a un server"), CustomMinimumSize = new Vector2(0, 48) };
remote.Pressed += () => ConnectToServer?.Invoke();
col.AddChild(remote);
var lang = new HBoxContainer();
lang.AddThemeConstantOverride("separation", 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);
lang.AddChild(b);
}
col.AddChild(lang);
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(0, 40) };
quit.Pressed += () => GetTree().Quit();
col.AddChild(quit);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
}
public void SetStatus(string text) => _status.Text = text;
}
@@ -1 +0,0 @@
uid://b5eyw35w2vo7l