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>
368 lines
18 KiB
C#
368 lines
18 KiB
C#
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;
|
||
}
|
||
}
|