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

@@ -1,16 +1,21 @@
keys,it,en
Abitanti,,Population
Accetta,,Accept
Aggiorna,,Refresh
Ambra,,Amber
Annulla,,Cancel
Anteprima non disponibile: ,,Preview unavailable:
Assegna,,Assign
Attendi il pieno alla prima fermata (max 2 giorni),,Wait for full load at the first stop (max 2 days)
Attiva,,Active
Avvio del server locale…,,Starting the local server…
Binari,,Track
Binari di stazione,,Platforms
Blu,,Blue
Cantiere,,Construction
Carico,,Load
Cartella di manutenzione,,Maintenance record
Cartella in arrivo dal server…,,Record on its way from the server…
Cassa,,Cash
Celeste,,Light blue
Chiedi il prestito,,Request loan
@@ -26,34 +31,49 @@ Collegamento in corso…,,Connecting…
Collegamento non riuscito,,Connection failed
Collegati,,Connect
Collegati a un server,,Connect to a server
Come la linea o la flotta,,Same as line or fleet
Componi,,Compose
Compra veicoli,,Buy vehicles
Condizione,,Condition
Connessione persa,,Connection lost
Consuma,,Consumes
Convenzioni,,Agreements
Coperto dalla riserva,,Covered by reserve
Costi dell'anno,,Costs this year
Costo,,Cost
Costruisci,,Build
Crea linea,,Create line
Dati del gioco non trovati o non validi.,,Game data missing or invalid.
Demolisci,,Demolish
Depositi e officine,,Depots and workshops
Deposito,,Depot
Deragliamento,,Derailment
Disconnesso,,Disconnected
Doppio binario,,Double track
Dove lavorano gli abitanti,,Where residents work
Efficienza,,Efficiency
Elettrificato,,Electrified
Esci,,Quit
Finanze,,Finance
"Flotta, dal treno più usurato",,"Fleet, most worn first"
Galleria,,Tunnel
Gallerie,,Tunnels
Gestionale ferroviario dall'alto,,Top-down railway management
Grano,,Wheat
Guasti nell'anno,,Failures this year
Guasto grave,,Major failure
Guasto lieve,,Minor failure
Il server non risponde più. La partita continua sul server.,,The server is not responding. The game goes on on the server.
Impianti,,Plant
Impieghi,,Jobs
Indica l'indirizzo del server,,Enter the server address
Indietro,,Back
Indirizzo (host:porta),,Address (host:port)
Indirizzo non valido,,Invalid address
Km di servizio al giorno,,Service km per day
La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).,,The connection is not encrypted: over the Internet use a TLS reverse proxy (wss://).
Lavoratori,,Workers
Lavoratori e personale,,Workers and staff
Linea,,Line
Linee,,Lines
Linee della compagnia,,Company lines
@@ -61,33 +81,57 @@ Livello,,Level
Locomotiva,,Locomotive
Lunghezza,,Length
Manda al deposito,,Send to depot
Manutenzione,,Maintenance
Mappa di calore della condizione,,Condition heat map
Mercato,,Market
Merci e passeggeri in attesa,,Waiting goods and passengers
Minimappa,,Minimap
Nel bacino,,In the catchment
Nessun posto di lavoro servito dai tuoi treni.,,No workplace served by your trains.
Nessun tracciato,,No route
Nessun treno in officina,,No trains in the workshop
Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno.,,No agreements: industries offer one when your trains carry at least 20 commuters a day.
Nessuna linea,,No line
Nome automatico,,Automatic name
Nome del treno,,Train name
Nome della linea,,Line name
Notizie,,News
Officine,,Workshops
"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é.",,"Every month towns send their workers to the industries and depots your trains reach within 60 minutes (staff: 90). Here you see where they come from, how many jobs stay vacant and why."
Ordina,,Order
Partita locale,,Local game
Partita locale non avviata,,Local game not started
Patrimonio netto,,Net worth
Pausa,,Pause
Pendenza massima,,Max gradient
Personale,,Staff
Politica del treno,,Train policy
Politica della flotta,,Fleet policy
Ponte,,Bridge
Ponti,,Bridges
Posti di lavoro,,Workplaces
Prenotato,,Booked
Prestito,,Loan
Prezzi globali di oggi (la borsa arriva in seguito).,,Today's global prices (the stock market comes later).
Produce,,Produces
Prossimo intervento,,Next intervention
Quota rispetto al terreno,,Height above ground
Raggio minimo,,Min radius
Rating,,Rating
Regione di,,Region of
Registro degli impieghi,,Employment register
Registro in arrivo dal server…,,Register on its way from the server…
Registro officina,,Workshop register
Ricambi,,Spare parts
Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto.,,Spare parts exhausted: interventions are waiting. Bring parts by train from a machine factory or a port.
Ricambi già destinati,,Parts already allocated
Rifiuta,,Reject
Rilevato,,Embankment
Ritmo di lavoro (manca personale),,Work rate (staff shortage)
Rosso coppo,,Tile red
"Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda.",,"Pick a tool on the left or click a train, station, industry or town to see its card."
Scorta desiderata,,Target stock
Se la capacità manca per 30 giorni la convenzione salta con una penale.,,If capacity falls short for 30 days the agreement breaks with a penalty.
Segnali,,Signals
Seleziona i veicoli da comporre,,Select the vehicles to compose
Seleziona un treno,,Select a train
@@ -97,34 +141,76 @@ Server locale non trovato: compila src/ViaFerrea.Server o imposta VF_SERVER_PATH
Servizi,,Services
Servono almeno due fermate,,At least two stops are needed
Soddisfazione,,Satisfaction
Stalli,,Stalls
Stato,,Status
Stazione,,Station
Storico,,History
Svuota,,Clear
Token,,Token
Token del server,,Server token
Torna al menu,,Back to menu
Treni,,Trains
Treni della compagnia,,Company trains
Treno di riserva in deposito,,Reserve train in depot
Trincea,,Cutting
Veicoli,,Vehicles
"Veicoli liberi nel deposito (selezione multipla, in ordine)",,"Free vehicles in the depot (multiple selection, in order)"
Velocità,,Speed
Verde,,Green
Via Ferrea,,Via Ferrea
a piedi,,on foot
abitanti,,inhabitants
al mese,,per month
anni,,years
attende i ricambi,,waiting for parts
attendi il pieno,,wait for full load
capacità delle carrozze insufficiente sulla,,not enough coach capacity on
capacità mancante da,,capacity short for
carica,,load
città senza servizi per il personale,,towns without services for staff
copertura,,coverage
da,,from
fermo in linea,,stranded on the line
fermo in salita,,stalled on grade
g,,d
giorni,,days
giorno,,day
guasto,,broken down
guasto lieve,,minor failure
hub mercato mondiale,,world market hub
in arrivo,,arriving
in attesa,,waiting
in attesa di via libera,,waiting for clearance
in coda,,queued
in deposito,,in depot
in marcia,,running
in officina,,in the workshop
in servizio,,in service
in stazione,,at station
intervento prenotato,,intervention booked
large,Grande,Large
lavoratori,,workers
lavori,,jobs
le città raggiungibili non hanno lavoratori liberi,,reachable towns have no free workers
linea,,line
medium,Medio,Medium
mila km,,thousand km
nessuna città raggiungibile entro,,no town reachable within
nessuna stazione serve il posto di lavoro,,no station serves the workplace
ore,,hours
personale,,staff
posti al giorno garantiti,,guaranteed seats a day
ricambi,,parts
rimorchiato,,towed
riserva,,reserve
scaduta,,overdue
scaduto,,overdue
scarica,,unload
senza linea,,no line
senza percorso,,no route
small,Piccolo,Small
soccorso tra,,rescue in
stallo,,stall
tecnici,,staff
tra,,in
treni,,trains
1 keys it en
2 Abitanti Population
3 Accetta Accept
4 Aggiorna Refresh
5 Ambra Amber
6 Annulla Cancel
7 Anteprima non disponibile: Preview unavailable:
8 Assegna Assign
9 Attendi il pieno alla prima fermata (max 2 giorni) Wait for full load at the first stop (max 2 days)
10 Attiva Active
11 Avvio del server locale… Starting the local server…
12 Binari Track
13 Binari di stazione Platforms
14 Blu Blue
15 Cantiere Construction
16 Carico Load
17 Cartella di manutenzione Maintenance record
18 Cartella in arrivo dal server… Record on its way from the server…
19 Cassa Cash
20 Celeste Light blue
21 Chiedi il prestito Request loan
31 Collegamento non riuscito Connection failed
32 Collegati Connect
33 Collegati a un server Connect to a server
34 Come la linea o la flotta Same as line or fleet
35 Componi Compose
36 Compra veicoli Buy vehicles
37 Condizione Condition
38 Connessione persa Connection lost
39 Consuma Consumes
40 Convenzioni Agreements
41 Coperto dalla riserva Covered by reserve
42 Costi dell'anno Costs this year
43 Costo Cost
44 Costruisci Build
45 Crea linea Create line
46 Dati del gioco non trovati o non validi. Game data missing or invalid.
47 Demolisci Demolish
48 Depositi e officine Depots and workshops
49 Deposito Depot
50 Deragliamento Derailment
51 Disconnesso Disconnected
52 Doppio binario Double track
53 Dove lavorano gli abitanti Where residents work
54 Efficienza Efficiency
55 Elettrificato Electrified
56 Esci Quit
57 Finanze Finance
58 Flotta, dal treno più usurato Fleet, most worn first
59 Galleria Tunnel
60 Gallerie Tunnels
61 Gestionale ferroviario dall'alto Top-down railway management
62 Grano Wheat
63 Guasti nell'anno Failures this year
64 Guasto grave Major failure
65 Guasto lieve Minor failure
66 Il server non risponde più. La partita continua sul server. The server is not responding. The game goes on on the server.
67 Impianti Plant
68 Impieghi Jobs
69 Indica l'indirizzo del server Enter the server address
70 Indietro Back
71 Indirizzo (host:porta) Address (host:port)
72 Indirizzo non valido Invalid address
73 Km di servizio al giorno Service km per day
74 La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://). The connection is not encrypted: over the Internet use a TLS reverse proxy (wss://).
75 Lavoratori Workers
76 Lavoratori e personale Workers and staff
77 Linea Line
78 Linee Lines
79 Linee della compagnia Company lines
81 Locomotiva Locomotive
82 Lunghezza Length
83 Manda al deposito Send to depot
84 Manutenzione Maintenance
85 Mappa di calore della condizione Condition heat map
86 Mercato Market
87 Merci e passeggeri in attesa Waiting goods and passengers
88 Minimappa Minimap
89 Nel bacino In the catchment
90 Nessun posto di lavoro servito dai tuoi treni. No workplace served by your trains.
91 Nessun tracciato No route
92 Nessun treno in officina No trains in the workshop
93 Nessuna convenzione: le industrie la propongono quando i tuoi treni portano almeno 20 pendolari al giorno. No agreements: industries offer one when your trains carry at least 20 commuters a day.
94 Nessuna linea No line
95 Nome automatico Automatic name
96 Nome del treno Train name
97 Nome della linea Line name
98 Notizie News
99 Officine Workshops
100 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é. Every month towns send their workers to the industries and depots your trains reach within 60 minutes (staff: 90). Here you see where they come from, how many jobs stay vacant and why.
101 Ordina Order
102 Partita locale Local game
103 Partita locale non avviata Local game not started
104 Patrimonio netto Net worth
105 Pausa Pause
106 Pendenza massima Max gradient
107 Personale Staff
108 Politica del treno Train policy
109 Politica della flotta Fleet policy
110 Ponte Bridge
111 Ponti Bridges
112 Posti di lavoro Workplaces
113 Prenotato Booked
114 Prestito Loan
115 Prezzi globali di oggi (la borsa arriva in seguito). Today's global prices (the stock market comes later).
116 Produce Produces
117 Prossimo intervento Next intervention
118 Quota rispetto al terreno Height above ground
119 Raggio minimo Min radius
120 Rating Rating
121 Regione di Region of
122 Registro degli impieghi Employment register
123 Registro in arrivo dal server… Register on its way from the server…
124 Registro officina Workshop register
125 Ricambi Spare parts
126 Ricambi esauriti: gli interventi aspettano. Porta i ricambi in treno da una fabbrica di macchinari o da un porto. Spare parts exhausted: interventions are waiting. Bring parts by train from a machine factory or a port.
127 Ricambi già destinati Parts already allocated
128 Rifiuta Reject
129 Rilevato Embankment
130 Ritmo di lavoro (manca personale) Work rate (staff shortage)
131 Rosso coppo Tile red
132 Scegli uno strumento a sinistra oppure fai clic su un treno, una stazione, un'industria o una città per vederne la scheda. Pick a tool on the left or click a train, station, industry or town to see its card.
133 Scorta desiderata Target stock
134 Se la capacità manca per 30 giorni la convenzione salta con una penale. If capacity falls short for 30 days the agreement breaks with a penalty.
135 Segnali Signals
136 Seleziona i veicoli da comporre Select the vehicles to compose
137 Seleziona un treno Select a train
141 Servizi Services
142 Servono almeno due fermate At least two stops are needed
143 Soddisfazione Satisfaction
144 Stalli Stalls
145 Stato Status
146 Stazione Station
147 Storico History
148 Svuota Clear
149 Token Token
150 Token del server Server token
151 Torna al menu Back to menu
152 Treni Trains
153 Treni della compagnia Company trains
154 Treno di riserva in deposito Reserve train in depot
155 Trincea Cutting
156 Veicoli Vehicles
157 Veicoli liberi nel deposito (selezione multipla, in ordine) Free vehicles in the depot (multiple selection, in order)
158 Velocità Speed
159 Verde Green
160 Via Ferrea Via Ferrea
161 a piedi on foot
162 abitanti inhabitants
163 al mese per month
164 anni years
165 attende i ricambi waiting for parts
166 attendi il pieno wait for full load
167 capacità delle carrozze insufficiente sulla not enough coach capacity on
168 capacità mancante da capacity short for
169 carica load
170 città senza servizi per il personale towns without services for staff
171 copertura coverage
172 da from
173 fermo in linea stranded on the line
174 fermo in salita stalled on grade
175 g d
176 giorni days
177 giorno day
178 guasto broken down
179 guasto lieve minor failure
180 hub mercato mondiale world market hub
181 in arrivo arriving
182 in attesa waiting
183 in attesa di via libera waiting for clearance
184 in coda queued
185 in deposito in depot
186 in marcia running
187 in officina in the workshop
188 in servizio in service
189 in stazione at station
190 intervento prenotato intervention booked
191 large Grande Large
192 lavoratori workers
193 lavori jobs
194 le città raggiungibili non hanno lavoratori liberi reachable towns have no free workers
195 linea line
196 medium Medio Medium
197 mila km thousand km
198 nessuna città raggiungibile entro no town reachable within
199 nessuna stazione serve il posto di lavoro no station serves the workplace
200 ore hours
201 personale staff
202 posti al giorno garantiti guaranteed seats a day
203 ricambi parts
204 rimorchiato towed
205 riserva reserve
206 scaduta overdue
207 scaduto overdue
208 scarica unload
209 senza linea no line
210 senza percorso no route
211 small Piccolo Small
212 soccorso tra rescue in
213 stallo stall
214 tecnici staff
215 tra in
216 treni trains
@@ -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;