F3: client Godot minimo, replay dei comandi e collaudi automatici

- Client Godot 4.7 .NET (Godot.NET.Sdk 4.7.2): menu, collegamento, partita
  locale con server figlio; mappa con terreno (fasce, ombreggiatura, rive
  curve con shader, curve di livello), opere, entità, alberi, treni
  interpolati con fumo; strumenti binari con profilo, stazione, deposito,
  segnali, demolizione; pannelli treni, linee, mercato, finanze, schede;
  barra superiore, minimappa, notiziario; italiano e inglese.
- Pilota automatico del client e scripts/client-autopilot.sh: partita locale,
  linea con ponte, treni in moto e schermate (docs/screenshots).
- Registro dei comandi del server (--record) e viaferrea-tools replay.
- PROTOCOL.md normativo, ADR 0009, ARCHITECTURE, STATE e README aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-02 00:47:42 +00:00
1 parent 5a318e6528
commit 9a4ada6d9d
97 files changed
+5151 -96

No files matched your search

@@ -0,0 +1,166 @@
using Godot;
using ViaFerrea.Client.Hud;
using ViaFerrea.Client.Map;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Screens;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.App;
/// <summary>
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
/// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno,
/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo.
/// </summary>
public partial class AutoPilot : Node
{
private readonly GameScreen _game;
private readonly string _out;
public AutoPilot(GameScreen game, string outDir)
{
_game = game;
_out = outDir;
}
private GameSession Session => _game.Session;
private ClientWorld World => _game.Session.World;
public override async void _Ready()
{
int code = 0;
try
{
await Run();
GD.Print("autopilot: ok");
}
catch (Exception e)
{
GD.PrintErr($"autopilot: FALLITO {e.Message}\n{e.StackTrace}");
code = 1;
}
GetTree().Quit(code);
}
private async Task Frame() => await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
private async Task Until(Func<bool> condition, string what, double timeoutS = 120)
{
ulong start = Time.GetTicksMsec();
while (!condition())
{
if (Time.GetTicksMsec() - start > timeoutS * 1000) throw new TimeoutException(what);
await Frame();
}
}
private Task<CommandResultMessage> Do(GameCommand command)
{
var tcs = new TaskCompletionSource<CommandResultMessage>();
Session.Command(command, r => tcs.TrySetResult(r));
return tcs.Task;
}
private async Task<int> Ok(GameCommand command)
{
var r = await Do(command);
if (!r.Ok) throw new InvalidOperationException($"{command.Type}: {r.Message}");
GD.Print($"autopilot: {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
private async Task Shot(string name, int settleFrames = 30)
{
for (int i = 0; i < settleFrames; i++) await Frame();
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
var image = GetViewport().GetTexture().GetImage();
string path = Path.Combine(_out, name + ".jpg");
image.SaveJpg(path, 0.88f);
GD.Print($"autopilot: schermata {path}");
}
private async Task Run()
{
Directory.CreateDirectory(_out);
var summary = World.Summary!;
Session.Send(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 });
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
await Until(() => World.Chunks.Count == chunks && World.Towns.Count > 0, "terreno");
await Shot("01_avvio", 90);
await Ok(new TakeLoanCommand(Money.FromLire(200_000)));
var site = BridgeSiteFinder.Find(World) ?? throw new InvalidOperationException("nessun sito con ponte");
int a = await Ok(new BuildStationCommand(site.A, 2));
int b = await Ok(new BuildStationCommand(site.B, 2));
int depot = await Ok(new BuildDepotCommand(site.Depot, "small"));
await Until(() => World.Stations.ContainsKey(b) && World.Depots.ContainsKey(depot), "stazioni");
var main = new BuildTrackCommand([site.A, site.B]);
var plan = World.PreviewTrack(main);
await Ok(main with { ExpectedCostCents = plan.TotalCost.Cents });
await Until(() => World.Edges.Count > 0, "binario");
var spur = new BuildTrackCommand([site.Depot, site.A]);
await Ok(spur with { ExpectedCostCents = World.PreviewTrack(spur).TotalCost.Cents });
// vista d'insieme del cantiere
var center = MapScale.V((site.A + site.B) / 2);
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("02_cantiere");
Session.SetSpeed(8);
await Until(() => World.Edges.Count >= 2 && World.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri", 240);
var loco = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var wagons = await Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3));
int train = await Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
var loco2 = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var coaches = await Do(new BuyVehicleCommand("coach_worker", new DepotId(depot), 2));
int train2 = await Ok(new ComposeTrainCommand(new DepotId(depot), loco2.Created.Concat(coaches.Created).Select(i => new VehicleId(i)).ToList(), "Treno 2"));
int line = await Ok(new CreateLineCommand("Linea 1, collaudo", "#e0a526", [new LineStop(new StationId(a)), new LineStop(new StationId(b))]));
await Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
Session.SetSpeed(1);
await Until(() => World.Motions.TryGetValue(train, out var m) && m.Speed > 3, "treno in moto", 120);
await Ok(new AssignTrainCommand(new TrainId(train2), new LineId(line)));
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("03_linea");
// ponte da vicino (immagine 02)
_game.Map.CenterOn(MapScale.V(site.River));
_game.Map.SetZoom(0.9f);
await Shot("04_ponte");
// treno da vicino (immagine 03): la camera lo segue per qualche fotogramma
for (int i = 0; i < 40; i++)
{
if (World.TrainHead(train) is { } head) _game.Map.CenterOn(MapScale.V(head));
_game.Map.SetZoom(1.4f);
await Frame();
}
_game.SelectTrain(train);
await Shot("05_treno", 5);
// scheda del treno con la mappa d'insieme
_game.Map.SetZoom(0.3f);
await Shot("06_scheda_treno", 20);
// strumento binari con il profilo di un tracciato in collina
_game.UseTool(Tool.Track);
var dir = (site.B - site.A).Normalized();
var normal = new Vec2(-dir.Y, dir.X);
var p0 = MapScale.V(site.B);
var p1 = MapScale.V(site.B + normal * 2500);
var p2 = MapScale.V(site.B + normal * 4000 + dir * 1500);
_game.SetTrackPoints([p0, p1], p2);
_game.Map.CenterOn(MapScale.V(site.B + normal * 2000 + dir * 500));
_game.Map.SetZoom(0.2f);
await Shot("07_profilo", 40);
_game.UseTool(Tool.None);
_game.Map.SetZoom(0.06f);
await Shot("08_panoramica", 60);
}
}
@@ -0,0 +1 @@
uid://bdw1fy2qphri5
@@ -0,0 +1,26 @@
using Godot;
using ViaFerrea.Core.Data;
namespace ViaFerrea.Client.App;
/// <summary>File dati del gioco dentro il progetto Godot (res://data, copiati dalla build del client).</summary>
public sealed class GodotDataSource(string root = "res://data") : IDataSource
{
public string Description => root;
public bool Exists(string relativePath) => Godot.FileAccess.FileExists($"{root}/{relativePath}");
public string ReadText(string relativePath)
{
using var f = Godot.FileAccess.Open($"{root}/{relativePath}", Godot.FileAccess.ModeFlags.Read)
?? throw new FileNotFoundException(relativePath);
return f.GetAsText();
}
/// <summary>Dati del gioco: res://data se presenti, altrimenti la cartella data del repository.</summary>
public static GameData LoadGameData()
{
var source = new GodotDataSource();
return source.Exists("goods.json") ? GameData.Load(source) : GameData.LoadDefault();
}
}
@@ -0,0 +1 @@
uid://bn1h4nbl2f1rc
@@ -0,0 +1,43 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>
/// Testi dell'interfaccia: la lingua sorgente è l'italiano (le chiavi sono i testi italiani),
/// le traduzioni stanno in <c>assets/i18n/strings.csv</c> (colonne keys, it, en) e si caricano
/// all'avvio senza passare dall'importazione dell'editor.
/// </summary>
public static class Localization
{
public static void Load(string locale)
{
const string path = "res://assets/i18n/strings.csv";
using var file = Godot.FileAccess.Open(path, Godot.FileAccess.ModeFlags.Read);
if (file is null)
{
GD.PushWarning("Traduzioni non trovate");
return;
}
string[] header = file.GetCsvLine();
var translations = new List<Translation>();
for (int c = 1; c < header.Length; c++)
{
var t = new Translation { Locale = header[c] };
translations.Add(t);
}
while (!file.EofReached())
{
string[] row = file.GetCsvLine();
if (row.Length < 2 || row[0].Length == 0) continue;
for (int c = 1; c < row.Length && c - 1 < translations.Count; c++)
{
if (row[c].Length > 0) translations[c - 1].AddMessage(row[0], row[c]);
}
}
foreach (var t in translations) TranslationServer.AddTranslation(t);
TranslationServer.SetLocale(locale);
}
/// <summary>Traduce un testo dell'interfaccia (chiave = testo italiano).</summary>
public static string T(string italian) => TranslationServer.Translate(italian);
}
@@ -0,0 +1 @@
uid://bxob5yr4t8lu8
@@ -0,0 +1,43 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>Palette dell'immagine di riferimento 05: interfaccia blu-ardesia con accento ambra, mappa cartografica chiara.</summary>
public static class Palette
{
// interfaccia
public static readonly Color AppBackground = new("11181c");
public static readonly Color Panel = new("172127");
public static readonly Color Inner = new("1f2a30");
public static readonly Color Border = new("2c3a42");
public static readonly Color Text = new("dde3e6");
public static readonly Color TextSecondary = new("9fb0b8");
public static readonly Color Amber = new("e0a526");
public static readonly Color AmberLight = new("f0bd52");
public static readonly Color AmberDark = new("3a2c12");
public static readonly Color Workers = new("3f86d1");
public static readonly Color Staff = new("9cc9f2");
public static readonly Color Ok = new("5fc39b");
public static readonly Color Danger = new("b3573e");
// mappa
public static readonly Color Plain = new("cfd7bd");
public static readonly Color Hill = new("c0c8a6");
public static readonly Color Highland = new("aeb690");
public static readonly Color Undergrowth = new("9db38a");
public static readonly Color Canopy = new("5f8f4a");
public static readonly Color Water = new("8fb4c6");
public static readonly Color Banks = new("b9bf9c");
public static readonly Color Grain = new("d9c26a");
public static readonly Color TileRoof = new("b3573e");
public static readonly Color IndustrialRoof = new("7c8590");
public static readonly Color Ballast = new("bfb79f");
public static readonly Color Sleepers = new("5b4a39");
public static readonly Color Rails = new("3b3f42");
public static readonly Color Construction = new("8a7a52");
public static readonly Color Rock = new("9a9a8c");
public static readonly Color Marsh = new("a9bba0");
public static readonly Color Sea = new("86adc0");
public static Color WithAlpha(Color c, float a) => new(c.R, c.G, c.B, a);
}
@@ -0,0 +1 @@
uid://blsg133y5mi21
@@ -0,0 +1,144 @@
using Godot;
namespace ViaFerrea.Client.App;
/// <summary>
/// Tema dell'interfaccia costruito in codice dalla palette (immagine 05): titoli in Big Shoulders
/// Display 800, testo e numeri in IBM Plex Sans; raggio 8–12 px, bordi 1 px #2c3a42, nessuna ombra.
/// </summary>
public static class UiTheme
{
public static Font Body { get; private set; } = ThemeDB.FallbackFont;
public static Font BodyBold { get; private set; } = ThemeDB.FallbackFont;
public static Font Title { get; private set; } = ThemeDB.FallbackFont;
public static Theme Build()
{
Body = LoadFont("res://assets/fonts/IBMPlexSans-Regular.ttf");
BodyBold = LoadFont("res://assets/fonts/IBMPlexSans-SemiBold.ttf");
Title = LoadFont("res://assets/fonts/BigShouldersDisplay-ExtraBold.ttf");
var t = new Theme { DefaultFont = Body, DefaultFontSize = 14 };
foreach (string type in new[] { "Label", "Button", "LineEdit", "CheckBox", "OptionButton", "SpinBox", "ItemList", "PopupMenu", "TooltipLabel" })
{
t.SetColor("font_color", type, Palette.Text);
}
t.SetColor("font_color", "TooltipLabel", Palette.Text);
t.SetStylebox("panel", "TooltipPanel", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("panel", "PanelContainer", Box(Palette.Panel, Palette.Border, 10, 12));
t.SetStylebox("panel", "Panel", Box(Palette.Panel, Palette.Border, 0, 0));
var normal = Box(Palette.Panel, Palette.Border, 8, 10);
t.SetStylebox("normal", "Button", normal);
t.SetStylebox("hover", "Button", Box(Palette.Inner, Palette.TextSecondary, 8, 10));
t.SetStylebox("pressed", "Button", Box(Palette.Amber, Palette.Amber, 8, 10));
t.SetStylebox("disabled", "Button", Box(Palette.AppBackground, Palette.Border, 8, 10));
t.SetStylebox("focus", "Button", Box(new Color(0, 0, 0, 0), Palette.AmberLight, 8, 10));
t.SetColor("font_pressed_color", "Button", Palette.AppBackground);
t.SetColor("font_hover_color", "Button", Palette.Text);
t.SetColor("font_disabled_color", "Button", Palette.TextSecondary);
t.SetColor("font_hover_pressed_color", "Button", Palette.AppBackground);
t.SetStylebox("normal", "LineEdit", Box(Palette.Inner, Palette.Border, 8, 8));
t.SetStylebox("focus", "LineEdit", Box(Palette.Inner, Palette.Amber, 8, 8));
t.SetColor("caret_color", "LineEdit", Palette.Amber);
t.SetStylebox("panel", "ItemList", Box(Palette.Inner, Palette.Border, 8, 6));
t.SetColor("font_selected_color", "ItemList", Palette.AppBackground);
t.SetStylebox("selected", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
t.SetStylebox("selected_focus", "ItemList", Box(Palette.Amber, Palette.Amber, 4, 4));
t.SetStylebox("background", "ProgressBar", Box(Palette.Border, Palette.Border, 4, 0));
t.SetStylebox("fill", "ProgressBar", Box(Palette.Workers, Palette.Workers, 4, 0));
t.SetColor("font_color", "ProgressBar", Palette.Text);
return t;
}
/// <summary>Riquadro piatto con bordo di 1 px.</summary>
public static StyleBoxFlat Box(Color bg, Color border, int radius, int margin)
{
var s = new StyleBoxFlat { BgColor = bg, BorderColor = border };
s.SetBorderWidthAll(1);
s.SetCornerRadiusAll(radius);
s.ContentMarginLeft = margin;
s.ContentMarginRight = margin;
s.ContentMarginTop = margin * 0.6f;
s.ContentMarginBottom = margin * 0.6f;
return s;
}
/// <summary>Carica un font importato dall'editor oppure, in mancanza, direttamente dal file.</summary>
private static Font LoadFont(string path)
{
if (ResourceLoader.Exists(path))
{
var imported = ResourceLoader.Load<FontFile>(path);
if (imported is not null) return imported;
}
var font = new FontFile();
if (font.LoadDynamicFont(path) == Error.Ok) return font;
GD.PushWarning($"Font non trovato: {path}");
return ThemeDB.FallbackFont;
}
/// <summary>Etichetta con il font dei titoli.</summary>
public static Label TitleLabel(string text, int size, Color? color = null)
{
var l = new Label { Text = text };
l.AddThemeFontOverride("font", Title);
l.AddThemeFontSizeOverride("font_size", size);
l.AddThemeColorOverride("font_color", color ?? Palette.Text);
return l;
}
public static Label Text(string text, int size = 14, Color? color = null, bool bold = false)
{
var l = new Label { Text = text };
l.AddThemeFontOverride("font", bold ? BodyBold : Body);
l.AddThemeFontSizeOverride("font_size", size);
l.AddThemeColorOverride("font_color", color ?? Palette.Text);
return l;
}
/// <summary>Pulsante d'azione primaria (ambra).</summary>
public static Button Primary(string text)
{
var b = new Button { Text = text };
b.AddThemeStyleboxOverride("normal", Box(Palette.Amber, Palette.Amber, 8, 12));
b.AddThemeStyleboxOverride("hover", Box(Palette.AmberLight, Palette.AmberLight, 8, 12));
b.AddThemeColorOverride("font_color", Palette.AppBackground);
b.AddThemeColorOverride("font_hover_color", Palette.AppBackground);
b.AddThemeFontOverride("font", BodyBold);
return b;
}
/// <summary>Distintivo ambra (livello della compagnia, linea).</summary>
public static PanelContainer Badge(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.Amber, Palette.Amber, 4, 6));
var l = Text(text, 12, Palette.AppBackground, bold: true);
p.AddChild(l);
return p;
}
/// <summary>Etichetta di linea: ambra su fondo ambra scuro, su una riga (immagine 01).</summary>
public static PanelContainer LineBadge(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.AmberDark, Palette.AmberDark, 6, 10));
p.AddChild(Text(text, 13, Palette.AmberLight, bold: true));
return p;
}
/// <summary>Riquadro d'avviso ambra scuro (colli di bottiglia e opportunità).</summary>
public static PanelContainer Notice(string text)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", Box(Palette.AmberDark, Palette.AmberDark, 8, 12));
var l = Text(text, 13, Palette.AmberLight);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
p.AddChild(l);
return p;
}
}
@@ -0,0 +1 @@
uid://fvsnf1rxxhbh
@@ -0,0 +1,104 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Map;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Hud;
/// <summary>Minimappa: terreno ridotto, linee, città e rettangolo della vista; un clic centra la mappa.</summary>
public partial class Minimap : Control
{
private ClientWorld? _world;
private MapView? _map;
private ImageTexture? _texture;
private int _terrainVersion = -1;
public void Bind(ClientWorld world, MapView map)
{
_world = world;
_map = map;
_terrainVersion = -1;
CustomMinimumSize = new Vector2(0, 220);
MouseFilter = MouseFilterEnum.Stop;
}
public override void _Process(double delta)
{
if (_world?.Terrain is { } t && _world.TerrainVersion != _terrainVersion && Engine.GetProcessFrames() % 30 == 0)
{
_terrainVersion = _world.TerrainVersion;
int step = Math.Max(1, t.Width / 256);
int w = t.Width / step, h = t.Height / step;
var data = new byte[w * h * 4];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
var type = (CellType)t.Types[y * step * t.Width + x * step];
var c = type switch
{
CellType.Sea => Palette.Sea,
CellType.Water => Palette.Water,
CellType.Forest => Palette.Undergrowth,
CellType.Town => Palette.TileRoof.Lightened(0.3f),
CellType.Mountain or CellType.Rock => Palette.Highland,
CellType.Hill => Palette.Hill,
_ => Palette.Plain,
};
int i = (y * w + x) * 4;
data[i] = (byte)(c.R * 255);
data[i + 1] = (byte)(c.G * 255);
data[i + 2] = (byte)(c.B * 255);
data[i + 3] = 255;
}
}
_texture = ImageTexture.CreateFromImage(Image.CreateFromData(w, h, false, Image.Format.Rgba8, data));
}
QueueRedraw();
}
private Rect2 MapRect()
{
var t = _world!.Terrain!;
float aspect = (float)t.Width / t.Height;
float w = Size.X, h = Size.X / aspect;
if (h > Size.Y)
{
h = Size.Y;
w = h * aspect;
}
return new Rect2((Size.X - w) / 2, (Size.Y - h) / 2, w, h);
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
if (_world?.Terrain is not { } t || _texture is null || _map is null) return;
var r = MapRect();
DrawTextureRect(_texture, r, false);
float k = r.Size.X / (float)(t.Width * t.CellSizeM);
Vector2 P(Vector2 world) => r.Position + world * k;
foreach (var e in _world.Edges.Values)
{
if (e.S.Length < 2) continue;
DrawLine(P(MapScale.V(e.X[0], e.Y[0])), P(MapScale.V(e.X[^1], e.Y[^1])), new Color("2a2f2c"), 2);
}
foreach (var town in _world.Towns.Values) DrawCircle(P(MapScale.V(town.Position)), 3.5f, new Color("8a6a55"));
var view = _map.VisibleRect();
DrawRect(new Rect2(P(view.Position), view.Size * k), Palette.Amber, false, 2);
}
public override void _GuiInput(InputEvent e)
{
if (_world?.Terrain is not { } t || _map is null) return;
if (e is InputEventMouseButton { ButtonIndex: MouseButton.Left, Pressed: true } b || e is InputEventMouseMotion { ButtonMask: MouseButtonMask.Left })
{
var pos = e is InputEventMouse m ? m.Position : Vector2.Zero;
var r = MapRect();
float k = r.Size.X / (float)(t.Width * t.CellSizeM);
_map.CenterOn((pos - r.Position) / k);
AcceptEvent();
}
}
}
@@ -0,0 +1 @@
uid://ci04fqk4we7bk
@@ -0,0 +1,42 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Notiziario in basso (immagine 01): «Notizie» e gli ultimi eventi che scorrono.</summary>
public partial class Ticker : PanelContainer
{
private readonly List<string> _items = [];
private readonly Label _text = UiTheme.Text("", 14);
private readonly Control _clip = new() { ClipContents = true, SizeFlagsHorizontal = SizeFlags.ExpandFill, CustomMinimumSize = new Vector2(0, 22) };
private float _offset;
public override void _Ready()
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 14));
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 18);
AddChild(row);
row.AddChild(UiTheme.Text(T("Notizie"), 14, Palette.Amber, bold: true));
row.AddChild(_clip);
_clip.AddChild(_text);
}
public void Add(EventInfo e)
{
_items.Insert(0, e.Text);
if (_items.Count > 8) _items.RemoveAt(_items.Count - 1);
_text.Text = string.Join(" | ", _items);
}
public override void _Process(double delta)
{
if (_items.Count == 0) return;
_offset += (float)delta * 40f;
float width = _text.GetMinimumSize().X;
if (_offset > width) _offset = -_clip.Size.X;
_text.Position = new Vector2(-_offset, 0);
}
}
@@ -0,0 +1 @@
uid://c57cbfp1dm0qo
@@ -0,0 +1,139 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Market, Finance, Demolish }
/// <summary>Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto.</summary>
public partial class Toolbar : PanelContainer
{
private readonly Dictionary<Tool, ToolButton> _buttons = [];
public event Action<Tool>? Selected;
public Tool Current { get; private set; }
public override void _Ready()
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 6));
CustomMinimumSize = new Vector2(88, 0);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 6);
AddChild(col);
foreach (var (tool, label) in new[]
{
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Market, "Mercato"), (Tool.Finance, "Finanze"), (Tool.Demolish, "Demolisci"),
})
{
var b = new ToolButton(tool, T(label));
b.Pressed += () => Select(Current == tool ? Tool.None : tool);
_buttons[tool] = b;
col.AddChild(b);
}
}
public void Select(Tool tool)
{
Current = tool;
foreach (var (t, b) in _buttons) b.Active = t == tool;
Selected?.Invoke(tool);
}
/// <summary>Pulsante con icona vettoriale.</summary>
private sealed partial class ToolButton : Button
{
private readonly Tool _tool;
private readonly string _label;
private bool _active;
public ToolButton(Tool tool, string label)
{
_tool = tool;
_label = label;
CustomMinimumSize = new Vector2(76, 72);
Flat = true;
TooltipText = label;
MouseEntered += QueueRedraw;
MouseExited += QueueRedraw;
}
public bool Active
{
get => _active;
set
{
_active = value;
QueueRedraw();
}
}
public override void _Draw()
{
if (_active) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Inner, 8, 0), new Rect2(Vector2.Zero, Size));
else if (IsHovered()) DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
var color = _active ? Palette.Amber : Palette.Text;
var c = new Vector2(Size.X / 2, 26);
DrawGlyph(c, color);
var font = _active ? UiTheme.BodyBold : UiTheme.Body;
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 13);
DrawString(font, new Vector2((Size.X - dims.X) / 2, 60), _label, HorizontalAlignment.Left, -1, 13, color);
}
private void DrawGlyph(Vector2 c, Color col)
{
const float w = 2.2f;
switch (_tool)
{
case Tool.Track:
DrawLine(c + new Vector2(-5, -11), c + new Vector2(-5, 11), col, w);
DrawLine(c + new Vector2(5, -11), c + new Vector2(5, 11), col, w);
for (int i = -1; i <= 1; i++) DrawLine(c + new Vector2(-10, i * 7), c + new Vector2(10, i * 7), col, w);
break;
case Tool.Station:
DrawPolyline([c + new Vector2(-11, -1), c + new Vector2(0, -11), c + new Vector2(11, -1)], col, w);
DrawRect(new Rect2(c + new Vector2(-8, -1), new Vector2(16, 12)), col, false, w);
DrawRect(new Rect2(c + new Vector2(-2, 4), new Vector2(4, 7)), col, false, w);
break;
case Tool.Signal:
DrawCircle(c + new Vector2(0, -6), 5, col, false, w);
DrawLine(c + new Vector2(0, -1), c + new Vector2(0, 11), col, w);
DrawLine(c + new Vector2(-5, 11), c + new Vector2(5, 11), col, w);
break;
case Tool.Depot:
DrawPolyline([c + new Vector2(-11, 11), c + new Vector2(-11, -3), c + new Vector2(0, -11), c + new Vector2(11, -3), c + new Vector2(11, 11)], col, w);
DrawRect(new Rect2(c + new Vector2(-6, 1), new Vector2(12, 10)), col, false, w);
break;
case Tool.Trains:
DrawRect(new Rect2(c + new Vector2(-8, -11), new Vector2(16, 17)), col, false, w);
DrawLine(c + new Vector2(-8, -2), c + new Vector2(8, -2), col, w);
DrawLine(c + new Vector2(-5, 6), c + new Vector2(-8, 12), col, w);
DrawLine(c + new Vector2(5, 6), c + new Vector2(8, 12), col, w);
break;
case Tool.Lines:
DrawCircle(c + new Vector2(-8, -8), 3.5f, col, false, w);
DrawCircle(c + new Vector2(8, 8), 3.5f, col, false, w);
DrawPolyline([c + new Vector2(-4, -8), c + new Vector2(8, -8), c + new Vector2(8, -2), c + new Vector2(-8, 2), c + new Vector2(-8, 8), c + new Vector2(4, 8)], col, w);
break;
case Tool.Market:
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
break;
case Tool.Finance:
DrawArc(c + new Vector2(0, -7), 9, 0, MathF.Tau, 24, col, w);
DrawLine(c + new Vector2(-9, -7), c + new Vector2(-9, 7), col, w);
DrawLine(c + new Vector2(9, -7), c + new Vector2(9, 7), col, w);
DrawArc(c + new Vector2(0, 7), 9, 0, MathF.PI, 16, col, w);
break;
case Tool.Demolish:
DrawLine(c + new Vector2(-10, -8), c + new Vector2(10, -8), col, w);
DrawLine(c + new Vector2(-4, -11), c + new Vector2(4, -11), col, w);
DrawPolyline([c + new Vector2(-7, -8), c + new Vector2(-5, 11), c + new Vector2(5, 11), c + new Vector2(7, -8)], col, w);
break;
}
}
}
}
@@ -0,0 +1 @@
uid://bngg3p5mnbnru
@@ -0,0 +1,111 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server.</summary>
public partial class TopBar : PanelContainer
{
private GameSession? _session;
private readonly Label _company = UiTheme.TitleLabel("", 30);
private readonly PanelContainer _tier = UiTheme.Badge("");
private readonly Label _date = UiTheme.Text("", 17, bold: true);
private readonly Label _cash = UiTheme.Text("", 20, Palette.AmberLight, bold: true);
private readonly Label _worth = UiTheme.Text("", 20, bold: true);
private readonly Label _rating = UiTheme.Text("", 20, bold: true);
private readonly Label _server = UiTheme.Text("", 14);
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
private readonly List<Button> _speeds = [];
public override void _Ready()
{
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 14));
CustomMinimumSize = new Vector2(0, 68);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 18);
AddChild(row);
row.AddChild(new Logo { CustomMinimumSize = new Vector2(40, 40) });
row.AddChild(_company);
var tierBox = new CenterContainer();
tierBox.AddChild(_tier);
row.AddChild(tierBox);
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
row.AddChild(_date);
var speeds = new HBoxContainer();
speeds.AddThemeConstantOverride("separation", 4);
foreach (byte speed in new byte[] { 0, 1, 2, 4, 8 })
{
var b = new Button { Text = speed == 0 ? "II" : $"{speed}×", ToggleMode = true, CustomMinimumSize = new Vector2(46, 40) };
b.Pressed += () => _session?.SetSpeed(speed);
b.TooltipText = speed == 0 ? T("Pausa") : T("Velocità");
_speeds.Add(b);
speeds.AddChild(b);
}
row.AddChild(speeds);
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
row.AddChild(Stat(T("Cassa"), _cash));
row.AddChild(Stat(T("Patrimonio netto"), _worth));
row.AddChild(Stat(T("Rating"), _rating));
var chip = new PanelContainer();
chip.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 16, 12));
var chipRow = new HBoxContainer();
chipRow.AddThemeConstantOverride("separation", 8);
var dotBox = new CenterContainer();
dotBox.AddChild(_serverDot);
chipRow.AddChild(dotBox);
chipRow.AddChild(_server);
chip.AddChild(chipRow);
var chipCenter = new CenterContainer();
chipCenter.AddChild(chip);
row.AddChild(chipCenter);
}
private static VBoxContainer Stat(string caption, Label value)
{
var box = new VBoxContainer();
box.AddThemeConstantOverride("separation", -2);
var c = UiTheme.Text(caption, 12, Palette.TextSecondary);
c.HorizontalAlignment = HorizontalAlignment.Right;
value.HorizontalAlignment = HorizontalAlignment.Right;
box.AddChild(c);
box.AddChild(value);
return box;
}
public void Bind(GameSession session) => _session = session;
public override void _Process(double delta)
{
var w = _session?.World;
if (w?.Summary is null) return;
var me = w.Companies.GetValueOrDefault(w.Summary.CompanyId);
_company.Text = me?.Name ?? w.Summary.CompanyName;
int tier = Math.Clamp(me?.Tier ?? 1, 1, w.Data.Tiers.Tiers.Count);
((Label)_tier.GetChild(0)).Text = TranslationServer.GetLocale().StartsWith("en") ? w.Data.Tiers.Tiers[tier - 1].NameEn : w.Data.Tiers.Tiers[tier - 1].NameIt;
_date.Text = w.LastDigest?.Date ?? w.Summary.Date;
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString("short");
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
byte speed = _session!.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
for (int i = 0; i < _speeds.Count; i++) _speeds[i].SetPressedNoSignal(new byte[] { 0, 1, 2, 4, 8 }[i] == speed);
bool open = _session!.IsOpen;
_serverDot.Color = !open ? Palette.Danger : w.LastDigest?.Slow == true ? Palette.Amber : Palette.Ok;
_server.Text = open ? $"{_session.ServerLabel} {_session.LatencyMs:0} ms" : T("Disconnesso");
}
/// <summary>Marchio: ruota stilizzata ambra (immagine 01).</summary>
private sealed partial class Logo : Control
{
public override void _Draw()
{
var c = Size / 2;
float r = Math.Min(Size.X, Size.Y) / 2 - 3;
DrawArc(c, r, 0, MathF.Tau, 48, Palette.Amber, 3, true);
DrawLine(c - new Vector2(r, 0), c + new Vector2(r, 0), Palette.Amber, 3);
DrawLine(c - new Vector2(0, r), c + new Vector2(0, r), Palette.Amber, 3);
DrawCircle(c, r * 0.28f, Palette.Amber);
}
}
}
@@ -0,0 +1 @@
uid://dgi7tae6dnp32
+150
View File
@@ -0,0 +1,150 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Screens;
using ViaFerrea.Core.Data;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client;
/// <summary>
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra menu, collegamento e partita;
/// alla chiusura termina la sessione e l'eventuale server locale.
/// </summary>
public partial class Main : Node
{
private const string SettingsPath = "user://settings.cfg";
private GameData? _data;
private Node? _screen;
private GameSession? _session;
private string? _autopilot;
public override void _Ready()
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
string locale = (string)cfg.GetValue("ui", "locale", "it");
Localization.Load(locale);
GetWindow().Theme = UiTheme.Build();
GetWindow().Title = "Via Ferrea";
try
{
_data = GodotDataSource.LoadGameData();
}
catch (Exception e)
{
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
}
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "");
var args = OS.GetCmdlineUserArgs();
int i = Array.IndexOf(args, "--autopilot");
if (i >= 0 && _data is not null)
{
// collaudo: mappa piccola e seme fisso per il server locale
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
System.Environment.SetEnvironmentVariable("VF_MAP_SIZE", "64");
System.Environment.SetEnvironmentVariable("VF_SEED", "3");
System.Environment.SetEnvironmentVariable("VF_AUTOSAVE_MIN", "0");
StartLocal();
}
}
private void Swap(Node screen)
{
_screen?.QueueFree();
_screen = screen;
AddChild(screen);
}
private void ShowMenu(string status = "")
{
var menu = new MenuScreen();
menu.LocalGame += StartLocal;
menu.ConnectToServer += ShowConnect;
menu.LanguageChanged += code =>
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("ui", "locale", code);
cfg.Save(SettingsPath);
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);
}
private async void StartLocal()
{
if (_data is null) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
ShowMenu(T("Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_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);
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;
ShowGame(session);
}
catch (Exception e)
{
launcher.Dispose();
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}");
}
}
private void ShowGame(GameSession session)
{
_session = session;
var game = new GameScreen(session);
game.Exit += async () =>
{
var s = _session;
_session = null;
ShowMenu();
if (s is not null) await s.DisposeAsync();
};
Swap(game);
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
}
public override void _Notification(int what)
{
if (what == NotificationWMCloseRequest && _session is not null)
{
_session.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
_session = null;
}
}
}
@@ -0,0 +1 @@
uid://dva7myhv6o38v
@@ -0,0 +1,267 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Entità sulla mappa (immagine 04): case con tetti in coppi sulle celle d'abitato, impronte
/// delle industrie per tipo, stazioni con marciapiedi e fabbricato, depositi, porto e valico;
/// alberi delle foreste con MultiMeshInstance2D per chunk.
/// </summary>
public partial class EntityLayer : Node2D
{
private ClientWorld? _world;
private int _drawnEntities = -1;
private int _drawnTerrain = -1;
private int _drawnTrack = -1;
private float _zoom = 1;
private readonly Dictionary<(int, int), MultiMeshInstance2D> _forests = [];
private Texture2D? _treeTexture;
public int SelectedStation { get; set; } = -1;
public void Bind(ClientWorld world)
{
_world = world;
foreach (var f in _forests.Values) f.QueueFree();
_forests.Clear();
_drawnEntities = _drawnTerrain = _drawnTrack = -1;
}
public void SetZoom(float zoom)
{
bool redraw = (zoom >= MapScale.OverviewZoom) != (_zoom >= MapScale.OverviewZoom);
_zoom = zoom;
if (redraw) QueueRedraw();
foreach (var f in _forests.Values) f.Visible = zoom >= 0.02f;
}
public void ForestChunk(int cx, int cy)
{
var w = _world;
if (w?.Terrain is null) return;
_treeTexture ??= TreeTexture();
var t = w.Terrain;
var trees = new List<Transform2D>();
var colors = new List<Color>();
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
for (int y = y0; y < Math.Min(t.Height, y0 + t.ChunkCells); y++)
{
for (int x = x0; x < Math.Min(t.Width, x0 + t.ChunkCells); x++)
{
if ((CellType)t.Types[y * t.Width + x] != CellType.Forest) continue;
uint h = (uint)(x * 73856093 ^ y * 19349663);
for (int k = 0; k < 5; k++)
{
h = h * 1664525 + 1013904223;
float jx = (h & 0xFFFF) / 65535f, jy = (h >> 16) / 65535f;
float r = (float)t.CellSizeM * (0.16f + 0.08f * ((h >> 8) & 7) / 7f);
var pos = new Vector2((float)((x + jx) * t.CellSizeM), (float)((y + jy) * t.CellSizeM));
trees.Add(new Transform2D(0, new Vector2(r * 2, r * 2), 0, pos));
colors.Add(Palette.Canopy.Lerp(new Color("7aa65a"), ((h >> 4) & 15) / 15f));
}
}
}
if (_forests.Remove((cx, cy), out var old)) old.QueueFree();
if (trees.Count == 0) return;
var mesh = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform2D,
UseColors = true,
Mesh = new QuadMesh { Size = Vector2.One },
InstanceCount = trees.Count,
};
for (int i = 0; i < trees.Count; i++)
{
mesh.SetInstanceTransform2D(i, trees[i]);
mesh.SetInstanceColor(i, colors[i]);
}
var node = new MultiMeshInstance2D { Multimesh = mesh, Texture = _treeTexture, ZIndex = 3 };
AddChild(node);
_forests[(cx, cy)] = node;
}
/// <summary>Chioma d'albero: disco con bordo più scuro (immagine 02).</summary>
private static Texture2D TreeTexture()
{
const int n = 64;
var img = Image.CreateEmpty(n, n, false, Image.Format.Rgba8);
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
float dx = (x + 0.5f) / n * 2 - 1, dy = (y + 0.5f) / n * 2 - 1;
float d = MathF.Sqrt(dx * dx + dy * dy);
if (d > 1) { img.SetPixel(x, y, new Color(0, 0, 0, 0)); continue; }
float light = 1.05f - 0.25f * Math.Clamp(dx + dy + 0.3f, 0, 1) - (d > 0.82f ? 0.25f : 0);
img.SetPixel(x, y, new Color(light, light, light, 1));
}
}
return ImageTexture.CreateFromImage(img);
}
public override void _Process(double delta)
{
if (_world is null) return;
if (_world.EntityVersion != _drawnEntities || _world.TerrainVersion != _drawnTerrain || _world.TrackVersion != _drawnTrack) QueueRedraw();
}
public override void _Draw()
{
var w = _world;
if (w?.Terrain is null) return;
_drawnEntities = w.EntityVersion;
_drawnTerrain = w.TerrainVersion;
_drawnTrack = w.TrackVersion;
var t = w.Terrain;
float cs = (float)t.CellSizeM;
// case: blocchi per cella d'abitato, disposizione fissa per cella
foreach (var town in w.Towns.Values)
{
int r = (int)Math.Ceiling(town.RadiusCells) + 1;
var (tcx, tcy) = t.CellAt(town.Position);
for (int y = tcy - r; y <= tcy + r; y++)
{
for (int x = tcx - r; x <= tcx + r; x++)
{
if (x < 0 || y < 0 || x >= t.Width || y >= t.Height || (CellType)t.Types[y * t.Width + x] != CellType.Town) continue;
DrawHouses(x, y, cs);
}
}
}
foreach (var ind in w.Industries.Values) DrawIndustry(ind, cs);
foreach (var hub in w.Hubs.Values) DrawHub(hub, cs);
foreach (var d in w.Depots.Values) DrawDepot(w, d);
foreach (var st in w.Stations.Values) DrawStation(w, st);
}
private void DrawHouses(int x, int y, float cs)
{
uint h = (uint)(x * 2654435761u ^ y * 40503u);
int count = 3 + (int)(h % 3);
for (int k = 0; k < count; k++)
{
h = h * 1664525 + 1013904223;
float fx = (h & 1023) / 1023f * 0.62f + 0.06f, fy = ((h >> 10) & 1023) / 1023f * 0.62f + 0.06f;
float wpx = cs * (0.18f + ((h >> 20) & 7) * 0.02f), hpx = cs * (0.13f + ((h >> 23) & 7) * 0.015f);
var rect = new Rect2(x * cs + fx * cs, y * cs + fy * cs, wpx, hpx);
var roof = ((h >> 26) & 3) switch { 0 => Palette.IndustrialRoof.Lightened(0.15f), 1 => new Color("a8836a"), _ => Palette.TileRoof };
DrawRect(new Rect2(rect.Position + new Vector2(cs * 0.02f, cs * 0.02f), rect.Size), new Color(0, 0, 0, 0.18f));
DrawRect(rect, roof);
DrawLine(rect.Position + new Vector2(0, rect.Size.Y / 2), rect.Position + new Vector2(rect.Size.X, rect.Size.Y / 2), roof.Darkened(0.25f), cs * 0.012f);
}
}
private void DrawIndustry(IndustryInfo ind, float cs)
{
float size = Math.Max(1, ind.FootprintCells) * cs;
var c = MapScale.V(ind.Position);
var pad = new Rect2(c - new Vector2(size, size) * 0.45f, new Vector2(size, size) * 0.9f);
var ground = ind.Closed ? new Color("b8b4a6") : new Color("bdb6a2");
DrawRect(pad, ground);
DrawRect(pad, new Color("8f8a7a"), false, cs * 0.03f);
string type = ind.Type;
if (type.Contains("mine") || type.Contains("quarry") || type.Contains("well"))
{
DrawCircle(c, size * 0.28f, new Color("6b5e4f"));
DrawCircle(c, size * 0.18f, new Color("3d3630"));
DrawRect(new Rect2(c + new Vector2(size * 0.12f, -size * 0.38f), new Vector2(size * 0.22f, size * 0.14f)), Palette.IndustrialRoof);
}
else if (type.Contains("farm") || type.Contains("ranch") || type.Contains("logging"))
{
DrawRect(new Rect2(c - new Vector2(size * 0.3f, size * 0.2f), new Vector2(size * 0.32f, size * 0.22f)), Palette.TileRoof);
DrawCircle(c + new Vector2(size * 0.2f, -size * 0.1f), size * 0.08f, new Color("9a9a90"));
}
else
{
// capannoni con lucernari (immagine 04)
int sheds = Math.Max(2, ind.FootprintCells);
float sw = size * 0.8f / sheds;
for (int i = 0; i < sheds; i++)
{
var r = new Rect2(pad.Position + new Vector2(size * 0.05f + i * sw, size * 0.08f), new Vector2(sw * 0.92f, size * 0.55f));
DrawRect(new Rect2(r.Position + new Vector2(cs * 0.04f, cs * 0.04f), r.Size), new Color(0, 0, 0, 0.2f));
DrawRect(r, Palette.IndustrialRoof);
DrawLine(r.Position + new Vector2(r.Size.X / 2, 0), r.Position + new Vector2(r.Size.X / 2, r.Size.Y), Palette.IndustrialRoof.Darkened(0.3f), cs * 0.02f);
}
DrawCircle(pad.Position + new Vector2(size * 0.78f, size * 0.75f), size * 0.07f, new Color("6e7175"));
}
if (ind.Closed) DrawLine(pad.Position, pad.End, Palette.Danger, cs * 0.05f);
}
private void DrawHub(HubInfo hub, float cs)
{
var c = MapScale.V(hub.Position);
if (hub.Kind == "port")
{
DrawRect(new Rect2(c - new Vector2(cs * 0.9f, cs * 0.35f), new Vector2(cs * 1.8f, cs * 0.7f)), new Color("9d968a"));
DrawRect(new Rect2(c + new Vector2(cs * 0.2f, -cs * 0.15f), new Vector2(cs * 1.2f, cs * 0.3f)), new Color("4b5560"));
}
else
{
DrawRect(new Rect2(c - new Vector2(cs * 0.4f, cs * 0.25f), new Vector2(cs * 0.8f, cs * 0.5f)), Palette.IndustrialRoof);
for (int i = 0; i < 6; i++)
DrawLine(c + new Vector2(-cs * 0.6f + i * cs * 0.2f, cs * 0.4f), c + new Vector2(-cs * 0.5f + i * cs * 0.2f, cs * 0.4f), i % 2 == 0 ? Palette.Danger : Colors.White, cs * 0.06f);
}
}
/// <summary>Direzione del binario che entra nel nodo (per orientare marciapiedi e fabbricati).</summary>
private static Vector2 NodeDirection(ClientWorld w, int nodeId)
{
if (nodeId < 0 || nodeId >= w.Network.Nodes.Count) return Vector2.Right;
var node = w.Network.Nodes[nodeId];
foreach (var eid in node.Edges)
{
if (!w.Edges.TryGetValue(eid.Value, out var e) || e.S.Length < 2) continue;
bool atA = e.A == nodeId;
var p0 = atA ? MapScale.V(e.X[0], e.Y[0]) : MapScale.V(e.X[^1], e.Y[^1]);
var p1 = atA ? MapScale.V(e.X[1], e.Y[1]) : MapScale.V(e.X[^2], e.Y[^2]);
var d = p1 - p0;
if (d.LengthSquared() > 0) return atA ? d.Normalized() : -d.Normalized();
}
return Vector2.Right;
}
private void DrawStation(ClientWorld w, StationInfo st)
{
float s = MapScale.Symbol(_zoom);
var c = MapScale.V(st.Position);
var dir = NodeDirection(w, st.Node);
var n = new Vector2(-dir.Y, dir.X);
float len = 60f * Math.Max(1, s * 0.6f);
float pw = 3.5f * s;
// marciapiedi ai lati dei binari (immagine 02) e fabbricato con tetto in coppi
for (int k = 0; k < Math.Min(st.Platforms, 4); k++)
{
float side = (k % 2 == 0 ? 1 : -1) * (7f + 6f * (k / 2)) * s;
DrawLine(c - dir * len / 2 + n * side, c + dir * len / 2 + n * side, new Color("d9d4c6"), pw);
}
var b = c + n * 15f * s;
DrawSetTransform(b, dir.Angle());
DrawRect(new Rect2(new Vector2(-12, -5.5f) * s + new Vector2(1.5f, 1.5f) * s, new Vector2(24, 11) * s), new Color(0, 0, 0, 0.2f));
DrawRect(new Rect2(new Vector2(-12, -5.5f) * s, new Vector2(24, 11) * s), Palette.TileRoof);
DrawLine(new Vector2(-12, 0) * s, new Vector2(12, 0) * s, Palette.TileRoof.Darkened(0.3f), 0.8f * s);
DrawSetTransform(Vector2.Zero, 0);
if (st.Id == SelectedStation)
{
float radius = (float)(w.Data.Construction.Stations.CatchmentKm * 1000);
DrawArc(c, radius, 0, MathF.Tau, 96, Palette.Amber, 2f * s);
}
}
private void DrawDepot(ClientWorld w, DepotInfo d)
{
float s = MapScale.Symbol(_zoom);
var c = MapScale.V(d.Position);
var dir = NodeDirection(w, d.Node);
DrawSetTransform(c, dir.Angle());
DrawRect(new Rect2(new Vector2(-16, -9) * s + new Vector2(2, 2) * s, new Vector2(32, 18) * s), new Color(0, 0, 0, 0.2f));
DrawRect(new Rect2(new Vector2(-16, -9) * s, new Vector2(32, 18) * s), new Color("5a6670"));
for (int i = -1; i <= 1; i++) DrawLine(new Vector2(-14, i * 5) * s, new Vector2(14, i * 5) * s, new Color("8a96a0"), 1f * s);
DrawSetTransform(Vector2.Zero, 0);
}
}
@@ -0,0 +1 @@
uid://b3e42tuyvbw27
@@ -0,0 +1,105 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Etichette a dimensione costante sullo schermo: città in Big Shoulders Display con gli abitanti,
/// industrie e stazioni in IBM Plex Sans; scala grafica in basso a destra (immagine 01).
/// </summary>
public partial class LabelLayer : Control
{
private ClientWorld? _world;
private Camera2D? _camera;
public void Bind(ClientWorld world, Camera2D camera)
{
_world = world;
_camera = camera;
MouseFilter = MouseFilterEnum.Ignore;
SetAnchorsPreset(LayoutPreset.FullRect);
}
public override void _Process(double delta) => QueueRedraw();
private Vector2 ToScreen(Vector2 world)
{
var vt = GetViewport().GetCanvasTransform();
return vt * world;
}
public override void _Draw()
{
var w = _world;
if (w?.Terrain is null || _camera is null) return;
float zoom = _camera.Zoom.X;
var size = GetViewportRect().Size;
bool InView(Vector2 p) => p.X > -200 && p.Y > -100 && p.X < size.X + 200 && p.Y < size.Y + 100;
foreach (var town in w.Towns.Values)
{
var p = ToScreen(MapScale.V(town.Position));
if (!InView(p)) continue;
int titleSize = town.Population >= 10000 ? 30 : town.Population >= 3000 ? 26 : 22;
Centered(UiTheme.Title, town.Name, p + new Vector2(0, -6), titleSize, new Color("2a2f2c"), outline: true);
Centered(UiTheme.Body, $"{Money.GroupThousands((ulong)town.Population)} {Localization.T("abitanti")}", p + new Vector2(0, 12), 13, new Color("3d4440"), outline: true);
}
if (zoom >= 0.02f)
{
foreach (var ind in w.Industries.Values)
{
var p = ToScreen(MapScale.V(ind.Position) + new Vector2(0, (float)(ind.FootprintCells * w.Terrain.CellSizeM * 0.5)));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, ind.Name, p + new Vector2(0, 14), 13, new Color("2a2f2c"), outline: true);
}
foreach (var hub in w.Hubs.Values)
{
var p = ToScreen(MapScale.V(hub.Position));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, hub.Name, p + new Vector2(0, 26), 13, new Color("2a2f2c"), outline: true);
Centered(UiTheme.Body, Localization.T("hub mercato mondiale"), p + new Vector2(0, 42), 12, new Color("3d4440"), outline: true);
}
}
foreach (var st in w.Stations.Values)
{
var p = ToScreen(MapScale.V(st.Position));
if (!InView(p)) continue;
Centered(UiTheme.Body, st.Name, p + new Vector2(0, -18), 12, new Color("2a2f2c"), outline: true);
}
foreach (var d in w.Depots.Values)
{
var p = ToScreen(MapScale.V(d.Position));
if (!InView(p)) continue;
Centered(UiTheme.BodyBold, Localization.T("Deposito"), p + new Vector2(0, 26), 12, new Color("2a2f2c"), outline: true);
}
DrawScaleBar(size, zoom);
}
private void Centered(Font font, string text, Vector2 at, int size, Color color, bool outline)
{
var dims = font.GetStringSize(text, HorizontalAlignment.Left, -1, size);
var pos = at - new Vector2(dims.X / 2, 0);
if (outline) DrawStringOutline(font, pos, text, HorizontalAlignment.Left, -1, size, 4, new Color(0.86f, 0.88f, 0.82f, 0.85f));
DrawString(font, pos, text, HorizontalAlignment.Left, -1, size, color);
}
/// <summary>Scala grafica con una lunghezza «tonda» di circa 100 px.</summary>
private void DrawScaleBar(Vector2 size, float zoom)
{
double meters = 100 / zoom;
double[] nice = [50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000];
double m = nice.FirstOrDefault(v => v >= meters, nice[^1]);
float px = (float)(m * zoom);
var end = new Vector2(size.X - 30, size.Y - 60);
var start = end - new Vector2(px, 0);
var c = new Color("2a2f2c");
DrawLine(start, end, c, 2);
DrawLine(start, start + new Vector2(0, -8), c, 2);
DrawLine(end, end + new Vector2(0, -8), c, 2);
DrawLine((start + end) / 2, (start + end) / 2 + new Vector2(0, -5), c, 2);
string label = m >= 1000 ? $"{m / 1000:0} km" : $"{m:0} m";
Centered(UiTheme.Body, label, (start + end) / 2 + new Vector2(0, 18), 12, c, outline: true);
}
}
@@ -0,0 +1 @@
uid://b843xbckahtip
@@ -0,0 +1,66 @@
using Godot;
using ViaFerrea.Core.Common;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Scala dei simboli: a zoom ravvicinato binari e treni hanno le misure della guida in metri
/// (1 unità = 1 m: rotaie a ±2,4, traversine ogni 5,3, carro 16); allontanandosi i simboli si
/// ingrandiscono per restare leggibili come nell'immagine 01. LOD sotto 0,4 e 0,15.
/// </summary>
public static class MapScale
{
public const float DetailZoom = 0.4f;
public const float OverviewZoom = 0.15f;
public const float ContourMinZoom = 1.0f;
/// <summary>Moltiplicatore dei simboli per lo zoom (pixel per metro).</summary>
/// <remarks>
/// Tarata sui riferimenti: nell'immagine 01 (circa 0,02 px/m) un carro è lungo ~16 px, nella 02
/// (circa 0,6 px/m) ~70 px: pixel per unità = 5,5·zoom^0,44, cioè unità di mondo = 5,5·zoom^−0,56.
/// </remarks>
public static float Symbol(float zoom) => Math.Max(1f, 5.5f * MathF.Pow(Math.Max(zoom, 0.001f), -0.56f));
public static Vector2 V(Vec2 p) => new((float)p.X, (float)p.Y);
public static Vector2 V(double x, double y) => new((float)x, (float)y);
public static Vec2 W(Vector2 p) => new(p.X, p.Y);
/// <summary>Polilinea spostata lateralmente di offset (normale media ai vertici).</summary>
public static Vector2[] Offset(Vector2[] pts, float offset)
{
var result = new Vector2[pts.Length];
for (int i = 0; i < pts.Length; i++)
{
Vector2 dir;
if (i == 0) dir = pts[1] - pts[0];
else if (i == pts.Length - 1) dir = pts[i] - pts[i - 1];
else dir = (pts[i + 1] - pts[i - 1]);
dir = dir.LengthSquared() > 0 ? dir.Normalized() : Vector2.Right;
result[i] = pts[i] + new Vector2(-dir.Y, dir.X) * offset;
}
return result;
}
/// <summary>Punti e direzioni ogni «step» metri lungo una polilinea.</summary>
public static IEnumerable<(Vector2 Point, Vector2 Dir)> Every(Vector2[] pts, float step, float start = 0)
{
float next = start;
float acc = 0;
for (int i = 0; i < pts.Length - 1; i++)
{
var a = pts[i];
var b = pts[i + 1];
float len = a.DistanceTo(b);
if (len <= 0) continue;
var dir = (b - a) / len;
while (next <= acc + len)
{
yield return (a + dir * (next - acc), dir);
next += step;
}
acc += len;
}
}
}
@@ -0,0 +1 @@
uid://cb6evw1enekmi
@@ -0,0 +1,145 @@
using Godot;
using ViaFerrea.Client.Net;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Vista della mappa: Node2D con Camera2D e i livelli (terreno, opere e binari, entità, treni,
/// strumenti). Rotella = zoom attorno al cursore, tasto destro o centrale = spostamento,
/// WASD/frecce = spostamento da tastiera. Coordinate del mondo in metri (1 unità = 1 m).
/// </summary>
public partial class MapView : Node2D
{
public const float MinZoom = 0.008f;
public const float MaxZoom = 6f;
public Camera2D Camera { get; } = new();
public TerrainLayer Terrain { get; } = new() { ZIndex = 0 };
public TrackLayer Track { get; } = new() { ZIndex = 2 };
public EntityLayer Entities { get; } = new() { ZIndex = 1 };
public TrainLayer Trains { get; } = new() { ZIndex = 5 };
public ToolOverlay Tools { get; } = new() { ZIndex = 8 };
/// <summary>Clic sinistro sulla mappa (posizione nel mondo).</summary>
public event Action<Vector2>? Clicked;
/// <summary>Clic destro senza trascinamento (annulla lo strumento).</summary>
public event Action? Cancelled;
/// <summary>Spostamento del mouse sulla mappa (posizione nel mondo).</summary>
public event Action<Vector2>? Hovered;
private bool _dragging;
private Vector2 _dragDistance;
private float _lastZoom = -1;
public override void _Ready()
{
AddChild(Terrain);
AddChild(Entities);
AddChild(Track);
AddChild(Trains);
AddChild(Tools);
AddChild(Camera);
Camera.Enabled = true;
Camera.MakeCurrent();
}
public void Bind(GameSession session)
{
Terrain.Bind(session.World);
Track.Bind(session.World);
Entities.Bind(session.World);
Trains.Bind(session);
Tools.Bind(session.World);
var t = session.World.Summary!;
Camera.Position = new Vector2((float)(t.WidthCells * t.CellSizeM / 2), (float)(t.HeightCells * t.CellSizeM / 2));
float fit = (float)(GetViewportRect().Size.X / (t.WidthCells * t.CellSizeM));
SetZoom(Math.Clamp(fit * 2.5f, MinZoom, MaxZoom));
}
public float Zoom => Camera.Zoom.X;
public void SetZoom(float zoom)
{
zoom = Math.Clamp(zoom, MinZoom, MaxZoom);
Camera.Zoom = new Vector2(zoom, zoom);
}
public void CenterOn(Vector2 world) => Camera.Position = world;
/// <summary>Rettangolo del mondo visibile.</summary>
public Rect2 VisibleRect()
{
var size = GetViewportRect().Size / Zoom;
return new Rect2(Camera.GetScreenCenterPosition() - size / 2, size);
}
public override void _Process(double delta)
{
var move = Vector2.Zero;
if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) move.Y -= 1;
if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) move.Y += 1;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) move.X -= 1;
if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) move.X += 1;
if (move != Vector2.Zero && GetViewport().GuiGetFocusOwner() is not LineEdit)
Camera.Position += move.Normalized() * (float)delta * 700f / Zoom;
if (Math.Abs(Zoom - _lastZoom) > 1e-6)
{
_lastZoom = Zoom;
Terrain.SetZoom(Zoom);
Track.SetZoom(Zoom);
Entities.SetZoom(Zoom);
Trains.SetZoom(Zoom);
Tools.SetZoom(Zoom);
}
}
public override void _UnhandledInput(InputEvent e)
{
switch (e)
{
case InputEventMouseButton { ButtonIndex: MouseButton.WheelUp, Pressed: true } wheel:
ZoomAt(wheel.Position, 1.15f);
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.WheelDown, Pressed: true } wheel:
ZoomAt(wheel.Position, 1 / 1.15f);
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.Right or MouseButton.Middle } b:
if (b.Pressed)
{
_dragging = true;
_dragDistance = Vector2.Zero;
}
else
{
_dragging = false;
if (b.ButtonIndex == MouseButton.Right && _dragDistance.Length() < 4) Cancelled?.Invoke();
}
GetViewport().SetInputAsHandled();
break;
case InputEventMouseButton { ButtonIndex: MouseButton.Left, Pressed: true }:
Clicked?.Invoke(GetGlobalMousePosition());
GetViewport().SetInputAsHandled();
break;
case InputEventMouseMotion motion:
if (_dragging)
{
Camera.Position -= motion.Relative / Zoom;
_dragDistance += motion.Relative;
}
Hovered?.Invoke(GetGlobalMousePosition());
break;
}
}
private void ZoomAt(Vector2 screen, float factor)
{
var before = GetCanvasTransform().AffineInverse() * screen;
SetZoom(Zoom * factor);
// la camera si sposta perché il punto sotto il cursore resti fermo
var size = GetViewportRect().Size;
var offset = (screen - size / 2) / Zoom;
Camera.Position = before - offset;
}
}
@@ -0,0 +1 @@
uid://3frpv33rahht
@@ -0,0 +1,202 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Map;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Terreno a chunk (immagine 01): colori per tipo di cella e fascia altimetrica, ombreggiatura
/// con luce da nord-ovest (ombre verso sud-est), sponde chiare lungo l'acqua, campi a strisce;
/// curve di livello ogni 20 m su una texture separata visibile oltre lo zoom 1.
/// </summary>
public partial class TerrainLayer : Node2D
{
private const float ContourStepM = 20f;
private readonly Dictionary<(int, int), (Sprite2D Base, Sprite2D Contours)> _sprites = [];
private readonly Queue<(int, int)> _dirty = new();
private readonly HashSet<(int, int)> _queued = [];
private ClientWorld? _world;
public void Bind(ClientWorld world)
{
_world = world;
foreach (var (b, c) in _sprites.Values)
{
b.QueueFree();
c.QueueFree();
}
_sprites.Clear();
_dirty.Clear();
_queued.Clear();
}
/// <summary>Segna un chunk (e i vicini, per la continuità dell'ombreggiatura) da ridisegnare.</summary>
public void MarkDirty(int cx, int cy)
{
for (int dy = -1; dy <= 1; dy++)
{
for (int dx = -1; dx <= 1; dx++)
{
var key = (cx + dx, cy + dy);
if (_world is null || !_world.Chunks.Contains(key) || !_queued.Add(key)) continue;
_dirty.Enqueue(key);
}
}
}
public void SetZoom(float zoom)
{
bool contours = zoom >= MapScale.ContourMinZoom;
foreach (var (_, c) in _sprites.Values) c.Visible = contours;
}
public override void _Process(double delta)
{
// pochi chunk per fotogramma: l'ingresso in partita resta fluido
for (int i = 0; i < 6 && _dirty.Count > 0; i++)
{
var key = _dirty.Dequeue();
_queued.Remove(key);
Build(key.Item1, key.Item2);
}
}
private void Build(int cx, int cy)
{
var w = _world;
if (w?.Terrain is null || w.Sampler is null) return;
var t = w.Terrain;
int ppc = t.Width <= 700 ? 4 : t.Width <= 1300 ? 2 : 1;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int cellsW = Math.Min(t.ChunkCells, t.Width - x0), cellsH = Math.Min(t.ChunkCells, t.Height - y0);
int pw = cellsW * ppc, ph = cellsH * ppc;
var pixels = new byte[pw * ph * 4];
var contour = new byte[pw * ph * 4];
double cs = t.CellSizeM, px = cs / ppc;
// per cella (con un bordo): ombreggiatura dalle differenze centrali e indicatore d'acqua
int gw = cellsW + 3, gh = cellsH + 3;
var shade = new float[gw * gh];
var water = new float[gw * gh];
for (int gy = 0; gy < gh; gy++)
{
for (int gx = 0; gx < gw; gx++)
{
int x = Math.Clamp(x0 + gx - 1, 0, t.Width - 1), y = Math.Clamp(y0 + gy - 1, 0, t.Height - 1);
double hx = (H(t, x + 1, y) - H(t, x - 1, y)) / (2 * cs);
double hy = (H(t, x, y + 1) - H(t, x, y - 1)) / (2 * cs);
// luce da nord-ovest: i pendii rivolti a sud-est si scuriscono
shade[gy * gw + gx] = (float)Math.Clamp(1.0 - (hx + hy) * 1.8, 0.80, 1.12);
water[gy * gw + gx] = IsWater((CellType)t.Types[y * t.Width + x]) ? 1f : 0f;
}
}
var corner = new Color[4];
for (int y = 0; y < ph; y++)
{
for (int x = 0; x < pw; x++)
{
// posizione in celle rispetto ai centri: interpolazione bilineare tra quattro celle
double fx = (x + 0.5) / ppc - 0.5, fy = (y + 0.5) / ppc - 0.5;
int ix = (int)Math.Floor(fx), iy = (int)Math.Floor(fy);
float tx = (float)(fx - ix), ty = (float)(fy - iy);
int g00 = (iy + 1) * gw + ix + 1;
float wv = Bilinear(water[g00], water[g00 + 1], water[g00 + gw], water[g00 + gw + 1], tx, ty);
float sh = Bilinear(shade[g00], shade[g00 + 1], shade[g00 + gw], shade[g00 + gw + 1], tx, ty);
double h = w.Sampler.HeightAt(x0 * cs + (x + 0.5) * px, y0 * cs + (y + 0.5) * px);
for (int k = 0; k < 4; k++)
{
int cxCell = Math.Clamp(x0 + ix + (k & 1), 0, t.Width - 1), cyCell = Math.Clamp(y0 + iy + (k >> 1), 0, t.Height - 1);
corner[k] = BaseColor((CellType)t.Types[cyCell * t.Width + cxCell], h, cxCell, cyCell, x, y, ppc);
}
var c = corner[0].Lerp(corner[1], tx).Lerp(corner[2].Lerp(corner[3], tx), ty);
if (wv < 0.5f) c = new Color(c.R * sh, c.G * sh, c.B * sh);
SetPixel(pixels, pw, x, y, new Color(c.R, c.G, c.B, wv));
if (wv < 0.5f)
{
double hR = w.Sampler.HeightAt(x0 * cs + (x + 1.5) * px, y0 * cs + (y + 0.5) * px);
double hD = w.Sampler.HeightAt(x0 * cs + (x + 0.5) * px, y0 * cs + (y + 1.5) * px);
int band = (int)Math.Floor(h / ContourStepM);
if (band != (int)Math.Floor(hR / ContourStepM) || band != (int)Math.Floor(hD / ContourStepM))
SetPixel(contour, pw, x, y, new Color(0.25f, 0.27f, 0.22f, (band % 5 == 0) ? 0.45f : 0.22f));
}
}
}
var key = (cx, cy);
if (!_sprites.TryGetValue(key, out var pair))
{
pair = (NewSprite(), NewSprite());
pair.Base.Material = TerrainMaterial();
AddChild(pair.Base);
AddChild(pair.Contours);
pair.Contours.ZIndex = 1;
_sprites[key] = pair;
}
foreach (var (sprite, data) in new[] { (pair.Base, pixels), (pair.Contours, contour) })
{
sprite.Texture = ImageTexture.CreateFromImage(Image.CreateFromData(pw, ph, false, Image.Format.Rgba8, data));
sprite.Position = new Vector2((float)(x0 * cs), (float)(y0 * cs));
sprite.Scale = new Vector2((float)px, (float)px);
}
pair.Contours.Visible = GetViewport().GetCamera2D() is { } cam && cam.Zoom.X >= MapScale.ContourMinZoom;
}
private static ShaderMaterial? _material;
private static ShaderMaterial TerrainMaterial()
{
if (_material is not null) return _material;
var shader = ResourceLoader.Load<Shader>("res://assets/shaders/terrain.gdshader");
_material = new ShaderMaterial { Shader = shader };
_material.SetShaderParameter("bank_color", Palette.Banks);
return _material;
}
private static double H(Terrain t, int x, int y) => t.CellHeightM(Math.Clamp(x, 0, t.Width - 1), Math.Clamp(y, 0, t.Height - 1));
private static float Bilinear(float a, float b, float c, float d, float tx, float ty) => (a + (b - a) * tx) + ((c + (d - c) * tx) - (a + (b - a) * tx)) * ty;
private static Sprite2D NewSprite() => new() { Centered = false, TextureFilter = TextureFilterEnum.Linear };
private static bool IsWater(CellType type) => type is CellType.Water or CellType.Sea;
private static Color BaseColor(CellType type, double h, int cellX, int cellY, int x, int y, int ppc)
{
switch (type)
{
case CellType.Sea: return Palette.Sea;
case CellType.Water: return Palette.Water;
case CellType.Marsh: return (x + y) % 6 < 2 ? Palette.Water.Lerp(Palette.Marsh, 0.6f) : Palette.Marsh;
case CellType.Forest: return Palette.Undergrowth;
case CellType.Field:
{
// campi a strisce, con orientamento e colore per cella
uint hash = (uint)(cellX * 73856093 ^ cellY * 19349663);
bool vertical = (hash & 1) == 0;
int stripe = (vertical ? x : y) * 4 / Math.Max(1, ppc);
var baseColor = ((hash >> 1) % 3) switch { 0 => Palette.Grain, 1 => new Color("a9c46a"), _ => new Color("c8a86a") };
return stripe % 2 == 0 ? baseColor : baseColor.Darkened(0.08f);
}
case CellType.Town: return new Color("d6d2bf");
case CellType.Industry: return new Color("c9c4b2");
case CellType.Rock: return Palette.Rock;
case CellType.Mountain: return Palette.Highland.Darkened(0.05f);
default:
{
// fasce altimetriche: pianura, collina, altura
if (h < 120) return Palette.Plain;
if (h < 320) return Palette.Plain.Lerp(Palette.Hill, (float)((h - 120) / 200));
return Palette.Hill.Lerp(Palette.Highland, (float)Math.Min(1, (h - 320) / 300));
}
}
}
private static void SetPixel(byte[] data, int width, int x, int y, Color c)
{
int i = (y * width + x) * 4;
data[i] = (byte)(Math.Clamp(c.R, 0, 1) * 255);
data[i + 1] = (byte)(Math.Clamp(c.G, 0, 1) * 255);
data[i + 2] = (byte)(Math.Clamp(c.B, 0, 1) * 255);
data[i + 3] = (byte)(Math.Clamp(c.A, 0, 1) * 255);
}
}
@@ -0,0 +1 @@
uid://cjsaug4ypro7
@@ -0,0 +1,122 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
namespace ViaFerrea.Client.Map;
/// <summary>Sagome degli strumenti: tracciato in corso con l'anteprima delle opere, stazione o deposito da posare, fermate di una linea.</summary>
public partial class ToolOverlay : Node2D
{
public enum Ghost { None, Station, Depot, Demolish }
private ClientWorld? _world;
private float _zoom = 1;
private List<Vector2> _points = [];
private Vector2? _mouse;
private TrackPlan? _plan;
private Ghost _ghost;
private Vector2? _ghostAt;
private List<Vector2> _stops = [];
public void Bind(ClientWorld world) => _world = world;
public void SetZoom(float zoom)
{
_zoom = zoom;
QueueRedraw();
}
public void SetTrack(List<Vector2> points, Vector2? mouse, TrackPlan? plan)
{
_points = points;
_mouse = mouse;
_plan = plan;
QueueRedraw();
}
public void SetGhost(Ghost ghost, Vector2? at)
{
_ghost = ghost;
_ghostAt = at;
QueueRedraw();
}
public void SetStops(List<Vector2> stops)
{
_stops = stops;
QueueRedraw();
}
public void Clear()
{
_points = [];
_mouse = null;
_plan = null;
_ghost = Ghost.None;
_ghostAt = null;
_stops = [];
QueueRedraw();
}
public static Color WorkColor(WorkKind kind) => kind switch
{
WorkKind.Embankment => new Color("e8e0c2"),
WorkKind.Cutting => new Color("8f8a73"),
WorkKind.Bridge => new Color("5b8fb0"),
WorkKind.Tunnel => new Color("4a4740"),
_ => Palette.Ballast,
};
public override void _Draw()
{
float s = MapScale.Symbol(_zoom);
if (_plan is { Samples.Count: > 1 } plan)
{
var color = plan.Valid ? Palette.Ok : Palette.Danger;
for (int i = 0; i < plan.Samples.Count - 1; i++)
{
var a = MapScale.V(plan.Samples[i].Point);
var b = MapScale.V(plan.Samples[i + 1].Point);
DrawLine(a, b, Palette.WithAlpha(color, 0.45f), 14f * s);
if (plan.Samples[i].Kind == WorkKind.Tunnel) DrawDashedLine(a, b, WorkColor(WorkKind.Tunnel), 5f * s, 6f * s);
else DrawLine(a, b, WorkColor(plan.Samples[i].Kind), 7f * s);
}
}
var pts = new List<Vector2>(_points);
if (_mouse is { } m && pts.Count > 0) pts.Add(m);
for (int i = 0; i < pts.Count - 1; i++) DrawDashedLine(pts[i], pts[i + 1], Palette.Amber, 2f * s, 8f * s);
foreach (var p in _points) DrawCircle(p, 4f * s, Palette.Amber);
if (_ghostAt is { } g && _world is not null)
{
switch (_ghost)
{
case Ghost.Station:
float radius = (float)(_world.Data.Construction.Stations.CatchmentKm * 1000);
for (int k = 0; k < 48; k += 2)
{
float a0 = k * MathF.Tau / 48, a1 = (k + 1) * MathF.Tau / 48;
DrawLine(g + new Vector2(MathF.Cos(a0), MathF.Sin(a0)) * radius, g + new Vector2(MathF.Cos(a1), MathF.Sin(a1)) * radius, Palette.Amber, 2.5f * s);
}
DrawCircle(g, radius, Palette.WithAlpha(Palette.Amber, 0.08f));
DrawRect(new Rect2(g - new Vector2(12, 6) * s, new Vector2(24, 12) * s), Palette.WithAlpha(Palette.TileRoof, 0.8f));
break;
case Ghost.Depot:
DrawRect(new Rect2(g - new Vector2(16, 9) * s, new Vector2(32, 18) * s), Palette.WithAlpha(new Color("5a6670"), 0.8f));
break;
case Ghost.Demolish:
DrawCircle(g, 30f * s, Palette.WithAlpha(Palette.Danger, 0.3f));
DrawLine(g - new Vector2(10, 10) * s, g + new Vector2(10, 10) * s, Palette.Danger, 3f * s);
DrawLine(g + new Vector2(-10, 10) * s, g + new Vector2(10, -10) * s, Palette.Danger, 3f * s);
break;
}
}
for (int i = 0; i < _stops.Count; i++)
{
if (i > 0) DrawDashedLine(_stops[i - 1], _stops[i], Palette.Amber, 3f * s, 10f * s);
DrawCircle(_stops[i], 9f * s, Palette.Amber);
DrawString(UiTheme.BodyBold, _stops[i] + new Vector2(-4, 5) * s, (i + 1).ToString(), HorizontalAlignment.Left, -1, (int)Math.Max(8, 12 * s), Palette.AppBackground);
}
}
}
@@ -0,0 +1 @@
uid://itdwbft1rwnw
@@ -0,0 +1,218 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Binari e opere (immagini 01 e 02): massicciata #bfb79f, traversine #5b4a39 ogni 5,3 unità,
/// rotaie #3b3f42 a ±2,4; rilevati come banda chiara con ombra, trincee come banda scura, ponti
/// con pile ogni 30 m e spallette, gallerie con portali e binario tratteggiato; cantieri con
/// tratteggio #8a7a52 e barriera ambra. LOD: sotto 0,4 niente traversine fitte, sotto 0,15 solo
/// massicciata e rotaia.
/// </summary>
public partial class TrackLayer : Node2D
{
private ClientWorld? _world;
private int _drawnVersion = -1;
private float _drawnScale = -1;
private float _zoom = 1;
public void Bind(ClientWorld world)
{
_world = world;
_drawnVersion = -1;
QueueRedraw();
}
public void SetZoom(float zoom)
{
_zoom = zoom;
float s = Quantize(MapScale.Symbol(zoom));
if (Math.Abs(s - _drawnScale) > 1e-3) QueueRedraw();
}
private static float Quantize(float s) => s <= 1 ? 1 : MathF.Pow(1.25f, MathF.Round(MathF.Log(s) / MathF.Log(1.25f)));
public override void _Process(double delta)
{
if (_world is not null && _world.TrackVersion != _drawnVersion) QueueRedraw();
}
public override void _Draw()
{
if (_world is null) return;
_drawnVersion = _world.TrackVersion;
float s = Quantize(MapScale.Symbol(_zoom));
_drawnScale = s;
var edges = _world.Edges.Values.OrderBy(e => e.Id).ToList();
// prima le opere sotto il binario, poi i binari, infine i dettagli
foreach (var e in edges) DrawWorks(e, s);
foreach (var e in edges) DrawTrack(e, s);
}
private static Vector2[] Points(EdgeInfo e, int from, int to)
{
var pts = new Vector2[to - from + 1];
for (int i = from; i <= to; i++) pts[i - from] = MapScale.V(e.X[i], e.Y[i]);
return pts;
}
/// <summary>Tratti consecutivi con la stessa opera.</summary>
private static IEnumerable<(WorkKind Kind, int From, int To)> Runs(EdgeInfo e)
{
int start = 0;
for (int i = 1; i <= e.Kinds.Length; i++)
{
if (i < e.Kinds.Length && e.Kinds[i] == e.Kinds[start]) continue;
yield return ((WorkKind)e.Kinds[start], Math.Max(0, start - (start > 0 ? 1 : 0)), Math.Min(e.Kinds.Length - 1, i));
start = i;
}
}
private void DrawWorks(EdgeInfo e, float s)
{
float width = (e.DoubleTrack ? 19f : 9f) * s;
foreach (var (kind, from, to) in Runs(e))
{
if (to <= from) continue;
var pts = Points(e, from, to);
switch (kind)
{
case WorkKind.Embankment:
DrawPolyline(Shift(pts, 2.5f * s), new Color(0.35f, 0.36f, 0.3f, 0.35f), width * 2.2f);
DrawPolyline(pts, new Color("ddd6bf"), width * 2.0f);
break;
case WorkKind.Cutting:
DrawPolyline(pts, new Color("8f8a73"), width * 2.2f);
DrawPolyline(pts, new Color("a8a38a"), width * 1.5f);
break;
case WorkKind.Bridge:
DrawBridge(pts, width, s);
break;
case WorkKind.Tunnel:
DrawPortal(pts[0], pts[1] - pts[0], width, s);
DrawPortal(pts[^1], pts[^2] - pts[^1], width, s);
break;
}
}
}
private void DrawBridge(Vector2[] pts, float width, float s)
{
// pile ogni 30 m, impalcato e spallette alle estremità
foreach (var (p, dir) in MapScale.Every(pts, 30f * Math.Max(1, s * 0.5f), 15f))
{
var n = new Vector2(-dir.Y, dir.X);
DrawLine(p - n * width * 0.85f, p + n * width * 0.85f, new Color("6f6a5e"), 3f * s);
}
DrawPolyline(Shift(pts, 2f * s), new Color(0.2f, 0.25f, 0.28f, 0.35f), width * 1.4f);
DrawPolyline(pts, new Color("b9b3a3"), width * 1.35f);
DrawPolyline(Offset(pts, width * 0.68f), new Color("7a7468"), 1.6f * s);
DrawPolyline(Offset(pts, -width * 0.68f), new Color("7a7468"), 1.6f * s);
foreach (var (end, inner) in new[] { (pts[0], pts[1]), (pts[^1], pts[^2]) })
{
var dir = (inner - end).Normalized();
var n = new Vector2(-dir.Y, dir.X);
DrawLine(end - n * width, end + n * width, new Color("8d877a"), 4f * s);
}
}
private void DrawPortal(Vector2 at, Vector2 inward, float width, float s)
{
if (inward.LengthSquared() <= 0) return;
var dir = inward.Normalized();
var n = new Vector2(-dir.Y, dir.X);
var c = new Color("4a4740");
DrawLine(at - n * width, at + n * width, c, 5f * s);
DrawLine(at - n * width, at - n * width + dir * 8f * s, c, 3f * s);
DrawLine(at + n * width, at + n * width + dir * 8f * s, c, 3f * s);
}
private void DrawTrack(EdgeInfo e, float s)
{
var all = Points(e, 0, e.S.Length - 1);
bool building = e.State == (byte)EdgeState.UnderConstruction;
int built = all.Length - 1;
if (building)
{
// parte costruita in proporzione all'avanzamento, il resto tratteggiato
double target = e.Progress * e.S[^1];
built = 0;
while (built < e.S.Length - 1 && e.S[built + 1] <= target) built++;
}
float[] offsets = e.DoubleTrack ? [-5f * s, 5f * s] : [0f];
foreach (float off in offsets)
{
var line = off == 0 ? all : Offset(all, off);
foreach (var (kind, from, to) in Runs(e))
{
int a = from, b = Math.Min(to, built);
if (b <= a) continue;
var seg = line[a..(b + 1)];
if (kind == WorkKind.Tunnel)
{
for (int i = 0; i < seg.Length - 1; i++) DrawDashedLine(seg[i], seg[i + 1], Palette.Rails, 1.5f * s, 6f * s);
continue;
}
DrawSingleTrack(seg, s, e.State == (byte)EdgeState.Closed);
}
if (building && built < all.Length - 1)
{
var rest = line[built..];
for (int i = 0; i < rest.Length - 1; i++) DrawDashedLine(rest[i], rest[i + 1], Palette.Construction, 2.5f * s, 7f * s);
// barriera ambra al fronte del cantiere
var front = rest[0];
var dir = (rest[Math.Min(1, rest.Length - 1)] - front).Normalized();
var n = new Vector2(-dir.Y, dir.X);
for (int k = -2; k <= 1; k++)
{
var c = k % 2 == 0 ? Palette.Amber : Palette.AppBackground;
DrawLine(front + n * k * 2.5f * s, front + n * (k + 1) * 2.5f * s, c, 2.2f * s);
}
}
}
// segnali: piccoli dischi accanto al binario
foreach (double sig in e.Signals)
{
int i = Array.BinarySearch(e.S, sig);
if (i < 0) i = Math.Max(0, ~i - 1);
i = Math.Min(i, e.S.Length - 2);
var p = all[i];
var dir = (all[i + 1] - p).Normalized();
var n = new Vector2(-dir.Y, dir.X);
DrawCircle(p + n * 7f * s, 1.8f * s, Palette.Rails);
DrawCircle(p + n * 7f * s, 1.1f * s, Palette.Ok);
}
}
private void DrawSingleTrack(Vector2[] pts, float s, bool closed)
{
float zoomDetail = _zoom;
DrawPolyline(pts, closed ? Palette.Ballast.Darkened(0.2f) : Palette.Ballast, 9f * s);
if (zoomDetail >= MapScale.OverviewZoom || s > 1)
{
float spacing = 5.3f * s * (zoomDetail >= MapScale.DetailZoom ? 1 : 1.6f);
var sleepers = new List<Vector2>();
foreach (var (p, dir) in MapScale.Every(pts, spacing, spacing / 2))
{
var n = new Vector2(-dir.Y, dir.X);
sleepers.Add(p - n * 3.6f * s);
sleepers.Add(p + n * 3.6f * s);
}
if (sleepers.Count > 0) DrawMultiline(sleepers.ToArray(), Palette.Sleepers, 1.3f * s);
DrawPolyline(Offset(pts, 2.4f * s), Palette.Rails, 0.9f * s);
DrawPolyline(Offset(pts, -2.4f * s), Palette.Rails, 0.9f * s);
}
else
{
DrawPolyline(pts, Palette.Rails, 1.4f * s);
}
}
private static Vector2[] Offset(Vector2[] pts, float off) => MapScale.Offset(pts, off);
private static Vector2[] Shift(Vector2[] pts, float d) => pts.Select(p => p + new Vector2(d, d)).ToArray();
}
@@ -0,0 +1 @@
uid://ckvbn0wqdgoiy
@@ -0,0 +1,212 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Map;
/// <summary>
/// Treni dall'alto (immagine 03): locomotiva scura con dettagli ambra, carri e carrozze con le
/// proporzioni della guida (larghezza 9, carro 16, carrozza 20, locomotiva 20–26), posizione
/// interpolata avanzando la testa alla velocità ricevuta; fumo per le vaporiere; sfumatura e
/// icona d'avviso sotto condizione 40.
/// </summary>
public partial class TrainLayer : Node2D
{
private GameSession? _session;
private float _zoom = 1;
private readonly List<GpuParticles2D> _smoke = [];
private Dictionary<string, VehicleDef> _defs = [];
public int SelectedTrain { get; set; } = -1;
/// <summary>Teste dei treni disegnate nell'ultimo fotogramma (per la selezione col mouse).</summary>
public Dictionary<int, Vector2> Heads { get; } = [];
public void Bind(GameSession session)
{
_session = session;
_defs = session.World.Data.Vehicles.ToDictionary(v => v.Id);
}
public void SetZoom(float zoom) => _zoom = zoom;
public override void _Process(double delta) => QueueRedraw();
/// <summary>Secondi di orologio dei treni trascorsi dall'arrivo del moto (fattore 60 per la velocità).</summary>
private double Elapsed(int trainId, ClientWorld w)
{
if (_session is null || !_session.MotionReceivedMs.TryGetValue(trainId, out long at)) return 0;
double realSeconds = Math.Max(0, ((long)Time.GetTicksMsec() - at) / 1000.0);
double perTick = w.Calendar?.TrainSecondsPerTick ?? 3;
double ticksPerSecond = 1000.0 / (w.Calendar?.TickMs ?? 50);
// senza interpolare oltre mezzo secondo: il moto successivo arriva ogni 100 ms
return Math.Min(realSeconds, 0.5) * ticksPerSecond * perTick * w.Speed;
}
public override void _Draw()
{
Heads.Clear();
var w = _session?.World;
if (w is null) return;
float s = MapScale.Symbol(_zoom);
var view = VisibleWorldRect().Grow(400 * s);
int smokeUsed = 0;
foreach (var (id, motion) in w.Motions)
{
if (!w.Trains.TryGetValue(id, out var train) || train.State == (byte)TrainState.InDepot) continue;
double total = ClientWorld.TotalLength(motion);
double head = Math.Min(motion.HeadDistance + motion.Speed * Elapsed(id, w), total);
var headPoint = w.PointAlong(motion, head);
if (headPoint is null || !view.HasPoint(MapScale.V(headPoint.Value))) continue;
Heads[id] = MapScale.V(headPoint.Value);
double d = head;
bool first = true;
foreach (int vid in train.Vehicles)
{
if (!w.Vehicles.TryGetValue(vid, out var v) || !_defs.TryGetValue(v.Type, out var def)) continue;
float length = DrawLength(def) * s;
var front = w.PointAlong(motion, Math.Max(0, d));
var back = w.PointAlong(motion, Math.Max(0, d - length));
if (front is null || back is null) break;
var f = MapScale.V(front.Value);
var b = MapScale.V(back.Value);
if (f.DistanceTo(b) < length * 0.9f)
{
// la coda esce dai tratti noti: si prolunga all'indietro lungo la direzione del binario
var ahead = w.PointAlong(motion, Math.Min(total, Math.Max(0, d) + 5));
var dir = ahead is { } ap && MapScale.V(ap).DistanceTo(f) > 0.01f ? (MapScale.V(ap) - f).Normalized()
: (f - b).LengthSquared() > 0.0001f ? (f - b).Normalized() : Vector2.Right;
if (ahead is { } ap2 && MapScale.V(ap2).DistanceTo(f) <= 0.01f && (f - b).LengthSquared() > 0.0001f) dir = (f - b).Normalized();
b = f - dir * length;
}
DrawVehicle(def, v, f, b, s, id == SelectedTrain);
if (first && def.Kind == VehicleKind.Locomotive && def.Traction == Traction.Steam && motion.Speed > 0.5f && smokeUsed < 24)
PlaceSmoke(smokeUsed++, f.Lerp(b, 0.25f), s);
first = false;
d -= length + 1.5f * s;
if (d < 0) break;
}
if (motion.Condition < 40)
{
// icona d'avviso: triangolo ambra sopra la testa
var p = MapScale.V(headPoint.Value) + new Vector2(0, -16 * s);
DrawColoredPolygon([p + new Vector2(0, -6 * s), p + new Vector2(6 * s, 5 * s), p + new Vector2(-6 * s, 5 * s)], Palette.Amber);
DrawLine(p + new Vector2(0, -2.5f * s), p + new Vector2(0, 1.5f * s), Palette.AppBackground, 1.4f * s);
}
}
for (int i = smokeUsed; i < _smoke.Count; i++) _smoke[i].Emitting = false;
}
private static float DrawLength(VehicleDef def) => def.Kind switch
{
VehicleKind.Locomotive => (float)Math.Clamp(def.LengthM * 1.25, 20, 26),
VehicleKind.Coach => 20f,
_ => 16f,
};
private void DrawVehicle(VehicleDef def, VehicleInfo v, Vector2 front, Vector2 back, float s, bool selected)
{
var center = (front + back) / 2;
var dir = front - back;
float length = dir.Length();
DrawSetTransform(center, dir.Angle());
float width = 9f * s;
var rect = new Rect2(-length / 2, -width / 2, length, width);
Color body = def.Kind switch
{
VehicleKind.Locomotive => new Color("1d2226"),
VehicleKind.Coach => def.Class == PaxClass.Staff ? Palette.Staff : Palette.Workers,
_ => def.WagonType switch
{
WagonType.Hopper => new Color("6b4a3a"),
WagonType.Flat => new Color("8a8f94"),
WagonType.Tank => new Color("4b5258"),
_ => new Color("8a5a44"),
},
};
if (v.Condition < 40) body = body.Lerp(Palette.Danger, 0.45f);
DrawRect(new Rect2(rect.Position + new Vector2(1.2f, 1.2f) * s, rect.Size), new Color(0, 0, 0, 0.25f));
DrawRect(rect, body);
DrawRect(rect, selected ? Palette.Amber : body.Darkened(0.35f), false, (selected ? 1.1f : 0.6f) * s);
switch (def.Kind)
{
case VehicleKind.Locomotive:
// cabina ambra verso la coda, caldaia e fanale verso la testa
DrawRect(new Rect2(-length / 2 + 1.5f * s, -width / 2 + 1.2f * s, 4.5f * s, width - 2.4f * s), Palette.Amber);
DrawCircle(new Vector2(length / 2 - 3.5f * s, 0), 1.8f * s, Palette.AmberLight);
DrawLine(new Vector2(-length / 2 + 7 * s, 0), new Vector2(length / 2 - 6 * s, 0), body.Lightened(0.15f), 1f * s);
break;
case VehicleKind.Coach:
for (float x = -length / 2 + 3 * s; x < length / 2 - 2 * s; x += 3.2f * s)
DrawRect(new Rect2(x, -width / 2 + 1.2f * s, 1.8f * s, 1.4f * s), Colors.White.Lerp(body, 0.4f));
break;
default:
if (def.WagonType == WagonType.Hopper)
DrawRect(new Rect2(-length / 2 + 2 * s, -width / 2 + 1.5f * s, length - 4 * s, width - 3 * s), body.Darkened(0.3f));
else if (def.WagonType == WagonType.Tank)
DrawCircle(Vector2.Zero, width * 0.35f, body.Lightened(0.15f));
break;
}
DrawSetTransform(Vector2.Zero, 0);
}
private void PlaceSmoke(int index, Vector2 at, float s)
{
while (_smoke.Count <= index)
{
var gradient = new Gradient();
gradient.SetColor(0, new Color(0.92f, 0.92f, 0.9f, 0.55f));
gradient.SetColor(1, new Color(0.92f, 0.92f, 0.9f, 0f));
var material = new ParticleProcessMaterial
{
Direction = new Vector3(1, -1, 0),
Spread = 25,
InitialVelocityMin = 6,
InitialVelocityMax = 12,
Gravity = new Vector3(4, -2, 0),
ScaleMin = 0.8f,
ScaleMax = 1.6f,
ColorRamp = new GradientTexture1D { Gradient = gradient },
};
var p = new GpuParticles2D { Amount = 16, Lifetime = 1.6, ProcessMaterial = material, Texture = SmokePuff(), ZIndex = 6, LocalCoords = false };
AddChild(p);
_smoke.Add(p);
}
var smoke = _smoke[index];
smoke.Position = at;
smoke.Scale = new Vector2(s, s) * 0.25f;
smoke.Emitting = true;
}
private static Texture2D? _puff;
private static Texture2D SmokePuff()
{
if (_puff is not null) return _puff;
const int n = 32;
var img = Image.CreateEmpty(n, n, false, Image.Format.Rgba8);
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
float dx = (x + 0.5f) / n * 2 - 1, dy = (y + 0.5f) / n * 2 - 1;
float a = Math.Clamp(1 - MathF.Sqrt(dx * dx + dy * dy), 0, 1);
img.SetPixel(x, y, new Color(1, 1, 1, a * a));
}
}
return _puff = ImageTexture.CreateFromImage(img);
}
private Rect2 VisibleWorldRect()
{
var canvas = GetCanvasTransform().AffineInverse();
var size = GetViewportRect().Size;
var a = canvas * Vector2.Zero;
var b = canvas * size;
return new Rect2(a, b - a).Abs();
}
}
@@ -0,0 +1 @@
uid://dsfaatx2pgfka
@@ -0,0 +1,142 @@
using Godot;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Data;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
namespace ViaFerrea.Client.Net;
/// <summary>
/// Sessione di gioco del client: connessione, copia locale del mondo, esiti dei comandi e
/// notifiche. I messaggi si applicano sul thread principale in <see cref="Poll"/>.
/// </summary>
public sealed class GameSession : IAsyncDisposable
{
private readonly Dictionary<uint, Action<CommandResultMessage>> _callbacks = [];
private long _pingSentMs;
private ulong _pingNonce;
public ProtocolClient Connection { get; }
public ClientWorld World { get; }
public string ServerLabel { get; }
public LocalServerLauncher? LocalServer { get; set; }
/// <summary>Istante di arrivo (ms) dell'ultimo moto di ogni treno, per l'interpolazione.</summary>
public Dictionary<int, long> MotionReceivedMs { get; } = [];
/// <summary>Ritardo di andata e ritorno dell'ultimo ping (ms).</summary>
public double LatencyMs { get; private set; }
public event Action<IMessage>? MessageApplied;
public event Action<EventInfo>? Notified;
public event Action<CommandResultMessage>? CommandFailed;
private GameSession(ProtocolClient connection, ClientWorld world, string label)
{
Connection = connection;
World = world;
ServerLabel = label;
}
public static async Task<GameSession> ConnectAsync(GameData data, Uri uri, string token, string label, CancellationToken ct = default)
{
var connection = await ProtocolClient.ConnectAsync(uri, ct);
try
{
var welcome = await connection.HandshakeAsync(new Hello
{
ClientVersion = typeof(GameSession).Assembly.GetName().Version?.ToString() ?? "0",
Token = token,
DataHash = data.Hash,
}, ct);
var world = new ClientWorld(data);
world.Apply(welcome);
return new GameSession(connection, world, label);
}
catch
{
await connection.DisposeAsync();
throw;
}
}
public bool IsOpen => Connection.IsOpen;
/// <summary>Applica i messaggi arrivati (al massimo maxMessages per fotogramma).</summary>
public int Poll(int maxMessages = 2000)
{
int n = 0;
while (n < maxMessages && Connection.TryReceive(out var message))
{
n++;
World.Apply(message);
switch (message)
{
case CommandResultMessage r:
if (_callbacks.Remove(r.Seq, out var callback)) callback(r);
if (!r.Ok) CommandFailed?.Invoke(r);
break;
case TrainMotion motion:
MotionReceivedMs[motion.TrainId] = (long)Time.GetTicksMsec();
break;
case Notification note:
Notified?.Invoke(note.Event);
break;
case DailyDigest digest when RequestedSpeed == digest.Speed:
RequestedSpeed = null;
break;
case Pong pong when pong.Nonce == _pingNonce:
LatencyMs = (long)Time.GetTicksMsec() - _pingSentMs;
break;
}
MessageApplied?.Invoke(message);
}
if ((long)Time.GetTicksMsec() - _pingSentMs > 2000) Ping();
return n;
}
private void Ping()
{
_pingSentMs = (long)Time.GetTicksMsec();
_pingNonce++;
Send(new Ping { Nonce = _pingNonce });
}
public void Send(IMessage message) => _ = SendSafe(message);
private async Task SendSafe(IMessage message)
{
try
{
await Connection.SendAsync(message);
}
catch (Exception e)
{
GD.PrintErr($"Invio non riuscito: {e.Message}");
}
}
/// <summary>Invia un comando; la callback riceve l'esito sul thread principale.</summary>
public void Command(GameCommand command, Action<CommandResultMessage>? onResult = null)
{
uint seq = Connection.ReserveSeq();
if (onResult is not null) _callbacks[seq] = onResult;
Send(new CommandMessage { Seq = seq, Command = command });
}
/// <summary>Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).</summary>
public byte? RequestedSpeed { get; private set; }
public void SetSpeed(byte speed)
{
RequestedSpeed = speed;
Send(new SetSpeed { Speed = speed });
}
public async ValueTask DisposeAsync()
{
await Connection.DisposeAsync();
LocalServer?.Dispose();
}
}
@@ -0,0 +1 @@
uid://b8etsc0caa35g
@@ -0,0 +1,94 @@
using System.Diagnostics;
using Godot;
namespace ViaFerrea.Client.Net;
/// <summary>
/// Partita locale: avvia il server come processo figlio con <c>--local --token</c>, legge
/// «LISTENING porta» dallo standard output e lo termina alla chiusura del client.
/// </summary>
public sealed class LocalServerLauncher : IDisposable
{
private Process? _process;
public int Port { get; private set; }
public string Token { get; } = Guid.NewGuid().ToString("N");
/// <summary>Percorso del server: variabile VF_SERVER_PATH, cartella «server» accanto al gioco, build del repository.</summary>
public static string? FindServer()
{
string? env = System.Environment.GetEnvironmentVariable("VF_SERVER_PATH");
if (!string.IsNullOrWhiteSpace(env) && File.Exists(env)) return env;
string exeDir = Path.GetDirectoryName(OS.GetExecutablePath()) ?? ".";
foreach (string name in new[] { "ViaFerrea.Server.exe", "ViaFerrea.Server", "ViaFerrea.Server.dll" })
{
string candidate = Path.Combine(exeDir, "server", name);
if (File.Exists(candidate)) return candidate;
}
// sviluppo: il progetto Godot sta in client/ViaFerrea.Client, il server in src/
string project = ProjectSettings.GlobalizePath("res://");
foreach (string config in new[] { "Release", "Debug" })
{
string candidate = Path.GetFullPath(Path.Combine(project, "..", "..", "src", "ViaFerrea.Server", "bin", config, "net10.0", "ViaFerrea.Server.dll"));
if (File.Exists(candidate)) return candidate;
}
return null;
}
/// <summary>Avvia il server e attende la porta (al massimo timeout).</summary>
public async Task<int> StartAsync(string serverPath, string dataDir, TimeSpan timeout)
{
bool dll = serverPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase);
var info = new ProcessStartInfo
{
FileName = dll ? "dotnet" : serverPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = Path.GetDirectoryName(serverPath) ?? ".",
};
if (dll) info.ArgumentList.Add(serverPath);
info.ArgumentList.Add("--local");
info.ArgumentList.Add("--token");
info.ArgumentList.Add(Token);
info.ArgumentList.Add("--data");
info.ArgumentList.Add(dataDir);
_process = Process.Start(info) ?? throw new InvalidOperationException("Server non avviato");
_process.ErrorDataReceived += (_, e) => { if (e.Data is not null) GD.PrintErr("[server] " + e.Data); };
_process.BeginErrorReadLine();
using var cts = new CancellationTokenSource(timeout);
while (!cts.IsCancellationRequested)
{
string? line = await _process.StandardOutput.ReadLineAsync(cts.Token);
if (line is null) break;
if (line.StartsWith("LISTENING ", StringComparison.Ordinal) && int.TryParse(line.AsSpan(10), out int port))
{
Port = port;
// il resto dell'output (log JSON) si scarta per non riempire il buffer
_ = Task.Run(async () =>
{
while (await _process.StandardOutput.ReadLineAsync() is not null)
{
}
});
return port;
}
}
throw new TimeoutException("Il server locale non ha risposto");
}
public void Dispose()
{
try
{
if (_process is { HasExited: false }) _process.Kill(entireProcessTree: true);
}
catch (InvalidOperationException)
{
}
_process?.Dispose();
_process = null;
}
}
@@ -0,0 +1 @@
uid://cr4o72tey2gop
@@ -0,0 +1,151 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>Scheda dell'entità selezionata (treno, stazione, industria, città) come nel pannello destro dell'immagine 01.</summary>
public partial class InfoPanel : VBoxContainer
{
public enum Kind { None, Train, Station, Industry, Town }
private readonly GameSession _session;
private Kind _kind;
private int _id = -1;
private double _refresh;
public InfoPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
Select(Kind.None, -1);
}
public void Select(Kind kind, int id)
{
_kind = kind;
_id = id;
Rebuild();
}
public override void _Process(double delta)
{
_refresh += delta;
if (_refresh < 0.5) return;
_refresh = 0;
Rebuild();
}
private void Rebuild()
{
foreach (var c in GetChildren()) c.QueueFree();
var w = _session.World;
switch (_kind)
{
case Kind.Train when w.Trains.TryGetValue(_id, out var t):
{
var head = PanelKit.Row();
var title = UiTheme.TitleLabel(t.Name, 38);
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
head.AddChild(title);
if (t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var line))
{
var badge = new CenterContainer();
var b = UiTheme.LineBadge(line.Name);
badge.AddChild(b);
head.AddChild(badge);
AddChild(head);
string route = string.Join(" → ", line.Stops.Select(s => w.Stations.TryGetValue(s.Station.Value, out var st) ? st.Name : "?"));
AddChild(UiTheme.Text(route, 17, bold: true));
}
else
{
AddChild(head);
}
var loco = t.Vehicles.Select(v => w.Vehicles.GetValueOrDefault(v)).FirstOrDefault(v => v is not null && w.Data.Vehicles.Any(d => d.Id == v.Type && d.Kind == Core.Data.VehicleKind.Locomotive));
var locoDef = loco is null ? null : w.Data.Vehicles.First(d => d.Id == loco.Type);
AddChild(UiTheme.Text($"{T("Locomotiva")} {locoDef?.NameIt ?? "—"} · {TrainsPanel.StateName((TrainState)t.State)}", 14, Palette.TextSecondary));
var stats = PanelKit.Row();
double speed = w.Motions.TryGetValue(t.Id, out var m) ? m.Speed * 3.6 : 0;
double condition = w.Motions.TryGetValue(t.Id, out var m2) ? m2.Condition : t.Vehicles.Select(v => w.Vehicles.GetValueOrDefault(v)?.Condition ?? 100).DefaultIfEmpty(100).Min();
stats.AddChild(PanelKit.Stat(T("Velocità"), PanelKit.Value($"{speed:0} km/h")));
stats.AddChild(PanelKit.Stat(T("Condizione"), PanelKit.Value($"{condition:0}%")));
stats.AddChild(PanelKit.Stat(T("Veicoli"), PanelKit.Value($"{t.Vehicles.Length}")));
AddChild(stats);
AddChild(PanelKit.Pair(T("Carico"), PanelKit.Value($"{t.Load} / {t.Capacity}")));
var bar = new ProgressBar { MaxValue = Math.Max(1, t.Capacity), Value = t.Load, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 4, 0));
AddChild(bar);
if (t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var l2))
{
for (int i = 0; i < l2.Stops.Length; i++)
{
var s = l2.Stops[i];
string name = w.Stations.TryGetValue(s.Station.Value, out var st) ? st.Name : "?";
string orders = (s.Load ? T("carica") : "") + (s.Unload ? (s.Load ? ", " : "") + T("scarica") : "")
+ (s.WaitFull ? $", {T("attendi il pieno")} (max {s.MaxWaitDays} {T("giorni")})" : "");
var row = PanelKit.Row();
row.AddChild(UiTheme.Text($"{i + 1}", 14, Palette.TextSecondary, bold: true));
var col = PanelKit.Column(0);
col.AddChild(UiTheme.Text(name, 15, bold: true));
col.AddChild(UiTheme.Text(orders, 13, Palette.TextSecondary));
row.AddChild(col);
AddChild(row);
}
}
break;
}
case Kind.Station when w.Stations.TryGetValue(_id, out var s):
{
AddChild(UiTheme.TitleLabel(s.Name, 38));
AddChild(PanelKit.Pair(T("Binari di stazione"), PanelKit.Value($"{s.Platforms}")));
AddChild(PanelKit.Pair(T("Merci e passeggeri in attesa"), PanelKit.Value($"{s.WaitingUnits}")));
AddChild(UiTheme.Text(T("Nel bacino"), 14, bold: true));
foreach (int i in s.Industries)
if (w.Industries.TryGetValue(i, out var ind)) AddChild(UiTheme.Text($"• {ind.Name}", 13));
foreach (int i in s.Towns)
if (w.Towns.TryGetValue(i, out var town)) AddChild(UiTheme.Text($"• {town.Name}", 13));
break;
}
case Kind.Industry when w.Industries.TryGetValue(_id, out var ind):
{
AddChild(UiTheme.TitleLabel(ind.Name, 38));
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
AddChild(UiTheme.Text(def?.NameIt ?? ind.Type, 14, Palette.TextSecondary));
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Livello"), PanelKit.Value($"{ind.Level}")));
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value($"{ind.Efficiency * 100:0}%")));
stats.AddChild(PanelKit.Stat(T("Impianti"), PanelKit.Value($"{ind.Condition:0}%")));
AddChild(stats);
if (def is not null)
{
string inputs = string.Join(", ", def.Recipe.Inputs.Select(i => w.Data.Goods.First(g => g.Id == i.Good).NameIt));
string outputs = string.Join(", ", def.Recipe.Outputs.Select(o => w.Data.Goods.First(g => g.Id == o.Good).NameIt));
if (inputs.Length > 0) AddChild(PanelKit.Pair(T("Consuma"), PanelKit.Value(inputs)));
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
}
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
break;
}
case Kind.Town when w.Towns.TryGetValue(_id, out var town):
{
AddChild(UiTheme.TitleLabel(town.Name, 38));
AddChild(PanelKit.Pair(T("Abitanti"), PanelKit.Value(Money.GroupThousands((ulong)town.Population))));
AddChild(PanelKit.Pair(T("Soddisfazione"), PanelKit.Value($"{town.Satisfaction * 100:0}%")));
AddChild(PanelKit.Pair(T("Servizi"), PanelKit.Value($"{town.Services}")));
break;
}
default:
{
AddChild(UiTheme.TitleLabel(T("Via Ferrea"), 38));
var help = UiTheme.Text(T("Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda."), 14, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
break;
}
}
}
}
@@ -0,0 +1 @@
uid://b48ikeoeho1rb
@@ -0,0 +1,117 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>Linee: fermate scelte con un clic sulle stazioni, nome e colore, attesa del pieno alla prima fermata.</summary>
public partial class LinesPanel : VBoxContainer
{
private static readonly (string Name, string Hex)[] Colors =
[
("Ambra", "#e0a526"), ("Blu", "#3f86d1"), ("Rosso coppo", "#b3573e"), ("Verde", "#5fc39b"), ("Celeste", "#9cc9f2"), ("Grano", "#d9c26a"),
];
private readonly GameSession _session;
private readonly ItemList _stopsList = new() { CustomMinimumSize = new Vector2(0, 110) };
private readonly LineEdit _name = new() { PlaceholderText = T("Nome della linea") };
private readonly OptionButton _color = new();
private readonly CheckBox _waitFull = new() { Text = T("Attendi il pieno alla prima fermata (max 2 giorni)") };
private readonly ItemList _lines = new() { CustomMinimumSize = new Vector2(0, 120) };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private int _version = -1;
public List<int> Stops { get; } = [];
public event Action? StopsChanged;
public LinesPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 8);
AddChild(UiTheme.TitleLabel(T("Linee"), 34));
var help = UiTheme.Text(T("Clic sulle stazioni della mappa per aggiungere le fermate in ordine; la linea torna alla prima."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(_stopsList);
foreach (var (name, _) in Colors) _color.AddItem(T(name));
_color.Selected = 0;
AddChild(_name);
AddChild(_color);
AddChild(_waitFull);
var row = PanelKit.Row();
var create = UiTheme.Primary(T("Crea linea"));
create.SizeFlagsHorizontal = SizeFlags.ExpandFill;
create.Pressed += Create;
var clear = new Button { Text = T("Svuota") };
clear.Pressed += () =>
{
Stops.Clear();
RefreshStops();
};
row.AddChild(create);
row.AddChild(clear);
AddChild(row);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Linee della compagnia"), 14, bold: true));
AddChild(_lines);
}
public void AddStop(int station)
{
if (Stops.Count > 0 && Stops[^1] == station) return;
Stops.Add(station);
RefreshStops();
}
private void RefreshStops()
{
_stopsList.Clear();
for (int i = 0; i < Stops.Count; i++)
{
string name = _session.World.Stations.TryGetValue(Stops[i], out var s) ? s.Name : $"#{Stops[i]}";
_stopsList.AddItem($"{i + 1}. {name}");
}
StopsChanged?.Invoke();
}
public override void _Process(double delta)
{
var w = _session.World;
if (w.EntityVersion == _version) return;
_version = w.EntityVersion;
_lines.Clear();
int company = w.Summary?.CompanyId ?? 0;
foreach (var l in w.Lines.Values.Where(l => l.Owner == company).OrderBy(l => l.Id))
{
int trains = w.Trains.Values.Count(t => t.Line == l.Id);
string stops = string.Join(" → ", l.Stops.Select(s => w.Stations.TryGetValue(s.Station.Value, out var st) ? st.Name : "?"));
_lines.AddItem($"{l.Name} ({trains} {T("treni")}): {stops}");
}
}
private void Create()
{
if (Stops.Count < 2)
{
_status.Text = T("Servono almeno due fermate");
return;
}
var stops = Stops.Select((s, i) => new LineStop(new StationId(s), WaitFull: i == 0 && _waitFull.ButtonPressed, MaxWaitDays: i == 0 && _waitFull.ButtonPressed ? 2 : 0)).ToList();
string name = string.IsNullOrWhiteSpace(_name.Text) ? $"{T("Linea")} {_session.World.Lines.Count + 1}" : _name.Text.Trim();
_session.Command(new CreateLineCommand(name, Colors[Math.Max(0, _color.Selected)].Hex, stops), r =>
{
_status.Text = r.Message;
if (!r.Ok) return;
Stops.Clear();
_name.Text = "";
RefreshStops();
});
}
}
@@ -0,0 +1 @@
uid://c5bnynb60j4xs
@@ -0,0 +1,56 @@
using Godot;
using ViaFerrea.Client.App;
namespace ViaFerrea.Client.Panels;
/// <summary>Mattoni comuni dei pannelli laterali.</summary>
public static class PanelKit
{
public static VBoxContainer Column(int separation = 10)
{
var v = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
v.AddThemeConstantOverride("separation", separation);
return v;
}
public static HBoxContainer Row(int separation = 10)
{
var h = new HBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
h.AddThemeConstantOverride("separation", separation);
return h;
}
/// <summary>Riga etichetta : valore.</summary>
public static HBoxContainer Pair(string caption, Label value)
{
var row = Row();
var c = UiTheme.Text(caption, 14, Palette.TextSecondary);
c.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
value.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(c);
row.AddChild(value);
return row;
}
/// <summary>Riquadro statistico (velocità, affidabilità, età…) come nell'immagine 01.</summary>
public static PanelContainer Stat(string caption, Label value)
{
var p = new PanelContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
p.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Inner, 8, 12));
var v = Column(2);
v.AddChild(UiTheme.Text(caption, 12, Palette.TextSecondary));
value.AddThemeFontSizeOverride("font_size", 20);
v.AddChild(value);
p.AddChild(v);
return p;
}
public static Label Value(string text = "") => UiTheme.Text(text, 14, bold: true);
public static HSeparator Separator()
{
var s = new HSeparator();
s.AddThemeStyleboxOverride("separator", UiTheme.Box(Palette.Border, Palette.Border, 0, 0));
return s;
}
}
@@ -0,0 +1 @@
uid://lo82o2847rj3
@@ -0,0 +1,53 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Map;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Client.Panels;
/// <summary>Grafico altimetrico del tracciato: terreno, quota del binario e opere colorate (pannello TrackProfile).</summary>
public partial class ProfileChart : Control
{
private TrackPlan? _plan;
public ProfileChart() => CustomMinimumSize = new Vector2(0, 140);
public void Show(TrackPlan? plan)
{
_plan = plan;
QueueRedraw();
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
if (_plan is not { Samples.Count: > 1 } plan) return;
var samples = plan.Samples;
double minH = samples.Min(s => Math.Min(s.TerrainM, s.TrackM)), maxH = samples.Max(s => Math.Max(s.TerrainM, s.TrackM));
if (maxH - minH < 10) maxH = minH + 10;
double length = Math.Max(1, samples[^1].S);
var area = new Rect2(10, 10, Size.X - 20, Size.Y - 40);
Vector2 P(double s, double h) => new(area.Position.X + (float)(s / length) * area.Size.X, area.End.Y - (float)((h - minH) / (maxH - minH)) * area.Size.Y);
// terreno pieno
var ground = new List<Vector2> { new(area.Position.X, area.End.Y) };
foreach (var s in samples) ground.Add(P(s.S, s.TerrainM));
ground.Add(new Vector2(area.End.X, area.End.Y));
DrawColoredPolygon(ground.ToArray(), Palette.WithAlpha(Palette.Hill, 0.55f));
// opere sotto la linea del binario
for (int i = 0; i < samples.Count - 1; i++)
{
var a = samples[i];
var b = samples[i + 1];
var color = ToolOverlay.WorkColor(a.Kind);
if (a.Kind == WorkKind.Natural) continue;
DrawRect(new Rect2(P(a.S, minH).X, area.End.Y + 6, Math.Max(1, P(b.S, minH).X - P(a.S, minH).X), 8), color);
if (a.Kind == WorkKind.Bridge) DrawLine(P(a.S, a.TrackM), P(a.S, a.TerrainM), Palette.WithAlpha(color, 0.6f), 1.5f);
}
var track = samples.Select(s => P(s.S, s.TrackM)).ToArray();
DrawPolyline(track, plan.Valid ? Palette.Amber : Palette.Danger, 2.5f, true);
DrawString(UiTheme.Body, new Vector2(area.Position.X + 4, area.Position.Y + 12), $"{maxH:0} m", HorizontalAlignment.Left, -1, 11, Palette.TextSecondary);
DrawString(UiTheme.Body, new Vector2(area.Position.X + 4, area.End.Y - 4), $"{minH:0} m", HorizontalAlignment.Left, -1, 11, Palette.TextSecondary);
DrawString(UiTheme.Body, new Vector2(area.End.X - 60, Size.Y - 6), $"{length / 1000:0.0} km", HorizontalAlignment.Left, -1, 11, Palette.TextSecondary);
}
}
@@ -0,0 +1 @@
uid://d1kct34qv0wvl
@@ -0,0 +1,150 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>Strumento stazione: numero di binari, nome facoltativo, costo stimato; clic sulla mappa per posarla.</summary>
public partial class StationPanel : VBoxContainer
{
public SpinBox Platforms { get; } = new() { MinValue = 1, Value = 2, SizeFlagsHorizontal = SizeFlags.ExpandFill };
public LineEdit StationName { get; } = new() { PlaceholderText = T("Nome automatico") };
private readonly Label _cost = PanelKit.Value();
private readonly GameSession _session;
public StationPanel(GameSession session)
{
_session = session;
var data = session.World.Data;
Platforms.MaxValue = data.Construction.Stations.MaxPlatforms;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Stazione"), 34));
AddChild(UiTheme.Text(T("Clic sulla mappa: la stazione si aggancia al binario vicino o nasce come capolinea. Il cerchio è il bacino di utenza."), 13, Palette.TextSecondary));
AddChild(PanelKit.Pair(T("Binari di stazione"), new Label()));
AddChild(Platforms);
AddChild(StationName);
AddChild(PanelKit.Pair(T("Costo"), _cost));
Platforms.ValueChanged += _ => UpdateCost();
UpdateCost();
foreach (var l in GetChildren().OfType<Label>()) l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
}
private void UpdateCost()
{
var c = _session.World.Data.Construction.Costs;
double mult = _session.World.Summary?.CostMultiplier ?? 1;
_cost.Text = (new Money(c.StationBase + c.StationPerPlatform * (long)Platforms.Value) * mult).ToString();
}
}
/// <summary>Strumento deposito: dimensione e costo; clic sulla mappa per posarlo.</summary>
public partial class DepotPanel : VBoxContainer
{
public OptionButton SizeChoice { get; } = new();
private readonly List<string> _sizes;
public DepotPanel(GameSession session)
{
var data = session.World.Data;
_sizes = data.Construction.Costs.DepotBySize.Keys.OrderBy(k => data.Construction.Costs.DepotBySize[k]).ToList();
double mult = session.World.Summary?.CostMultiplier ?? 1;
foreach (string s in _sizes)
SizeChoice.AddItem($"{T(s)} — {new Money(data.Construction.Costs.DepotBySize[s]) * mult}");
SizeChoice.Selected = 0;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Deposito"), 34));
var help = UiTheme.Text(T("Clic sulla mappa vicino a un binario, poi raccordalo con lo strumento Binari. Nel deposito si comprano i veicoli e si compongono i treni."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(SizeChoice);
}
public string SelectedSize => _sizes[Math.Max(0, SizeChoice.Selected)];
}
/// <summary>Testo d'aiuto per gli strumenti senza opzioni (segnali, demolizione).</summary>
public partial class HelpPanel : VBoxContainer
{
public HelpPanel(string title, string help)
{
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(title, 34));
var l = UiTheme.Text(help, 13, Palette.TextSecondary);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(l);
}
}
/// <summary>Prezzi globali del giorno (resoconto giornaliero).</summary>
public partial class MarketPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly VBoxContainer _rows = PanelKit.Column(4);
private long _day = -1;
public MarketPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Mercato"), 34));
AddChild(UiTheme.Text(T("Prezzi globali di oggi (la borsa arriva in seguito)."), 13, Palette.TextSecondary));
AddChild(_rows);
}
public override void _Process(double delta)
{
var digest = _session.World.LastDigest;
if (digest is null || digest.Day == _day) return;
_day = digest.Day;
foreach (var c in _rows.GetChildren()) c.QueueFree();
var goods = _session.World.Data.Goods;
for (int g = 0; g < Math.Min(goods.Count, digest.Prices.Count); g++)
{
var ratio = digest.Prices[g].Cents / (double)Math.Max(1, goods[g].BasePrice);
var value = PanelKit.Value($"{digest.Prices[g]} / {goods[g].Unit}");
value.AddThemeColorOverride("font_color", ratio > 1.15 ? Palette.AmberLight : ratio < 0.85 ? Palette.Staff : Palette.Text);
_rows.AddChild(PanelKit.Pair(goods[g].NameIt, value));
}
}
}
/// <summary>Conti della compagnia e prestiti.</summary>
public partial class FinancePanel : VBoxContainer
{
private readonly GameSession _session;
private readonly Label _cash = PanelKit.Value();
private readonly Label _worth = PanelKit.Value();
private readonly Label _rating = PanelKit.Value();
private readonly SpinBox _loan = new() { MinValue = 10_000, MaxValue = 10_000_000, Step = 10_000, Value = 100_000, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
public FinancePanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Finanze"), 34));
AddChild(PanelKit.Pair(T("Cassa"), _cash));
AddChild(PanelKit.Pair(T("Patrimonio netto"), _worth));
AddChild(PanelKit.Pair(T("Rating"), _rating));
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Prestito"), 14, bold: true));
AddChild(_loan);
var take = UiTheme.Primary(T("Chiedi il prestito"));
take.Pressed += () => _session.Command(new TakeLoanCommand(Money.FromLire((long)_loan.Value)), r => _status.Text = r.Message);
AddChild(take);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
}
public override void _Process(double delta)
{
var w = _session.World;
var me = w.Summary is null ? null : w.Companies.GetValueOrDefault(w.Summary.CompanyId);
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString();
_rating.Text = w.LastDigest?.Rating ?? me?.Rating ?? "—";
}
}
@@ -0,0 +1 @@
uid://bnvriayoaoihl
@@ -0,0 +1,124 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Client;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Strumento binari: classe, ponti, gallerie, doppio binario, elettrificazione e quota; anteprima
/// del profilo con opere, costo e giorni (calcolata con Core come farà il server).
/// </summary>
public partial class TrackPanel : VBoxContainer
{
private readonly ClientWorld _world;
private readonly OptionButton _class = new();
private readonly CheckBox _bridges = new() { Text = T("Ponti"), ButtonPressed = true };
private readonly CheckBox _tunnels = new() { Text = T("Gallerie"), ButtonPressed = true };
private readonly CheckBox _double = new() { Text = T("Doppio binario") };
private readonly CheckBox _electric = new() { Text = T("Elettrificato") };
private readonly HSlider _height = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, Step = 0.5 };
private readonly Label _heightValue = PanelKit.Value("0 m");
private readonly ProfileChart _chart = new();
private readonly VBoxContainer _summary = PanelKit.Column(4);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
public Button Build { get; } = UiTheme.Primary(T("Costruisci"));
public Button Cancel { get; } = new() { Text = T("Annulla") };
public event Action? OptionsChanged;
public TrackPanel(ClientWorld world)
{
_world = world;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Binari"), 34));
AddChild(UiTheme.Text(T("Clic sulla mappa per i punti del tracciato (Maiusc: senza scatto a 45°), Invio per costruire, tasto destro per annullare."), 13, Palette.TextSecondary));
foreach (var cls in world.Data.Eras.TrackClasses)
{
_class.AddItem($"{cls.NameIt}", cls.Index);
_class.SetItemDisabled(_class.ItemCount - 1, cls.From > world.Year);
}
_class.Selected = 0;
AddChild(PanelKit.Pair(T("Classe"), new Label()));
AddChild(_class);
var flags = new GridContainer { Columns = 2 };
flags.AddChild(_bridges);
flags.AddChild(_tunnels);
flags.AddChild(_double);
flags.AddChild(_electric);
AddChild(flags);
double range = world.Data.Construction.Profile.HeightOffsetRangeM;
_height.MinValue = -range;
_height.MaxValue = range;
AddChild(PanelKit.Pair(T("Quota rispetto al terreno"), _heightValue));
AddChild(_height);
var buttons = PanelKit.Row();
Build.SizeFlagsHorizontal = SizeFlags.ExpandFill;
Cancel.SizeFlagsHorizontal = SizeFlags.ExpandFill;
buttons.AddChild(Build);
buttons.AddChild(Cancel);
AddChild(buttons);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
AddChild(_chart);
AddChild(_summary);
_class.ItemSelected += _ => OptionsChanged?.Invoke();
foreach (var c in new[] { _bridges, _tunnels, _double, _electric }) c.Toggled += _ => OptionsChanged?.Invoke();
_height.ValueChanged += v =>
{
_heightValue.Text = $"{v:+0.0;-0.0;0} m";
OptionsChanged?.Invoke();
};
Show(null);
}
public string TrackClass => _world.Data.Eras.TrackClasses[Math.Max(0, _class.Selected)].Id;
public bool AllowBridges => _bridges.ButtonPressed;
public bool AllowTunnels => _tunnels.ButtonPressed;
public bool DoubleTrack => _double.ButtonPressed;
public bool Electrified => _electric.ButtonPressed;
public double HeightOffset => _height.Value;
public void SetStatus(string text, bool error = false)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", error ? Palette.Danger : Palette.TextSecondary);
}
public void Show(TrackPlan? plan)
{
_chart.Show(plan);
foreach (var child in _summary.GetChildren()) child.QueueFree();
Build.Disabled = plan is not { Valid: true };
if (plan is null)
{
_summary.AddChild(UiTheme.Text(T("Nessun tracciato"), 13, Palette.TextSecondary));
return;
}
_summary.AddChild(PanelKit.Pair(T("Lunghezza"), PanelKit.Value($"{plan.LengthM / 1000:0.00} km")));
_summary.AddChild(PanelKit.Pair(T("Pendenza massima"), PanelKit.Value($"{plan.MaxGradient * 100:0.0} % / {plan.GradientLimit * 100:0.0} %")));
_summary.AddChild(PanelKit.Pair(T("Raggio minimo"), PanelKit.Value(double.IsInfinity(plan.MinRadiusM) ? "—" : $"{plan.MinRadiusM:0} m")));
foreach (var kind in new[] { WorkKind.Embankment, WorkKind.Cutting, WorkKind.Bridge, WorkKind.Tunnel })
{
double len = plan.LengthOf(kind);
if (len <= 0) continue;
string name = kind switch
{
WorkKind.Embankment => T("Rilevato"),
WorkKind.Cutting => T("Trincea"),
WorkKind.Bridge => T("Ponte") + (plan.BridgeType is { } b ? $" ({b})" : ""),
_ => T("Galleria"),
};
_summary.AddChild(PanelKit.Pair(name, PanelKit.Value($"{len:0} m")));
}
var cost = PanelKit.Value(plan.TotalCost.ToString());
cost.AddThemeColorOverride("font_color", Palette.AmberLight);
_summary.AddChild(PanelKit.Pair(T("Costo"), cost));
_summary.AddChild(PanelKit.Pair(T("Cantiere"), PanelKit.Value($"{plan.Days} {T("giorni")}")));
foreach (var e in plan.Errors.Take(3)) _summary.AddChild(UiTheme.Notice(e.Message));
foreach (var e in plan.Warnings.Take(2)) _summary.AddChild(UiTheme.Text(e.Message, 12, Palette.AmberLight));
}
}
@@ -0,0 +1 @@
uid://x2netu5v1ewj
@@ -0,0 +1,195 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Panels;
/// <summary>
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro.
/// Ogni azione è un comando; la lista si aggiorna con i delta del server.
/// </summary>
public partial class TrainsPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly OptionButton _depot = new();
private readonly OptionButton _vehicle = new();
private readonly SpinBox _count = new() { MinValue = 1, MaxValue = 12, Value = 1 };
private readonly ItemList _inDepot = new() { SelectMode = ItemList.SelectModeEnum.Multi, CustomMinimumSize = new Vector2(0, 120) };
private readonly LineEdit _name = new() { PlaceholderText = T("Nome del treno") };
private readonly ItemList _trains = new() { CustomMinimumSize = new Vector2(0, 140) };
private readonly OptionButton _line = new();
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<int> _depotIds = [];
private readonly List<VehicleDef> _catalog = [];
private readonly List<int> _vehicleIds = [];
private readonly List<int> _trainIds = [];
private readonly List<int> _lineIds = [];
private int _version = -1;
public event Action<int>? TrainSelected;
public TrainsPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 8);
AddChild(UiTheme.TitleLabel(T("Treni"), 34));
AddChild(PanelKit.Pair(T("Deposito"), new Label()));
AddChild(_depot);
var buy = PanelKit.Row();
_vehicle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
buy.AddChild(_vehicle);
buy.AddChild(_count);
AddChild(buy);
var buyButton = UiTheme.Primary(T("Compra veicoli"));
buyButton.Pressed += Buy;
AddChild(buyButton);
AddChild(UiTheme.Text(T("Veicoli liberi nel deposito (selezione multipla, in ordine)"), 13, Palette.TextSecondary));
AddChild(_inDepot);
var compose = PanelKit.Row();
_name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
compose.AddChild(_name);
var composeButton = new Button { Text = T("Componi") };
composeButton.Pressed += Compose;
compose.AddChild(composeButton);
AddChild(compose);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Treni della compagnia"), 14, bold: true));
AddChild(_trains);
var assign = PanelKit.Row();
_line.SizeFlagsHorizontal = SizeFlags.ExpandFill;
assign.AddChild(_line);
var assignButton = new Button { Text = T("Assegna") };
assignButton.Pressed += Assign;
assign.AddChild(assignButton);
AddChild(assign);
var home = new Button { Text = T("Manda al deposito") };
home.Pressed += SendHome;
AddChild(home);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_depot.ItemSelected += _ => Refresh(force: true);
_trains.ItemSelected += i => TrainSelected?.Invoke(_trainIds[(int)i]);
}
public override void _Process(double delta)
{
if (_session.World.EntityVersion != _version) Refresh(force: false);
}
private int Company => _session.World.Summary?.CompanyId ?? 0;
private void Refresh(bool force)
{
var w = _session.World;
_version = w.EntityVersion;
int selectedDepot = _depot.Selected >= 0 && _depot.Selected < _depotIds.Count ? _depotIds[_depot.Selected] : -1;
_depotIds.Clear();
_depot.Clear();
foreach (var d in w.Depots.Values.Where(d => d.Owner == Company).OrderBy(d => d.Id))
{
_depotIds.Add(d.Id);
_depot.AddItem(d.Name);
}
int di = _depotIds.IndexOf(selectedDepot);
_depot.Selected = di >= 0 ? di : _depotIds.Count > 0 ? 0 : -1;
if (_catalog.Count == 0 || force)
{
int keep = _vehicle.Selected;
_catalog.Clear();
_vehicle.Clear();
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
{
_catalog.Add(def);
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
}
_vehicle.Selected = keep >= 0 && keep < _catalog.Count ? keep : 0;
}
int depot = _depot.Selected >= 0 ? _depotIds[_depot.Selected] : -1;
_vehicleIds.Clear();
_inDepot.Clear();
foreach (var v in w.Vehicles.Values.Where(v => v.Owner == Company && v.Depot == depot && v.Train < 0).OrderBy(v => v.Id))
{
_vehicleIds.Add(v.Id);
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
_inDepot.AddItem($"{def?.NameIt ?? v.Type} #{v.Id}");
}
var selectedTrain = _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
_trainIds.Clear();
_trains.Clear();
foreach (var t in w.Trains.Values.Where(t => t.Owner == Company).OrderBy(t => t.Id))
{
_trainIds.Add(t.Id);
string line = t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var l) ? l.Name : T("senza linea");
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}");
}
int ti = _trainIds.IndexOf(selectedTrain);
if (ti >= 0) _trains.Select(ti);
int selectedLine = _line.Selected >= 0 && _line.Selected < _lineIds.Count ? _lineIds[_line.Selected] : -1;
_lineIds.Clear();
_line.Clear();
_lineIds.Add(-1);
_line.AddItem(T("Nessuna linea"));
foreach (var l in w.Lines.Values.Where(l => l.Owner == Company).OrderBy(l => l.Id))
{
_lineIds.Add(l.Id);
_line.AddItem(l.Name);
}
int li = _lineIds.IndexOf(selectedLine);
_line.Selected = li >= 0 ? li : Math.Min(1, _lineIds.Count - 1);
}
public static string StateName(TrainState s) => s switch
{
TrainState.InDepot => T("in deposito"),
TrainState.Moving => T("in marcia"),
TrainState.Waiting => T("in attesa di via libera"),
TrainState.Loading => T("in stazione"),
TrainState.Stalled => T("fermo in salita"),
TrainState.Broken => T("guasto"),
TrainState.NoRoute => T("senza percorso"),
_ => s.ToString(),
};
private void Result(CommandResultMessage r) => _status.Text = r.Message;
private void Buy()
{
if (_depot.Selected < 0 || _vehicle.Selected < 0) { _status.Text = T("Serve un deposito"); return; }
_session.Command(new BuyVehicleCommand(_catalog[_vehicle.Selected].Id, new DepotId(_depotIds[_depot.Selected]), (int)_count.Value), Result);
}
private void Compose()
{
if (_depot.Selected < 0) return;
var selected = _inDepot.GetSelectedItems().OrderBy(i => i).Select(i => new VehicleId(_vehicleIds[i])).ToList();
if (selected.Count == 0) { _status.Text = T("Seleziona i veicoli da comporre"); return; }
string? name = string.IsNullOrWhiteSpace(_name.Text) ? null : _name.Text.Trim();
_session.Command(new ComposeTrainCommand(new DepotId(_depotIds[_depot.Selected]), selected, name), Result);
}
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
private void Assign()
{
int train = SelectedTrain;
if (train < 0 || _line.Selected < 0) { _status.Text = T("Seleziona un treno"); return; }
_session.Command(new AssignTrainCommand(new TrainId(train), new LineId(_lineIds[_line.Selected])), Result);
}
private void SendHome()
{
int train = SelectedTrain;
if (train < 0 || _depot.Selected < 0) { _status.Text = T("Seleziona un treno e un deposito"); return; }
_session.Command(new SendToDepotCommand(new TrainId(train), new DepotId(_depotIds[_depot.Selected])), Result);
}
}
@@ -0,0 +1 @@
uid://s6uq2ln014q2
@@ -0,0 +1,91 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.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.
/// </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"));
public event Action<Uri, string, string>? ConnectRequested;
public event Action? Back;
public override void _Ready()
{
SetAnchorsPreset(LayoutPreset.FullRect);
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);
_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)
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
}
_token.TextSubmitted += _ => Submit();
}
public void SetStatus(string text, bool busy)
{
_status.Text = text;
_connect.Disabled = busy;
}
private void Submit()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
SetStatus(T("Indica l'indirizzo del server"), false);
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);
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);
}
}
@@ -0,0 +1 @@
uid://3yfity6oaer
@@ -0,0 +1,555 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Hud;
using ViaFerrea.Client.Map;
using ViaFerrea.Client.Net;
using ViaFerrea.Client.Panels;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Screens;
/// <summary>
/// Partita: mappa con i livelli, HUD (barra superiore, strumenti, pannello destro con minimappa,
/// notiziario) e logica degli strumenti. Ogni modifica è un comando al server; il client calcola
/// solo l'anteprima del tracciato con le classi di Core.
/// </summary>
public partial class GameScreen : Node
{
private readonly GameSession _session;
private readonly MapView _map = new();
private readonly LabelLayer _labels = new();
private readonly TopBar _top = new();
private readonly Toolbar _toolbar = new();
private readonly Ticker _ticker = new();
private readonly Minimap _minimap = new();
private readonly ScrollContainer _scroll = new() { SizeFlagsVertical = Control.SizeFlags.ExpandFill, HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
private readonly VBoxContainer _content = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
private readonly VBoxContainer _toasts = new();
private readonly Control _disconnected = new();
private Tool _tool = Tool.None;
private TrackPanel? _trackPanel;
private StationPanel? _stationPanel;
private DepotPanel? _depotPanel;
private LinesPanel? _linesPanel;
private InfoPanel? _info;
private readonly List<Vector2> _trackPoints = [];
private Vector2? _mouse;
private bool _previewDirty;
private double _sincePreview;
private TrackPlan? _plan;
private Vector2 _lastViewportCenter;
private float _lastViewportZoom;
public event Action? Exit;
public GameScreen(GameSession session) => _session = session;
public GameSession Session => _session;
public MapView Map => _map;
/// <summary>Seleziona uno strumento come dalla barra (anche per il pilota automatico).</summary>
public void UseTool(Tool tool) => _toolbar.Select(tool);
/// <summary>Imposta i punti del tracciato in corso e aggiorna l'anteprima.</summary>
public void SetTrackPoints(IEnumerable<Vector2> points, Vector2? mouse)
{
_trackPoints.Clear();
_trackPoints.AddRange(points);
_mouse = mouse;
_previewDirty = true;
}
/// <summary>Mostra la scheda di un treno e lo evidenzia.</summary>
public void SelectTrain(int id)
{
_map.Trains.SelectedTrain = id;
_info?.Select(InfoPanel.Kind.Train, id);
}
public override void _Ready()
{
AddChild(_map);
var labelLayer = new CanvasLayer { Layer = 1 };
AddChild(labelLayer);
labelLayer.AddChild(_labels);
_labels.Bind(_session.World, _map.Camera);
var hud = new CanvasLayer { Layer = 2 };
AddChild(hud);
var root = new VBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
root.AddThemeConstantOverride("separation", 0);
hud.AddChild(root);
root.AddChild(_top);
var middle = new HBoxContainer { SizeFlagsVertical = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddThemeConstantOverride("separation", 0);
root.AddChild(middle);
middle.AddChild(_toolbar);
var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddChild(mapArea);
_toasts.SetAnchorsPreset(Control.LayoutPreset.TopWide);
_toasts.OffsetLeft = 16;
_toasts.OffsetRight = -16;
_toasts.OffsetTop = 12;
_toasts.MouseFilter = Control.MouseFilterEnum.Ignore;
mapArea.AddChild(_toasts);
var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18));
middle.AddChild(side);
var sideCol = new VBoxContainer();
sideCol.AddThemeConstantOverride("separation", 12);
side.AddChild(sideCol);
sideCol.AddChild(_scroll);
_scroll.AddChild(_content);
var miniHeader = new HBoxContainer();
var miniTitle = UiTheme.Text(T("Minimappa"), 13, Palette.TextSecondary);
miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
miniHeader.AddChild(miniTitle);
miniHeader.AddChild(UiTheme.Text(_session.World.Summary?.RegionId is { Length: > 0 } r ? $"{T("Regione di")} {char.ToUpperInvariant(r[0])}{r[1..]}" : "", 13, Palette.TextSecondary));
sideCol.AddChild(miniHeader);
sideCol.AddChild(_minimap);
root.AddChild(_ticker);
BuildDisconnectedOverlay(hud);
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
_top.Bind(_session);
_toolbar.Selected += SelectTool;
_map.Clicked += OnMapClicked;
_map.Hovered += OnMapHovered;
_map.Cancelled += () => _toolbar.Select(Tool.None);
_session.MessageApplied += OnMessage;
_session.Notified += e => _ticker.Add(e);
_session.CommandFailed += r => Toast(r.Message, error: true);
SelectTool(Tool.None);
SendViewport(force: true);
}
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
private void BuildDisconnectedOverlay(CanvasLayer hud)
{
_disconnected.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.Visible = false;
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.55f) };
shade.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.AddChild(shade);
var center = new CenterContainer();
center.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_disconnected.AddChild(center);
var panel = new PanelContainer();
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
col.AddChild(UiTheme.TitleLabel(T("Connessione persa"), 36));
col.AddChild(UiTheme.Text(T("Il server non risponde più. La partita continua sul server."), 14, Palette.TextSecondary));
var back = UiTheme.Primary(T("Torna al menu"));
back.Pressed += () => Exit?.Invoke();
col.AddChild(back);
panel.AddChild(col);
center.AddChild(panel);
hud.AddChild(_disconnected);
}
// ------------------------------------------------------------------ messaggi e ciclo
private void OnMessage(IMessage m)
{
switch (m)
{
case MapChunk c:
_map.Terrain.MarkDirty(c.Cx, c.Cy);
_map.Entities.ForestChunk(c.Cx, c.Cy);
break;
case Welcome:
// nuova partita o caricamento: si ricomincia dalla copia locale vuota
_map.Bind(_session);
_minimap.Bind(_session.World, _map);
SendViewport(force: true);
break;
case DailyDigest d:
foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e);
break;
}
}
public override void _Process(double delta)
{
_session.Poll();
_disconnected.Visible = !_session.IsOpen;
SendViewport(force: false);
_sincePreview += delta;
if (_previewDirty && _sincePreview > 0.12)
{
_previewDirty = false;
_sincePreview = 0;
UpdateTrackPreview();
}
}
/// <summary>Sottoscrive l'area visibile quando la camera si sposta di almeno un quarto di schermo.</summary>
private void SendViewport(bool force)
{
var w = _session.World;
if (w.Summary is null) return;
var view = _map.VisibleRect();
var center = view.GetCenter();
if (!force && center.DistanceTo(_lastViewportCenter) < view.Size.X / 4 && Math.Abs(_map.Zoom - _lastViewportZoom) < _lastViewportZoom * 0.3f) return;
_lastViewportCenter = center;
_lastViewportZoom = _map.Zoom;
double cs = w.Summary.CellSizeM;
_session.Send(new Subscribe
{
X0 = Math.Max(0, (int)(view.Position.X / cs)),
Y0 = Math.Max(0, (int)(view.Position.Y / cs)),
X1 = Math.Min(w.Summary.WidthCells - 1, (int)(view.End.X / cs)),
Y1 = Math.Min(w.Summary.HeightCells - 1, (int)(view.End.Y / cs)),
Lod = (byte)(_map.Zoom >= MapScale.DetailZoom ? 0 : _map.Zoom >= MapScale.OverviewZoom ? 1 : 2),
});
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (e is not InputEventKey { Pressed: true } key) return;
switch (key.Keycode)
{
case Key.Escape:
_toolbar.Select(Tool.None);
break;
case Key.Enter or Key.KpEnter when _tool == Tool.Track:
BuildTrack();
break;
case Key.Backspace when _tool == Tool.Track && _trackPoints.Count > 0:
_trackPoints.RemoveAt(_trackPoints.Count - 1);
_previewDirty = true;
break;
case Key.Space:
_session.SetSpeed(_session.World.Speed == 0 ? (byte)1 : (byte)0);
break;
}
}
// ------------------------------------------------------------------ strumenti
private void SelectTool(Tool tool)
{
_tool = tool;
_trackPoints.Clear();
_plan = null;
_map.Tools.Clear();
_map.Entities.SelectedStation = -1;
foreach (var c in _content.GetChildren()) c.QueueFree();
_trackPanel = null;
_stationPanel = null;
_depotPanel = null;
_linesPanel = null;
_info = null;
Control panel;
switch (tool)
{
case Tool.Track:
_trackPanel = new TrackPanel(_session.World);
_trackPanel.OptionsChanged += () => _previewDirty = true;
_trackPanel.Build.Pressed += BuildTrack;
_trackPanel.Cancel.Pressed += () => _toolbar.Select(Tool.None);
panel = _trackPanel;
break;
case Tool.Station:
panel = _stationPanel = new StationPanel(_session);
break;
case Tool.Depot:
panel = _depotPanel = new DepotPanel(_session);
break;
case Tool.Signal:
panel = new HelpPanel(T("Segnali"), T("Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea."));
break;
case Tool.Demolish:
panel = new HelpPanel(T("Demolisci"), T("Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo."));
break;
case Tool.Trains:
var trains = new TrainsPanel(_session);
trains.TrainSelected += id =>
{
_map.Trains.SelectedTrain = id;
if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p);
};
panel = trains;
break;
case Tool.Lines:
_linesPanel = new LinesPanel(_session);
_linesPanel.StopsChanged += UpdateStopsOverlay;
panel = _linesPanel;
break;
case Tool.Market:
panel = new MarketPanel(_session);
break;
case Tool.Finance:
panel = new FinancePanel(_session);
break;
default:
panel = _info = new InfoPanel(_session);
break;
}
panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
_content.AddChild(panel);
}
private void OnMapHovered(Vector2 world)
{
_mouse = world;
switch (_tool)
{
case Tool.Track:
if (_trackPoints.Count > 0) _previewDirty = true;
_map.Tools.SetTrack(_trackPoints, Snap(world), _plan);
break;
case Tool.Station:
_map.Tools.SetGhost(ToolOverlay.Ghost.Station, world);
break;
case Tool.Depot:
_map.Tools.SetGhost(ToolOverlay.Ghost.Depot, world);
break;
case Tool.Demolish:
_map.Tools.SetGhost(ToolOverlay.Ghost.Demolish, world);
break;
}
}
private void OnMapClicked(Vector2 world)
{
var w = _session.World;
var p = MapScale.W(world);
switch (_tool)
{
case Tool.Track:
_trackPoints.Add(Snap(world));
_previewDirty = true;
break;
case Tool.Station when _stationPanel is not null:
string? name = string.IsNullOrWhiteSpace(_stationPanel.StationName.Text) ? null : _stationPanel.StationName.Text.Trim();
_session.Command(new BuildStationCommand(p, (int)_stationPanel.Platforms.Value, name), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Depot when _depotPanel is not null:
_session.Command(new BuildDepotCommand(p, _depotPanel.SelectedSize), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Signal:
if (NearestEdge(world) is { } hit)
_session.Command(new PlaceSignalCommand(new EdgeId(hit.Edge), hit.S), r => { if (r.Ok) Toast(r.Message); });
break;
case Tool.Demolish:
Demolish(world);
break;
case Tool.Lines when _linesPanel is not null:
if (NearestStation(world) is { } station) _linesPanel.AddStop(station);
break;
default:
SelectAt(world);
break;
}
}
/// <summary>Scatto a 45° rispetto al punto precedente (Maiusc per disattivarlo).</summary>
private Vector2 Snap(Vector2 world)
{
if (_trackPoints.Count == 0 || Input.IsKeyPressed(Key.Shift)) return world;
var prev = _trackPoints[^1];
var d = world - prev;
if (d.LengthSquared() < 1) return world;
float step = MathF.PI / 4;
float angle = MathF.Round(d.Angle() / step) * step;
return prev + Vector2.FromAngle(angle) * d.Length();
}
private void UpdateTrackPreview()
{
if (_tool != Tool.Track || _trackPanel is null) return;
var pts = new List<Vector2>(_trackPoints);
if (_mouse is { } m && pts.Count >= 1) pts.Add(Snap(m));
if (pts.Count < 2)
{
_plan = null;
_trackPanel.Show(null);
_map.Tools.SetTrack(_trackPoints, _mouse, null);
return;
}
try
{
_plan = _session.World.PreviewTrack(TrackCommand(pts, 0));
_trackPanel.Show(_plan);
_trackPanel.SetStatus("");
}
catch (Exception e)
{
_plan = null;
_trackPanel.Show(null);
_trackPanel.SetStatus(T("Anteprima non disponibile: ") + e.Message, error: true);
}
_map.Tools.SetTrack(_trackPoints, _mouse is { } mm ? Snap(mm) : null, _plan);
}
private BuildTrackCommand TrackCommand(List<Vector2> pts, long expectedCost)
{
var p = _trackPanel!;
return new BuildTrackCommand(pts.Select(MapScale.W).ToList(), p.HeightOffset, p.AllowBridges, p.AllowTunnels, p.TrackClass, p.DoubleTrack, p.Electrified, expectedCost);
}
private void BuildTrack()
{
if (_trackPanel is null || _trackPoints.Count < 2) return;
// si costruisce il tracciato dei punti fissati (senza il punto sotto il mouse)
var plan = _session.World.PreviewTrack(TrackCommand(_trackPoints, 0));
if (!plan.Valid)
{
_trackPanel.SetStatus(plan.Errors[0].Message, error: true);
return;
}
_session.Command(TrackCommand(_trackPoints, plan.TotalCost.Cents), r =>
{
if (!r.Ok)
{
_trackPanel?.SetStatus(r.Message, error: true);
return;
}
Toast(r.Message);
// il prossimo tratto parte dall'ultimo punto
var last = _trackPoints[^1];
_trackPoints.Clear();
_trackPoints.Add(last);
_plan = null;
_trackPanel?.Show(null);
_map.Tools.SetTrack(_trackPoints, _mouse, null);
});
}
private void UpdateStopsOverlay()
{
if (_linesPanel is null) return;
var pts = _linesPanel.Stops.Where(_session.World.Stations.ContainsKey).Select(s => MapScale.V(_session.World.Stations[s].Position)).ToList();
_map.Tools.SetStops(pts);
}
private float PickRadius => 24f / _map.Zoom;
private int? NearestStation(Vector2 world)
{
int? best = null;
float bestD = Math.Max(PickRadius, 150);
foreach (var s in _session.World.Stations.Values)
{
float d = MapScale.V(s.Position).DistanceTo(world);
if (d < bestD)
{
bestD = d;
best = s.Id;
}
}
return best;
}
private int? NearestDepot(Vector2 world)
{
int? best = null;
float bestD = Math.Max(PickRadius, 120);
foreach (var d in _session.World.Depots.Values)
{
float dist = MapScale.V(d.Position).DistanceTo(world);
if (dist < bestD)
{
bestD = dist;
best = d.Id;
}
}
return best;
}
private (int Edge, double S)? NearestEdge(Vector2 world)
{
(int, double)? best = null;
double bestD = Math.Max(PickRadius, 25);
var p = MapScale.W(world);
foreach (var e in _session.World.Edges.Values)
{
for (int i = 0; i < e.S.Length - 1; i++)
{
var a = new Vec2(e.X[i], e.Y[i]);
var b = new Vec2(e.X[i + 1], e.Y[i + 1]);
double d = RailNetwork.DistanceToSegment(p, a, b, out double t);
if (d >= bestD) continue;
bestD = d;
best = (e.Id, e.S[i] + (e.S[i + 1] - e.S[i]) * t);
}
}
return best;
}
private void Demolish(Vector2 world)
{
if (NearestStation(world) is { } st)
_session.Command(new DemolishCommand(DemolishTarget.Station, st), r => { if (r.Ok) Toast(r.Message); });
else if (NearestDepot(world) is { } dp)
_session.Command(new DemolishCommand(DemolishTarget.Depot, dp), r => { if (r.Ok) Toast(r.Message); });
else if (NearestEdge(world) is { } hit)
_session.Command(new DemolishCommand(DemolishTarget.Edge, hit.Edge), r => { if (r.Ok) Toast(r.Message); });
}
private void SelectAt(Vector2 world)
{
if (_info is null) return;
var w = _session.World;
foreach (var (id, head) in _map.Trains.Heads)
{
if (head.DistanceTo(world) < PickRadius * 1.5f)
{
_map.Trains.SelectedTrain = id;
_info.Select(InfoPanel.Kind.Train, id);
return;
}
}
_map.Trains.SelectedTrain = -1;
if (NearestStation(world) is { } st)
{
_map.Entities.SelectedStation = st;
_map.Entities.QueueRedraw();
_info.Select(InfoPanel.Kind.Station, st);
return;
}
_map.Entities.SelectedStation = -1;
_map.Entities.QueueRedraw();
double cs = w.Summary?.CellSizeM ?? 100;
foreach (var ind in w.Industries.Values)
{
if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6))
{
_info.Select(InfoPanel.Kind.Industry, ind.Id);
return;
}
}
foreach (var town in w.Towns.Values)
{
if (MapScale.V(town.Position).DistanceTo(world) < Math.Max(PickRadius, (town.RadiusCells + 0.5) * cs))
{
_info.Select(InfoPanel.Kind.Town, town.Id);
return;
}
}
_info.Select(InfoPanel.Kind.None, -1);
}
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
private void Toast(string text, bool error = false)
{
var notice = UiTheme.Notice(text);
if (error) notice.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 12));
_toasts.AddChild(notice);
GetTree().CreateTimer(4.5).Timeout += () =>
{
if (IsInstanceValid(notice)) notice.QueueFree();
};
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
}
}
@@ -0,0 +1 @@
uid://ddktpojqhxvg6
@@ -0,0 +1,54 @@
using Godot;
using ViaFerrea.Client.App;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.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()
{
SetAnchorsPreset(LayoutPreset.FullRect);
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("Via Ferrea", 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;
}
@@ -0,0 +1 @@
uid://b5eyw35w2vo7l