Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s

Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-07 11:14:54 +01:00
1 parent f6c2a17b4d
commit c1a0049bcf
300 files changed
+1602 -1045

No files matched your search

@@ -0,0 +1,946 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Compagnie e borsa (sezione 12, pannello a tutto schermo con palette e componenti dell'immagine
/// 05): listino delle compagnie, offerte pubbliche in corso con adesioni e difese, scheda della
/// compagnia scelta (libro dei soci, prezzo mensile, storico annuale) e operazioni: compravendita,
/// quotazione, dividendo, riacquisto, offerta pubblica, fusione, offerte alle aste delle fallite.
/// I dati arrivano dal listino giornaliero (MarketTape) e dalle schede chieste al server; ogni
/// operazione è un comando e l'esito (anche il rifiuto per livello) si mostra com'è.
/// </summary>
public partial class CompaniesPanel : VBoxContainer
{
private const float WPrice = 80, WCap = 86, WWorth = 86, WMine = 56;
private readonly GameSession _session;
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly VBoxContainer _banner = PanelKit.Column(6);
private readonly VBoxContainer _rows = PanelKit.Column(4);
private readonly VBoxContainer _bids = PanelKit.Column(8);
private readonly VBoxContainer _card = PanelKit.Column(8);
private readonly SeriesChart _chart = new(150);
private readonly Label _chartCaption = UiTheme.Text("", 14, bold: true);
private readonly VBoxContainer _register = PanelKit.Column(6);
private readonly VBoxContainer _history = PanelKit.Column(4);
private readonly VBoxContainer _actions = PanelKit.Column(8);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly Dictionary<int, CompanyRow> _rowById = [];
private readonly Dictionary<int, (Label Text, ProgressBar Bar)> _bidProgress = [];
private string _bidsKey = "", _actionsKey = "", _bannerKey = "", _rowsKey = "";
private int _selected = -1;
private int _tapeVersion = -1, _entityVersion = -1, _detailVersion = -1;
private double _requestSelected, _requestAll = double.MaxValue, _sinceRefresh = double.MaxValue;
private Action? _updateEstimates;
public event Action? CloseRequested;
public event Action? ChronicleRequested;
public CompaniesPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 14);
SizeFlagsVertical = SizeFlags.ExpandFill;
var header = PanelKit.Row(12);
var titles = PanelKit.Column(0);
titles.AddChild(UiTheme.TitleLabel(T("Compagnie e borsa"), 40));
titles.AddChild(_subtitle);
header.AddChild(titles);
var chronicle = new Button { Text = T("Cronaca provvisoria"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(0, 40) };
chronicle.TooltipText = T("La storia della tua compagnia finora: grafici, primati, fatti salienti e prestigio.");
chronicle.Pressed += () => ChronicleRequested?.Invoke();
header.AddChild(chronicle);
var close = new Button { Text = T("Chiudi"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(96, 40) };
close.Pressed += () => CloseRequested?.Invoke();
header.AddChild(close);
AddChild(header);
AddChild(_banner);
var body = PanelKit.Row(16);
body.SizeFlagsVertical = SizeFlags.ExpandFill;
AddChild(body);
var left = Column(body, 1.5f);
left.AddChild(UiTheme.Text(T("Listino"), 16, bold: true));
var sm = session.World.Data.Balance.StockMarket;
left.AddChild(Wrapped($"{T("Clic su una compagnia per la scheda, il libro dei soci e le operazioni. Prezzo per azione: il maggiore tra patrimonio netto e")} " +
$"{Fmt.Number(sm.EarningsMultiple, 0)} {T("volte l'utile annuo, diviso per le azioni e moltiplicato per il sentiment del mercato.")}", 12, Palette.TextSecondary));
left.AddChild(TableHeader());
left.AddChild(_rows);
left.AddChild(PanelKit.Separator());
left.AddChild(UiTheme.Text(T("Offerte pubbliche in corso"), 16, bold: true));
left.AddChild(_bids);
var center = Column(body, 1f);
center.AddChild(_card);
center.AddChild(_chartCaption);
center.AddChild(_chart);
center.AddChild(UiTheme.Text(T("Libro dei soci"), 16, bold: true));
center.AddChild(_register);
var right = Column(body, 0.9f);
right.AddChild(UiTheme.Text(T("Storico annuale"), 16, bold: true));
right.AddChild(_history);
right.AddChild(PanelKit.Separator());
right.AddChild(UiTheme.Text(T("Operazioni"), 16, bold: true));
right.AddChild(_actions);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
right.AddChild(_status);
Select(session.World.Summary?.CompanyId ?? 0);
}
/// <summary>Compagnia della scheda (−1 se nessuna).</summary>
public int Selected => _selected;
public void Select(int company)
{
_selected = company;
_requestSelected = double.MaxValue;
_sinceRefresh = double.MaxValue;
_status.Text = "";
foreach (var (id, row) in _rowById) row.SetSelected(id == company);
}
private static VBoxContainer Column(HBoxContainer body, float ratio)
{
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 10, 16));
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
frame.AddChild(scroll);
// margine destro: la barra di scorrimento non tocca i numeri allineati a destra
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
margin.AddThemeConstantOverride("margin_right", 10);
scroll.AddChild(margin);
var col = PanelKit.Column(10);
margin.AddChild(col);
body.AddChild(frame);
return col;
}
public override void _Process(double delta)
{
var w = _session.World;
_requestSelected += delta;
_requestAll += delta;
_sinceRefresh += delta;
// tutte le schede ogni 5 s (quote del giocatore e soci dei bersagli), quella aperta ogni secondo
if (_requestAll >= 5)
{
_requestAll = 0;
_requestSelected = 0;
foreach (int id in w.Companies.Values.Where(c => !c.Merged).Select(c => c.Id).Order())
_session.Send(new RequestDetail { Kind = DetailKind.Company, Target = id });
}
else if (_requestSelected >= 1 && _selected >= 0)
{
_requestSelected = 0;
_session.Send(new RequestDetail { Kind = DetailKind.Company, Target = _selected });
}
bool changed = w.TapeVersion != _tapeVersion || w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion;
if (changed && _sinceRefresh >= 0.25) Refresh();
}
private void Result(CommandResultMessage r)
{
_status.Text = r.Message;
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.Ok : Palette.Danger);
_requestAll = double.MaxValue;
}
private void Refresh()
{
var w = _session.World;
_sinceRefresh = 0;
_tapeVersion = w.TapeVersion;
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
int me = Me(w);
double portfolio = w.Companies.Values.Where(c => c.Id != me && !c.Merged && !c.Bankrupt).Sum(c => Mine(w, c.Id) * PriceCents(w, c.Id));
_subtitle.Text = (w.Tape is { } tape ? $"{T("Listino del")} {Fmt.Date(w, tape.Day)}" : T("In attesa del listino del giorno…")) +
$" · {T("portafoglio azioni")} {Money.FromCentsRounded(portfolio)}";
RefreshBanner(w);
RefreshRows(w);
RefreshBids(w);
RefreshCard(w);
RefreshHistory(w);
RefreshActions(w);
_updateEstimates?.Invoke();
}
// ------------------------------------------------------------------ dati di comodo (solo lettura)
private static int Me(ClientWorld w) => w.Summary?.CompanyId ?? 0;
private static SharePrice? Quote(ClientWorld w, int id) => w.Tape?.Shares.FirstOrDefault(s => s.Company == id);
/// <summary>Prezzo per azione in centesimi: dal listino se c'è, altrimenti dalla scheda dell'entità.</summary>
private static double PriceCents(ClientWorld w, int id) =>
Quote(w, id) is { PriceCents: > 0 } q ? q.PriceCents : w.Companies.TryGetValue(id, out var c) ? c.SharePriceCents : 0;
private static long Outstanding(ClientWorld w, int id)
{
if (Quote(w, id) is { Outstanding: > 0 } q) return q.Outstanding;
if (w.CompanyCards.TryGetValue(id, out var card)) return card.TotalShares - card.Treasury;
return w.Data.Balance.StockMarket.Shares;
}
/// <summary>Azioni della compagnia del giocatore nella compagnia indicata (dal libro dei soci).</summary>
private static long Mine(ClientWorld w, int id)
{
int me = Me(w);
if (!w.CompanyCards.TryGetValue(id, out var card)) return 0;
return card.Holdings.Where(h => id == me ? h.Holder == HoldingInfo.Founder : h.Holder == me).Sum(h => h.Shares);
}
/// <summary>Vero/falso se il libro dei soci è noto, null se la scheda non è ancora arrivata.</summary>
private static bool? Holds(ClientWorld w, int id) => w.CompanyCards.ContainsKey(id) ? Mine(w, id) > 0 : null;
// ------------------------------------------------------------------ amministrazione controllata
private void RefreshBanner(ClientWorld w)
{
int me = Me(w);
var info = w.Companies.GetValueOrDefault(me);
long today = Fmt.Today(w);
string key = info is { Receivership: true } ? $"{info.ReceivershipUntilDay}|{info.ControlledBy}|{today}|{info.FounderShare:0.000}" : "";
if (key == _bannerKey) return;
_bannerKey = key;
foreach (var c in _banner.GetChildren()) c.QueueFree();
if (info is not { Receivership: true }) return;
var sm = w.Data.Balance.StockMarket;
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 14));
var row = PanelKit.Row(16);
box.AddChild(row);
var col = PanelKit.Column(4);
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
col.AddChild(UiTheme.Text($"{T("Amministrazione controllata")} · {T("controlla la compagnia")} {Fmt.Company(w, info.ControlledBy)}", 16, Palette.AmberLight, bold: true));
long left = Math.Max(0, info.ReceivershipUntilDay - today);
col.AddChild(Wrapped($"{T("Riacquista almeno il")} {Fmt.Pct(sm.RansomShare, 0)} {T("delle azioni entro il")} {Fmt.Date(w, info.ReceivershipUntilDay)} ({left} {T("giorni")}), " +
$"{T("altrimenti la partita finisce. Intanto versi il")} {Fmt.Pct(sm.ReceivershipDividend, 0)} {T("degli utili come dividendo e non puoi chiedere prestiti.")} " +
$"{T("Oggi il fondatore ha il")} {Fmt.Pct(info.FounderShare)}.", 13, Palette.Text));
row.AddChild(col);
var buy = UiTheme.Primary(T("Riacquista azioni"));
buy.SizeFlagsVertical = SizeFlags.ShrinkCenter;
buy.Pressed += () => Select(me);
row.AddChild(buy);
_banner.AddChild(box);
}
// ------------------------------------------------------------------ listino
private static Control TableHeader()
{
var row = PanelKit.Row(6);
var name = UiTheme.Text(T("Compagnia"), 12, Palette.TextSecondary);
name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
name.CustomMinimumSize = new Vector2(24, 0);
row.AddChild(new Control { CustomMinimumSize = new Vector2(10, 0) });
row.AddChild(name);
foreach (var (text, width) in new[] { (T("Prezzo · var."), WPrice), (T("Capitalizz."), WCap), (T("Patrimonio"), WWorth), (T("Tua quota"), WMine) })
{
var l = UiTheme.Text(text, 12, Palette.TextSecondary);
l.CustomMinimumSize = new Vector2(width, 0);
l.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(l);
}
row.AddChild(new Control { CustomMinimumSize = new Vector2(4, 0) });
return row;
}
private void RefreshRows(ClientWorld w)
{
int me = Me(w);
var companies = w.Companies.Values.Where(c => !c.Merged)
.OrderBy(c => c.Id == me ? 0 : c.Bankrupt ? 2 : 1)
.ThenByDescending(c => PriceCents(w, c.Id) * Outstanding(w, c.Id))
.ThenBy(c => c.Id).ToList();
string key = string.Join(",", companies.Select(c => c.Id));
if (key != _rowsKey)
{
_rowsKey = key;
foreach (var c in _rows.GetChildren()) c.QueueFree();
_rowById.Clear();
foreach (var c in companies)
{
int id = c.Id;
var row = new CompanyRow();
row.Pressed += () => Select(id);
_rowById[id] = row;
_rows.AddChild(row);
row.SetSelected(id == _selected);
}
}
foreach (var c in companies)
{
var q = Quote(w, c.Id);
double price = PriceCents(w, c.Id);
long outstanding = Outstanding(w, c.Id);
var parts = new List<string>();
if (c.Id == me) parts.Add(T("la tua compagnia"));
if (c.Bankrupt)
{
parts.Add(T("fallita, attivi all'asta"));
}
else
{
parts.Add(Fmt.Tier(w, c.Tier));
if (c.Personality.Length > 0) parts.Add(Fmt.Personality(w, c.Personality));
if (!c.Listed) parts.Add(T("non quotata"));
if (c.ControlledBy >= 0) parts.Add($"{T("controllata da")} {Fmt.Company(w, c.ControlledBy)}");
if (c.Receivership) parts.Add(T("amministrazione controllata"));
}
double mine = c.Id == me ? c.FounderShare : outstanding > 0 && w.CompanyCards.ContainsKey(c.Id) ? (double)Mine(w, c.Id) / outstanding : -1;
_rowById[c.Id].Update(
Fmt.CompanyColor(w, c.Id), c.Name, string.Join(" · ", parts),
c.Bankrupt ? "—" : Fmt.Price(price), c.Listed && q is not null && !c.Bankrupt ? Fmt.Change(q.Change) : "—",
!c.Listed || q is null ? Palette.TextSecondary : q.Change > 0.0005f ? Palette.Ok : q.Change < -0.0005f ? Palette.Danger : Palette.TextSecondary,
c.Bankrupt ? "—" : Money.FromCentsRounded(price * outstanding).ToString("short"), c.NetWorth.ToString("short"),
mine < 0 ? "…" : mine <= 0 ? "—" : Fmt.Pct(mine), c.Listed && !c.Bankrupt, c.Bankrupt || c.Receivership);
}
}
/// <summary>Riga del listino: pulsante piatto con le colonne allineate.</summary>
private sealed partial class CompanyRow : Button
{
private readonly ColorRect _swatch = new() { CustomMinimumSize = new Vector2(10, 28), SizeFlagsVertical = SizeFlags.ShrinkCenter };
private readonly Label _name = UiTheme.Text("", 14, bold: true);
private readonly Label _sub = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly Label _price = UiTheme.Text("", 14, bold: true);
private readonly Label _change = UiTheme.Text("", 12);
private readonly Label _cap = UiTheme.Text("", 13);
private readonly Label _worth = UiTheme.Text("", 13);
private readonly Label _mine = UiTheme.Text("", 13, Palette.AmberLight, bold: true);
public CompanyRow()
{
CustomMinimumSize = new Vector2(0, 50);
FocusMode = FocusModeEnum.None;
AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.Border, 8, 8));
AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8));
SetSelected(false);
var row = new HBoxContainer { MouseFilter = MouseFilterEnum.Ignore };
row.AddThemeConstantOverride("separation", 6);
row.SetAnchorsPreset(LayoutPreset.FullRect);
row.OffsetLeft = 8;
row.OffsetRight = -8;
AddChild(row);
row.AddChild(_swatch);
var names = new VBoxContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
names.AddThemeConstantOverride("separation", -2);
foreach (var l in new[] { _name, _sub })
{
l.ClipText = true;
l.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
l.CustomMinimumSize = new Vector2(24, 0);
names.AddChild(l);
}
row.AddChild(names);
// prezzo con la variazione del giorno sotto
var price = new VBoxContainer { CustomMinimumSize = new Vector2(WPrice, 0), SizeFlagsVertical = SizeFlags.ShrinkCenter, MouseFilter = MouseFilterEnum.Ignore };
price.AddThemeConstantOverride("separation", -2);
foreach (var l in new[] { _price, _change })
{
l.HorizontalAlignment = HorizontalAlignment.Right;
price.AddChild(l);
}
row.AddChild(price);
foreach (var (l, width) in new[] { (_cap, WCap), (_worth, WWorth), (_mine, WMine) })
{
l.CustomMinimumSize = new Vector2(width, 0);
l.HorizontalAlignment = HorizontalAlignment.Right;
l.SizeFlagsVertical = SizeFlags.ShrinkCenter;
row.AddChild(l);
}
foreach (var l in new[] { _name, _sub, _price, _change, _cap, _worth, _mine }) l.MouseFilter = MouseFilterEnum.Ignore;
_swatch.MouseFilter = MouseFilterEnum.Ignore;
}
public void SetSelected(bool on)
{
AddThemeStyleboxOverride("normal", on ? UiTheme.Box(Palette.Inner, Palette.Amber, 8, 8) : UiTheme.Box(Palette.Panel, Palette.Panel, 8, 8));
}
public void Update(Color color, string name, string sub, string price, string change, Color changeColor, string cap, string worth, string mine, bool listed, bool alarm)
{
_swatch.Color = color;
_name.Text = name;
_sub.Text = sub;
TooltipText = $"{name}\n{sub}";
_sub.AddThemeColorOverride("font_color", alarm ? Palette.Danger : Palette.TextSecondary);
_price.Text = price;
_price.AddThemeColorOverride("font_color", listed ? Palette.Text : Palette.TextSecondary);
_change.Text = change;
_change.AddThemeColorOverride("font_color", changeColor);
_cap.Text = cap;
_worth.Text = worth;
_mine.Text = mine;
}
}
// ------------------------------------------------------------------ offerte pubbliche
private void RefreshBids(ClientWorld w)
{
int me = Me(w);
var bids = w.Tape?.Bids ?? [];
string key = string.Join(";", bids.Select(b => $"{b.Bid},{b.Defenses},{b.Knight},{b.Accepted},{Holds(w, b.Target)}")) + "|" + string.Join(",", w.Companies.Values.Where(c => c.Bankrupt || c.Merged).Select(c => c.Id).Order());
if (key != _bidsKey)
{
_bidsKey = key;
_bidProgress.Clear();
foreach (var c in _bids.GetChildren()) c.QueueFree();
if (bids.Count == 0)
{
var sm = w.Data.Balance.StockMarket;
_bids.AddChild(Wrapped($"{T("Nessuna offerta in corso. Un'offerta dura")} {sm.BidDurationDays} {T("giorni e offre un premio tra il")} {Fmt.Pct(sm.BidPremiumMin, 0)} " +
$"{T("e il")} {Fmt.Pct(sm.BidPremiumMax, 0)} {T("sul prezzo di mercato.")}", 13, Palette.TextSecondary));
}
foreach (var b in bids) _bids.AddChild(BidBox(w, b, me));
}
long today = Fmt.Today(w);
foreach (var b in bids)
{
if (!_bidProgress.TryGetValue(b.Bid, out var p)) continue;
p.Text.Text = $"{T("impegnato")} {Fmt.Pct(b.CommittedShare)} {T("di")} {Fmt.Pct(b.TargetShare, 0)} · {T("scade il")} {Fmt.Date(w, b.ExpiresDay)} ({Math.Max(0, b.ExpiresDay - today)} {T("giorni")})";
p.Bar.MaxValue = Math.Max(0.0001, b.TargetShare);
p.Bar.Value = Math.Min(b.CommittedShare, b.TargetShare);
}
}
private Control BidBox(ClientWorld w, BidInfo b, int me)
{
bool mine = b.Target == me || b.Bidder == me;
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, mine ? Palette.Amber : Palette.Border, 8, 12));
var col = PanelKit.Column(6);
box.AddChild(col);
col.AddChild(Wrapped($"{Fmt.Company(w, b.Bidder)} → {Fmt.Company(w, b.Target)}", 15, null, bold: true));
double market = PriceCents(w, b.Target);
string premium = market > 0 ? $" ({Fmt.Change(b.PricePerShare.Cents / market - 1)} {T("sul mercato")})" : "";
col.AddChild(Wrapped($"{Fmt.Price(b.PricePerShare.Cents)} {T("per azione")}{premium} · {T("obiettivo")} {Fmt.Pct(b.TargetShare, 0)}", 13, null));
var bar = new ProgressBar { ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 3, 0));
col.AddChild(bar);
var progress = UiTheme.Text("", 12, Palette.TextSecondary);
col.AddChild(progress);
_bidProgress[b.Bid] = (progress, bar);
if (DefenseText(w, b) is { Length: > 0 } defenses) col.AddChild(Wrapped(defenses, 12, Palette.AmberLight));
int bidId = b.Bid;
if (b.Target == me)
{
var sm = w.Data.Balance.StockMarket;
col.AddChild(Wrapped($"{T("La tua compagnia è il bersaglio. Difese: riacquisto del flottante con la cassa; dividendo straordinario del")} {Fmt.Pct(sm.ExtraDividendCashShare, 0)} " +
$"{T("della cassa (il titolo sale); cavaliere bianco: un'alleata compra il flottante al prezzo dell'offerta più il")} {Fmt.Pct(sm.WhiteKnightPremium, 0)}.", 12, Palette.TextSecondary));
var row = PanelKit.Row(6);
var buyback = new Button { Text = T("Riacquisto"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
buyback.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.Buyback }, Result);
row.AddChild(buyback);
var dividend = new Button { Text = T("Dividendo straordinario"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
dividend.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.ExtraDividend }, Result);
row.AddChild(dividend);
col.AddChild(row);
var knightRow = PanelKit.Row(6);
var knights = new OptionButton { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
var knightIds = w.Companies.Values.Where(c => c.Id != me && c.Id != b.Bidder && !c.Bankrupt && !c.Merged).OrderBy(c => c.Id).Select(c => c.Id).ToList();
foreach (int k in knightIds) knights.AddItem(Fmt.Company(w, k));
knightRow.AddChild(knights);
var knight = new Button { Text = T("Cavaliere bianco"), Disabled = knightIds.Count == 0 };
knight.Pressed += () =>
{
if (knights.Selected < 0 || knights.Selected >= knightIds.Count) return;
_session.Command(new RespondBidCommand(new BidId(bidId), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(knightIds[knights.Selected]) }, Result);
};
knightRow.AddChild(knight);
col.AddChild(knightRow);
}
else if (b.Bidder == me)
{
col.AddChild(Wrapped(T("La tua offerta: gli azionisti aderiscono ogni giorno finché l'obiettivo non è raggiunto o l'offerta scade."), 12, Palette.TextSecondary));
}
else if (Holds(w, b.Target) != false)
{
var respond = b.Accepted ? new Button { Text = T("Ritira l'adesione") } : UiTheme.Primary(T("Aderisci con le tue azioni"));
bool accept = !b.Accepted;
respond.Pressed += () => _session.Command(new RespondBidCommand(new BidId(bidId), accept), Result);
col.AddChild(respond);
if (b.Accepted) col.AddChild(UiTheme.Text(T("Hai aderito con tutte le tue azioni."), 12, Palette.Ok));
}
return box;
}
private static string DefenseText(ClientWorld w, BidInfo b)
{
var parts = new List<string>();
if ((b.Defenses & (1 << (int)BidDefense.None)) != 0) parts.Add(T("respinta dal consiglio"));
if ((b.Defenses & (1 << (int)BidDefense.Buyback)) != 0) parts.Add(T("riacquisto"));
if ((b.Defenses & (1 << (int)BidDefense.ExtraDividend)) != 0) parts.Add(T("dividendo straordinario"));
if ((b.Defenses & (1 << (int)BidDefense.WhiteKnight)) != 0) parts.Add($"{T("cavaliere bianco")} {Fmt.Company(w, b.Knight)}");
return parts.Count == 0 ? "" : $"{T("Difese del bersaglio")}: {string.Join(", ", parts)}";
}
// ------------------------------------------------------------------ scheda della compagnia
private void RefreshCard(ClientWorld w)
{
foreach (var c in _card.GetChildren()) c.QueueFree();
foreach (var c in _register.GetChildren()) c.QueueFree();
int me = Me(w);
if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
{
_chartCaption.Text = "";
_chart.Show([], [], v => "", SeriesChart.Style.Line, Palette.Amber, T("Scegli una compagnia nel listino"));
return;
}
var card = w.CompanyCards.GetValueOrDefault(_selected);
var head = PanelKit.Row(10);
var swatch = new ColorRect { Color = Fmt.CompanyColor(w, info.Id), CustomMinimumSize = new Vector2(12, 34), SizeFlagsVertical = SizeFlags.ShrinkCenter };
head.AddChild(swatch);
var title = UiTheme.TitleLabel(info.Name, 30);
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
title.SizeFlagsHorizontal = SizeFlags.ExpandFill;
head.AddChild(title);
_card.AddChild(head);
var badges = new HFlowContainer();
badges.AddThemeConstantOverride("h_separation", 6);
badges.AddThemeConstantOverride("v_separation", 6);
badges.AddChild(UiTheme.Badge(Fmt.Tier(w, info.Tier)));
if (info.Id == me) badges.AddChild(Tag(T("la tua compagnia"), Palette.AmberLight));
if (info.Personality.Length > 0) badges.AddChild(Tag(Fmt.Personality(w, info.Personality), Palette.Staff));
badges.AddChild(Tag(info.Listed ? T("quotata") : T("non quotata"), info.Listed ? Palette.Ok : Palette.TextSecondary));
if (info.ControlledBy >= 0) badges.AddChild(Tag($"{T("controllata da")} {Fmt.Company(w, info.ControlledBy)}", Palette.Amber));
if (info.Receivership) badges.AddChild(Tag(T("amministrazione controllata"), Palette.Danger));
if (info.Bankrupt) badges.AddChild(Tag(T("fallita"), Palette.Danger));
_card.AddChild(badges);
double price = PriceCents(w, info.Id);
var stats1 = PanelKit.Row(8);
stats1.AddChild(PanelKit.Stat(T("Prezzo per azione"), PanelKit.Value(info.Bankrupt ? "—" : Fmt.Price(price))));
stats1.AddChild(PanelKit.Stat(T("Capitalizzazione"), PanelKit.Value(card?.MarketCap.ToString("short") ?? Money.FromCentsRounded(price * Outstanding(w, info.Id)).ToString("short"))));
stats1.AddChild(PanelKit.Stat(T("Patrimonio netto"), PanelKit.Value(info.NetWorth.ToString("short"))));
_card.AddChild(stats1);
var stats2 = PanelKit.Row(8);
var profit = PanelKit.Value(info.AnnualProfit.ToString("short"));
if (info.AnnualProfit.IsNegative) profit.AddThemeColorOverride("font_color", Palette.Danger);
stats2.AddChild(PanelKit.Stat(T("Utile annuo"), profit));
stats2.AddChild(PanelKit.Stat(T("Dividendi (12 mesi)"), PanelKit.Value(card?.DividendsYear.ToString("short") ?? "—")));
stats2.AddChild(PanelKit.Stat(T("Debito"), PanelKit.Value(card?.Debt.ToString("short") ?? "—")));
_card.AddChild(stats2);
_card.AddChild(PanelKit.Pair(T("Cassa"), PanelKit.Value(info.Cash.ToString())));
_card.AddChild(PanelKit.Pair(T("Sentiment del mercato"), PanelKit.Value("×" + Fmt.Number(info.Sentiment, 2))));
if (card is { ControlDays: >= 0 } && info.ControlledBy >= 0)
_card.AddChild(PanelKit.Pair(T("Controllo"), PanelKit.Value($"{Fmt.Company(w, info.ControlledBy)} · {card.ControlDays} {T("giorni")}")));
var prices = card?.PriceHistory ?? [];
_chartCaption.Text = prices.Count > 0 ? $"{T("Prezzo dell'azione a fine mese")} · {T("ultimi")} {prices.Count} {T("mesi")}" : T("Prezzo dell'azione a fine mese");
_chart.Show(prices, [], Fmt.PricePrecise, SeriesChart.Style.Line, Fmt.CompanyColor(w, info.Id),
card is null ? T("Scheda in arrivo dal server…") : T("Lo storico si forma alla fine di ogni mese"));
BuildRegister(w, info, card);
}
private void BuildRegister(ClientWorld w, CompanyInfo info, CompanyCard? card)
{
if (card is null)
{
_register.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
int me = Me(w);
long outstanding = Math.Max(1, card.TotalShares - card.Treasury);
var holders = card.Holdings.Where(h => h.Shares > 0)
.OrderBy(h => h.Holder == HoldingInfo.Founder ? 0 : h.Holder == HoldingInfo.Market ? 2 : 1)
.ThenByDescending(h => h.Shares).ThenBy(h => h.Holder).ToList();
// barra a segmenti delle quote
var bar = new HBoxContainer { CustomMinimumSize = new Vector2(0, 14) };
bar.AddThemeConstantOverride("separation", 2);
foreach (var h in holders)
bar.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = Math.Max(0.002f, h.Shares / (float)card.TotalShares) });
if (card.Treasury > 0)
bar.AddChild(new ColorRect { Color = Palette.Border, SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = card.Treasury / (float)card.TotalShares });
_register.AddChild(bar);
double control = w.Data.Balance.StockMarket.ControlShare;
foreach (var h in holders)
{
double share = (double)h.Shares / outstanding;
string name = h.Holder switch
{
HoldingInfo.Founder => info.Id == me ? T("Fondatore (tu)") : T("Fondatore privato"),
HoldingInfo.Market => T("Mercato (flottante)"),
_ => Fmt.Company(w, h.Holder) + (h.Holder == me ? " (" + T("tu") + ")" : ""),
};
var row = PanelKit.Row(8);
row.AddChild(new ColorRect { Color = HolderColor(w, h.Holder), CustomMinimumSize = new Vector2(10, 10), SizeFlagsVertical = SizeFlags.ShrinkCenter });
var n = UiTheme.Text(name, 13, h.Holder == me || (h.Holder == HoldingInfo.Founder && info.Id == me) ? Palette.AmberLight : Palette.Text);
n.SizeFlagsHorizontal = SizeFlags.ExpandFill;
n.ClipText = true;
n.TextOverrunBehavior = TextServer.OverrunBehavior.TrimEllipsis;
n.CustomMinimumSize = new Vector2(40, 0);
row.AddChild(n);
var count = UiTheme.Text(Fmt.Shares(h.Shares), 13, Palette.TextSecondary);
count.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(count);
var pct = UiTheme.Text(Fmt.Pct(share), 13, share > control && h.Holder != HoldingInfo.Market ? Palette.Amber : Palette.Text, bold: true);
pct.CustomMinimumSize = new Vector2(64, 0);
pct.HorizontalAlignment = HorizontalAlignment.Right;
row.AddChild(pct);
_register.AddChild(row);
}
if (card.Treasury > 0)
_register.AddChild(PanelKit.Pair(T("Azioni proprie (non votano)"), PanelKit.Value(Fmt.Shares(card.Treasury))));
_register.AddChild(Wrapped($"{T("Quote sulle")} {Fmt.Shares(outstanding)} {T("azioni in circolazione: oltre il")} {Fmt.Pct(control, 0)} {T("si controlla la compagnia.")}", 12, Palette.TextSecondary));
}
private static Color HolderColor(ClientWorld w, int holder) => holder switch
{
HoldingInfo.Founder => Palette.Amber,
HoldingInfo.Market => Palette.TextSecondary,
_ => Fmt.CompanyColor(w, holder),
};
// ------------------------------------------------------------------ storico annuale
private void RefreshHistory(ClientWorld w)
{
foreach (var c in _history.GetChildren()) c.QueueFree();
var card = _selected >= 0 ? w.CompanyCards.GetValueOrDefault(_selected) : null;
if (card is null || card.History.Count == 0)
{
_history.AddChild(Wrapped(card is null ? T("Scheda in arrivo dal server…") : T("Nessun anno concluso: lo storico si scrive a fine anno."), 13, Palette.TextSecondary));
return;
}
var grid = new GridContainer { Columns = 5, SizeFlagsHorizontal = SizeFlags.ExpandFill };
grid.AddThemeConstantOverride("h_separation", 12);
grid.AddThemeConstantOverride("v_separation", 4);
foreach (string h in new[] { T("Anno"), T("Patrimonio"), T("Utile"), T("Treni"), T("Liv.") })
{
var l = UiTheme.Text(h, 12, Palette.TextSecondary);
l.HorizontalAlignment = h == T("Anno") ? HorizontalAlignment.Left : HorizontalAlignment.Right;
if (h == T("Patrimonio")) l.SizeFlagsHorizontal = SizeFlags.ExpandFill;
grid.AddChild(l);
}
foreach (var y in Enumerable.Reverse(card.History).Take(8))
{
grid.AddChild(UiTheme.Text($"{y.Year}", 13, bold: true));
foreach (var (text, color) in new[]
{
(y.NetWorth.ToString("short"), Palette.Text),
(y.Profit.ToString("short"), y.Profit.IsNegative ? Palette.Danger : Palette.Text),
($"{y.Trains}", Palette.Text),
($"{y.Tier}", Palette.Text),
})
{
var l = UiTheme.Text(text, 13, color);
l.HorizontalAlignment = HorizontalAlignment.Right;
grid.AddChild(l);
}
}
_history.AddChild(grid);
}
// ------------------------------------------------------------------ operazioni
private void RefreshActions(ClientWorld w)
{
int me = Me(w);
if (_selected < 0 || !w.Companies.TryGetValue(_selected, out var info))
{
if (_actionsKey.Length > 0) Clear(_actions);
_actionsKey = "";
return;
}
var card = w.CompanyCards.GetValueOrDefault(_selected);
var meInfo = w.Companies.GetValueOrDefault(me);
bool auction = card is { AuctionEndDay: >= 0 };
bool bidOpen = w.Tape?.Bids.Any(b => b.Target == _selected) == true;
string key = $"{_selected}|{info.Listed}|{info.Bankrupt}|{info.Merged}|{info.ControlledBy == me}|{auction}|{bidOpen}|{meInfo?.Listed}|{meInfo?.Receivership}|{card is null}";
if (key == _actionsKey) return;
_actionsKey = key;
Clear(_actions);
_updateEstimates = null;
if (card is null)
{
_actions.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
if (info.Id == me) BuildOwnActions(w, info);
else if (info.Bankrupt) BuildAuction(w, info, card);
else BuildTradeActions(w, info, bidOpen);
}
private static void Clear(Container c)
{
foreach (var child in c.GetChildren()) child.QueueFree();
}
/// <summary>Operazioni sulla compagnia del giocatore: quotazione, dividendo, riacquisto.</summary>
private void BuildOwnActions(ClientWorld w, CompanyInfo me)
{
var sm = w.Data.Balance.StockMarket;
var updates = new List<Action>();
if (!me.Listed)
{
_actions.AddChild(UiTheme.Text(T("Quotazione in borsa"), 14, bold: true));
var slider = new HSlider { MinValue = 1, MaxValue = Math.Round(sm.IpoMaxShare * 100), Step = 1, Value = Math.Round(sm.IpoMaxShare * 100 / 2), SizeFlagsHorizontal = SizeFlags.ExpandFill };
var label = UiTheme.Text("", 13);
label.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(slider);
_actions.AddChild(label);
void Estimate()
{
long shares = (long)Math.Round(sm.Shares * slider.Value / 100);
label.Text = $"{T("Colloca il")} {Fmt.Number(slider.Value, 0)}% {T("del capitale")} ({Fmt.Shares(shares)} {T("azioni")}): {T("incasso stimato")} ≈ {Money.FromCentsRounded(shares * PriceCents(_session.World, me.Id))}";
}
slider.ValueChanged += _ => Estimate();
updates.Add(Estimate);
var ipo = UiTheme.Primary(T("Quotati in borsa"));
ipo.Pressed += () => _session.Command(new IpoCommand(slider.Value / 100), Result);
_actions.AddChild(ipo);
if (Fmt.UnlockTier(w, u => u.Ipo) is { } tier)
_actions.AddChild(Wrapped($"{T("La quotazione si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
else
{
_actions.AddChild(UiTheme.Text(T("Dividendo"), 14, bold: true));
var row = PanelKit.Row(6);
var perShare = new SpinBox { MinValue = 0.01, MaxValue = 1000, Step = 0.01, Value = 0.01, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
perShare.TooltipText = T("Dividendo per azione");
row.AddChild(perShare);
var pay = new Button { Text = T("Paga dividendo") };
pay.Pressed += () => _session.Command(new PayDividendCommand(new Money((long)Math.Round(perShare.Value * 100))), Result);
row.AddChild(pay);
_actions.AddChild(row);
var total = UiTheme.Text("", 12, Palette.TextSecondary);
total.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(total);
void Estimate() => total.Text = $"{T("Totale")} {new Money((long)Math.Round(perShare.Value * 100) * Outstanding(_session.World, me.Id))} {T("agli azionisti; i dividendi alzano il sentiment del titolo.")}";
perShare.ValueChanged += _ => Estimate();
updates.Add(Estimate);
}
if (me.Listed || me.Receivership)
{
_actions.AddChild(PanelKit.Separator());
_actions.AddChild(UiTheme.Text(T("Riacquisto di azioni proprie"), 14, bold: true));
updates.Add(QuantityRow(w, me.Id, T("Riacquista"), null, n => new BuySharesCommand(new CompanyId(me.Id), n, Money.Zero), null,
me.Receivership ? T("In amministrazione controllata compri anche dal controllante, con il premio di riscatto.") : T("Le azioni tornano al fondatore e alzano la tua quota.")));
}
_updateEstimates = () => { foreach (var u in updates) u(); };
}
/// <summary>Compravendita, offerta pubblica e fusione per le altre compagnie.</summary>
private void BuildTradeActions(ClientWorld w, CompanyInfo target, bool bidOpen)
{
var sm = w.Data.Balance.StockMarket;
int me = Me(w);
var updates = new List<Action>();
int id = target.Id;
if (target.Listed)
{
_actions.AddChild(UiTheme.Text(T("Compravendita di azioni"), 14, bold: true));
updates.Add(QuantityRow(w, id, T("Compra"), T("Vendi"),
n => new BuySharesCommand(new CompanyId(id), n, Money.Zero),
n => new SellSharesCommand(new CompanyId(id), n, Money.Zero),
$"{T("Spread")} {Fmt.Pct(sm.Spread, 0)}; {T("al massimo il")} {Fmt.Pct(sm.MaxDailyTradeShare, 0)} {T("del capitale per ordine.")}"));
}
else
{
_actions.AddChild(Wrapped(T("Non quotata: le sue azioni non sono sul mercato."), 13, Palette.TextSecondary));
}
if (target.ControlledBy == me)
{
_actions.AddChild(PanelKit.Separator());
_actions.AddChild(UiTheme.Text(T("Fusione"), 14, bold: true));
var info = UiTheme.Text("", 12, Palette.TextSecondary);
info.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(info);
updates.Add(() =>
{
long days = _session.World.CompanyCards.GetValueOrDefault(id)?.ControlDays ?? 0;
info.Text = $"{T("La controlli da")} {Math.Max(0, days)} {T("giorni")}; {T("la fusione è possibile dopo")} {sm.MergeAfterDays} {T("giorni e liquida le minoranze al prezzo di mercato.")}";
});
var merge = UiTheme.Primary(T("Incorpora la controllata"));
merge.Pressed += () => _session.Command(new MergeCompanyCommand(new CompanyId(id)), Result);
_actions.AddChild(merge);
}
else if (target.Listed)
{
_actions.AddChild(PanelKit.Separator());
_actions.AddChild(UiTheme.Text(T("Offerta pubblica di acquisto"), 14, bold: true));
if (bidOpen)
{
_actions.AddChild(Wrapped(T("C'è già un'offerta in corso su questa compagnia: la trovi nell'elenco a sinistra."), 12, Palette.TextSecondary));
}
else
{
double pMin = sm.BidPremiumMin * 100, pMax = sm.BidPremiumMax * 100;
var premiumLabel = UiTheme.Text("", 13);
var premium = new HSlider { MinValue = pMin, MaxValue = pMax, Step = 1, Value = pMin, SizeFlagsHorizontal = SizeFlags.ExpandFill };
_actions.AddChild(premiumLabel);
_actions.AddChild(premium);
var shareLabel = UiTheme.Text("", 13);
double minTarget = Math.Floor(sm.ControlShare * 100) + 1;
var share = new HSlider { MinValue = minTarget, MaxValue = 100, Step = 1, Value = minTarget, SizeFlagsHorizontal = SizeFlags.ExpandFill };
_actions.AddChild(shareLabel);
_actions.AddChild(share);
var cost = UiTheme.Text("", 12, Palette.TextSecondary);
cost.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(cost);
long Cents() => BidCents(PriceCents(_session.World, id), premium.Value / 100, sm.BidPremiumMin, sm.BidPremiumMax);
void Estimate()
{
var world = _session.World;
double market = PriceCents(world, id);
long cents = Cents();
string effective = market > 0 ? Fmt.Change(cents / market - 1) : "—";
premiumLabel.Text = $"{T("Premio")} {Fmt.Number(premium.Value, 0)}% · {Fmt.Price(cents)} {T("per azione")} ({effective} {T("sul mercato")}: {Fmt.PricePrecise(market)})";
shareLabel.Text = $"{T("Quota obiettivo")} {Fmt.Number(share.Value, 0)}%";
long outstanding = Outstanding(world, id);
long needed = Math.Max(0, (long)Math.Ceiling(share.Value / 100 * outstanding) - Mine(world, id));
cost.Text = $"{T("Impegno massimo")} {new Money(needed * cents)} {T("per")} {Fmt.Shares(needed)} {T("azioni")}; {T("durata")} {sm.BidDurationDays} {T("giorni")}.";
}
premium.ValueChanged += _ => Estimate();
share.ValueChanged += _ => Estimate();
updates.Add(Estimate);
var launch = UiTheme.Primary(T("Lancia l'offerta"));
launch.Pressed += () => _session.Command(new LaunchBidCommand(new CompanyId(id), new Money(Cents()), share.Value / 100), Result);
_actions.AddChild(launch);
if (Fmt.UnlockTier(w, u => u.HostileTakeover) is { } tier)
_actions.AddChild(Wrapped($"{T("Le scalate ostili si sbloccano al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
}
_updateEstimates = () => { foreach (var u in updates) u(); };
}
/// <summary>Offerta all'asta degli attivi di una compagnia fallita (offerta = prezzo per azione × azioni).</summary>
private void BuildAuction(ClientWorld w, CompanyInfo seller, CompanyCard card)
{
if (card.AuctionEndDay < 0)
{
_actions.AddChild(Wrapped(T("Compagnia fallita: nessuna asta in corso."), 13, Palette.TextSecondary));
return;
}
int id = seller.Id;
long total = Math.Max(1, card.TotalShares);
_actions.AddChild(UiTheme.Text(T("Asta degli attivi"), 14, bold: true));
var best = PanelKit.Value();
var closing = PanelKit.Value();
var minimum = PanelKit.Value();
_actions.AddChild(PanelKit.Pair(T("Base d'asta"), minimum));
_actions.AddChild(PanelKit.Pair(T("Miglior offerta"), best));
_actions.AddChild(PanelKit.Pair(T("Chiusura"), closing));
var row = PanelKit.Row(6);
// l'offerta si esprime in lire; il protocollo la trasmette come prezzo per azione intero in centesimi
double step = total / 100.0;
var offer = new SpinBox { MinValue = step, MaxValue = 1e12, Step = step, Prefix = "₤", SizeFlagsHorizontal = SizeFlags.ExpandFill };
row.AddChild(offer);
var bid = UiTheme.Primary(T("Offri all'asta"));
bid.Pressed += () =>
{
long perShare = (long)Math.Ceiling(offer.Value * 100 / total - 1e-9);
_session.Command(new LaunchBidCommand(new CompanyId(id), new Money(perShare), 1), Result);
};
row.AddChild(bid);
_actions.AddChild(row);
_actions.AddChild(Wrapped(T("Chi offre di più alla chiusura compra treni, binari, stazioni e industrie della compagnia fallita."), 12, Palette.TextSecondary));
bool initialized = false;
_updateEstimates = () =>
{
var world = _session.World;
var c = world.CompanyCards.GetValueOrDefault(id);
if (c is null || c.AuctionEndDay < 0) return;
minimum.Text = c.AuctionMin.ToString();
best.Text = c.AuctionBestBidder >= 0 ? $"{c.AuctionBest} · {Fmt.Company(world, c.AuctionBestBidder)}" : T("nessuna");
closing.Text = $"{Fmt.Date(world, c.AuctionEndDay)} ({Math.Max(0, c.AuctionEndDay - Fmt.Today(world))} {T("giorni")})";
double floor = Math.Max(c.AuctionMin.Cents, c.AuctionBest.Cents + 1) / 100.0;
double next = Math.Ceiling(floor / step) * step;
if (!initialized || (offer.Value < next && !offer.GetLineEdit().HasFocus()))
{
initialized = true;
offer.SetValueNoSignal(next);
}
};
}
/// <summary>Riga quantità di azioni + pulsanti, con la stima del controvalore e delle azioni possedute.</summary>
private Action QuantityRow(ClientWorld w, int company, string first, string? second,
Func<long, GameCommand> firstCommand, Func<long, GameCommand>? secondCommand, string note)
{
var sm = w.Data.Balance.StockMarket;
long max = Math.Max(1, (long)(sm.Shares * sm.MaxDailyTradeShare));
var row = PanelKit.Row(6);
var qty = new SpinBox { MinValue = 1, MaxValue = max, Step = 1, CustomArrowStep = 1000, Rounded = true, Value = Math.Min(10_000, max), SizeFlagsHorizontal = SizeFlags.ExpandFill };
qty.TooltipText = T("Numero di azioni");
row.AddChild(qty);
var a = UiTheme.Primary(first);
a.Pressed += () => _session.Command(firstCommand((long)qty.Value), Result);
row.AddChild(a);
if (second is not null && secondCommand is not null)
{
var b = new Button { Text = second };
b.Pressed += () => _session.Command(secondCommand((long)qty.Value), Result);
row.AddChild(b);
}
_actions.AddChild(row);
var estimate = UiTheme.Text("", 12, Palette.TextSecondary);
estimate.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_actions.AddChild(estimate);
_actions.AddChild(Wrapped(note, 12, Palette.TextSecondary));
void Estimate()
{
var world = _session.World;
long held = Mine(world, company);
long outstanding = Math.Max(1, Outstanding(world, company));
long free = Quote(world, company)?.FreeFloat ?? 0;
estimate.Text = $"{T("Controvalore")} ≈ {Money.FromCentsRounded(qty.Value * PriceCents(world, company))} · " +
$"{(company == Me(world) ? T("il fondatore ha") : T("possiedi"))} {Fmt.Shares(held)} {T("azioni")} ({Fmt.Pct((double)held / outstanding)}) · {T("sul mercato")} {Fmt.Shares(free)}";
}
qty.ValueChanged += _ => Estimate();
return Estimate;
}
/// <summary>
/// Prezzo intero (centesimi) dell'offerta per il premio scelto, tenuto dentro i limiti del premio
/// nonostante l'arrotondamento al centesimo.
/// </summary>
private static long BidCents(double market, double premium, double min, double max)
{
double basis = Math.Max(1e-6, market);
long cents = (long)Math.Round(basis * (1 + premium));
if (cents / basis - 1 < min) cents = (long)Math.Ceiling(basis * (1 + min) - 1e-9);
if (cents / basis - 1 > max) cents = (long)Math.Floor(basis * (1 + max) + 1e-9);
return Math.Max(1, cents);
}
// ------------------------------------------------------------------ mattoni
private static PanelContainer Tag(string text, Color color)
{
var p = new PanelContainer();
p.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, color, 4, 6));
p.AddChild(UiTheme.Text(text, 12, color, bold: true));
return p;
}
private static Label Wrapped(string text, int size, Color? color, bool bold = false)
{
var l = UiTheme.Text(text, size, color, bold);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://bxbrrccdi8qun
@@ -0,0 +1,156 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Registro degli impieghi (sezione 9): convenzioni proposte dalle industrie (accetta o rifiuta),
/// posti di lavoro serviti dai treni della compagnia e suoi depositi, con provenienza dei
/// pendolari per città e linea, posti scoperti e motivo.
/// </summary>
public partial class EmploymentPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly VBoxContainer _agreements = PanelKit.Column(8);
private readonly VBoxContainer _rows = PanelKit.Column(10);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private int _version = -1;
public EmploymentPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Registro degli impieghi"), 30));
var help = UiTheme.Text(T("Ogni mese le città mandano i loro lavoratori alle industrie e ai depositi raggiungibili con i tuoi treni entro 60 minuti (personale: 90). Qui vedi da dove arrivano, quanti posti restano scoperti e perché."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
var refresh = new Button { Text = T("Aggiorna") };
refresh.Pressed += Request;
AddChild(refresh);
AddChild(UiTheme.Text(T("Convenzioni"), 16, bold: true));
AddChild(_agreements);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Posti di lavoro"), 16, bold: true));
AddChild(_rows);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
Request();
}
private void Request() => _session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
public override void _Process(double delta)
{
if (_session.World.DetailVersion != _version) Refresh();
}
private void Refresh()
{
var w = _session.World;
_version = w.DetailVersion;
foreach (var c in _agreements.GetChildren()) c.QueueFree();
foreach (var c in _rows.GetChildren()) c.QueueFree();
var report = w.Employment;
if (report is null)
{
_rows.AddChild(UiTheme.Text(T("Registro in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
var open = report.Agreements.Where(a => a.State <= 1).ToList();
if (open.Count == 0) _agreements.AddChild(Wrapped(T("Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno."), 13, Palette.TextSecondary));
foreach (var a in open) _agreements.AddChild(AgreementRow(w, a));
foreach (var row in report.Rows.OrderBy(r => r.Kind).ThenBy(r => r.Industry)) _rows.AddChild(WorkplaceRow(w, row));
if (report.Rows.Count == 0) _rows.AddChild(Wrapped(T("Nessun posto di lavoro servito dai tuoi treni."), 13, Palette.TextSecondary));
}
private Control AgreementRow(ClientWorld w, AgreementInfo a)
{
var box = new PanelContainer();
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, a.State == 0 ? Palette.Amber : Palette.Border, 8, 10));
var col = PanelKit.Column(6);
box.AddChild(col);
string industry = w.Industries.TryGetValue(a.Industry, out var ind) ? ind.Name : $"#{a.Industry}";
col.AddChild(UiTheme.Text(industry, 15, bold: true));
col.AddChild(Wrapped($"{a.SeatsPerDay} {T("posti al giorno garantiti")} · {a.MonthlyFee} {T("al mese")}", 13, null));
if (a.State == 0)
{
var buttons = PanelKit.Row(6);
var accept = UiTheme.Primary(T("Accetta"));
accept.Pressed += () => _session.Command(new AcceptAgreementCommand(new AgreementId(a.Id)), r => _status.Text = r.Message);
var reject = new Button { Text = T("Rifiuta") };
reject.Pressed += () => _session.Command(new RejectAgreementCommand(new AgreementId(a.Id)), r => _status.Text = r.Message);
buttons.AddChild(accept);
buttons.AddChild(reject);
col.AddChild(buttons);
var risk = UiTheme.Text(T("Se la capacità manca per 30 giorni la convenzione salta con una penale."), 12, Palette.TextSecondary);
risk.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(risk);
}
else
{
col.AddChild(UiTheme.Text($"{T("Attiva")} · {T("copertura")} {a.Coverage * 100:0}%" +
(a.ShortDays > 0 ? $" · {T("capacità mancante da")} {a.ShortDays} {T("giorni")}" : ""), 13, a.ShortDays > 0 ? Palette.Danger : Palette.Ok));
}
return box;
}
private Control WorkplaceRow(ClientWorld w, EmploymentRow row)
{
var col = PanelKit.Column(4);
string name = row.Kind == 1
? (w.Depots.TryGetValue(row.Industry, out var d) ? d.Name : $"#{row.Industry}")
: (w.Industries.TryGetValue(row.Industry, out var ind) ? ind.Name : $"#{row.Industry}");
col.AddChild(UiTheme.Text(name, 15, bold: true));
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Lavoratori"), PanelKit.Value($"{row.WorkersPresent:0} / {row.JobsWorkers}")));
stats.AddChild(PanelKit.Stat(T("Personale"), PanelKit.Value($"{row.StaffPresent:0} / {row.JobsStaff}")));
col.AddChild(stats);
foreach (string reason in new[] { ReasonText(w, row.WorkersReason, row.WorkersReasonLine, staff: false), ReasonText(w, row.StaffReason, row.StaffReasonLine, staff: true) })
{
if (reason.Length == 0) continue;
var l = UiTheme.Text("⚠ " + reason, 13, Palette.Amber);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(l);
}
foreach (var s in row.Sources.OrderByDescending(s => s.Headcount))
{
string town = w.Towns.TryGetValue(s.Town, out var t) ? t.Name : $"#{s.Town}";
string via = s.Line >= 0 && w.Lines.TryGetValue(s.Line, out var line) ? line.Name : T("a piedi");
string who = s.Category == 1 ? T("tecnici") : T("lavoratori");
col.AddChild(Wrapped($"• {s.Headcount} {who} {T("da")} {town} · {via} · {T("copertura")} {s.Coverage * 100:0}%", 13,
s.Category == 1 ? Palette.Staff : Palette.Workers));
}
return col;
}
private static Label Wrapped(string text, int size, Color? color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
/// <summary>Motivo dei posti scoperti nella lingua dell'interfaccia (codici UncoveredReason).</summary>
public static string ReasonText(ClientWorld w, byte reason, int line, bool staff)
{
string who = staff ? T("Personale") : T("Lavoratori");
string minutes = staff ? $"{w.Data.Balance.Employment.StaffMaxMinutes:0}" : $"{w.Data.Balance.Employment.WorkerMaxMinutes:0}";
return reason switch
{
1 => $"{who}: {T("nessuna stazione serve il posto di lavoro")}",
2 => $"{who}: {T("nessuna città raggiungibile entro")} {minutes} min",
3 => $"{who}: {T("le città raggiungibili non hanno lavoratori liberi")}",
4 => $"{who}: {T("città senza servizi per il personale")}",
5 => $"{who}: {T("capacità delle carrozze insufficiente sulla")} {(w.Lines.TryGetValue(line, out var l) ? l.Name : T("linea"))}",
_ => "",
};
}
}
@@ -0,0 +1 @@
uid://bjfsfdctgdm1q
@@ -0,0 +1,86 @@
using System.Globalization;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Formati numerici dell'interfaccia (immagine 05): separatore delle migliaia con il punto,
/// decimali con la virgola, prezzi delle azioni in lire con i centesimi.
/// </summary>
public static class Fmt
{
/// <summary>Numero con i decimali indicati e la virgola («12,4»).</summary>
public static string Number(double value, int decimals = 1)
{
string text = value.ToString(decimals <= 0 ? "0" : "0." + new string('0', decimals), CultureInfo.InvariantCulture);
int dot = text.IndexOf('.');
string integer = dot < 0 ? text : text[..dot];
bool negative = integer.StartsWith('-');
if (negative) integer = integer[1..];
string grouped = ulong.TryParse(integer, NumberStyles.None, CultureInfo.InvariantCulture, out ulong n) ? Money.GroupThousands(n) : integer;
return (negative ? "−" : "") + grouped + (dot < 0 ? "" : "," + text[(dot + 1)..]);
}
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
/// <summary>Prezzo per azione dai centesimi frazionari («₤ 0,25»).</summary>
public static string Price(double cents) => Money.FromCentsRounded(cents).ToString("it2");
/// <summary>Prezzo per azione con i decimali che servono a leggere le variazioni sotto il centesimo («₤ 0,2534»).</summary>
public static string PricePrecise(double cents) => cents >= 10_000 ? Price(cents) : "₤ " + Number(cents / 100, cents >= 100 ? 2 : 4);
/// <summary>Numero di azioni con il punto delle migliaia.</summary>
public static string Shares(long shares) => shares < 0 ? "−" + Money.GroupThousands((ulong)(-shares)) : Money.GroupThousands((ulong)shares);
/// <summary>Giorno corrente della partita (dal resoconto giornaliero o dal tick).</summary>
public static long Today(ClientWorld w) =>
w.LastDigest?.Day ?? (w.Calendar is { } c ? w.Tick / c.TicksPerDay : 0);
/// <summary>Data di calendario di un giorno della partita.</summary>
public static string Date(ClientWorld w, long day) =>
w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).ToString() : $"{T("giorno")} {day}";
/// <summary>Nome di una compagnia (o «—» se sconosciuta).</summary>
public static string Company(ClientWorld w, int id) =>
w.Companies.TryGetValue(id, out var c) ? c.Name : id >= 0 ? $"#{id}" : "—";
/// <summary>Nome del livello della compagnia nella lingua dell'interfaccia.</summary>
public static string Tier(ClientWorld w, int tier)
{
var tiers = w.Data.Tiers.Tiers;
var def = tiers[Math.Clamp(tier, 1, tiers.Count) - 1];
return Godot.TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
}
/// <summary>
/// Livello che sblocca una funzione, se la compagnia del giocatore non ce l'ha ancora (solo per
/// il suggerimento: è il server a decidere).
/// </summary>
public static int? UnlockTier(ClientWorld w, Func<Core.Data.TierUnlocks, bool> unlock)
{
int tier = w.Companies.TryGetValue(w.Summary?.CompanyId ?? 0, out var me) ? me.Tier : 1;
var tiers = w.Data.Tiers.Tiers;
if (unlock(tiers[Math.Clamp(tier, 1, tiers.Count) - 1].Unlocks)) return null;
return tiers.FirstOrDefault(t => unlock(t.Unlocks))?.Level;
}
/// <summary>Carattere di una compagnia IA (id di ai.json); vuoto per il giocatore.</summary>
public static string Personality(ClientWorld w, string id) => id switch
{
"" => "",
"expansive" => T("Espansiva"),
"prudent" => T("Prudente"),
"predatory" => T("Predatoria"),
_ => w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == id)?.NameIt ?? id,
};
/// <summary>Colore di una compagnia dalla stringa esadecimale, con l'ambra in mancanza.</summary>
public static Godot.Color CompanyColor(ClientWorld w, int id) =>
w.Companies.TryGetValue(id, out var c) && Godot.Color.HtmlIsValid(c.Color) ? new Godot.Color(c.Color) : App.Palette.Amber;
}
@@ -0,0 +1 @@
uid://u5pgogq2sft1
@@ -0,0 +1,367 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Industrie (sezione 11): elenco delle industrie della regione e pannello del proprietario
/// dell'industria scelta: condizione degli impianti con il moltiplicatore di efficienza, budget di
/// manutenzione, scorta di ricambi e macchinari, storico dei fermi, «Fermo programmato»,
/// «Ammoderna», «Ordina ricambi»; per le industrie dei privati il prezzo chiesto e «Acquista».
/// La scheda del proprietario arriva su richiesta dal server (IndustryCard).
/// </summary>
public partial class IndustryPanel : VBoxContainer
{
private readonly GameSession _session;
private readonly ItemList _list = new() { CustomMinimumSize = new Vector2(0, 150) };
private readonly List<int> _ids = [];
private readonly VBoxContainer _header = PanelKit.Column(8);
private readonly VBoxContainer _controls = PanelKit.Column(8);
private readonly VBoxContainer _details = PanelKit.Column(6);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<Button> _budgetButtons = [];
private SpinBox? _partsOrder;
private int _industry = -1;
private (int Industry, int Owner) _controlsKey = (-2, -2);
private int _entityVersion = -1, _detailVersion = -1;
private double _request, _sinceRefresh;
public IndustryPanel(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Industrie"), 34));
var help = UiTheme.Text(T("Scegli un'industria nell'elenco o sulla mappa. Gli impianti si consumano con l'uso: il budget di manutenzione, i ricambi e i macchinari portati in treno li tengono in salute."), 13, Palette.TextSecondary);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
AddChild(_list);
AddChild(PanelKit.Separator());
AddChild(_header);
AddChild(_controls);
AddChild(_details);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_list.ItemSelected += i => Select(_ids[(int)i]);
RefreshList();
}
/// <summary>Industria mostrata (−1 se nessuna).</summary>
public int Industry => _industry;
public void Select(int id)
{
if (id == _industry) return;
_industry = id;
_status.Text = "";
SyncSelection();
Request();
Refresh();
}
private void Request()
{
if (_industry >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Industry, Target = _industry });
}
public override void _Process(double delta)
{
// la scheda aperta si aggiorna una volta al secondo; il pannello al massimo quattro volte
_request += delta;
_sinceRefresh += delta;
if (_request >= 1)
{
_request = 0;
Request();
}
var w = _session.World;
if ((w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) && _sinceRefresh >= 0.25) Refresh();
}
private void Result(CommandResultMessage r)
{
_status.Text = r.Message;
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
Request();
}
private void Refresh()
{
var w = _session.World;
_sinceRefresh = 0;
if (w.EntityVersion != _entityVersion) RefreshList();
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
foreach (var c in _header.GetChildren()) c.QueueFree();
foreach (var c in _details.GetChildren()) c.QueueFree();
if (_industry < 0 || !w.Industries.TryGetValue(_industry, out var ind))
{
BuildControls(null);
return;
}
var card = w.IndustryCards.GetValueOrDefault(_industry);
BuildHeader(w, ind, card);
BuildControls(ind);
UpdateControls(ind, card);
BuildDetails(w, ind, card);
}
// ------------------------------------------------------------------ elenco
/// <summary>Elenco: si ricostruisce solo se cambiano le industrie o il loro ordine, altrimenti si aggiornano i testi.</summary>
private void RefreshList()
{
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
long today = Fmt.Today(w);
var ordered = w.Industries.Values.Where(i => !i.Closed)
.OrderBy(i => i.Owner == me ? 0 : i.Owner < 0 ? 1 : 2).ThenBy(i => i.Name, StringComparer.Ordinal).ThenBy(i => i.Id).ToList();
bool same = ordered.Count == _ids.Count && ordered.Select(i => i.Id).SequenceEqual(_ids);
if (!same)
{
_ids.Clear();
_list.Clear();
}
for (int n = 0; n < ordered.Count; n++)
{
var ind = ordered[n];
string owner = ind.Owner == me ? T("tua") : ind.Owner < 0 ? T("privati") : Fmt.Company(w, ind.Owner);
string stop = ind.StoppedUntilDay >= today ? " · " + T("ferma") : "";
string text = $"{ind.Name} · {Fmt.Number(ind.Condition, 0)}% · {owner}{stop}";
if (!same)
{
_ids.Add(ind.Id);
_list.AddItem(text);
}
else if (_list.GetItemText(n) != text)
{
_list.SetItemText(n, text);
}
_list.SetItemCustomFgColor(n, ind.Owner == me ? Palette.AmberLight : MaintenancePanel.ConditionColor((int)ind.Condition));
}
if (!same) SyncSelection();
}
private void SyncSelection()
{
int index = _ids.IndexOf(_industry);
if (index < 0)
{
_list.DeselectAll();
return;
}
if (!_list.IsSelected(index)) _list.Select(index);
_list.EnsureCurrentIsVisible();
}
// ------------------------------------------------------------------ scheda
private void BuildHeader(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
int me = w.Summary?.CompanyId ?? 0;
var title = UiTheme.TitleLabel(ind.Name, 30);
title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_header.AddChild(title);
var def = w.Data.Industries.FirstOrDefault(d => d.Id == ind.Type);
_header.AddChild(UiTheme.Text($"{def?.NameIt ?? ind.Type} · {T("livello")} {ind.Level}", 14, Palette.TextSecondary));
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
_header.AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
long today = Fmt.Today(w);
if (ind.StoppedUntilDay >= today)
_header.AddChild(UiTheme.Notice($"{StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)} ({ind.StoppedUntilDay - today + 1} {T("giorni")})"));
else if (ind.PendingWork != 0)
_header.AddChild(UiTheme.Notice($"{WorkName(ind.PendingWork)}: {T("attende")} {card?.MachineryRequired ?? 0} {T("macchinari")} ({T("in scorta")} {ind.Machinery})" +
(ind.PendingWork == 1 ? " " + T("e personale sufficiente") : "")));
if (ind.PartsShort)
_header.AddChild(Wrapped(T("⚠ Ricambi esauriti: il recupero degli impianti si dimezza. Portali in treno da una fabbrica di macchinari o da un porto."), 13, Palette.Danger));
var stats = PanelKit.Row(8);
stats.AddChild(PanelKit.Stat(T("Condizione"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", MaintenancePanel.ConditionColor((int)ind.Condition))));
stats.AddChild(PanelKit.Stat(T("Resa impianti"), PanelKit.Value(card is null ? "—" : "×" + Fmt.Number(card.ConditionMultiplier, 2))));
stats.AddChild(PanelKit.Stat(T("Efficienza"), PanelKit.Value(Fmt.Pct(ind.Efficiency, 0))));
_header.AddChild(stats);
var bar = new ProgressBar { MaxValue = 100, Value = ind.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10) };
var color = MaintenancePanel.ConditionColor((int)ind.Condition);
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
_header.AddChild(bar);
var m = w.Data.Balance.IndustryMaintenance;
_header.AddChild(Wrapped($"{T("Sopra il")} {Fmt.Number(m.EfficiencyFullAbove, 0)}% {T("gli impianti rendono pieno; sotto calano fino a")} ×{Fmt.Number(m.EfficiencyAt20, 1)} {T("al 20% e si fermano più spesso.")}", 12, Palette.TextSecondary));
}
/// <summary>Comandi del proprietario o dell'acquirente: si ricostruiscono solo se cambia l'industria o il proprietario.</summary>
private void BuildControls(IndustryInfo? ind)
{
var key = ind is null ? (-1, -1) : (ind.Id, ind.Owner);
if (key == _controlsKey) return;
_controlsKey = key;
foreach (var c in _controls.GetChildren()) c.QueueFree();
_budgetButtons.Clear();
_partsOrder = null;
if (ind is null) return;
var w = _session.World;
int me = w.Summary?.CompanyId ?? 0;
int id = ind.Id;
if (ind.Owner == me)
{
_controls.AddChild(UiTheme.Text(T("Budget di manutenzione"), 14, bold: true));
var row = PanelKit.Row(6);
var group = new ButtonGroup();
foreach (var (budget, label) in new[] { (IndustryBudget.None, T("Nessuno")), (IndustryBudget.Base, T("Base")), (IndustryBudget.High, T("Alto")) })
{
var p = w.Data.Balance.IndustryMaintenance.For(budget);
var b = new Button { Text = label, ToggleMode = true, ButtonGroup = group, SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.TooltipText = $"{T("Recupero")} {Fmt.Number(p.RecoveryPerDay, 2)} {T("punti al giorno")} · {Fmt.Pct(p.CostShareOfRevenue, 0)} {T("dei ricavi")} · {p.SparePartsPerLevelPerMonth} {T("ricambi al mese per livello")}";
b.Pressed += () => _session.Command(new SetIndustryPolicyCommand(new IndustryId(id), budget), Result);
_budgetButtons.Add(b);
row.AddChild(b);
}
_controls.AddChild(row);
var order = PanelKit.Row(6);
var caption = UiTheme.Text(T("Ricambi extra"), 13, Palette.TextSecondary);
caption.TooltipText = T("Ricambi da ordinare oltre la scorta della politica: diventano domanda esplicita sulle tue linee.");
caption.MouseFilter = MouseFilterEnum.Pass;
order.AddChild(caption);
_partsOrder = new SpinBox { MinValue = 0, MaxValue = w.Data.Balance.IndustryMaintenance.MaxOrderedParts, SizeFlagsHorizontal = SizeFlags.ExpandFill };
order.AddChild(_partsOrder);
var orderButton = new Button { Text = T("Ordina ricambi") };
orderButton.Pressed += () => _session.Command(new OrderPartsCommand(DepotId.None, (int)(_partsOrder?.Value ?? 0)) { Industry = new IndustryId(id) }, Result);
order.AddChild(orderButton);
_controls.AddChild(order);
var actions = PanelKit.Row(6);
var m = w.Data.Balance.IndustryMaintenance;
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(overhaul);
var upgrade = UiTheme.Primary(T("Ammoderna"));
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
actions.AddChild(upgrade);
_controls.AddChild(actions);
}
else if (ind.Owner < 0)
{
_controls.AddChild(UiTheme.Text(T("In vendita"), 14, bold: true));
var price = PanelKit.Value("—");
price.Name = "Price";
_controls.AddChild(PanelKit.Pair(T("Prezzo chiesto dai proprietari"), price));
var buy = UiTheme.Primary(T("Acquista"));
buy.Pressed += () =>
{
if (_session.World.IndustryCards.TryGetValue(id, out var c))
_session.Command(new BuyIndustryCommand(new IndustryId(id), c.Valuation), Result);
else
Request();
};
_controls.AddChild(buy);
if (Fmt.UnlockTier(w, u => u.BuyIndustry) is { } tier)
_controls.AddChild(Wrapped($"{T("L'acquisto di industrie si sblocca al livello")} «{Fmt.Tier(w, tier)}».", 12, Palette.TextSecondary));
}
else
{
_controls.AddChild(Wrapped($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 13, Palette.TextSecondary));
}
}
private void UpdateControls(IndustryInfo ind, IndustryCard? card)
{
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
if (_controls.FindChild("Price", true, false) is Label price) price.Text = card?.Valuation.ToString() ?? "—";
}
private void BuildDetails(ClientWorld w, IndustryInfo ind, IndustryCard? card)
{
if (card is null)
{
_details.AddChild(UiTheme.Text(T("Scheda in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
int me = w.Summary?.CompanyId ?? 0;
_details.AddChild(UiTheme.Text(T("Impianti"), 14, bold: true));
_details.AddChild(PanelKit.Pair(T("Usura al giorno"), PanelKit.Value("−" + Fmt.Number(card.WearPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Recupero al giorno"), PanelKit.Value("+" + Fmt.Number(card.RecoveryPerDay, 3))));
_details.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
_details.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
if (ind.Owner == me)
{
_details.AddChild(PanelKit.Pair(T("Manutenzione al giorno"), PanelKit.Value(card.MaintenanceCostPerDay.ToString())));
_details.AddChild(PanelKit.Pair(T("Spesa di manutenzione nell'anno"), PanelKit.Value(card.MaintenanceSpentYear.ToString())));
_details.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
_details.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
}
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Scorte"), 14, bold: true));
_details.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
_details.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
_details.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
_details.AddChild(UiTheme.Text($"{T("servono")} {card.MachineryRequired} {T("macchinari per il prossimo lavoro")}", 12, Palette.TextSecondary));
_details.AddChild(PanelKit.Separator());
_details.AddChild(UiTheme.Text(T("Storico dei fermi"), 14, bold: true));
if (card.Stops.Count == 0) _details.AddChild(UiTheme.Text(T("Nessun fermo finora"), 13, Palette.TextSecondary));
foreach (var s in Enumerable.Reverse(card.Stops).Take(8))
{
var l = UiTheme.Text($"{Fmt.Date(w, s.Day)} · {StopName(s.Kind)} · {s.Days} {T("giorni")}", 13, s.Kind is 1 or 2 ? Palette.Amber : Palette.TextSecondary);
_details.AddChild(l);
}
}
private static Control StockRow(string caption, int have, int target, Color color)
{
var row = PanelKit.Row(8);
var name = UiTheme.Text(caption, 13, Palette.TextSecondary);
name.CustomMinimumSize = new Vector2(96, 0);
row.AddChild(name);
var bar = new ProgressBar { MaxValue = Math.Max(1, Math.Max(have, target)), Value = have, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10), SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ShrinkCenter };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 3, 0));
row.AddChild(bar);
row.AddChild(UiTheme.Text($"{have} / {target}", 13, bold: true));
return row;
}
// ------------------------------------------------------------------ testi
public static string StopName(byte kind) => kind switch
{
1 => T("Guasto"),
2 => T("Incidente grave"),
3 => T("Revisione"),
4 => T("Ammodernamento"),
_ => T("Fermo"),
};
private static string WorkName(byte work) => work switch
{
1 => T("Revisione programmata"),
2 => T("Ammodernamento programmato"),
_ => "",
};
private static Label ColoredValue(string text, Color color)
{
var l = PanelKit.Value(text);
l.AddThemeColorOverride("font_color", color);
return l;
}
private static Label Wrapped(string text, int size, Color? color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
return l;
}
}
@@ -0,0 +1 @@
uid://j8ci61w6roh6
@@ -0,0 +1,208 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.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 event Action<int>? MaintenanceRequested;
public event Action<int>? IndustryRequested;
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("Manutenzione"), PanelKit.Value(MaintenancePanel.StatusName(t.Maintenance) +
(t.Reserve ? " · " + T("riserva") : ""))));
if (t.NextIntervention.Length > 0)
{
string next = w.Data.Maintenance.Interventions.FirstOrDefault(i => i.Id == t.NextIntervention)?.NameIt ?? t.NextIntervention;
AddChild(PanelKit.Pair(T("Prossimo intervento"), PanelKit.Value(t.NextDueDays <= 0 ? $"{next} · {T("scaduto")}" : $"{next} · {T("tra")} {t.NextDueDays} {T("giorni")}")));
}
int trainId = t.Id;
var cardButton = new Button { Text = T("Cartella di manutenzione") };
cardButton.Pressed += () => MaintenanceRequested?.Invoke(trainId);
AddChild(cardButton);
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")));
// pannello del proprietario (sezione 11): manutenzione degli impianti o acquisto
int me = w.Summary?.CompanyId ?? 0;
string owner = ind.Owner == me ? T("La tua compagnia") : ind.Owner < 0 ? T("Proprietari privati") : Fmt.Company(w, ind.Owner);
AddChild(PanelKit.Pair(T("Proprietà"), PanelKit.Value(owner)));
if (ind.StoppedUntilDay >= Fmt.Today(w))
AddChild(UiTheme.Notice($"{IndustryPanel.StopName(ind.StopKind)}: {T("ferma fino al")} {Fmt.Date(w, ind.StoppedUntilDay)}"));
int industryId = ind.Id;
var ownerButton = new Button { Text = ind.Owner == me ? T("Gestisci l'industria") : T("Scheda del proprietario") };
ownerButton.Pressed += () => IndustryRequested?.Invoke(industryId);
AddChild(ownerButton);
// dal Registro degli impieghi: presenze, posti scoperti e provenienza dei pendolari
if (w.Employment?.Rows.FirstOrDefault(r => r.Kind == 0 && r.Industry == ind.Id) is { } row)
{
AddChild(UiTheme.Text(T("Lavoratori e personale"), 14, bold: true));
AddChild(PanelKit.Pair(T("Lavoratori"), PanelKit.Value($"{row.WorkersPresent:0} / {row.JobsWorkers}")));
AddChild(PanelKit.Pair(T("Personale"), PanelKit.Value($"{row.StaffPresent:0} / {row.JobsStaff}")));
foreach (string reason in new[] { EmploymentPanel.ReasonText(w, row.WorkersReason, row.WorkersReasonLine, false), EmploymentPanel.ReasonText(w, row.StaffReason, row.StaffReasonLine, true) })
{
if (reason.Length == 0) continue;
var l = UiTheme.Text("⚠ " + reason, 13, Palette.Amber);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(l);
}
foreach (var src in row.Sources.OrderByDescending(x => x.Headcount).Take(6))
{
string town = w.Towns.TryGetValue(src.Town, out var tw) ? tw.Name : "?";
string via = src.Line >= 0 && w.Lines.TryGetValue(src.Line, out var ln) ? ln.Name : T("a piedi");
AddChild(UiTheme.Text($"• {src.Headcount} {T("da")} {town} · {via}", 13, src.Category == 1 ? Palette.Staff : Palette.Workers));
}
}
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}")));
// dove lavorano gli abitanti (posti serviti dai tuoi treni)
if (w.Employment is { } report)
{
var jobs = report.Rows
.Select(r => (Row: r, Count: r.Sources.Where(x => x.Town == town.Id).Sum(x => x.Headcount)))
.Where(x => x.Count > 0).OrderByDescending(x => x.Count).ToList();
if (jobs.Count > 0) AddChild(UiTheme.Text(T("Dove lavorano gli abitanti"), 14, bold: true));
foreach (var (r, count) in jobs.Take(8))
{
string where = r.Kind == 1 ? (w.Depots.TryGetValue(r.Industry, out var d) ? d.Name : "?") : (w.Industries.TryGetValue(r.Industry, out var i2) ? i2.Name : "?");
AddChild(UiTheme.Text($"• {count} · {where}", 13));
}
}
break;
}
default:
{
AddChild(UiTheme.TitleLabel(T("Rail Enterprise"), 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 RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.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,352 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
/// mappa di calore, cartella di manutenzione del treno scelto, depositi con il Registro officina e
/// la scorta di ricambi. Le cartelle e i registri arrivano su richiesta dal server.
/// </summary>
public partial class MaintenancePanel : VBoxContainer
{
private static readonly string[] PolicyIds = ["economy", "standard", "thorough"];
private readonly GameSession _session;
private readonly OptionButton _fleetPolicy = new();
private readonly CheckButton _heat = new() { Text = T("Mappa di calore della condizione") };
private readonly VBoxContainer _alerts = PanelKit.Column(4);
private readonly ItemList _trains = new() { CustomMinimumSize = new Vector2(0, 150) };
private readonly VBoxContainer _card = PanelKit.Column(8);
private readonly VBoxContainer _cardControls = PanelKit.Column(8);
private readonly VBoxContainer _cardDetails = PanelKit.Column(6);
private readonly ItemList _depots = new() { CustomMinimumSize = new Vector2(0, 80) };
private readonly VBoxContainer _workshop = PanelKit.Column(8);
private readonly VBoxContainer _workshopDetails = PanelKit.Column(6);
private readonly HBoxContainer _orderRow = PanelKit.Row();
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<int> _trainIds = [];
private readonly List<int> _depotIds = [];
private int _train = -1, _depot = -1;
private int _entityVersion = -1, _detailVersion = -1;
private double _request;
private bool _updating;
public event Action<bool>? HeatMapToggled;
public event Action<int>? TrainSelected;
public MaintenancePanel(GameSession session, bool heatMap)
{
_session = session;
AddThemeConstantOverride("separation", 10);
AddChild(UiTheme.TitleLabel(T("Officine"), 34));
var policyRow = PanelKit.Row();
var caption = UiTheme.Text(T("Politica della flotta"), 14, Palette.TextSecondary);
caption.SizeFlagsHorizontal = SizeFlags.ExpandFill;
policyRow.AddChild(caption);
foreach (var p in session.World.Data.Maintenance.Policies) _fleetPolicy.AddItem(p.NameIt);
policyRow.AddChild(_fleetPolicy);
AddChild(policyRow);
_heat.ButtonPressed = heatMap;
_heat.Toggled += on => HeatMapToggled?.Invoke(on);
AddChild(_heat);
AddChild(_alerts);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Flotta, dal treno più usurato"), 14, bold: true));
AddChild(_trains);
AddChild(_card);
AddChild(_cardControls);
AddChild(_cardDetails);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Depositi e officine"), 14, bold: true));
AddChild(_depots);
AddChild(_workshop);
AddChild(_workshopDetails);
AddChild(_orderRow);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_fleetPolicy.ItemSelected += i =>
{
if (!_updating) _session.Command(new SetMaintenancePolicyCommand(MaintenanceScope.Company, 0, PolicyIds[i]), Result);
};
_trains.ItemSelected += i => SelectTrain(_trainIds[(int)i]);
_depots.ItemSelected += i => SelectDepot(_depotIds[(int)i]);
}
/// <summary>Allinea l'interruttore della mappa di calore senza rilanciare l'evento.</summary>
public void SetHeatMap(bool on) => _heat.SetPressedNoSignal(on);
public void SelectTrain(int id)
{
_train = id;
_detailVersion = -1;
_session.Send(new RequestDetail { Kind = DetailKind.TrainCard, Target = id });
TrainSelected?.Invoke(id);
BuildCardControls();
Refresh();
}
public void SelectDepot(int id)
{
_depot = id;
_detailVersion = -1;
_session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = id });
BuildOrderRow();
Refresh();
}
public override void _Process(double delta)
{
// cartella e registro aperti si aggiornano una volta al secondo
_request += delta;
if (_request >= 1)
{
_request = 0;
if (_train >= 0) _session.Send(new RequestDetail { Kind = DetailKind.TrainCard, Target = _train });
if (_depot >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = _depot });
}
var w = _session.World;
if (w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) Refresh();
}
private void Result(CommandResultMessage r) => _status.Text = r.Message;
private void Refresh()
{
var w = _session.World;
_entityVersion = w.EntityVersion;
_detailVersion = w.DetailVersion;
int company = w.Summary?.CompanyId ?? 0;
_updating = true;
if (w.Companies.TryGetValue(company, out var me)) _fleetPolicy.Selected = Math.Clamp(me.MaintenancePolicy, 0, PolicyIds.Length - 1);
_updating = false;
foreach (var c in _alerts.GetChildren()) c.QueueFree();
foreach (var a in w.Alerts.Take(4))
{
var l = UiTheme.Text("⚠ " + a.Text, 13, a.Condition < w.Data.Maintenance.Planner.CriticalCondition ? Palette.Danger : Palette.Amber);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_alerts.AddChild(l);
}
_trainIds.Clear();
_trains.Clear();
foreach (var t in w.Trains.Values.Where(t => t.Owner == company).OrderBy(t => t.Condition).ThenBy(t => t.Id))
{
_trainIds.Add(t.Id);
_trains.AddItem($"{t.Name} · {t.Condition}% · {StatusName(t.Maintenance)}{(t.Reserve ? " · " + T("riserva") : "")}{DueText(t)}");
_trains.SetItemCustomFgColor(_trains.ItemCount - 1, ConditionColor(t.Condition));
}
int ti = _trainIds.IndexOf(_train);
if (ti >= 0) _trains.Select(ti);
_depotIds.Clear();
_depots.Clear();
foreach (var d in w.Depots.Values.Where(d => d.Owner == company).OrderBy(d => d.Id))
{
_depotIds.Add(d.Id);
_depots.AddItem($"{d.Name} · {T("ricambi")} {d.SpareParts}/{d.PartsTarget} · {T("personale")} {d.StaffPercent}% · {d.Jobs} {T("lavori")}");
if (d.WaitingParts) _depots.SetItemCustomFgColor(_depots.ItemCount - 1, Palette.Danger);
}
int di = _depotIds.IndexOf(_depot);
if (di >= 0) _depots.Select(di);
BuildCard();
BuildWorkshop();
}
private string DueText(TrainInfo t)
{
if (t.NextIntervention.Length == 0 || t.Maintenance != TrainMaintenanceStatus.InService) return "";
return t.NextDueDays <= 0
? $" · {InterventionName(t.NextIntervention)} {T("scaduta")}"
: $" · {InterventionName(t.NextIntervention)} {T("tra")} {t.NextDueDays} {T("g")}";
}
// ------------------------------------------------------------------ cartella di manutenzione
private void BuildCard()
{
foreach (var c in _card.GetChildren()) c.QueueFree();
foreach (var c in _cardDetails.GetChildren()) c.QueueFree();
var w = _session.World;
if (_train < 0 || !w.Trains.TryGetValue(_train, out var t)) return;
_card.AddChild(UiTheme.TitleLabel(T("Cartella di manutenzione") + " · " + t.Name, 22));
var card = w.Cards.GetValueOrDefault(_train);
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Condizione"), PanelKit.Value($"{Math.Floor(card?.Condition ?? t.Condition):0}%")));
stats.AddChild(PanelKit.Stat(T("Guasti nell'anno"), PanelKit.Value($"{card?.FailuresThisYear ?? 0}")));
stats.AddChild(PanelKit.Stat(T("Costi dell'anno"), PanelKit.Value((card?.CostThisYear ?? Money.Zero).ToString())));
_card.AddChild(stats);
_card.AddChild(PanelKit.Pair(T("Stato"), PanelKit.Value(StatusName(t.Maintenance))));
if (card is not null)
{
if (card.Failure != 0)
_card.AddChild(UiTheme.Notice($"{FailureName(card.Failure)}: {ComponentName(card.FailedComponent)}" +
(card.RescueHours >= 0 ? $" · {T("soccorso tra")} {card.RescueHours:0.0} {T("ore")}" : "")));
if (card.PlannedIntervention.Length > 0 && card.MaintenanceDepot >= 0 && w.Depots.TryGetValue(card.MaintenanceDepot, out var md))
_card.AddChild(PanelKit.Pair(T("Prenotato"), PanelKit.Value($"{InterventionName(card.PlannedIntervention)} · {md.Name}")));
if (card.NextIntervention.Length > 0)
_card.AddChild(PanelKit.Pair(T("Prossimo intervento"), PanelKit.Value(card.NextDueDays <= 0
? $"{InterventionName(card.NextIntervention)} · {T("scaduto")}"
: $"{InterventionName(card.NextIntervention)} · {T("tra")} {Math.Ceiling(card.NextDueDays):0} {T("giorni")}")));
_card.AddChild(PanelKit.Pair(T("Km di servizio al giorno"), PanelKit.Value($"{card.ServiceKmPerDay:0}")));
if (card.CoveredBy >= 0 && w.Trains.TryGetValue(card.CoveredBy, out var cover))
_card.AddChild(PanelKit.Pair(T("Coperto dalla riserva"), PanelKit.Value(cover.Name)));
}
if (card is null)
{
_cardDetails.AddChild(UiTheme.Text(T("Cartella in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
foreach (var v in card.Vehicles)
{
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
_cardDetails.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {v.OdometerKm / 1000:0.#} {T("mila km")} · {v.AgeYears:0.#} {T("anni")}", 13, bold: true));
foreach (var c in v.Components)
{
var row = PanelKit.Row(6);
var name = UiTheme.Text(ComponentName(c.Component), 12, Palette.TextSecondary);
name.CustomMinimumSize = new Vector2(150, 0);
row.AddChild(name);
var bar = new ProgressBar { MaxValue = 100, Value = c.Condition, ShowPercentage = false, CustomMinimumSize = new Vector2(0, 10), SizeFlagsHorizontal = SizeFlags.ExpandFill };
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(ConditionColor((int)c.Condition), ConditionColor((int)c.Condition), 3, 0));
row.AddChild(bar);
row.AddChild(UiTheme.Text($"{c.Condition:0}%", 12, bold: true));
_cardDetails.AddChild(row);
}
}
if (card.History.Count > 0)
{
_cardDetails.AddChild(UiTheme.Text(T("Storico"), 14, bold: true));
foreach (var h in Enumerable.Reverse(card.History).Take(6))
{
string depot = w.Depots.TryGetValue(h.Depot, out var dd) ? dd.Name : "";
_cardDetails.AddChild(UiTheme.Text($"{T("giorno")} {h.Day} · {InterventionName(h.Intervention)} · {h.Cost} · {depot}", 12, Palette.TextSecondary));
}
}
}
// controlli della cartella: costruiti alla selezione, non a ogni aggiornamento
private void BuildCardControls()
{
foreach (var c in _cardControls.GetChildren()) c.QueueFree();
var w = _session.World;
if (_train < 0 || !w.Trains.TryGetValue(_train, out var t)) return;
// politica propria del treno e riserva
var policy = new OptionButton();
policy.AddItem(T("Come la linea o la flotta"));
foreach (var p in w.Data.Maintenance.Policies) policy.AddItem(p.NameIt);
policy.Selected = t.Policy == byte.MaxValue ? 0 : t.Policy + 1;
policy.ItemSelected += i => _session.Command(new SetMaintenancePolicyCommand(MaintenanceScope.Train, _train, i == 0 ? "inherit" : PolicyIds[i - 1]), Result);
_cardControls.AddChild(PanelKit.Pair(T("Politica del treno"), new Label()));
_cardControls.AddChild(policy);
var reserve = new CheckBox { Text = T("Treno di riserva in deposito"), ButtonPressed = t.Reserve };
reserve.Toggled += on => _session.Command(new SetReserveCommand(new TrainId(_train), on), Result);
_cardControls.AddChild(reserve);
var actions = PanelKit.Row(6);
foreach (string id in new[] { "inspection", "service", "overhaul" })
{
var b = new Button { Text = InterventionName(id), SizeFlagsHorizontal = SizeFlags.ExpandFill };
b.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(_train), id), Result);
actions.AddChild(b);
}
_cardControls.AddChild(actions);
}
// ------------------------------------------------------------------ registro officina
private void BuildWorkshop()
{
foreach (var c in _workshop.GetChildren()) c.QueueFree();
foreach (var c in _workshopDetails.GetChildren()) c.QueueFree();
var w = _session.World;
if (_depot < 0 || !w.Depots.TryGetValue(_depot, out var d)) return;
_workshop.AddChild(UiTheme.TitleLabel(T("Registro officina") + " · " + d.Name, 22));
var reg = w.Workshops.GetValueOrDefault(_depot);
var stats = PanelKit.Row();
stats.AddChild(PanelKit.Stat(T("Stalli"), PanelKit.Value($"{d.Stalls}")));
stats.AddChild(PanelKit.Stat(T("Personale"), PanelKit.Value($"{d.StaffPercent}%")));
stats.AddChild(PanelKit.Stat(T("Ricambi"), PanelKit.Value($"{d.SpareParts}")));
_workshop.AddChild(stats);
if (d.WaitingParts) _workshop.AddChild(UiTheme.Notice(T("Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.")));
if (reg is not null)
{
if (reg.WorkRate < 0.999f)
_workshopDetails.AddChild(PanelKit.Pair(T("Ritmo di lavoro (manca personale)"), PanelKit.Value($"{reg.WorkRate * 100:0}%")));
_workshopDetails.AddChild(PanelKit.Pair(T("Ricambi già destinati"), PanelKit.Value($"{reg.PartsReserved}")));
int stall = 0;
foreach (var j in reg.Jobs)
{
string train = w.Trains.TryGetValue(j.Train, out var t) ? t.Name : $"#{j.Train}";
string where = j.InStall ? $"{T("stallo")} {++stall}" : T("in coda");
string what = j.Started ? $"{j.Progress:0.0}/{j.Days:0} {T("giorni")}" : j.InStall ? T("attende i ricambi") : T("in attesa");
var line = UiTheme.Text($"{where} · {train} · {InterventionName(j.Intervention)} · {what}", 13);
line.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_workshopDetails.AddChild(line);
}
foreach (var j in reg.Booked)
{
string train = w.Trains.TryGetValue(j.Train, out var t) ? t.Name : $"#{j.Train}";
_workshopDetails.AddChild(UiTheme.Text($"{T("in arrivo")} · {train} · {InterventionName(j.Intervention)} · {j.Parts} {T("ricambi")}", 13, Palette.TextSecondary));
}
if (reg.Jobs.Count == 0 && reg.Booked.Count == 0) _workshopDetails.AddChild(UiTheme.Text(T("Nessun treno in officina"), 13, Palette.TextSecondary));
}
}
// scorta desiderata: costruita alla selezione del deposito
private void BuildOrderRow()
{
foreach (var c in _orderRow.GetChildren()) c.QueueFree();
var w = _session.World;
if (_depot < 0 || !w.Depots.TryGetValue(_depot, out var d)) return;
var target = new SpinBox { MinValue = 0, MaxValue = w.Data.Maintenance.Depots.MaxSpareParts, Value = d.PartsTarget, SizeFlagsHorizontal = SizeFlags.ExpandFill };
_orderRow.AddChild(UiTheme.Text(T("Scorta desiderata"), 13, Palette.TextSecondary));
_orderRow.AddChild(target);
var button = new Button { Text = T("Ordina") };
button.Pressed += () => _session.Command(new OrderPartsCommand(new DepotId(_depot), (int)target.Value), Result);
_orderRow.AddChild(button);
}
// ------------------------------------------------------------------ testi
public static string StatusName(TrainMaintenanceStatus s) => s switch
{
TrainMaintenanceStatus.Booked => T("intervento prenotato"),
TrainMaintenanceStatus.InWorkshop => T("in officina"),
TrainMaintenanceStatus.MinorFailure => T("guasto lieve"),
TrainMaintenanceStatus.Stranded => T("fermo in linea"),
TrainMaintenanceStatus.Towed => T("rimorchiato"),
_ => T("in servizio"),
};
private static string FailureName(byte f) => f switch
{
1 => T("Guasto lieve"),
2 => T("Guasto grave"),
3 => T("Deragliamento"),
_ => "",
};
public string InterventionName(string id) =>
_session.World.Data.Maintenance.Interventions.FirstOrDefault(i => i.Id == id)?.NameIt ?? id;
private string ComponentName(string id)
{
var m = _session.World.Data.Maintenance.Components;
return m.Locomotive.Concat(m.Car).FirstOrDefault(c => c.Id == id)?.NameIt ?? id;
}
/// <summary>Colore della condizione: verde sopra 70, ambra fino a 40, rosso sotto.</summary>
public static Color ConditionColor(int condition) =>
condition >= 70 ? Palette.Ok : condition >= 40 ? Palette.Amber : Palette.Danger;
}
@@ -0,0 +1 @@
uid://0pftav3413uj
@@ -0,0 +1,56 @@
using Godot;
using RailEnterprise.Client.App;
namespace RailEnterprise.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 RailEnterprise.Client.App;
using RailEnterprise.Client.Map;
using RailEnterprise.Core.Rail;
namespace RailEnterprise.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,119 @@
using Godot;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Grafico di una serie (come ProfileChart): linea con area per i prezzi mensili delle azioni,
/// barre per il patrimonio netto anno per anno della Cronaca. Disegna solo i valori ricevuti.
/// </summary>
public partial class SeriesChart : Control
{
public enum Style { Line, Bars }
private IReadOnlyList<double> _values = [];
private IReadOnlyList<string> _labels = [];
private Func<double, string> _format = v => Fmt.Number(v, 0);
private Style _style;
private Color _color = Palette.Amber;
private string _empty = "";
public SeriesChart(float height = 150)
{
CustomMinimumSize = new Vector2(0, height);
MouseFilter = MouseFilterEnum.Ignore;
}
/// <summary>Imposta la serie: valori, etichette dell'asse orizzontale (facoltative) e formato dei valori.</summary>
public void Show(IReadOnlyList<double> values, IReadOnlyList<string> labels, Func<double, string> format, Style style, Color color, string empty)
{
_values = values;
_labels = labels;
_format = format;
_style = style;
_color = color;
_empty = empty;
QueueRedraw();
}
public override void _Draw()
{
DrawStyleBox(UiTheme.Box(Palette.Inner, Palette.Border, 8, 0), new Rect2(Vector2.Zero, Size));
var font = UiTheme.Body;
const int fontSize = 11;
if (_values.Count == 0 || (_style == Style.Line && _values.Count < 2))
{
string text = _empty.Length > 0 ? _empty : T("Dati insufficienti");
var dims = font.GetStringSize(text, HorizontalAlignment.Left, -1, 13);
DrawString(font, new Vector2((Size.X - dims.X) / 2, Size.Y / 2 + 4), text, HorizontalAlignment.Left, -1, 13, Palette.TextSecondary);
return;
}
double min = _values.Min(), max = _values.Max();
if (_style == Style.Bars) min = Math.Min(0, min);
if (max - min < 1e-9)
{
max += Math.Max(1, Math.Abs(max) * 0.1);
if (_style == Style.Line) min -= Math.Max(1, Math.Abs(min) * 0.1);
}
string maxText = _format(max), minText = _format(min);
float left = 12 + Math.Max(font.GetStringSize(maxText, HorizontalAlignment.Left, -1, fontSize).X, font.GetStringSize(minText, HorizontalAlignment.Left, -1, fontSize).X) + 8;
bool hasLabels = _labels.Count == _values.Count;
var area = new Rect2(left, 12, Size.X - left - 14, Size.Y - (hasLabels ? 34 : 22));
float Y(double v) => area.End.Y - (float)((v - min) / (max - min)) * area.Size.Y;
// griglia: massimo, metà, minimo
foreach (double v in new[] { min, (min + max) / 2, max })
DrawLine(new Vector2(area.Position.X, Y(v)), new Vector2(area.End.X, Y(v)), Palette.WithAlpha(Palette.Border, 0.9f), 1);
DrawString(font, new Vector2(10, Y(max) + 4), maxText, HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
DrawString(font, new Vector2(10, Y(min) + 4), minText, HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
int n = _values.Count;
if (_style == Style.Bars)
{
float slot = area.Size.X / n;
float width = Math.Max(2, Math.Min(42, slot * 0.7f));
for (int i = 0; i < n; i++)
{
float x = area.Position.X + slot * (i + 0.5f);
float y0 = Y(Math.Max(min, 0)), y1 = Y(_values[i]);
var color = _values[i] < 0 ? Palette.Danger : i == n - 1 ? Palette.AmberLight : _color;
DrawRect(new Rect2(x - width / 2, Math.Min(y0, y1), width, Math.Max(1, Math.Abs(y1 - y0))), color);
}
DrawLabels(area, n, slot, font, fontSize, centered: true);
return;
}
float step = area.Size.X / (n - 1);
var points = new Vector2[n];
for (int i = 0; i < n; i++) points[i] = new Vector2(area.Position.X + step * i, Y(_values[i]));
var fill = new List<Vector2>(points) { new(area.End.X, area.End.Y), new(area.Position.X, area.End.Y) };
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
DrawPolyline(points, _color, 2.5f, true);
DrawCircle(points[^1], 4, Palette.AmberLight);
string last = _format(_values[^1]);
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
float lx = Math.Min(points[^1].X - lastDims.X / 2, Size.X - lastDims.X - 6);
float ly = points[^1].Y - 8 < area.Position.Y + 10 ? points[^1].Y + 18 : points[^1].Y - 8;
DrawString(UiTheme.BodyBold, new Vector2(lx, ly), last, HorizontalAlignment.Left, -1, 12, Palette.AmberLight);
DrawLabels(area, n, step, font, fontSize, centered: false);
}
/// <summary>Etichette dell'asse orizzontale, diradate per non sovrapporsi.</summary>
private void DrawLabels(Rect2 area, int n, float step, Font font, int fontSize, bool centered)
{
if (_labels.Count != n) return;
float widest = _labels.Max(l => font.GetStringSize(l, HorizontalAlignment.Left, -1, fontSize).X) + 10;
int every = Math.Max(1, (int)Math.Ceiling(widest / Math.Max(1, step)));
for (int i = 0; i < n; i++)
{
// l'ultima etichetta si aggiunge solo se non tocca la precedente
bool show = i % every == 0 || (i == n - 1 && (n - 1) % every * step >= widest);
if (!show) continue;
var dims = font.GetStringSize(_labels[i], HorizontalAlignment.Left, -1, fontSize);
float x = area.Position.X + step * (centered ? i + 0.5f : i) - dims.X / 2;
x = Math.Clamp(x, area.Position.X - 4, Size.X - dims.X - 4);
DrawString(font, new Vector2(x, area.End.Y + 16), _labels[i], HorizontalAlignment.Left, -1, fontSize, Palette.TextSecondary);
}
}
}
@@ -0,0 +1 @@
uid://cvus3vxujok5q
@@ -0,0 +1,150 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.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,126 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Client;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.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));
var help = 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);
help.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(help);
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 RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.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