337 lines
15 KiB
C#
337 lines
15 KiB
C#
using Godot;
|
|
using RailEnterprise.Client.App;
|
|
using RailEnterprise.Client.Net;
|
|
using RailEnterprise.Core.Commands;
|
|
using RailEnterprise.Core.Common;
|
|
using RailEnterprise.Core.Data;
|
|
using RailEnterprise.Core.Rail;
|
|
using RailEnterprise.Protocol.Messages;
|
|
using static RailEnterprise.Client.App.Localization;
|
|
using ExplainSubject = RailEnterprise.Core.Economy.ExplainSubject;
|
|
using ExplainTarget = RailEnterprise.Core.Economy.ExplainTarget;
|
|
|
|
namespace RailEnterprise.Client.Panels;
|
|
|
|
/// <summary>
|
|
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro, vendita
|
|
/// dei veicoli liberi e rinnovo dei treni con veicoli superati. Ogni azione è un comando; la lista si
|
|
/// aggiorna con i delta del server. Catalogo, obsolescenza, successori e valori di rivendita vengono dal
|
|
/// quadro della flotta (FleetReport, ADR 0020), chiesto all'apertura, a ogni nuovo giorno e dopo i comandi:
|
|
/// il pannello non calcola nulla.
|
|
/// </summary>
|
|
public partial class TrainsPanel : VBoxContainer
|
|
{
|
|
private readonly GameSession _session;
|
|
private readonly OptionButton _depot = new();
|
|
private readonly OptionButton _vehicle = new();
|
|
private readonly SpinBox _count = new() { MinValue = 1, MaxValue = 12, Value = 1 };
|
|
private readonly Label _modelInfo = UiTheme.Text("", 13, Palette.TextSecondary);
|
|
private readonly ItemList _inDepot = new() { SelectMode = ItemList.SelectModeEnum.Multi, CustomMinimumSize = new Vector2(0, 120) };
|
|
private readonly LineEdit _name = new() { PlaceholderText = T("Nome del treno") };
|
|
private readonly ItemList _trains = new() { CustomMinimumSize = new Vector2(0, 140) };
|
|
private readonly OptionButton _line = new();
|
|
private readonly Label _renewInfo = UiTheme.Text("", 13, Palette.TextSecondary);
|
|
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
|
private readonly List<int> _depotIds = [];
|
|
private readonly List<VehicleDef> _catalog = [];
|
|
private readonly List<int> _vehicleIds = [];
|
|
private readonly List<int> _trainIds = [];
|
|
private readonly List<int> _lineIds = [];
|
|
private int _version = -1;
|
|
private FleetReport? _fleetShown;
|
|
private long _requestedDay = long.MinValue;
|
|
private double _sinceRequest = double.MaxValue;
|
|
|
|
public event Action<int>? TrainSelected;
|
|
|
|
/// <summary>Pulsanti di acquisto, composizione e assegnazione (per l'evidenziazione del tutorial).</summary>
|
|
public Control? BuyButton { get; }
|
|
public Control? ComposeButton { get; }
|
|
public Control? AssignButton { get; }
|
|
|
|
public TrainsPanel(GameSession session)
|
|
{
|
|
_session = session;
|
|
AddThemeConstantOverride("separation", 8);
|
|
AddChild(UiTheme.TitleLabel(T("Treni"), 34));
|
|
AddChild(PanelKit.Pair(T("Deposito"), new Label()));
|
|
AddChild(_depot);
|
|
var buy = PanelKit.Row();
|
|
_vehicle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
|
buy.AddChild(_vehicle);
|
|
buy.AddChild(_count);
|
|
AddChild(buy);
|
|
_modelInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
|
AddChild(_modelInfo);
|
|
var buyButton = UiTheme.Primary(T("Compra veicoli"));
|
|
buyButton.Pressed += Buy;
|
|
AddChild(buyButton);
|
|
BuyButton = buyButton;
|
|
AddChild(UiTheme.Text(T("Veicoli liberi nel deposito (selezione multipla, in ordine)"), 13, Palette.TextSecondary));
|
|
AddChild(_inDepot);
|
|
// «perché»: valore del veicolo sotto il puntatore (residuo, valore contabile, rivendita)
|
|
WhyTooltip.Attach(_inDepot, () => HoveredId(_inDepot, _vehicleIds) is int v and >= 0
|
|
? new ExplainTarget(ExplainSubject.VehicleValue, v)
|
|
: null);
|
|
var compose = PanelKit.Row();
|
|
_name.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
|
compose.AddChild(_name);
|
|
var composeButton = new Button { Text = T("Componi") };
|
|
composeButton.Pressed += Compose;
|
|
compose.AddChild(composeButton);
|
|
ComposeButton = composeButton;
|
|
var sellButton = new Button { Text = T("Vendi") };
|
|
sellButton.Pressed += Sell;
|
|
compose.AddChild(sellButton);
|
|
AddChild(compose);
|
|
AddChild(PanelKit.Separator());
|
|
AddChild(UiTheme.Text(T("Treni della compagnia"), 14, bold: true));
|
|
AddChild(_trains);
|
|
WhyTooltip.Attach(_trains, () => HoveredId(_trains, _trainIds) is int t and >= 0
|
|
? new ExplainTarget(ExplainSubject.TrainCondition, t)
|
|
: null);
|
|
var assign = PanelKit.Row();
|
|
_line.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
|
assign.AddChild(_line);
|
|
var assignButton = new Button { Text = T("Assegna") };
|
|
assignButton.Pressed += Assign;
|
|
assign.AddChild(assignButton);
|
|
AssignButton = assignButton;
|
|
AddChild(assign);
|
|
var home = new Button { Text = T("Manda al deposito") };
|
|
home.Pressed += SendHome;
|
|
AddChild(home);
|
|
var renew = new Button { Text = T("Rinnova i veicoli superati") };
|
|
renew.Pressed += Renew;
|
|
AddChild(renew);
|
|
_renewInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
|
AddChild(_renewInfo);
|
|
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
|
AddChild(_status);
|
|
_depot.ItemSelected += _ => Refresh(force: true);
|
|
_vehicle.ItemSelected += _ => ShowModel();
|
|
_trains.ItemSelected += i =>
|
|
{
|
|
TrainSelected?.Invoke(_trainIds[(int)i]);
|
|
ShowRenewal();
|
|
};
|
|
}
|
|
|
|
public override void _Process(double delta)
|
|
{
|
|
var w = _session.World;
|
|
_sinceRequest += delta;
|
|
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
|
|
long today = Fmt.Today(w);
|
|
if (today != _requestedDay || (w.Fleet is null && _sinceRequest > 5)) RequestFleet(today);
|
|
bool fleetChanged = !ReferenceEquals(w.Fleet, _fleetShown);
|
|
if (w.EntityVersion != _version || fleetChanged) Refresh(force: fleetChanged);
|
|
}
|
|
|
|
private void RequestFleet(long day)
|
|
{
|
|
_requestedDay = day;
|
|
_sinceRequest = 0;
|
|
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
|
|
}
|
|
|
|
private int Company => _session.World.Summary?.CompanyId ?? 0;
|
|
|
|
private void Refresh(bool force)
|
|
{
|
|
var w = _session.World;
|
|
var fleet = w.Fleet;
|
|
_version = w.EntityVersion;
|
|
_fleetShown = fleet;
|
|
int selectedDepot = _depot.Selected >= 0 && _depot.Selected < _depotIds.Count ? _depotIds[_depot.Selected] : -1;
|
|
_depotIds.Clear();
|
|
_depot.Clear();
|
|
foreach (var d in w.Depots.Values.Where(d => d.Owner == Company).OrderBy(d => d.Id))
|
|
{
|
|
_depotIds.Add(d.Id);
|
|
_depot.AddItem(d.Name);
|
|
}
|
|
int di = _depotIds.IndexOf(selectedDepot);
|
|
_depot.Selected = di >= 0 ? di : _depotIds.Count > 0 ? 0 : -1;
|
|
|
|
if (_catalog.Count == 0 || force)
|
|
{
|
|
string? keep = _vehicle.Selected >= 0 && _vehicle.Selected < _catalog.Count ? _catalog[_vehicle.Selected].Id : null;
|
|
_catalog.Clear();
|
|
_vehicle.Clear();
|
|
if (fleet is not null)
|
|
{
|
|
// catalogo del server: solo i modelli in produzione, i superati segnati con il successore
|
|
foreach (var m in fleet.Models)
|
|
{
|
|
if (Def(m.Type) is not { } def) continue;
|
|
_catalog.Add(def);
|
|
string mark = m.Superseded ? $" · {T("superato")}" + (m.Successor.Length > 0 ? $" → {Def(m.Successor)?.NameIt ?? m.Successor}" : "") : "";
|
|
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}{mark}");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// in attesa del quadro del server: i modelli dell'anno, senza segni
|
|
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
|
|
{
|
|
_catalog.Add(def);
|
|
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
|
|
}
|
|
}
|
|
int index = keep is null ? -1 : _catalog.FindIndex(d => d.Id == keep);
|
|
_vehicle.Selected = index >= 0 ? index : _catalog.Count > 0 ? 0 : -1;
|
|
}
|
|
ShowModel();
|
|
|
|
int depot = _depot.Selected >= 0 ? _depotIds[_depot.Selected] : -1;
|
|
_vehicleIds.Clear();
|
|
_inDepot.Clear();
|
|
foreach (var v in w.Vehicles.Values.Where(v => v.Owner == Company && v.Depot == depot && v.Train < 0).OrderBy(v => v.Id))
|
|
{
|
|
_vehicleIds.Add(v.Id);
|
|
var info = fleet?.Vehicles.FirstOrDefault(x => x.Vehicle == v.Id);
|
|
string extra = info is null
|
|
? ""
|
|
: (info.Superseded ? $" · {T("superato")}" : "") + " · " + string.Format(T("rivendita {0}"), info.Resale);
|
|
_inDepot.AddItem($"{Def(v.Type)?.NameIt ?? v.Type} #{v.Id}{extra}");
|
|
if (info is { Superseded: true }) _inDepot.SetItemCustomFgColor(_inDepot.ItemCount - 1, Palette.Amber);
|
|
}
|
|
|
|
var selectedTrain = SelectedTrain;
|
|
_trainIds.Clear();
|
|
_trains.Clear();
|
|
foreach (var t in w.Trains.Values.Where(t => t.Owner == Company).OrderBy(t => t.Id))
|
|
{
|
|
_trainIds.Add(t.Id);
|
|
string line = t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var l) ? l.Name : T("senza linea");
|
|
var renewal = fleet?.Trains.FirstOrDefault(r => r.Train == t.Id);
|
|
string mark = renewal is null ? "" : " · " + (renewal.Booked ? T("rinnovo prenotato") : T("da rinnovare"));
|
|
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}{mark}");
|
|
if (renewal is { Booked: false }) _trains.SetItemCustomFgColor(_trains.ItemCount - 1, Palette.Amber);
|
|
}
|
|
int ti = _trainIds.IndexOf(selectedTrain);
|
|
if (ti >= 0) _trains.Select(ti);
|
|
|
|
int selectedLine = _line.Selected >= 0 && _line.Selected < _lineIds.Count ? _lineIds[_line.Selected] : -1;
|
|
_lineIds.Clear();
|
|
_line.Clear();
|
|
_lineIds.Add(-1);
|
|
_line.AddItem(T("Nessuna linea"));
|
|
foreach (var l in w.Lines.Values.Where(l => l.Owner == Company).OrderBy(l => l.Id))
|
|
{
|
|
_lineIds.Add(l.Id);
|
|
_line.AddItem(l.Name);
|
|
}
|
|
int li = _lineIds.IndexOf(selectedLine);
|
|
_line.Selected = li >= 0 ? li : Math.Min(1, _lineIds.Count - 1);
|
|
ShowRenewal();
|
|
}
|
|
|
|
private VehicleDef? Def(string id) => _session.World.Data.Vehicles.FirstOrDefault(v => v.Id == id);
|
|
|
|
/// <summary>Modello scelto nel catalogo: superato o no, successore con prestazioni e prezzo, ultimo anno di produzione.</summary>
|
|
private void ShowModel()
|
|
{
|
|
var fleet = _session.World.Fleet;
|
|
if (fleet is null || _vehicle.Selected < 0 || _vehicle.Selected >= _catalog.Count) { _modelInfo.Text = ""; return; }
|
|
var model = fleet.Models.FirstOrDefault(m => m.Type == _catalog[_vehicle.Selected].Id);
|
|
if (model is null) { _modelInfo.Text = ""; return; }
|
|
var parts = new List<string>();
|
|
if (model.Superseded)
|
|
{
|
|
var next = Def(model.Successor);
|
|
parts.Add(next is null
|
|
? string.Format(T("Superato dal {0}."), model.SupersededYear)
|
|
: string.Format(T("Superato dal {0}: successore {1} ({2} kW, {3} km/h, {4})."),
|
|
model.SupersededYear, next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
|
|
}
|
|
if (model.LastYear > 0) parts.Add(string.Format(T("In produzione fino al {0}."), model.LastYear));
|
|
_modelInfo.Text = string.Join(" ", parts);
|
|
}
|
|
|
|
/// <summary>Rinnovo del treno scelto: veicoli superati e spesa netta calcolati dal server.</summary>
|
|
private void ShowRenewal()
|
|
{
|
|
int train = SelectedTrain;
|
|
var renewal = train >= 0 ? _session.World.Fleet?.Trains.FirstOrDefault(r => r.Train == train) : null;
|
|
_renewInfo.Text = renewal is null
|
|
? ""
|
|
: string.Format(T("Rinnovo: {0} veicoli superati, spesa netta {1} dopo le rivendite."), renewal.Vehicles, renewal.NetCost)
|
|
+ (renewal.Booked ? " " + T("Rinnovo già prenotato.") : renewal.Affordable ? "" : " " + T("Cassa insufficiente."));
|
|
}
|
|
|
|
public static string StateName(TrainState s) => s switch
|
|
{
|
|
TrainState.InDepot => T("in deposito"),
|
|
TrainState.Moving => T("in marcia"),
|
|
TrainState.Waiting => T("in attesa di via libera"),
|
|
TrainState.Loading => T("in stazione"),
|
|
TrainState.Stalled => T("fermo in salita"),
|
|
TrainState.Broken => T("guasto"),
|
|
TrainState.NoRoute => T("senza percorso"),
|
|
_ => s.ToString(),
|
|
};
|
|
|
|
private void Result(CommandResultMessage r)
|
|
{
|
|
_status.Text = r.Message;
|
|
// acquisti, vendite e rinnovi cambiano il quadro della flotta
|
|
RequestFleet(Fmt.Today(_session.World));
|
|
}
|
|
|
|
private void Buy()
|
|
{
|
|
if (_depot.Selected < 0 || _vehicle.Selected < 0) { _status.Text = T("Serve un deposito"); return; }
|
|
_session.Command(new BuyVehicleCommand(_catalog[_vehicle.Selected].Id, new DepotId(_depotIds[_depot.Selected]), (int)_count.Value), Result);
|
|
}
|
|
|
|
private void Compose()
|
|
{
|
|
if (_depot.Selected < 0) return;
|
|
var selected = _inDepot.GetSelectedItems().OrderBy(i => i).Select(i => new VehicleId(_vehicleIds[i])).ToList();
|
|
if (selected.Count == 0) { _status.Text = T("Seleziona i veicoli da comporre"); return; }
|
|
string? name = string.IsNullOrWhiteSpace(_name.Text) ? null : _name.Text.Trim();
|
|
_session.Command(new ComposeTrainCommand(new DepotId(_depotIds[_depot.Selected]), selected, name), Result);
|
|
}
|
|
|
|
private void Sell()
|
|
{
|
|
var selected = _inDepot.GetSelectedItems().OrderBy(i => i).Select(i => _vehicleIds[i]).ToList();
|
|
if (selected.Count == 0) { _status.Text = T("Seleziona i veicoli da vendere"); return; }
|
|
foreach (int id in selected) _session.Command(new SellVehicleCommand(new VehicleId(id)), Result);
|
|
}
|
|
|
|
/// <summary>Identificativo della voce sotto il puntatore, -1 se il puntatore non è su una voce.</summary>
|
|
private static int HoveredId(ItemList list, List<int> ids)
|
|
{
|
|
int i = list.GetItemAtPosition(list.GetLocalMousePosition(), true);
|
|
return i >= 0 && i < ids.Count ? ids[i] : -1;
|
|
}
|
|
|
|
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel && sel[0] < _trainIds.Count ? _trainIds[sel[0]] : -1;
|
|
|
|
private void Assign()
|
|
{
|
|
int train = SelectedTrain;
|
|
if (train < 0 || _line.Selected < 0) { _status.Text = T("Seleziona un treno"); return; }
|
|
_session.Command(new AssignTrainCommand(new TrainId(train), new LineId(_lineIds[_line.Selected])), Result);
|
|
}
|
|
|
|
private void SendHome()
|
|
{
|
|
int train = SelectedTrain;
|
|
if (train < 0 || _depot.Selected < 0) { _status.Text = T("Seleziona un treno e un deposito"); return; }
|
|
_session.Command(new SendToDepotCommand(new TrainId(train), new DepotId(_depotIds[_depot.Selected])), Result);
|
|
}
|
|
|
|
private void Renew()
|
|
{
|
|
int train = SelectedTrain;
|
|
if (train < 0) { _status.Text = T("Seleziona un treno"); return; }
|
|
string intervention = _session.World.Fleet?.RenewalIntervention ?? "";
|
|
if (intervention.Length == 0) { _status.Text = T("Quadro della flotta in arrivo dal server…"); return; }
|
|
_session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
|
|
}
|
|
}
|