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:
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
|
||||
|
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -43,7 +43,7 @@ Clock → Commands → Construction → Trains → Signals → Stations → Main
|
||||
→ Finance → StockMarket → AiAgents (mensile) → Events → Contracts → Hash (giornaliero)
|
||||
```
|
||||
|
||||
Sistemi implementati (F1–F2), nella loro posizione:
|
||||
Sistemi implementati (F1–F4), nella loro posizione:
|
||||
|
||||
| Sistema | Frequenza | Cosa fa |
|
||||
|---|---|---|
|
||||
@@ -53,8 +53,9 @@ Sistemi implementati (F1–F2), nella loro posizione:
|
||||
| `TrainSystem` | tick | percorsi, prenotazioni di blocchi, versi e binari di stazione fino al punto sicuro, fisica, soste, carico e scarico (`StationWork`), `Stalled` |
|
||||
| `StationSystem` | giorno | bacini (mensili), scadenze dei pacchetti, consegne in attesa del consumatore, ritiro della produzione verso la destinazione migliore |
|
||||
| `LocalTransportSystem` | giorno | trasporto locale su strada tra produttori, consumatori e hub entro 3 km (posto di «Stations», ADR 0004) |
|
||||
| `FleetMaintenanceSystem` | giorno | usura per componente in km di servizio, rischio e guasti (lieve, grave con soccorso, deragliamento), pianificatore predittivo e prenotazioni, officine con stalli, ricambi e personale, riserve, avvisi (posto di «Maintenance», ADR 0010); formule senza stato in `Fleet` |
|
||||
| `DemandSystem` | giorno | domanda delle città (con elasticità) e input richiesti dalle industrie |
|
||||
| `EmploymentSystem` | giorno/mese | servizi cittadini, lavoratori in sede, contratti a piedi e su rotaia (abbinamento mensile sul `LineGraph`), pacchetti giornalieri dei pendolari, presenze e coperture (posto di «Commuting», ADR 0008) |
|
||||
| `EmploymentSystem` | giorno/mese | servizi cittadini, lavoratori in sede, contratti a piedi e su rotaia per industrie e depositi (`IWorkplace`, abbinamento mensile sul `LineGraph`), motivi dei posti scoperti, convenzioni, pacchetti giornalieri dei pendolari, presenze e coperture (posto di «Commuting», ADR 0008 e 0010) |
|
||||
| `IndustrySystem` | giorno/trimestre/anno | produzione, esaurimento giacimenti, salari, crescita delle industrie servite, chiusure, nascite |
|
||||
| `TownSystem` | giorno/mese/anno | consumo e soddisfazione, crescita, migrazione, espansione dell'abitato |
|
||||
| `MarketSystem` | giorno | prezzi globali con componente mondiale e shock, domanda insoddisfatta |
|
||||
@@ -96,13 +97,14 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- `SaveFile`: intestazione `VFSV` leggibile senza decomprimere, corpo Brotli scritto da `WorldSerializer` con `SaveWriter` (little endian, nessuna reflection).
|
||||
- Definizioni salvate per id testuale e rimappate al caricamento; terreno salvato per intero.
|
||||
- `StateHasher` = XxHash64 di `WorldSerializer.WriteDynamic` (stato senza terreno, impostazioni ed eventi; il terreno entra con il suo hash). Dettagli: ADR 0006.
|
||||
- Corpo versione 2 (F4): `MaintenanceSerializer` aggiunge in coda allo stato dinamico manutenzione di veicoli e treni, officine, politiche, convenzioni e motivi dei posti scoperti; i salvataggi della versione 1 si migrano (ADR 0010).
|
||||
|
||||
## 8. Server
|
||||
|
||||
- `ServerProgram`: Kestrel minimale, log JSON su stdout, configurazione da ambiente (`ServerConfig`: `VF_PORT`, `VF_TOKEN`, `VF_DATA_DIR`, `VF_TICK_MS`, `VF_AUTOSAVE_MIN`, `VF_SEED`, `VF_MAP_SIZE`, `VF_DIFFICULTY`, `VF_LOG_LEVEL`) e argomenti `--local` (127.0.0.1 su porta casuale, stampa `LISTENING porta`), `--healthcheck`, `--token`, `--port`, `--data`.
|
||||
- `GameHost`: possiede il mondo su un thread dedicato. Ogni giro drena la coda delle azioni (messaggi delle sessioni, richieste HTTP), esegue i tick dovuti con un accumulatore (velocità 0/1/2/4/8, budget `VF_TICK_MS`), adegua la velocità effettiva se i tick costano troppo (`slow`), pubblica e fa l'autosave a rotazione.
|
||||
- `Session` / `SessionEndpoint`: WebSocket su `/ws`, primo frame `Hello`, coda d'invio a due classi (affidabili e moti scartabili), ripresa con `sessionId` entro 120 s.
|
||||
- `Projection`: mondo → record del protocollo (entità, archi, chunk, moto dei treni, resoconti); i delta per sessione si calcolano con gli hash dei record.
|
||||
- `Projection`: mondo → record del protocollo (entità, archi, chunk, moto dei treni, resoconti, cartelle di manutenzione, registri officina, Registro degli impieghi); i delta per sessione si calcolano con gli hash dei record; i dettagli F4 si mandano su `RequestDetail`, gli avvisi di manutenzione (`World.Alerts`) come `MaintenanceAlert`.
|
||||
- `SaveStore`: salvataggi `.vfsave` in `$VF_DATA_DIR/saves`, ultimi cinque automatici; all'avvio si riprende il più recente.
|
||||
- HTTP: `/health`, `/metrics` (Prometheus), `GET/POST /api/saves`, `GET /api/saves/{id}`.
|
||||
- Docker: `docker/Dockerfile` (build in due stadi, utente non root, healthcheck), `docker-compose.yml`, `unraid-template.xml`; `scripts/publish-image.sh` per il registry Gitea.
|
||||
@@ -113,7 +115,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- `Main` → `MenuScreen` / `ConnectScreen` / `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
|
||||
- `GameSession` applica i messaggi a `ClientWorld` (Protocol) sul thread principale; i comandi sono l'unico modo di cambiare il mondo; le anteprime del tracciato usano `TrackPreview` di Core.
|
||||
- `MapView` (Node2D + Camera2D): `TerrainLayer` (texture per chunk con fasce, ombreggiatura, sponde e curve di livello; shader per le rive), `EntityLayer` (case, industrie, stazioni, depositi, alberi in MultiMesh), `TrackLayer` (massicciata, traversine, rotaie, opere, cantieri, segnali), `TrainLayer` (veicoli interpolati, fumo, avvisi), `ToolOverlay`; `LabelLayer` disegna le etichette in coordinate schermo.
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, mercato, finanze, scheda dell'entità.
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze, scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti).
|
||||
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
|
||||
|
||||
## 10. Prestazioni
|
||||
|
||||
+33
-9
@@ -43,6 +43,9 @@ offset tipo campo
|
||||
- I campi nuovi si aggiungono in coda, dopo il byte `flags`, che dice quali blocchi seguono. Un
|
||||
lettore vecchio ignora i byte residui; un messaggio vecchio senza `flags` vale 0.
|
||||
- `protocolVersion` (oggi 1) cresce solo per modifiche incompatibili.
|
||||
- Blocchi: il bit 0 di `flags` annuncia il blocco 1 (campi della fase F4), i bit successivi i blocchi
|
||||
delle fasi future. Messaggi e comandi nuovi prendono id nuovi; un lettore vecchio scarta i messaggi
|
||||
che non conosce.
|
||||
|
||||
## 3. Handshake
|
||||
|
||||
@@ -74,6 +77,7 @@ costMultiplier: f64 }`
|
||||
| 7 | Save | `name: string` |
|
||||
| 8 | Load | `saveId: string` |
|
||||
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
|
||||
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi), `target: i32` (id del treno o del deposito; ignorato per 3). Aggiunto in F4 |
|
||||
|
||||
### Comandi (`Command.type`, payload in ordine)
|
||||
|
||||
@@ -119,8 +123,11 @@ costMultiplier: f64 }`
|
||||
| 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` |
|
||||
|
||||
`LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`.
|
||||
I codici coincidono con l'enum `CommandType` di Core. Fino alla loro fase i comandi 15–18 e 21–38
|
||||
(tranne 26) rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
|
||||
I codici coincidono con l'enum `CommandType` di Core. Dalla F4 i comandi 15–18 e 21–22 sono attivi
|
||||
(`policy`: `economy`, `standard`, `thorough`, oppure `inherit` per togliere l'eccezione di linea o
|
||||
treno; `intervention`: `inspection`, `service`, `overhaul`; `OrderParts` fissa la scorta desiderata
|
||||
del deposito). Fino alla loro fase i comandi 23–38 (tranne 26) rispondono `NotImplemented`. Il server
|
||||
imposta l'emittente in base alla sessione.
|
||||
|
||||
## 5. Messaggi Server → Client
|
||||
|
||||
@@ -136,8 +143,10 @@ I codici coincidono con l'enum `CommandType` di Core. Fino alla loro fase i coma
|
||||
| 114 | TrainMotion | `trainId: i32`, `tick: i64`, `state: u8`, `condition: f32`, `speed: f32` (m/s), `lengthM: f32`, `headDistance: f64`, `segments: [(edge: i32, forward: bool, fromS: f64, toS: f64)]` |
|
||||
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32` |
|
||||
| 121 | MaintenanceAlert | `train: i32`, `depot: i32`, `component: string`, `condition: f32`, `dueDays: i32`, `text: string` |
|
||||
| 122 | EmploymentReport | `day: i64`, `rows: [EmploymentRow]` (mensile) |
|
||||
| 122 | EmploymentReport | `day: i64`, `rows: [EmploymentRow]`; blocco 1: `agreements: [AgreementInfo]` (mensile, su richiesta e dopo Accept/RejectAgreement) |
|
||||
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
|
||||
| 124 | MaintenanceCard | `train, day: i64, condition: f32, status: u8, policy: u8, policyOverride: u8, reserve, failure: u8, failedVehicle, failedComponent: string, rescueHours: f32, nextIntervention: string, nextDueDays: f32, plannedIntervention: string, maintenanceDepot, serviceKmPerDay: f32, costThisYear: Money, costLastYear: Money, failuresThisYear, failuresTotal, coveredBy, covering, vehicles: [VehicleCard], history: [MaintenanceRecordInfo]` (su richiesta, F4) |
|
||||
| 125 | WorkshopRegister | `depot, day: i64, stalls, jobsStaff, staffPresent: f32, workRate: f32, spareParts, partsTarget, partsReserved, jobs: [WorkshopJobInfo], booked: [WorkshopJobInfo]` (su richiesta, F4) |
|
||||
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
|
||||
| 131 | Notification | `EventInfo` |
|
||||
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
|
||||
@@ -146,19 +155,29 @@ I codici coincidono con l'enum `CommandType` di Core. Fino alla loro fase i coma
|
||||
Record (ognuno chiude con `flags`):
|
||||
|
||||
- `EntityLists`: liste in quest'ordine di `CompanyInfo`, `TownInfo`, `IndustryInfo`, `HubInfo`, `NodeInfo`, `StationInfo`, `DepotInfo`, `LineInfo`, `VehicleInfo`, `TrainInfo`.
|
||||
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`
|
||||
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`; blocco 1: `maintenancePolicy: u8` (0 economica, 1 standard, 2 accurata)
|
||||
- `TownInfo { id, name, position: Vec2, population: i32, radiusCells: f64, satisfaction: f32, services: i32 }`
|
||||
- `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }`
|
||||
- `HubInfo { id, kind: string, name, position }`
|
||||
- `NodeInfo { id, position, heightM: f64, owner, station, depot, edges: [i32] }`
|
||||
- `StationInfo { id, owner, name, node, position, platforms: i32, waitingUnits: i32, industries: [i32], towns: [i32] }`
|
||||
- `DepotInfo { id, owner, name, node, position, size: string }`
|
||||
- `LineInfo { id, owner, name, color, stops: [LineStop] }`
|
||||
- `DepotInfo { id, owner, name, node, position, size: string }`; blocco 1: `stalls, jobsStaff, staffPercent: u8, spareParts, partsTarget, jobs, waitingParts: bool`
|
||||
- `LineInfo { id, owner, name, color, stops: [LineStop] }`; blocco 1: `policy: u8` (255 = quella della compagnia)
|
||||
- `VehicleInfo { id, owner, type: string, depot, train, condition: f32 }`
|
||||
- `TrainInfo { id, owner, name, line, state: u8, vehicles: [i32], maxSpeedKmh: f32, lengthM: f32, load: i32, capacity: i32, depot: i32 }`
|
||||
- `TrainInfo { id, owner, name, line, state: u8, vehicles: [i32], maxSpeedKmh: f32, lengthM: f32, load: i32, capacity: i32, depot: i32 }`;
|
||||
blocco 1: `condition: u8` (componente più debole), `maintenance: u8` (0 in servizio, 1 intervento prenotato, 2 in officina,
|
||||
3 guasto lieve, 4 fermo in linea, 5 rimorchiato), `reserve: bool`, `policy: u8` (255 = ereditata), `nextIntervention: string`,
|
||||
`nextDueDays: i32`, `maintenanceDepot: i32`
|
||||
- `EdgeInfo { id, owner, a, b, trackClass: u8, doubleTrack, electrified, state: u8, condition: f32, structureCondition: f32, progress: f32, samples: [(s, x, y, h, ground: f64, kind: u8, speedLimitKmh: f64)], signals: [f64] }`
|
||||
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`
|
||||
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`
|
||||
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`;
|
||||
blocco 1: `kind: u8` (0 industria, 1 deposito: `industry` è allora l'id del deposito), `workersReason: u8`, `staffReason: u8`
|
||||
(0 nessuno, 1 nessuna stazione, 2 nessuna città entro il tempo massimo, 3 nessun lavoratore libero, 4 città senza servizi
|
||||
per il personale, 5 capacità delle carrozze insufficiente), `workersReasonLine: i32`, `staffReasonLine: i32`
|
||||
- `AgreementInfo { id, industry, carrier, seatsPerDay, monthlyFee: Money, state: u8 (0 proposta, 1 attiva, 2 rifiutata, 3 scaduta, 4 saltata, 5 conclusa), proposedDay: i64, startDay: i64, endDay: i64, coverage: f32, shortDays }`
|
||||
- `VehicleCard { vehicle, type: string, odometerKm: f32, ageYears: f32, ageFactor: f32, components: [ComponentCard { component: string, condition: f32, wearPerDay: f32 }] }`
|
||||
- `MaintenanceRecordInfo { day: i64, intervention: string, cost: Money, depot, parts }`
|
||||
- `WorkshopJobInfo { train, intervention: string, inStall, started, progress: f32, days: f32, parts, queuedDay: i64 }`
|
||||
- `SharePrice { company, price: Money, change: f32, listed }`, `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }`
|
||||
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
|
||||
|
||||
@@ -172,7 +191,12 @@ Record (ognuno chiude con `flags`):
|
||||
per quelli fermi: al massimo 10 aggiornamenti al secondo per treno. Il client avanza la testa a
|
||||
velocità costante tra un moto e l'altro (fattore 60: un tick = 3 s di orologio dei treni).
|
||||
- `DailyDigest` a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non
|
||||
informativi della compagnia della sessione.
|
||||
informativi della compagnia della sessione; `MaintenanceAlert` quando un treno scende sotto le soglie
|
||||
d'avviso (40) o critica (30) e quando un'officina resta senza ricambi.
|
||||
- Dettagli su richiesta (F4): `MaintenanceCard`, `WorkshopRegister` ed `EmploymentReport` rispondono a
|
||||
`RequestDetail` per entità della compagnia della sessione (le richieste per entità altrui o
|
||||
inesistenti non hanno risposta). Il client li richiede mentre il pannello è aperto (una volta al
|
||||
secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità.
|
||||
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
|
||||
sessione si chiude (il client può riprenderla).
|
||||
- Obiettivo di banda in regime: < 100 KB/s per client.
|
||||
+23
-4
@@ -54,13 +54,27 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Accettazione F3 verificata senza intervento umano: test in processo (linea con ponte via WebSocket, anteprima identica al server, scarto client/server sotto 1 cm), `viaferrea-tools smoke` contro il container Docker (ponte di 275 m, scarto 0,00 m) e pilota automatico del client Godot con schermate (`docs/screenshots/`).
|
||||
- 85 test.
|
||||
|
||||
### F4 — Pendolarismo e manutenzione dei treni
|
||||
- Manutenzione della flotta (`FleetMaintenanceSystem`, formule in `Fleet`, ADR 0010): usura giornaliera per componente in km di servizio (`wear.distanceScale` = 30 km per km simulato) con pendenza, alta velocità, carico, età e difficoltà; rischio di guasto del componente più esposto; guasti lievi (velocità dimezzata fino al deposito), gravi (fermo in linea con soccorso dal deposito o da una riserva, poi rimorchio) e deragliamenti (carico perso, binario chiuso tre giorni, notizia e insoddisfazione); effetti su velocità, consumo, comfort e rivendita.
|
||||
- Interventi (ispezione, tagliando, revisione, riparazioni, ricostruzione) con costi e ricambi per veicolo, effetti scalati dalla politica; officine con stalli in ordine d'arrivo, lavori che aspettano i ricambi occupando lo stallo e ritmo ridotto senza personale; politiche per flotta, linea e treno; pianificatore predittivo (scadenze della politica e stima del giorno a condizione 40) con scelta del deposito raggiungibile e con ricambi; treni di riserva che coprono le linee durante gli interventi lunghi; avvisi sotto 40 e 30 e per ricambi esauriti.
|
||||
- Ricambi via treno: depositi consumatori di `spare_parts` nel bacino delle stazioni, scorta desiderata (`OrderParts`), importazione dagli hub verso la stazione con più bisogno.
|
||||
- Pendolarismo completo: depositi come posti di lavoro (personale e operai per stallo), motivi dei posti scoperti nel Registro degli impieghi, convenzioni `CommuteAgreement` proposte dalle industrie (canone, copertura, rottura con penale) con i comandi Accetta e Rifiuta.
|
||||
- Comandi attivi: `SetReserve`, `SetMaintenancePolicy`, `ScheduleService`, `OrderParts`, `AcceptAgreement`, `RejectAgreement`.
|
||||
- Circolazione: inversione di marcia in un nodo intermedio come sosta tecnica e transito in stazione che libera l'arco d'arrivo (due stalli trovati con i viaggi verso le officine).
|
||||
- Salvataggio: corpo versione 2 con sezione di manutenzione e migrazione dei salvataggi F3.
|
||||
- Protocollo: riepilogo di manutenzione nei record (blocco 1), `RequestDetail` (10), `MaintenanceCard` (124), `WorkshopRegister` (125), `EmploymentReport` con depositi, motivi e convenzioni, `MaintenanceAlert` dagli avvisi.
|
||||
- Client: pannelli «Officine» (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione con componenti e storico, Registro officina, scorta di ricambi, mappa di calore della condizione) e «Impieghi» (Registro degli impieghi con convenzioni da accettare o rifiutare); schede di treno, industria e città con i dati nuovi; schermate in `docs/screenshots/f4-*.jpg`.
|
||||
- Test di 14.5 su manutenzione (rischio monotono, usura monotona nei fattori, condizione che non sale senza interventi, tagliando/revisione/ispezione con la condizione attesa, pianificatore sopra 30 con politica Standard e ricambi) e pendolarismo; guasto grave con soccorso e riserva, deragliamento, ricambi dal porto, politiche, salvataggio a metà officina, convenzioni, registro, dettagli via WebSocket.
|
||||
- Accettazione F4 (rete di Valdoria con officina a Valdoria e due treni per linea): senza la linea dei ricambi la flotta scende sotto 40 al giorno 697 con 12 guasti (19,5 per milione di km di servizio); con la linea dal Porto di Levante resta sopra 73 con 3 guasti (3,2 per milione di km).
|
||||
- 102 test.
|
||||
|
||||
## In corso
|
||||
|
||||
- Nessun lavoro a metà: F3 chiusa.
|
||||
- Nessun lavoro a metà: F4 chiusa.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F4: pendolarismo completo (Registro degli impieghi, convenzioni `CommuteAgreement`, posti di personale nei depositi) e manutenzione dei treni della sezione 10 (componenti, guasti, soccorso, interventi, ricambi via treno, politiche, pianificatore predittivo, riserve); accettazione nello scenario con e senza linea dei ricambi.
|
||||
- F5: manutenzione delle industrie (sezione 11: condizione degli impianti, fermi, ammodernamenti, acquisto delle industrie con il pannello del proprietario), poi agenti IA, borsa, quotazione e scalate (sezione 12) con i test di 14.5 e il determinismo con le IA.
|
||||
|
||||
## Limiti noti
|
||||
|
||||
@@ -72,8 +86,9 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
|
||||
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
|
||||
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
|
||||
- I depositi non hanno ancora posti per personale né officine (F4); le convenzioni (`CommuteAgreement`) e il Registro degli impieghi arrivano in F4.
|
||||
- Comandi ancora `NotImplemented`: riserve, politiche di manutenzione, interventi, ricambi, convenzioni, commercio, industrie, borsa, concessioni, contratti, ricerca, regioni (fasi F4–F7).
|
||||
- Comandi ancora `NotImplemented`: commercio, industrie, borsa, concessioni, contratti, ricerca, regioni (fasi F5–F7).
|
||||
- Manutenzione (ADR 0010): il viaggio verso l'officina si stima in linea d'aria; un treno rimorchiato completa il tratto in corso prima di dirigersi all'officina; con un solo treno su una linea di pendolari e un deposito senza personale la copertura cala durante gli interventi (servono riserve e personale); la mappa dei flussi dei pendolari (frecce blu, opzionale nella guida) non è ancora disegnata.
|
||||
- Una rete a binario semplice con pochi binari di stazione può ancora bloccarsi se tutti i binari alle due estremità sono occupati da treni che devono incrociarsi (stallo di capacità segnalato al giocatore come «possibile stallo»): la rete dell'accettazione F4 è dimensionata di conseguenza.
|
||||
- La manutenzione degli impianti (sezione 11) arriva in F5: fino ad allora la condizione delle industrie resta 100.
|
||||
|
||||
## Misure di prestazione
|
||||
@@ -93,3 +108,7 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
| `smoke` contro il container (64 km, tick 50 ms) | 48 s: 28 giorni di cantiere a 8×, treno in moto, scarto 0,00 m | F3 |
|
||||
| Build del client Godot (Debug) | ~13 s | F3 |
|
||||
| Pilota automatico del client sotto Xvfb | ~60 s, 8 schermate | F3 |
|
||||
| `bench --trains 2000` con la manutenzione | tick medio 0,97–1,02 ms, p99 1,6–2,0; cambio di giorno ~19 ms (hash 10, manutenzione 5, stazioni 2) | F4 |
|
||||
| Accettazione F4 (due corse di 3 anni, 6–7 treni) | 3,7 s | F4 |
|
||||
| Suite di test (102, parallela su 4 core) | ~15 s | F4 |
|
||||
| Pilota automatico del client con i pannelli F4 | ~90 s, 12 schermate | F4 |
|
||||
@@ -0,0 +1,102 @@
|
||||
# ADR 0010 — Manutenzione della flotta, officine e pendolarismo completo (F4)
|
||||
|
||||
Stato: accettato (F4).
|
||||
|
||||
## Contesto
|
||||
|
||||
Le sezioni 9 e 10 della guida fissano componenti, formule di usura e rischio, interventi, politiche e
|
||||
pianificatore, ma lasciano aperti: la scala dei chilometri rispetto all'orologio dei treni, la misura
|
||||
della «condizione della flotta», se costi e ricambi valgano per treno o per veicolo, cosa succede quando
|
||||
i ricambi mancano, i tempi del soccorso, il rallentamento delle officine sotto metà personale, i termini
|
||||
delle convenzioni e come portare cartelle e registri al client senza appesantire il protocollo.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Km di servizio.** Un giorno di calendario contiene 12 minuti di marcia (fattore 60, 240 tick da 3 s):
|
||||
un treno percorre 6–15 km al giorno, 2.000–5.000 km l'anno. Con questi km le ispezioni ogni 45 giorni
|
||||
(+10 agli altri componenti) compenserebbero per sempre l'usura e la flotta non scenderebbe mai.
|
||||
Ogni km simulato vale quindi `wear.distanceScale` = 30 km di servizio: un giorno di calendario
|
||||
rappresenta l'esercizio di tutta una giornata. La scala vale per usura, contachilometri dei veicoli e
|
||||
intervalli in km (ispezione ogni 3.000 km ≈ ogni 15 giorni, tagliando ogni 15.000 km ≈ 75 giorni).
|
||||
Il valore è tarato su due vincoli: l'accettazione F4 (con e senza ricambi) e il test di pendolarismo
|
||||
(14.5) con un solo treno e un deposito senza personale, che con scale da 35 in su scende sotto 0,9.
|
||||
2. **Condizione.** La condizione di un veicolo e di un treno è quella del componente più debole (lo stesso
|
||||
che determina il rischio, gli avvisi e il pianificatore); la condizione della flotta è la media dei
|
||||
treni. È il valore di `simulate` («condizione media flotta») e dell'accettazione.
|
||||
3. **Rischio.** Una volta al giorno, per ogni treno che ha percorso km, il rischio è il massimo `h` dei suoi
|
||||
componenti (×0,5 nei 30 giorni dopo un'ispezione); il componente più esposto è quello che si guasta.
|
||||
Il tipo si estrae con 70/27/3 %; un catastrofico diventa grave se il componente non è sotto 15 o il
|
||||
treno non va oltre l'80 % della velocità massima in quel momento.
|
||||
4. **Interventi.** Si fanno sul treno intero; costo (quota del prezzo) e ricambi valgono per veicolo. Le
|
||||
riparazioni lievi e gravi riguardano solo il veicolo guasto; la ricostruzione dopo un deragliamento
|
||||
sostituisce tutti i veicoli (età, contachilometri e fattore d'età azzerati) a 40 % del prezzo e 8
|
||||
ricambi ciascuno. Gli effetti si applicano come guadagno scalato dalla politica: `c + Δ·effetto`, al
|
||||
massimo 100 (la revisione «Economica» porta a c + 0,7·(100 − c)). Il tagliando vale anche come
|
||||
ispezione; l'ispezione non ripara i guasti. La revisione riduce il fattore d'età di 0,5 senza
|
||||
portarlo sotto 1 e senza accumulare credito.
|
||||
5. **Officine.** I treni occupano gli stalli in ordine d'arrivo; i ricambi si prelevano e l'intervento si
|
||||
paga all'inizio. Un lavoro senza ricambi aspetta occupando lo stallo: senza rifornimento l'officina
|
||||
si intasa e anche le ispezioni si fermano. Ritmo di lavoro = 1 / (1 + (2 − 1)·(1 − r)/0,5) con r la
|
||||
quota di personale presente: durate ×2 a metà personale (guida), ×3 senza nessuno («rallenta», non si
|
||||
ferma). Ogni stallo offre 4 posti di personale e 6 di operai; nei depositi nessuno vive in sede.
|
||||
6. **Pianificatore.** Ogni giorno, per i treni in linea: scadenze della politica in km (con i km di
|
||||
servizio medi) e in giorni, e stima del giorno in cui un componente scende a 40 con l'usura media dei
|
||||
15 giorni, meno 5 giorni. Tra gli interventi scaduti sceglie il più completo; la stima chiede
|
||||
un'ispezione se il componente critico sono i freni, altrimenti un tagliando. Il deposito è quello con
|
||||
viaggio (linea d'aria alla velocità del treno) + giorni di lavoro in coda per stallo minimi, tra quelli
|
||||
raggiungibili (A*) e con ricambi non già destinati. Senza ricambi in nessun deposito resta solo
|
||||
l'ispezione prevista dalla politica (non quella chiesta dalla stima: il treno farebbe ispezioni ogni
|
||||
giorno). Un guasto lieve senza ricambi lascia il treno in servizio a velocità dimezzata. La
|
||||
prenotazione si esegue dopo la fermata corrente; a fine intervento il treno riprende la linea.
|
||||
7. **Soccorso e deragliamenti.** Il tempo è in ore dell'orologio dei treni: distanza dal deposito più
|
||||
vicino / 40 km/h + 2 ore, oppure distanza da una riserva libera alla sua velocità, senza preparazione,
|
||||
se arriva prima. Il treno fermo tiene le sue risorse (blocca il binario). Arrivato il soccorso, è
|
||||
rimorchiato a 40 km/h fino alla fine del tratto in corso (scarica ma non carica) e poi all'officina
|
||||
scelta, con ricambi se possibile. Il deragliamento perde il carico (contato come deperito), chiude
|
||||
l'arco per 3 giorni e aggiunge 0,05 di insoddisfazione «lavoro» alle città servite dalla linea.
|
||||
8. **Riserve.** Un treno marcato riserva rientra al suo deposito e lascia la linea; finché è fermo lì
|
||||
copre la linea di un treno con un intervento di almeno 5 giorni effettivi (`planner.reserveMinDays`)
|
||||
e a fine intervento torna al deposito. Accorcia anche il soccorso.
|
||||
9. **Effetti della condizione.** Velocità massima ×(0,6 + 0,4·c/100) con il motore sotto 70 (×0,5 in più
|
||||
con un guasto lieve, tetto di 40 km/h se rimorchiato); il consumo è il costo d'esercizio della
|
||||
locomotiva ×(1 + 0,4·(1 − c/100)); il comfort (cassa delle carrozze) moltiplica la tariffa dei
|
||||
passeggeri tra 0,8 e 1,05; la rivendita resta quella di F2 (residuo × condizione media).
|
||||
10. **Ricambi via treno.** I depositi sono consumatori del bene `spare_parts` nel bacino delle stazioni della
|
||||
stessa compagnia; la domanda è scorta desiderata − scorta (40 all'inizio, `OrderParts` la cambia fino a
|
||||
400). La compagnia li paga al prezzo globale alla consegna. Un hub nel bacino di una stazione servita
|
||||
da una linea li importa verso la stazione con più bisogno, entro la capacità mensile dell'hub. La
|
||||
scorta iniziale di 10 casse è compresa nel prezzo del deposito ed è contabilizzata come importata.
|
||||
11. **Pendolarismo.** Industrie e depositi sono posti di lavoro (`IWorkplace`) trattati allo stesso modo.
|
||||
All'abbinamento mensile si annota il motivo dei posti scoperti (nessuna stazione, nessuna città entro
|
||||
il tempo massimo, nessun lavoratore libero, città senza servizi per il personale, capacità delle
|
||||
carrozze insufficiente su una linea). Convenzioni: ogni mese, con probabilità 0,5, un'industria a cui
|
||||
un vettore porta almeno 20 pendolari propone posti garantiti per 25 lire a posto al mese, pagati
|
||||
dall'industria; la proposta decade in 30 giorni; la copertura è la media a 30 giorni di arrivati/posti
|
||||
e sotto 0,9 per 30 giorni la convenzione salta con 3 mensilità di penale; dura 24 mesi; dopo un rifiuto,
|
||||
una rottura o la fine passano 6 mesi prima di una nuova proposta.
|
||||
12. **Circolazione.** Due stalli emersi con i viaggi verso le officine sono stati corretti: un'inversione
|
||||
di marcia in un nodo intermedio diventa una sosta tecnica (il percorso si tronca lì, nessun carico né
|
||||
scarico) e il transito in una stazione o in un deposito libera subito l'arco d'arrivo, come l'arrivo
|
||||
(il treno è tutto dentro). Senza queste regole un treno fermo con la coda sull'arco d'arrivo ne teneva
|
||||
il verso mentre chiedeva quello opposto o incrociava un altro treno.
|
||||
13. **Protocollo.** I record di treni, depositi, linee e compagnie portano un riepilogo nel blocco 1
|
||||
(condizione, stato, politica, prossimo intervento, ricambi, stalli); cartella di manutenzione e
|
||||
registro officina arrivano solo su richiesta (`RequestDetail` 10, `MaintenanceCard` 124,
|
||||
`WorkshopRegister` 125), così i componenti di migliaia di veicoli non viaggiano ogni giorno nei delta.
|
||||
`EmploymentReport` aggiunge i depositi, i codici dei motivi e le convenzioni.
|
||||
14. **Salvataggi.** Il corpo passa alla versione 2 con una sezione di manutenzione in coda allo stato
|
||||
dinamico (entra nell'hash). I salvataggi della versione 1 si caricano con valori iniziali coerenti.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Accettazione F4 nella rete di Valdoria dimensionata (acciaieria con 6 binari, Valdoria con 4,
|
||||
officina media a Valdoria, due treni per linea): senza la linea dei ricambi la flotta scende sotto 40
|
||||
al giorno 697 (23 mesi) con 12 guasti (19,5 per milione di km di servizio); con la linea dal Porto di
|
||||
Levante resta sopra 73 con 3 guasti (3,2 per milione di km). «I guasti raddoppiano» si verifica sia nel
|
||||
numero sia nel tasso per km.
|
||||
- Con un solo treno su una linea di pendolari e un deposito senza personale la copertura scende durante
|
||||
gli interventi: le riserve e il personale delle officine contano davvero.
|
||||
- Il viaggio verso l'officina si stima in linea d'aria; il treno rimorchiato completa il tratto in corso
|
||||
prima di dirigersi all'officina.
|
||||
- I nodi di testa (binari morti) non tengono il treno «dentro»: un'inversione lì libera comunque l'arco.
|
||||
- La taratura economica (canoni, costi, prezzi dei ricambi) è provvisoria fino alla F6.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 170 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 169 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 174 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 177 KiB |
@@ -35,6 +35,18 @@ public sealed class ClientWorld(GameData data)
|
||||
public HashSet<(int Cx, int Cy)> Chunks { get; } = [];
|
||||
|
||||
public DailyDigest? LastDigest { get; private set; }
|
||||
|
||||
/// <summary>Dettagli ricevuti su richiesta (F4): cartelle dei treni, registri delle officine, registro degli impieghi.</summary>
|
||||
public Dictionary<int, MaintenanceCard> Cards { get; } = [];
|
||||
public Dictionary<int, WorkshopRegister> Workshops { get; } = [];
|
||||
public EmploymentReport? Employment { get; private set; }
|
||||
|
||||
/// <summary>Ultimi avvisi di manutenzione, dal più recente.</summary>
|
||||
public List<MaintenanceAlert> Alerts { get; } = [];
|
||||
private const int AlertCapacity = 50;
|
||||
|
||||
/// <summary>Contatore dei dettagli ricevuti (per aggiornare i pannelli).</summary>
|
||||
public int DetailVersion { get; private set; }
|
||||
public long Tick { get; private set; }
|
||||
public byte Speed { get; private set; }
|
||||
|
||||
@@ -78,6 +90,23 @@ public sealed class ClientWorld(GameData data)
|
||||
case Pong m:
|
||||
Tick = Math.Max(Tick, (long)m.ServerTick);
|
||||
return true;
|
||||
case MaintenanceCard m:
|
||||
Cards[m.Train] = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case WorkshopRegister m:
|
||||
Workshops[m.Depot] = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case EmploymentReport m:
|
||||
Employment = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case MaintenanceAlert m:
|
||||
Alerts.Insert(0, m);
|
||||
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
|
||||
DetailVersion++;
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -85,6 +114,10 @@ public sealed class ClientWorld(GameData data)
|
||||
|
||||
private void Reset(Welcome m)
|
||||
{
|
||||
Cards.Clear();
|
||||
Workshops.Clear();
|
||||
Employment = null;
|
||||
Alerts.Clear();
|
||||
Summary = m.Summary;
|
||||
SessionId = m.SessionId;
|
||||
Tick = m.Summary.Tick;
|
||||
|
||||
@@ -12,6 +12,8 @@ public enum MessageId : ushort
|
||||
Save = 7,
|
||||
Load = 8,
|
||||
NewGame = 9,
|
||||
/// <summary>Richiesta di un dettaglio (F4): cartella di manutenzione, registro officina, registro impieghi.</summary>
|
||||
RequestDetail = 10,
|
||||
|
||||
Welcome = 101,
|
||||
Reject = 102,
|
||||
@@ -25,6 +27,10 @@ public enum MessageId : ushort
|
||||
MaintenanceAlert = 121,
|
||||
EmploymentReport = 122,
|
||||
MarketTape = 123,
|
||||
/// <summary>Cartella di manutenzione di un treno (F4).</summary>
|
||||
MaintenanceCard = 124,
|
||||
/// <summary>Registro officina di un deposito (F4).</summary>
|
||||
WorkshopRegister = 125,
|
||||
CommandResult = 130,
|
||||
Notification = 131,
|
||||
Newspaper = 132,
|
||||
|
||||
@@ -221,3 +221,36 @@ public sealed class NewGame : IMessage
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dettaglio richiesto dal client (F4).</summary>
|
||||
public enum DetailKind : byte
|
||||
{
|
||||
/// <summary>Cartella di manutenzione di un treno (risposta MaintenanceCard).</summary>
|
||||
TrainCard = 1,
|
||||
/// <summary>Registro officina di un deposito (risposta WorkshopRegister).</summary>
|
||||
Workshop = 2,
|
||||
/// <summary>Registro degli impieghi della compagnia (risposta EmploymentReport; Id ignorato).</summary>
|
||||
Employment = 3,
|
||||
}
|
||||
|
||||
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
|
||||
public sealed class RequestDetail : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.RequestDetail;
|
||||
public DetailKind Kind { get; init; }
|
||||
public int Target { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8((byte)Kind);
|
||||
w.I32(Target);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static RequestDetail Read(ref SpanReader r)
|
||||
{
|
||||
var m = new RequestDetail { Kind = (DetailKind)r.U8(), Target = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ public static class MessageCodec
|
||||
MessageId.Hello => Hello.Read(ref r),
|
||||
MessageId.Ping => Ping.Read(ref r),
|
||||
MessageId.Subscribe => Subscribe.Read(ref r),
|
||||
MessageId.RequestDetail => RequestDetail.Read(ref r),
|
||||
MessageId.Command => CommandMessage.Read(ref r),
|
||||
MessageId.SetSpeed => SetSpeed.Read(ref r),
|
||||
MessageId.ListSaves => ListSaves.Read(ref r),
|
||||
@@ -25,6 +26,8 @@ public static class MessageCodec
|
||||
MessageId.DailyDigest => DailyDigest.Read(ref r),
|
||||
MessageId.MaintenanceAlert => MaintenanceAlert.Read(ref r),
|
||||
MessageId.EmploymentReport => EmploymentReport.Read(ref r),
|
||||
MessageId.MaintenanceCard => MaintenanceCard.Read(ref r),
|
||||
MessageId.WorkshopRegister => WorkshopRegister.Read(ref r),
|
||||
MessageId.MarketTape => MarketTape.Read(ref r),
|
||||
MessageId.CommandResult => CommandResultMessage.Read(ref r),
|
||||
MessageId.Notification => Notification.Read(ref r),
|
||||
|
||||
@@ -68,11 +68,15 @@ public sealed class CompanyInfo : IWritable
|
||||
public byte Tier { get; init; }
|
||||
public bool Bankrupt { get; init; }
|
||||
|
||||
// blocco 1 (F4): politica di manutenzione della flotta
|
||||
public byte MaintenancePolicy { get; set; } = 1;
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Id); w.String(Name); w.String(Color); w.Bool(IsPlayer); w.Money(Cash); w.Money(NetWorth);
|
||||
w.String(Rating); w.U8(Tier); w.Bool(Bankrupt);
|
||||
w.Flags(0);
|
||||
w.Flags(1);
|
||||
w.U8(MaintenancePolicy);
|
||||
}
|
||||
|
||||
public static CompanyInfo Read(ref SpanReader r)
|
||||
@@ -82,7 +86,8 @@ public sealed class CompanyInfo : IWritable
|
||||
Id = r.I32(), Name = r.String(), Color = r.String(), IsPlayer = r.Bool(), Cash = r.Money(), NetWorth = r.Money(),
|
||||
Rating = r.String(), Tier = r.U8(), Bankrupt = r.Bool(),
|
||||
};
|
||||
r.Flags();
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0) m.MaintenancePolicy = r.U8();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -242,16 +247,33 @@ public sealed class DepotInfo : IWritable
|
||||
public Vec2 Position { get; init; }
|
||||
public string Size { get; init; } = "";
|
||||
|
||||
// blocco 1 (F4): officina
|
||||
public int Stalls { get; set; }
|
||||
public int JobsStaff { get; set; }
|
||||
/// <summary>Personale presente in percentuale (0–100).</summary>
|
||||
public byte StaffPercent { get; set; }
|
||||
public int SpareParts { get; set; }
|
||||
public int PartsTarget { get; set; }
|
||||
/// <summary>Lavori in officina (in coda e negli stalli).</summary>
|
||||
public int Jobs { get; set; }
|
||||
public bool WaitingParts { get; set; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Id); w.I32(Owner); w.String(Name); w.I32(Node); w.Vec2(Position); w.String(Size);
|
||||
w.Flags(0);
|
||||
w.Flags(1);
|
||||
w.I32(Stalls); w.I32(JobsStaff); w.U8(StaffPercent); w.I32(SpareParts); w.I32(PartsTarget); w.I32(Jobs); w.Bool(WaitingParts);
|
||||
}
|
||||
|
||||
public static DepotInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new DepotInfo { Id = r.I32(), Owner = r.I32(), Name = r.String(), Node = r.I32(), Position = r.Vec2(), Size = r.String() };
|
||||
r.Flags();
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
m.Stalls = r.I32(); m.JobsStaff = r.I32(); m.StaffPercent = r.U8(); m.SpareParts = r.I32(); m.PartsTarget = r.I32();
|
||||
m.Jobs = r.I32(); m.WaitingParts = r.Bool();
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -264,6 +286,9 @@ public sealed class LineInfo : IWritable
|
||||
public string Color { get; init; } = "";
|
||||
public LineStop[] Stops { get; init; } = [];
|
||||
|
||||
// blocco 1 (F4): politica di manutenzione propria della linea (255 = quella della compagnia)
|
||||
public byte Policy { get; set; } = byte.MaxValue;
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Id); w.I32(Owner); w.String(Name); w.String(Color);
|
||||
@@ -272,7 +297,8 @@ public sealed class LineInfo : IWritable
|
||||
{
|
||||
w.I32(s.Station.Value); w.Bool(s.Load); w.Bool(s.Unload); w.Bool(s.WaitFull); w.I32(s.MaxWaitDays);
|
||||
}
|
||||
w.Flags(0);
|
||||
w.Flags(1);
|
||||
w.U8(Policy);
|
||||
}
|
||||
|
||||
public static LineInfo Read(ref SpanReader r)
|
||||
@@ -281,8 +307,10 @@ public sealed class LineInfo : IWritable
|
||||
string name = r.String(), color = r.String();
|
||||
var stops = new LineStop[r.Count()];
|
||||
for (int i = 0; i < stops.Length; i++) stops[i] = new LineStop(new StationId(r.I32()), r.Bool(), r.Bool(), r.Bool(), r.I32());
|
||||
r.Flags();
|
||||
return new LineInfo { Id = id, Owner = owner, Name = name, Color = color, Stops = stops };
|
||||
var m = new LineInfo { Id = id, Owner = owner, Name = name, Color = color, Stops = stops };
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0) m.Policy = r.U8();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,6 +337,21 @@ public sealed class VehicleInfo : IWritable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stato di manutenzione di un treno nel riepilogo (blocco F4 di TrainInfo).</summary>
|
||||
public enum TrainMaintenanceStatus : byte
|
||||
{
|
||||
InService = 0,
|
||||
/// <summary>Intervento prenotato: va in officina dopo la fermata corrente.</summary>
|
||||
Booked = 1,
|
||||
InWorkshop = 2,
|
||||
/// <summary>Guasto lieve: velocità dimezzata fino al deposito.</summary>
|
||||
MinorFailure = 3,
|
||||
/// <summary>Fermo in linea in attesa del soccorso (guasto grave o deragliamento).</summary>
|
||||
Stranded = 4,
|
||||
/// <summary>Rimorchiato verso l'officina.</summary>
|
||||
Towed = 5,
|
||||
}
|
||||
|
||||
public sealed class TrainInfo : IWritable
|
||||
{
|
||||
public int Id { get; init; }
|
||||
@@ -323,13 +366,28 @@ public sealed class TrainInfo : IWritable
|
||||
public int Capacity { get; init; }
|
||||
public int Depot { get; init; } = -1;
|
||||
|
||||
// blocco 1 (F4): riepilogo di manutenzione (la cartella completa si chiede con RequestDetail)
|
||||
/// <summary>Condizione del componente più debole (0–100).</summary>
|
||||
public byte Condition { get; set; } = 100;
|
||||
public TrainMaintenanceStatus Maintenance { get; set; }
|
||||
public bool Reserve { get; set; }
|
||||
/// <summary>Politica propria del treno (255 = quella della linea o della compagnia).</summary>
|
||||
public byte Policy { get; set; } = byte.MaxValue;
|
||||
/// <summary>Prossimo intervento (id di maintenance.json) e giorni alla scadenza (negativi se scaduto).</summary>
|
||||
public string NextIntervention { get; set; } = "";
|
||||
public int NextDueDays { get; set; }
|
||||
/// <summary>Officina prenotata o in cui si trova (−1 nessuna).</summary>
|
||||
public int MaintenanceDepot { get; set; } = -1;
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Id); w.I32(Owner); w.String(Name); w.I32(Line); w.U8(State);
|
||||
w.Count(Vehicles.Length);
|
||||
foreach (int v in Vehicles) w.I32(v);
|
||||
w.F32(MaxSpeedKmh); w.F32(LengthM); w.I32(Load); w.I32(Capacity); w.I32(Depot);
|
||||
w.Flags(0);
|
||||
w.Flags(1);
|
||||
w.U8(Condition); w.U8((byte)Maintenance); w.Bool(Reserve); w.U8(Policy); w.String(NextIntervention); w.I32(NextDueDays);
|
||||
w.I32(MaintenanceDepot);
|
||||
}
|
||||
|
||||
public static TrainInfo Read(ref SpanReader r)
|
||||
@@ -345,7 +403,12 @@ public sealed class TrainInfo : IWritable
|
||||
Id = id, Owner = owner, Name = name, Line = line, State = state, Vehicles = vehicles,
|
||||
MaxSpeedKmh = r.F32(), LengthM = r.F32(), Load = r.I32(), Capacity = r.I32(), Depot = r.I32(),
|
||||
};
|
||||
r.Flags();
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
m.Condition = r.U8(); m.Maintenance = (TrainMaintenanceStatus)r.U8(); m.Reserve = r.Bool(); m.Policy = r.U8();
|
||||
m.NextIntervention = r.String(); m.NextDueDays = r.I32(); m.MaintenanceDepot = r.I32();
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,22 +403,34 @@ public sealed class EmploymentSource
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Riga del Registro degli impieghi: un posto di lavoro (industria o deposito).</summary>
|
||||
public sealed class EmploymentRow
|
||||
{
|
||||
/// <summary>Indice del posto di lavoro (industria o deposito secondo <see cref="Kind"/>).</summary>
|
||||
public int Industry { get; init; }
|
||||
public int JobsWorkers { get; init; }
|
||||
public int JobsStaff { get; init; }
|
||||
public float WorkersPresent { get; init; }
|
||||
public float StaffPresent { get; init; }
|
||||
/// <summary>Motivo dei posti scoperti, in italiano (per i lettori senza il blocco F4).</summary>
|
||||
public string Reason { get; init; } = "";
|
||||
public List<EmploymentSource> Sources { get; init; } = [];
|
||||
|
||||
// blocco 1 (F4): tipo di posto e codici dei motivi (UncoveredReason di Core)
|
||||
/// <summary>0 = industria, 1 = deposito.</summary>
|
||||
public byte Kind { get; set; }
|
||||
public byte WorkersReason { get; set; }
|
||||
public byte StaffReason { get; set; }
|
||||
public int WorkersReasonLine { get; set; } = -1;
|
||||
public int StaffReasonLine { get; set; } = -1;
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Industry); w.I32(JobsWorkers); w.I32(JobsStaff); w.F32(WorkersPresent); w.F32(StaffPresent); w.String(Reason);
|
||||
w.Count(Sources.Count);
|
||||
foreach (var s in Sources) s.Write(ref w);
|
||||
w.Flags(0);
|
||||
w.Flags(1);
|
||||
w.U8(Kind); w.U8(WorkersReason); w.U8(StaffReason); w.I32(WorkersReasonLine); w.I32(StaffReasonLine);
|
||||
}
|
||||
|
||||
public static EmploymentRow Read(ref SpanReader r)
|
||||
@@ -428,30 +440,293 @@ public sealed class EmploymentRow
|
||||
string reason = r.String();
|
||||
var sources = new List<EmploymentSource>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) sources.Add(EmploymentSource.Read(ref r));
|
||||
r.Flags();
|
||||
return new EmploymentRow { Industry = ind, JobsWorkers = jw, JobsStaff = js, WorkersPresent = wp, StaffPresent = sp, Reason = reason, Sources = sources };
|
||||
var m = new EmploymentRow { Industry = ind, JobsWorkers = jw, JobsStaff = js, WorkersPresent = wp, StaffPresent = sp, Reason = reason, Sources = sources };
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
m.Kind = r.U8(); m.WorkersReason = r.U8(); m.StaffReason = r.U8(); m.WorkersReasonLine = r.I32(); m.StaffReasonLine = r.I32();
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resoconto mensile del pendolarismo della compagnia.</summary>
|
||||
/// <summary>Convenzione di pendolarismo (sezione 9) nel Registro degli impieghi.</summary>
|
||||
public sealed class AgreementInfo
|
||||
{
|
||||
public int Id { get; init; }
|
||||
public int Industry { get; init; }
|
||||
public int Carrier { get; init; }
|
||||
public int SeatsPerDay { get; init; }
|
||||
public Money MonthlyFee { get; init; }
|
||||
/// <summary>AgreementState di Core: 0 proposta, 1 attiva, 2 rifiutata, 3 scaduta, 4 saltata, 5 conclusa.</summary>
|
||||
public byte State { get; init; }
|
||||
public long ProposedDay { get; init; }
|
||||
public long StartDay { get; init; } = -1;
|
||||
public long EndDay { get; init; } = -1;
|
||||
public float Coverage { get; init; }
|
||||
public int ShortDays { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Id); w.I32(Industry); w.I32(Carrier); w.I32(SeatsPerDay); w.Money(MonthlyFee); w.U8(State);
|
||||
w.I64(ProposedDay); w.I64(StartDay); w.I64(EndDay); w.F32(Coverage); w.I32(ShortDays);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static AgreementInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new AgreementInfo
|
||||
{
|
||||
Id = r.I32(), Industry = r.I32(), Carrier = r.I32(), SeatsPerDay = r.I32(), MonthlyFee = r.Money(), State = r.U8(),
|
||||
ProposedDay = r.I64(), StartDay = r.I64(), EndDay = r.I64(), Coverage = r.F32(), ShortDays = r.I32(),
|
||||
};
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Registro degli impieghi della compagnia: ogni mese, dopo le convenzioni e su richiesta.</summary>
|
||||
public sealed class EmploymentReport : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.EmploymentReport;
|
||||
public long Day { get; init; }
|
||||
public List<EmploymentRow> Rows { get; init; } = [];
|
||||
|
||||
// blocco 1 (F4): convenzioni proposte e attive
|
||||
public List<AgreementInfo> Agreements { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day);
|
||||
w.Count(Rows.Count);
|
||||
foreach (var row in Rows) row.Write(ref w);
|
||||
w.Flags(0);
|
||||
w.Flags(1);
|
||||
w.Count(Agreements.Count);
|
||||
foreach (var a in Agreements) a.Write(ref w);
|
||||
}
|
||||
|
||||
public static EmploymentReport Read(ref SpanReader r)
|
||||
{
|
||||
var m = new EmploymentReport { Day = r.I64() };
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Rows.Add(EmploymentRow.Read(ref r));
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Agreements.Add(AgreementInfo.Read(ref r));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Componente di un veicolo nella cartella di manutenzione.</summary>
|
||||
public sealed class ComponentCard
|
||||
{
|
||||
public string Component { get; init; } = "";
|
||||
public float Condition { get; init; }
|
||||
/// <summary>Usura media giornaliera degli ultimi giorni (punti/giorno).</summary>
|
||||
public float WearPerDay { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.String(Component); w.F32(Condition); w.F32(WearPerDay);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ComponentCard Read(ref SpanReader r)
|
||||
{
|
||||
var m = new ComponentCard { Component = r.String(), Condition = r.F32(), WearPerDay = r.F32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class VehicleCard
|
||||
{
|
||||
public int Vehicle { get; init; }
|
||||
public string Type { get; init; } = "";
|
||||
public float OdometerKm { get; init; }
|
||||
public float AgeYears { get; init; }
|
||||
public float AgeFactor { get; init; }
|
||||
public List<ComponentCard> Components { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Vehicle); w.String(Type); w.F32(OdometerKm); w.F32(AgeYears); w.F32(AgeFactor);
|
||||
w.Count(Components.Count);
|
||||
foreach (var c in Components) c.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static VehicleCard Read(ref SpanReader r)
|
||||
{
|
||||
var m = new VehicleCard { Vehicle = r.I32(), Type = r.String(), OdometerKm = r.F32(), AgeYears = r.F32(), AgeFactor = r.F32() };
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Components.Add(ComponentCard.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Voce dello storico della cartella di manutenzione.</summary>
|
||||
public sealed class MaintenanceRecordInfo
|
||||
{
|
||||
public long Day { get; init; }
|
||||
public string Intervention { get; init; } = "";
|
||||
public Money Cost { get; init; }
|
||||
public int Depot { get; init; } = -1;
|
||||
public int Parts { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.String(Intervention); w.Money(Cost); w.I32(Depot); w.I32(Parts);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static MaintenanceRecordInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new MaintenanceRecordInfo { Day = r.I64(), Intervention = r.String(), Cost = r.Money(), Depot = r.I32(), Parts = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cartella di manutenzione di un treno (10.3): componenti per veicolo, guasto in corso, politica,
|
||||
/// prossimo intervento, costi dell'anno e storico. Si invia su richiesta (RequestDetail).
|
||||
/// </summary>
|
||||
public sealed class MaintenanceCard : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.MaintenanceCard;
|
||||
public int Train { get; init; }
|
||||
public long Day { get; init; }
|
||||
public float Condition { get; init; }
|
||||
public TrainMaintenanceStatus Status { get; init; }
|
||||
/// <summary>Politica effettiva e quella propria del treno (255 = ereditata).</summary>
|
||||
public byte Policy { get; init; }
|
||||
public byte PolicyOverride { get; init; } = byte.MaxValue;
|
||||
public bool Reserve { get; init; }
|
||||
/// <summary>FailureKind di Core e componente guasto.</summary>
|
||||
public byte Failure { get; init; }
|
||||
public int FailedVehicle { get; init; } = -1;
|
||||
public string FailedComponent { get; init; } = "";
|
||||
/// <summary>Ore (orologio dei treni) all'arrivo del soccorso, −1 se non serve.</summary>
|
||||
public float RescueHours { get; init; } = -1;
|
||||
public string NextIntervention { get; init; } = "";
|
||||
public float NextDueDays { get; init; }
|
||||
public string PlannedIntervention { get; init; } = "";
|
||||
public int MaintenanceDepot { get; init; } = -1;
|
||||
public float ServiceKmPerDay { get; init; }
|
||||
public Money CostThisYear { get; init; }
|
||||
public Money CostLastYear { get; init; }
|
||||
public int FailuresThisYear { get; init; }
|
||||
public int FailuresTotal { get; init; }
|
||||
public int CoveredBy { get; init; } = -1;
|
||||
public int Covering { get; init; } = -1;
|
||||
public List<VehicleCard> Vehicles { get; init; } = [];
|
||||
public List<MaintenanceRecordInfo> History { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Train); w.I64(Day); w.F32(Condition); w.U8((byte)Status); w.U8(Policy); w.U8(PolicyOverride); w.Bool(Reserve);
|
||||
w.U8(Failure); w.I32(FailedVehicle); w.String(FailedComponent); w.F32(RescueHours);
|
||||
w.String(NextIntervention); w.F32(NextDueDays); w.String(PlannedIntervention); w.I32(MaintenanceDepot);
|
||||
w.F32(ServiceKmPerDay); w.Money(CostThisYear); w.Money(CostLastYear); w.I32(FailuresThisYear); w.I32(FailuresTotal);
|
||||
w.I32(CoveredBy); w.I32(Covering);
|
||||
w.Count(Vehicles.Count);
|
||||
foreach (var v in Vehicles) v.Write(ref w);
|
||||
w.Count(History.Count);
|
||||
foreach (var h in History) h.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static MaintenanceCard Read(ref SpanReader r)
|
||||
{
|
||||
var m = new MaintenanceCard
|
||||
{
|
||||
Train = r.I32(), Day = r.I64(), Condition = r.F32(), Status = (TrainMaintenanceStatus)r.U8(), Policy = r.U8(), PolicyOverride = r.U8(),
|
||||
Reserve = r.Bool(), Failure = r.U8(), FailedVehicle = r.I32(), FailedComponent = r.String(), RescueHours = r.F32(),
|
||||
NextIntervention = r.String(), NextDueDays = r.F32(), PlannedIntervention = r.String(), MaintenanceDepot = r.I32(),
|
||||
ServiceKmPerDay = r.F32(), CostThisYear = r.Money(), CostLastYear = r.Money(), FailuresThisYear = r.I32(), FailuresTotal = r.I32(),
|
||||
CoveredBy = r.I32(), Covering = r.I32(),
|
||||
};
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Vehicles.Add(VehicleCard.Read(ref r));
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.History.Add(MaintenanceRecordInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Lavoro nel Registro officina.</summary>
|
||||
public sealed class WorkshopJobInfo
|
||||
{
|
||||
public int Train { get; init; }
|
||||
public string Intervention { get; init; } = "";
|
||||
public bool InStall { get; init; }
|
||||
public bool Started { get; init; }
|
||||
public float Progress { get; init; }
|
||||
public float Days { get; init; }
|
||||
public int Parts { get; init; }
|
||||
public long QueuedDay { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Train); w.String(Intervention); w.Bool(InStall); w.Bool(Started); w.F32(Progress); w.F32(Days); w.I32(Parts); w.I64(QueuedDay);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WorkshopJobInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WorkshopJobInfo
|
||||
{
|
||||
Train = r.I32(), Intervention = r.String(), InStall = r.Bool(), Started = r.Bool(), Progress = r.F32(), Days = r.F32(),
|
||||
Parts = r.I32(), QueuedDay = r.I64(),
|
||||
};
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registro officina di un deposito (10.3): stalli, personale, ricambi, coda dei lavori e treni
|
||||
/// prenotati. Si invia su richiesta (RequestDetail).
|
||||
/// </summary>
|
||||
public sealed class WorkshopRegister : IMessage
|
||||
{
|
||||
public MessageId Id => MessageId.WorkshopRegister;
|
||||
public int Depot { get; init; }
|
||||
public long Day { get; init; }
|
||||
public int Stalls { get; init; }
|
||||
public int JobsStaff { get; init; }
|
||||
public float StaffPresent { get; init; }
|
||||
/// <summary>Velocità del lavoro (1 a personale completo).</summary>
|
||||
public float WorkRate { get; init; }
|
||||
public int SpareParts { get; init; }
|
||||
public int PartsTarget { get; init; }
|
||||
/// <summary>Ricambi già destinati a lavori in coda e treni prenotati.</summary>
|
||||
public int PartsReserved { get; init; }
|
||||
public List<WorkshopJobInfo> Jobs { get; init; } = [];
|
||||
/// <summary>Treni prenotati in arrivo e relativo intervento.</summary>
|
||||
public List<WorkshopJobInfo> Booked { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Depot); w.I64(Day); w.I32(Stalls); w.I32(JobsStaff); w.F32(StaffPresent); w.F32(WorkRate);
|
||||
w.I32(SpareParts); w.I32(PartsTarget); w.I32(PartsReserved);
|
||||
w.Count(Jobs.Count);
|
||||
foreach (var j in Jobs) j.Write(ref w);
|
||||
w.Count(Booked.Count);
|
||||
foreach (var j in Booked) j.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WorkshopRegister Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WorkshopRegister
|
||||
{
|
||||
Depot = r.I32(), Day = r.I64(), Stalls = r.I32(), JobsStaff = r.I32(), StaffPresent = r.F32(), WorkRate = r.F32(),
|
||||
SpareParts = r.I32(), PartsTarget = r.I32(), PartsReserved = r.I32(),
|
||||
};
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Jobs.Add(WorkshopJobInfo.Read(ref r));
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Booked.Add(WorkshopJobInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
@@ -223,6 +224,9 @@ public sealed class GameHost : IDisposable
|
||||
_slow = false;
|
||||
_log.LogInformation("Velocità {Speed}×", _speed);
|
||||
break;
|
||||
case RequestDetail m:
|
||||
SendDetail(s, m);
|
||||
break;
|
||||
case ListSaves:
|
||||
s.Send(new SaveList { Saves = _saves.List() });
|
||||
break;
|
||||
@@ -362,7 +366,22 @@ public sealed class GameHost : IDisposable
|
||||
{
|
||||
Seq = p.ClientSeq, Type = (ushort)r.Type, Error = (ushort)r.Error, Message = r.Message, Created = r.Created, Tick = r.Tick,
|
||||
});
|
||||
// le convenzioni cambiano il Registro degli impieghi: lo si rimanda subito
|
||||
if (r.Ok && r.Type is CommandType.AcceptAgreement or CommandType.RejectAgreement)
|
||||
p.Session.Send(Projection.Employment(w, p.Session.Company));
|
||||
}
|
||||
foreach (var a in w.Alerts)
|
||||
{
|
||||
var alert = new MaintenanceAlert
|
||||
{
|
||||
Train = a.Train.Value, Depot = a.Depot.Value, Component = a.Component, Condition = (float)a.Condition, DueDays = a.DueDays, Text = a.Text,
|
||||
};
|
||||
foreach (var s in _sessions.Values)
|
||||
{
|
||||
if (s.Connected && s.Company == a.Company) s.Send(alert);
|
||||
}
|
||||
}
|
||||
w.Alerts.Clear();
|
||||
foreach (var e in w.Events.Drain())
|
||||
{
|
||||
var info = Projection.Event(e);
|
||||
@@ -599,37 +618,30 @@ public sealed class GameHost : IDisposable
|
||||
s.Send(Projection.Chunk(w, key.Cx, key.Cy));
|
||||
}
|
||||
}
|
||||
if (_monthlyDue) s.Send(EmploymentReport(w, s.Company));
|
||||
if (_monthlyDue) s.Send(Projection.Employment(w, s.Company));
|
||||
}
|
||||
_monthlyDue = false;
|
||||
_dayEvents.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Registro degli impieghi della compagnia: posti serviti dai suoi treni e provenienze.</summary>
|
||||
private static EmploymentReport EmploymentReport(World w, CompanyId company)
|
||||
/// <summary>Dettagli su richiesta: cartella di manutenzione, registro officina, registro degli impieghi.</summary>
|
||||
private void SendDetail(Session s, RequestDetail m)
|
||||
{
|
||||
var report = new EmploymentReport { Day = w.Clock.Day };
|
||||
foreach (var ind in w.Industries)
|
||||
var w = _world;
|
||||
switch (m.Kind)
|
||||
{
|
||||
if (ind.Closed) continue;
|
||||
var sources = new List<EmploymentSource>();
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
if (c.Walking || c.Carrier != company || c.Workplace.Kind != Core.Economy.WorkplaceKind.Industry || c.Workplace.Index != ind.Id.Value) continue;
|
||||
sources.Add(new EmploymentSource
|
||||
{
|
||||
Town = c.Town.Value, HomeStation = c.HomeStation.Value, Line = c.Route.Count > 0 ? c.Route[0].Value : -1,
|
||||
Category = (byte)c.Category, Headcount = c.Headcount, Coverage = (float)c.Coverage,
|
||||
});
|
||||
}
|
||||
if (sources.Count == 0) continue;
|
||||
report.Rows.Add(new EmploymentRow
|
||||
{
|
||||
Industry = ind.Id.Value, JobsWorkers = ind.JobsWorkers, JobsStaff = ind.JobsStaff,
|
||||
WorkersPresent = (float)ind.WorkersPresent, StaffPresent = (float)ind.StaffPresent, Sources = sources,
|
||||
});
|
||||
case DetailKind.TrainCard:
|
||||
if (m.Target >= 0 && m.Target < w.Trains.Count && w.Trains[m.Target] is { Removed: false } t && t.Owner == s.Company)
|
||||
s.Send(Projection.Card(w, t));
|
||||
break;
|
||||
case DetailKind.Workshop:
|
||||
if (m.Target >= 0 && m.Target < w.Network.Depots.Count && w.Network.Depots[m.Target] is { } d && d.Owner == s.Company && w.Network.IsAlive(d))
|
||||
s.Send(Projection.Workshop(w, d));
|
||||
break;
|
||||
case DetailKind.Employment:
|
||||
s.Send(Projection.Employment(w, s.Company));
|
||||
break;
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
private void PublishMotion()
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Economy;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ViaFerrea.Core.Simulation.Systems;
|
||||
using ViaFerrea.Protocol;
|
||||
using ViaFerrea.Protocol.Messages;
|
||||
|
||||
@@ -76,7 +78,7 @@ public static class Projection
|
||||
e.Companies.Add(new CompanyInfo
|
||||
{
|
||||
Id = c.Id.Value, Name = c.Name, Color = c.Color, IsPlayer = c.IsPlayer, Cash = c.Cash, NetWorth = c.NetWorth,
|
||||
Rating = c.Rating.ToString(), Tier = (byte)c.Tier, Bankrupt = c.Bankrupt,
|
||||
Rating = c.Rating.ToString(), Tier = (byte)c.Tier, Bankrupt = c.Bankrupt, MaintenancePolicy = (byte)c.MaintenancePolicy,
|
||||
});
|
||||
}
|
||||
foreach (var t in w.Towns)
|
||||
@@ -120,17 +122,29 @@ public static class Projection
|
||||
foreach (var d in net.Depots)
|
||||
{
|
||||
if (!net.IsAlive(d)) continue;
|
||||
e.Depots.Add(new DepotInfo { Id = d.Id.Value, Owner = d.Owner.Value, Name = d.Name, Node = d.Node.Value, Position = d.Position, Size = d.Size });
|
||||
bool waiting = false;
|
||||
foreach (var j in d.Jobs) waiting |= j.InStall && !j.Started && d.SpareParts < j.Parts;
|
||||
e.Depots.Add(new DepotInfo
|
||||
{
|
||||
Id = d.Id.Value, Owner = d.Owner.Value, Name = d.Name, Node = d.Node.Value, Position = d.Position, Size = d.Size,
|
||||
Stalls = d.Stalls, JobsStaff = d.JobsStaff, StaffPercent = (byte)Math.Round(d.StaffRatio * 100), SpareParts = d.SpareParts,
|
||||
PartsTarget = d.PartsTarget, Jobs = d.Jobs.Count, WaitingParts = waiting,
|
||||
});
|
||||
}
|
||||
foreach (var l in w.Lines)
|
||||
{
|
||||
if (l.Removed) continue;
|
||||
e.Lines.Add(new LineInfo { Id = l.Id.Value, Owner = l.Owner.Value, Name = l.Name, Color = l.Color, Stops = l.Stops.ToArray() });
|
||||
e.Lines.Add(new LineInfo
|
||||
{
|
||||
Id = l.Id.Value, Owner = l.Owner.Value, Name = l.Name, Color = l.Color, Stops = l.Stops.ToArray(),
|
||||
Policy = l.Policy is { } p ? (byte)p : byte.MaxValue,
|
||||
});
|
||||
}
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
if (v.Sold) continue;
|
||||
double cond = v.Components.Length == 0 ? 100 : v.Components.Min();
|
||||
// condizione arrotondata all'unità: il record cambia (e viaggia nei delta) solo quando serve
|
||||
double cond = Math.Floor(v.Components.Length == 0 ? 100 : v.Components.Min());
|
||||
e.Vehicles.Add(new VehicleInfo { Id = v.Id.Value, Owner = v.Owner.Value, Type = v.Def.Id, Depot = v.Depot.Value, Train = v.Train.Value, Condition = (float)cond });
|
||||
}
|
||||
foreach (var t in w.Trains)
|
||||
@@ -144,16 +158,163 @@ public static class Projection
|
||||
capacity += (v.Def.Capacity ?? 0) + (v.Def.PaxCapacity ?? 0);
|
||||
}
|
||||
var atDepot = t.AtNode.IsValid ? net.Nodes[t.AtNode.Value].Depot : DepotId.None;
|
||||
var next = t.Vehicles.Count > 0 ? Fleet.Next(w, t) : new NextIntervention(-1, 0);
|
||||
e.Trains.Add(new TrainInfo
|
||||
{
|
||||
Id = t.Id.Value, Owner = t.Owner.Value, Name = t.Name, Line = t.Line.Value, State = (byte)t.State,
|
||||
Vehicles = t.Vehicles.Select(x => x.Value).ToArray(), MaxSpeedKmh = (float)t.MaxSpeedKmh, LengthM = (float)t.LengthM,
|
||||
Load = load, Capacity = capacity, Depot = atDepot.Value,
|
||||
Condition = (byte)Math.Clamp(Math.Floor(Fleet.TrainCondition(w, t)), 0, 100), Maintenance = MaintenanceStatus(t),
|
||||
Reserve = t.Reserve, Policy = t.Policy is { } p ? (byte)p : byte.MaxValue,
|
||||
NextIntervention = next.Intervention >= 0 ? w.Data.Maintenance.Interventions[next.Intervention].Id : "",
|
||||
NextDueDays = (int)Math.Clamp(Math.Floor(next.Days), -9999, 9999), MaintenanceDepot = t.MaintenanceDepot.Value,
|
||||
});
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
public static TrainMaintenanceStatus MaintenanceStatus(Train t)
|
||||
{
|
||||
if (t.State == TrainState.Broken) return TrainMaintenanceStatus.Stranded;
|
||||
if (t.Towed) return TrainMaintenanceStatus.Towed;
|
||||
if (t.InWorkshop) return TrainMaintenanceStatus.InWorkshop;
|
||||
if (t.Failure == FailureKind.Minor) return TrainMaintenanceStatus.MinorFailure;
|
||||
return t.MaintenanceDepot.IsValid ? TrainMaintenanceStatus.Booked : TrainMaintenanceStatus.InService;
|
||||
}
|
||||
|
||||
/// <summary>Cartella di manutenzione di un treno (10.3).</summary>
|
||||
public static MaintenanceCard Card(World w, Train t)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
var next = t.Vehicles.Count > 0 ? Fleet.Next(w, t) : new NextIntervention(-1, 0);
|
||||
var card = new MaintenanceCard
|
||||
{
|
||||
Train = t.Id.Value, Day = w.Clock.Day, Condition = (float)Fleet.TrainCondition(w, t), Status = MaintenanceStatus(t),
|
||||
Policy = (byte)Fleet.PolicyOf(w, t).Id, PolicyOverride = t.Policy is { } p ? (byte)p : byte.MaxValue, Reserve = t.Reserve,
|
||||
Failure = (byte)t.Failure, FailedVehicle = t.FailedVehicle.Value,
|
||||
FailedComponent = t.FailedVehicle.IsValid && t.FailedComponent >= 0
|
||||
? Fleet.ComponentsOf(w.Data, w.Vehicles[t.FailedVehicle.Value].Def)[t.FailedComponent].Id : "",
|
||||
RescueHours = t.RescueTick >= 0 ? (float)((t.RescueTick - w.Clock.Tick) * w.Calendar.TrainSecondsPerTick / 3600) : -1,
|
||||
NextIntervention = next.Intervention >= 0 ? m.Interventions[next.Intervention].Id : "", NextDueDays = (float)next.Days,
|
||||
PlannedIntervention = t.PlannedIntervention >= 0 ? m.Interventions[t.PlannedIntervention].Id : "",
|
||||
MaintenanceDepot = t.MaintenanceDepot.Value, ServiceKmPerDay = (float)t.ServiceKmPerDay,
|
||||
CostThisYear = new Money(t.MaintenanceThisYear), CostLastYear = new Money(t.MaintenanceLastYear),
|
||||
FailuresThisYear = t.FailuresThisYear, FailuresTotal = t.FailuresTotal, CoveredBy = t.CoveredBy.Value, Covering = t.Covering.Value,
|
||||
};
|
||||
foreach (var id in t.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
var comps = Fleet.ComponentsOf(w.Data, v.Def);
|
||||
var vc = new VehicleCard
|
||||
{
|
||||
Vehicle = v.Id.Value, Type = v.Def.Id, OdometerKm = (float)v.OdometerKm,
|
||||
AgeYears = (float)((w.Clock.Day - v.BoughtDay) / (double)w.Calendar.DaysPerYear), AgeFactor = (float)Fleet.AgeFactor(w, v),
|
||||
};
|
||||
for (int j = 0; j < v.Components.Length && j < comps.Count; j++)
|
||||
vc.Components.Add(new ComponentCard { Component = comps[j].Id, Condition = (float)v.Components[j], WearPerDay = j < v.WearEma.Length ? (float)v.WearEma[j] : 0 });
|
||||
card.Vehicles.Add(vc);
|
||||
}
|
||||
foreach (var h in t.History)
|
||||
{
|
||||
card.History.Add(new MaintenanceRecordInfo
|
||||
{
|
||||
Day = h.Day, Intervention = m.Interventions[h.Intervention].Id, Cost = new Money(h.CostCents), Depot = h.Depot.Value, Parts = h.Parts,
|
||||
});
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
/// <summary>Registro officina di un deposito (10.3).</summary>
|
||||
public static WorkshopRegister Workshop(World w, Depot d)
|
||||
{
|
||||
var m = w.Data.Maintenance;
|
||||
var backlog = new double[w.Network.Depots.Count];
|
||||
var reserved = new int[w.Network.Depots.Count];
|
||||
FleetMaintenanceSystem.DepotLoads(w, null, backlog, reserved);
|
||||
var reg = new WorkshopRegister
|
||||
{
|
||||
Depot = d.Id.Value, Day = w.Clock.Day, Stalls = d.Stalls, JobsStaff = d.JobsStaff, StaffPresent = (float)d.StaffPresent,
|
||||
WorkRate = (float)FleetMaintenanceSystem.WorkRate(w, d), SpareParts = d.SpareParts, PartsTarget = d.PartsTarget,
|
||||
PartsReserved = reserved[d.Id.Value],
|
||||
};
|
||||
foreach (var j in d.Jobs)
|
||||
{
|
||||
reg.Jobs.Add(new WorkshopJobInfo
|
||||
{
|
||||
Train = j.Train.Value, Intervention = m.Interventions[j.Intervention].Id, InStall = j.InStall, Started = j.Started,
|
||||
Progress = (float)j.Progress, Days = (float)j.Days, Parts = j.Parts, QueuedDay = j.QueuedDay,
|
||||
});
|
||||
}
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (t.Removed || t.InWorkshop || t.MaintenanceDepot != d.Id || t.PlannedIntervention < 0) continue;
|
||||
var def = m.Interventions[t.PlannedIntervention];
|
||||
reg.Booked.Add(new WorkshopJobInfo { Train = t.Id.Value, Intervention = def.Id, Days = def.Days, Parts = Fleet.PartsFor(w, t, def), QueuedDay = -1 });
|
||||
}
|
||||
return reg;
|
||||
}
|
||||
|
||||
/// <summary>Testo italiano del motivo dei posti scoperti (per i lettori senza il blocco F4).</summary>
|
||||
public static string ReasonText(World w, UncoveredReason reason, LineId line, PaxClass cls) => reason switch
|
||||
{
|
||||
UncoveredReason.NoStation => "nessuna stazione serve il posto di lavoro",
|
||||
UncoveredReason.NoTownInReach => $"nessuna città raggiungibile entro {(cls == PaxClass.Staff ? w.Data.Balance.Employment.StaffMaxMinutes : w.Data.Balance.Employment.WorkerMaxMinutes):F0} min",
|
||||
UncoveredReason.NoFreeWorkers => "le città raggiungibili non hanno lavoratori liberi",
|
||||
UncoveredReason.NoStaffServices => "città senza servizi per il personale",
|
||||
UncoveredReason.LineCapacity => $"capacità delle carrozze insufficiente sulla {(line.IsValid && line.Value < w.Lines.Count ? w.Lines[line.Value].Name : "linea")}",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Registro degli impieghi della compagnia: industrie servite dai suoi treni e suoi depositi, con
|
||||
/// provenienze, posti scoperti e motivi, più le convenzioni proposte o attive.
|
||||
/// </summary>
|
||||
public static EmploymentReport Employment(World w, CompanyId company)
|
||||
{
|
||||
var report = new EmploymentReport { Day = w.Clock.Day };
|
||||
var places = new List<IWorkplace>();
|
||||
EmploymentSystem.Workplaces(w, places);
|
||||
foreach (var p in places)
|
||||
{
|
||||
bool mine = p is Depot depot && depot.Owner == company;
|
||||
var sources = new List<EmploymentSource>();
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
if (c.Workplace != p.Ref || (!mine && c.Carrier != company)) continue;
|
||||
sources.Add(new EmploymentSource
|
||||
{
|
||||
Town = c.Town.Value, HomeStation = c.HomeStation.Value, Line = c.Route.Count > 0 ? c.Route[0].Value : -1,
|
||||
Category = (byte)c.Category, Headcount = c.Headcount, Coverage = (float)c.Coverage,
|
||||
});
|
||||
}
|
||||
bool served = w.Network.Stations.Any(s => s.Owner == company && w.Network.IsAlive(s) && p is Industry ind && s.Industries.Contains(ind.Id));
|
||||
if (!mine && sources.Count == 0 && !served) continue;
|
||||
string reason = string.Join("; ", new[]
|
||||
{
|
||||
ReasonText(w, p.WorkersReason, p.WorkersReasonLine, PaxClass.Worker),
|
||||
ReasonText(w, p.StaffReason, p.StaffReasonLine, PaxClass.Staff),
|
||||
}.Where(x => x.Length > 0));
|
||||
report.Rows.Add(new EmploymentRow
|
||||
{
|
||||
Industry = p.Ref.Index, JobsWorkers = p.JobsWorkers, JobsStaff = p.JobsStaff,
|
||||
WorkersPresent = (float)p.WorkersPresent, StaffPresent = (float)p.StaffPresent, Reason = reason, Sources = sources,
|
||||
Kind = (byte)p.Ref.Kind, WorkersReason = (byte)p.WorkersReason, StaffReason = (byte)p.StaffReason,
|
||||
WorkersReasonLine = p.WorkersReasonLine.Value, StaffReasonLine = p.StaffReasonLine.Value,
|
||||
});
|
||||
}
|
||||
foreach (var a in w.Agreements)
|
||||
{
|
||||
if (a.Carrier != company) continue;
|
||||
report.Agreements.Add(new AgreementInfo
|
||||
{
|
||||
Id = a.Id.Value, Industry = a.Industry.Value, Carrier = a.Carrier.Value, SeatsPerDay = a.SeatsPerDay, MonthlyFee = a.MonthlyFee,
|
||||
State = (byte)a.State, ProposedDay = a.ProposedDay, StartDay = a.StartDay, EndDay = a.EndDay, Coverage = (float)a.Coverage,
|
||||
ShortDays = a.ShortDays,
|
||||
});
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
public static EdgeInfo Edge(World w, TrackEdge e)
|
||||
{
|
||||
float progress = 1;
|
||||
|
||||
@@ -20,6 +20,7 @@ public static class ProtocolTests
|
||||
yield return new Subscribe { X0 = -3, Y0 = 4, X1 = 300, Y1 = 200, Lod = 1 };
|
||||
yield return new CommandMessage { Seq = 99, Command = new BuildStationCommand(P, 3, "Stazione Nord") };
|
||||
yield return new SetSpeed { Speed = 4 };
|
||||
yield return new RequestDetail { Kind = DetailKind.Workshop, Target = 3 };
|
||||
yield return new ListSaves();
|
||||
yield return new Save { Name = "partita è bella" };
|
||||
yield return new Load { SaveId = "auto-0003" };
|
||||
@@ -61,8 +62,39 @@ public static class ProtocolTests
|
||||
{
|
||||
Industry = 2, JobsWorkers = 40, JobsStaff = 2, WorkersPresent = 39.5f, StaffPresent = 2, Reason = "capacità delle carrozze insufficiente",
|
||||
Sources = [new EmploymentSource { Town = 1, HomeStation = 3, Line = 1, Category = 0, Headcount = 28, Coverage = 0.97f }],
|
||||
Kind = 1, WorkersReason = 5, StaffReason = 4, WorkersReasonLine = 2, StaffReasonLine = -1,
|
||||
},
|
||||
],
|
||||
Agreements =
|
||||
[
|
||||
new AgreementInfo
|
||||
{
|
||||
Id = 4, Industry = 2, Carrier = 0, SeatsPerDay = 28, MonthlyFee = new Money(70000), State = 1, ProposedDay = 300,
|
||||
StartDay = 310, EndDay = 1030, Coverage = 0.95f, ShortDays = 2,
|
||||
},
|
||||
],
|
||||
};
|
||||
yield return new MaintenanceCard
|
||||
{
|
||||
Train = 12, Day = 400, Condition = 38.5f, Status = TrainMaintenanceStatus.Booked, Policy = 1, PolicyOverride = 2, Reserve = false,
|
||||
Failure = 1, FailedVehicle = 6, FailedComponent = "brakes", RescueHours = 2.5f, NextIntervention = "service", NextDueDays = -3.5f,
|
||||
PlannedIntervention = "repair_minor", MaintenanceDepot = 1, ServiceKmPerDay = 195, CostThisYear = new Money(123400),
|
||||
CostLastYear = new Money(98700), FailuresThisYear = 2, FailuresTotal = 5, CoveredBy = 14, Covering = -1,
|
||||
Vehicles =
|
||||
[
|
||||
new VehicleCard
|
||||
{
|
||||
Vehicle = 6, Type = "loco_steam_1850", OdometerKm = 45000, AgeYears = 3.5f, AgeFactor = 1,
|
||||
Components = [new ComponentCard { Component = "engine", Condition = 61.2f, WearPerDay = 0.8f }, new ComponentCard { Component = "brakes", Condition = 38.5f, WearPerDay = 1.1f }],
|
||||
},
|
||||
],
|
||||
History = [new MaintenanceRecordInfo { Day = 350, Intervention = "inspection", Cost = new Money(9000), Depot = 1, Parts = 0 }],
|
||||
};
|
||||
yield return new WorkshopRegister
|
||||
{
|
||||
Depot = 1, Day = 400, Stalls = 4, JobsStaff = 16, StaffPresent = 12.5f, WorkRate = 0.8f, SpareParts = 7, PartsTarget = 40, PartsReserved = 3,
|
||||
Jobs = [new WorkshopJobInfo { Train = 12, Intervention = "service", InStall = true, Started = true, Progress = 1.6f, Days = 3, Parts = 3, QueuedDay = 398 }],
|
||||
Booked = [new WorkshopJobInfo { Train = 13, Intervention = "inspection", Days = 1, QueuedDay = -1 }],
|
||||
};
|
||||
yield return new MarketTape
|
||||
{
|
||||
@@ -105,16 +137,24 @@ public static class ProtocolTests
|
||||
|
||||
private static EntityLists SampleEntities() => new()
|
||||
{
|
||||
Companies = [new CompanyInfo { Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2 }],
|
||||
Companies = [new CompanyInfo { Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2 }],
|
||||
Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }],
|
||||
Industries = [new IndustryInfo { Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1 }],
|
||||
Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }],
|
||||
Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }],
|
||||
Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }],
|
||||
Depots = [new DepotInfo { Id = 0, Owner = 0, Name = "Deposito", Node = 5, Position = P, Size = "small" }],
|
||||
Lines = [new LineInfo { Id = 0, Owner = 0, Name = "Linea 1", Color = "#e0a526", Stops = [new LineStop(new StationId(1)), new LineStop(new StationId(2), WaitFull: true, MaxWaitDays: 2)] }],
|
||||
Depots = [new DepotInfo { Id = 0, Owner = 0, Name = "Deposito", Node = 5, Position = P, Size = "small", Stalls = 2, JobsStaff = 8, StaffPercent = 75, SpareParts = 9, PartsTarget = 40, Jobs = 1, WaitingParts = true }],
|
||||
Lines = [new LineInfo { Id = 0, Owner = 0, Name = "Linea 1", Color = "#e0a526", Stops = [new LineStop(new StationId(1)), new LineStop(new StationId(2), WaitFull: true, MaxWaitDays: 2)], Policy = 0 }],
|
||||
Vehicles = [new VehicleInfo { Id = 7, Owner = 0, Type = "wagon_hopper", Depot = -1, Train = 2, Condition = 99.5f }],
|
||||
Trains = [new TrainInfo { Id = 2, Owner = 0, Name = "Treno 12", Line = 0, State = 3, Vehicles = [6, 7], MaxSpeedKmh = 60, LengthM = 27, Load = 20, Capacity = 20 }],
|
||||
Trains =
|
||||
[
|
||||
new TrainInfo
|
||||
{
|
||||
Id = 2, Owner = 0, Name = "Treno 12", Line = 0, State = 3, Vehicles = [6, 7], MaxSpeedKmh = 60, LengthM = 27, Load = 20, Capacity = 20,
|
||||
Condition = 41, Maintenance = TrainMaintenanceStatus.MinorFailure, Reserve = true, Policy = 2, NextIntervention = "inspection",
|
||||
NextDueDays = -2, MaintenanceDepot = 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/// <summary>Un esemplare per ogni tipo di comando, con campi non predefiniti.</summary>
|
||||
|
||||
@@ -209,6 +209,53 @@ public static class ServerTests
|
||||
Assert.True(client.Received.OfType<DailyDigest>().Any(), "resoconti giornalieri ricevuti");
|
||||
}
|
||||
|
||||
[Test(Description = "F4 in rete: riepilogo di manutenzione nei record, cartella, registro officina e registro impieghi su richiesta")]
|
||||
public static void MaintenanceDetailsOnRequest() => RunDetails().GetAwaiter().GetResult();
|
||||
|
||||
private static async Task RunDetails()
|
||||
{
|
||||
var scenario = ScenarioHelper.Load("valdoria");
|
||||
await using var server = ServerFixture.Start(scenario.World, tickMs: 50);
|
||||
await using var client = await TestClient.ConnectAsync(server);
|
||||
var w = client.World;
|
||||
await client.WaitFor(() => client.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot");
|
||||
int depot = await client.Ok(new BuildDepotCommand(K(13.2, 5.4), "medium", "Officina di Valdoria"));
|
||||
var loco = await client.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
|
||||
var wagon = await client.Do(new BuyVehicleCommand("wagon_box", new DepotId(depot), 1));
|
||||
int train = await client.Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagon.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
|
||||
await client.WaitUntil(() => w.Trains.ContainsKey(train) && w.Depots.ContainsKey(depot), "treno e officina nella copia locale");
|
||||
Assert.Equal((byte)100, w.Trains[train].Condition);
|
||||
Assert.Equal("inspection", w.Trains[train].NextIntervention);
|
||||
Assert.Equal(4, w.Depots[depot].Stalls);
|
||||
Assert.Equal(TestData.Data.Maintenance.Depots.InitialSpareParts, w.Depots[depot].SpareParts);
|
||||
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.TrainCard, Target = train });
|
||||
var card = await client.WaitFor(() => w.Cards.GetValueOrDefault(train), "cartella di manutenzione");
|
||||
Assert.Equal(2, card.Vehicles.Count);
|
||||
Assert.Equal(4, card.Vehicles[0].Components.Count);
|
||||
Assert.Equal("engine", card.Vehicles[0].Components[0].Component);
|
||||
Assert.Equal((byte)1, card.Policy);
|
||||
|
||||
await client.Ok(new ScheduleServiceCommand(new TrainId(train), "service"));
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Workshop, Target = depot });
|
||||
var register = await client.WaitFor(() => w.Workshops.GetValueOrDefault(depot), "registro officina");
|
||||
Assert.Equal(4, register.Stalls);
|
||||
Assert.Equal(1, register.Jobs.Count);
|
||||
Assert.Equal("service", register.Jobs[0].Intervention);
|
||||
await client.WaitUntil(() => w.Trains[train].Maintenance == TrainMaintenanceStatus.InWorkshop, "treno in officina nel riepilogo");
|
||||
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
|
||||
var report = await client.WaitFor(() => w.Employment, "registro degli impieghi");
|
||||
var row = report.Rows.FirstOrDefault(r => r.Kind == 1 && r.Industry == depot);
|
||||
Assert.True(row is not null, "l'officina compare nel registro");
|
||||
Assert.Equal(16, row!.JobsStaff);
|
||||
|
||||
// dettagli di entità altrui o inesistenti: nessuna risposta, nessun errore
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.TrainCard, Target = 999 });
|
||||
await client.Connection.SendAsync(new Ping { Nonce = 5 });
|
||||
await client.WaitFor(() => client.Received.OfType<Pong>().FirstOrDefault(p => p.Nonce == 5), "il server risponde ancora");
|
||||
}
|
||||
|
||||
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
|
||||
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();
|
||||
|
||||
|
||||
Reference in new issue
Block a user