F4: protocollo e client per manutenzione e impieghi, ADR 0010, stato dei lavori

- Protocollo: riepilogo di manutenzione nei record (blocco 1), RequestDetail, MaintenanceCard,
  WorkshopRegister, EmploymentReport con depositi, motivi e convenzioni, MaintenanceAlert.
- Server: dettagli su richiesta, avvisi dalla manutenzione, registro dopo le convenzioni.
- Client: pannelli Officine (cartella di manutenzione, Registro officina, scorta di ricambi,
  avvisi, mappa di calore) e Impieghi (Registro degli impieghi con convenzioni); schede
  di treno, industria e città aggiornate; pilota automatico con le nuove schermate.
- ADR 0010, PROTOCOL, ARCHITECTURE e STATE aggiornati; 102 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-02 01:54:58 +00:00
1 parent b6c326b79c
commit d285a38664
28 files changed
+1618 -64

No files matched your search

@@ -162,5 +162,27 @@ public partial class AutoPilot : Node
_game.UseTool(Tool.None);
_game.Map.SetZoom(0.06f);
await Shot("08_panoramica", 60);
// manutenzione (F4): un tagliando prenotato, cartella del treno, registro officina, mappa di calore
await Ok(new ScheduleServiceCommand(new TrainId(train2), "service"));
Session.SetSpeed(8);
await Until(() => World.Trains.TryGetValue(train2, out var t2) && t2.Maintenance == TrainMaintenanceStatus.InWorkshop, "treno in officina", 240);
Session.SetSpeed(1);
_game.OpenMaintenance(train);
_game.OpenWorkshop(depot);
await Until(() => World.Cards.ContainsKey(train) && World.Workshops.TryGetValue(depot, out var reg) && reg.Jobs.Count > 0, "cartella e registro", 30);
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("09_officine", 40);
_game.ScrollPanel(1);
await Shot("09b_registro_officina", 20);
_game.ScrollPanel(0);
_game.SetHeatMap(true);
await Shot("10_mappa_di_calore", 20);
// Registro degli impieghi (sezione 9)
_game.UseTool(Tool.Employment);
await Until(() => World.Employment is not null, "registro degli impieghi", 30);
await Shot("11_impieghi", 30);
}
}
+15 -2
View File
@@ -5,7 +5,7 @@ using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.Client.Hud;
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Market, Finance, Demolish }
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Market, Finance, Demolish }
/// <summary>Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto.</summary>
public partial class Toolbar : PanelContainer
@@ -26,7 +26,8 @@ public partial class Toolbar : PanelContainer
foreach (var (tool, label) in new[]
{
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Market, "Mercato"), (Tool.Finance, "Finanze"), (Tool.Demolish, "Demolisci"),
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
(Tool.Market, "Mercato"), (Tool.Finance, "Finanze"), (Tool.Demolish, "Demolisci"),
})
{
var b = new ToolButton(tool, T(label));
@@ -118,6 +119,18 @@ public partial class Toolbar : PanelContainer
DrawCircle(c + new Vector2(8, 8), 3.5f, col, false, w);
DrawPolyline([c + new Vector2(-4, -8), c + new Vector2(8, -8), c + new Vector2(8, -2), c + new Vector2(-8, 2), c + new Vector2(-8, 8), c + new Vector2(4, 8)], col, w);
break;
case Tool.Maintenance:
// chiave inglese
DrawArc(c + new Vector2(6, -6), 6, MathF.PI * 0.25f, MathF.PI * 1.75f, 16, col, w);
DrawLine(c + new Vector2(2, -2), c + new Vector2(-10, 10), col, w * 1.6f);
break;
case Tool.Employment:
// due persone
DrawCircle(c + new Vector2(-6, -6), 3.5f, col, false, w);
DrawCircle(c + new Vector2(6, -6), 3.5f, col, false, w);
DrawArc(c + new Vector2(-6, 9), 7, MathF.PI, MathF.Tau, 12, col, w);
DrawArc(c + new Vector2(6, 9), 7, MathF.PI, MathF.Tau, 12, col, w);
break;
case Tool.Market:
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
@@ -23,6 +23,9 @@ public partial class TrainLayer : Node2D
public int SelectedTrain { get; set; } = -1;
/// <summary>Mappa di calore della condizione (10.3): un alone colorato sotto ogni treno.</summary>
public bool HeatMap { get; set; }
/// <summary>Teste dei treni disegnate nell'ultimo fotogramma (per la selezione col mouse).</summary>
public Dictionary<int, Vector2> Heads { get; } = [];
@@ -90,6 +93,13 @@ public partial class TrainLayer : Node2D
d -= length + 1.5f * s;
if (d < 0) break;
}
if (HeatMap)
{
var hp = MapScale.V(headPoint.Value);
var col = Panels.MaintenancePanel.ConditionColor((int)motion.Condition);
DrawCircle(hp, 14 * s, Palette.WithAlpha(col, 0.35f));
DrawArc(hp, 14 * s, 0, MathF.Tau, 32, col, 2 * s);
}
if (motion.Condition < 40)
{
// icona d'avviso: triangolo ambra sopra la testa
@@ -0,0 +1,156 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.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
@@ -17,6 +17,8 @@ public partial class InfoPanel : VBoxContainer
private int _id = -1;
private double _refresh;
public event Action<int>? MaintenanceRequested;
public InfoPanel(GameSession session)
{
_session = session;
@@ -75,6 +77,17 @@ public partial class InfoPanel : VBoxContainer
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));
@@ -128,6 +141,26 @@ public partial class InfoPanel : VBoxContainer
AddChild(PanelKit.Pair(T("Produce"), PanelKit.Value(outputs)));
}
if (ind.Closed) AddChild(UiTheme.Notice(T("Chiusa")));
// 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):
@@ -136,6 +169,19 @@ public partial class InfoPanel : VBoxContainer
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:
@@ -0,0 +1,352 @@
using Godot;
using ViaFerrea.Client.App;
using ViaFerrea.Client.Net;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Protocol.Messages;
using static ViaFerrea.Client.App.Localization;
namespace ViaFerrea.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
@@ -37,6 +37,8 @@ public partial class GameScreen : Node
private DepotPanel? _depotPanel;
private LinesPanel? _linesPanel;
private InfoPanel? _info;
private MaintenancePanel? _maintenance;
private bool _heatMap;
private readonly List<Vector2> _trackPoints = [];
private Vector2? _mouse;
private bool _previewDirty;
@@ -65,6 +67,34 @@ public partial class GameScreen : Node
}
/// <summary>Mostra la scheda di un treno e lo evidenzia.</summary>
/// <summary>Apre la cartella di manutenzione del treno nel pannello Officine.</summary>
public void OpenMaintenance(int train)
{
_toolbar.Select(Tool.Maintenance);
_maintenance?.SelectTrain(train);
}
/// <summary>Apre il Registro officina del deposito nel pannello Officine.</summary>
public void OpenWorkshop(int depot)
{
if (_tool != Tool.Maintenance) _toolbar.Select(Tool.Maintenance);
_maintenance?.SelectDepot(depot);
}
/// <summary>Mappa di calore della condizione dei treni.</summary>
public void SetHeatMap(bool on)
{
_map.Trains.HeatMap = _heatMap = on;
_maintenance?.SetHeatMap(on);
}
/// <summary>Scorre il pannello laterale (0 = in cima, 1 = in fondo).</summary>
public void ScrollPanel(double fraction)
{
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
public void SelectTrain(int id)
{
_map.Trains.SelectedTrain = id;
@@ -129,6 +159,8 @@ public partial class GameScreen : Node
_session.CommandFailed += r => Toast(r.Message, error: true);
SelectTool(Tool.None);
SendViewport(force: true);
// il Registro degli impieghi alimenta anche le schede di industrie e città
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
}
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
@@ -249,6 +281,7 @@ public partial class GameScreen : Node
_depotPanel = null;
_linesPanel = null;
_info = null;
_maintenance = null;
Control panel;
switch (tool)
{
@@ -285,6 +318,19 @@ public partial class GameScreen : Node
_linesPanel.StopsChanged += UpdateStopsOverlay;
panel = _linesPanel;
break;
case Tool.Maintenance:
_maintenance = new MaintenancePanel(_session, _heatMap);
_maintenance.HeatMapToggled += on => _map.Trains.HeatMap = _heatMap = on;
_maintenance.TrainSelected += id =>
{
_map.Trains.SelectedTrain = id;
if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p);
};
panel = _maintenance;
break;
case Tool.Employment:
panel = new EmploymentPanel(_session);
break;
case Tool.Market:
panel = new MarketPanel(_session);
break;
@@ -293,6 +339,7 @@ public partial class GameScreen : Node
break;
default:
panel = _info = new InfoPanel(_session);
_info.MaintenanceRequested += OpenMaintenance;
break;
}
panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;