using Godot;
using RailEnterprise.Client.Screens;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Tutorial;
///
/// Collega il tutorial alla partita: raccoglie i fatti che il client osserva (entità della compagnia nella
/// copia locale, esiti dei comandi, pannello aperto, camera, velocità, anteprime del tracciato), fa avanzare
/// , aggiorna e salva l'avanzamento per partita.
/// Non invia comandi e non decide regole. F1 riapre o nasconde il tutorial.
///
public partial class TutorialController : Node
{
private const string ScriptPath = "res://assets/tutorial/tutorial.json";
private const double FactsInterval = 0.2;
private readonly GameScreen _game;
private bool _requested;
private bool _restart;
private readonly CanvasLayer _layer = new() { Layer = 3 };
private readonly TutorialOverlay _overlay = new();
private readonly TutorialFacts _facts = new();
private readonly Dictionary _vehicleKinds = [];
private TutorialMachine? _machine;
private string _gameKey = "";
private bool _visible;
private int _shownIndex = -1;
private double _sinceFacts = FactsInterval;
private Vector2? _lastCamera;
private float _lastZoom;
private byte? _lastSpeed;
/// casella «Mostra il tutorial» del menu
/// opzione «Tutorial» del menu: dal primo passo anche se già fatto
public TutorialController(GameScreen game, bool requested, bool restart)
{
_game = game;
_requested = requested;
_restart = restart;
}
public override void _Ready()
{
try
{
using var file = Godot.FileAccess.Open(ScriptPath, Godot.FileAccess.ModeFlags.Read)
?? throw new FileNotFoundException(ScriptPath);
var script = TutorialScript.Parse(file.GetAsText());
var errors = script.Validate();
if (errors.Count > 0) throw new InvalidDataException(string.Join("; ", errors));
_machine = new TutorialMachine(script);
}
catch (Exception e)
{
GD.PushWarning($"Tutorial non disponibile: {e.Message}");
return;
}
foreach (var v in _game.Session.World.Data.Vehicles) _vehicleKinds[v.Id] = v.Kind;
AddChild(_layer);
_layer.AddChild(_overlay);
_overlay.NextPressed += () => Act(m => m.Next());
_overlay.SkipPressed += () => Act(m => m.Skip());
_overlay.ClosePressed += () => Act(m => m.Close());
_game.Session.MessageApplied += OnMessage;
OpenForGame();
}
public override void _ExitTree() => _game.Session.MessageApplied -= OnMessage;
/// All'avvio e a ogni Welcome (nuova partita, caricamento): chiave della partita e piano di apertura.
private void OpenForGame()
{
if (_machine is null || _game.Session.World.Summary is not { } s) return;
_gameKey = TutorialProgress.GameKey(s.Seed, s.TerrainHash, s.CompanyId);
var saved = TutorialSettings.Read(_gameKey);
switch (TutorialMachine.Plan(_requested, _restart, saved))
{
case TutorialLaunch.StartFresh:
_machine.Restart();
Save();
_visible = true;
break;
case TutorialLaunch.Resume:
_machine.Restore(saved!.Value);
_visible = true;
break;
default:
if (saved is { } p) _machine.Restore(p);
else _machine.Close();
_visible = false;
break;
}
// casella e opzione del menu valgono per la partita aperta, non per le successive (Nuova partita+)
_requested = _restart = false;
_lastCamera = null;
_lastSpeed = null;
_shownIndex = -1;
Refresh();
}
private void OnMessage(IMessage message)
{
switch (message)
{
case Welcome:
OpenForGame();
break;
case CommandResultMessage { Ok: true } r:
_facts.Add(TutorialFacts.CommandCounter((CommandType)r.Type), 1);
break;
}
}
private void Act(Action action)
{
if (_machine is null) return;
action(_machine);
Save();
if (_machine.Status != TutorialStatus.Active) _visible = false;
Refresh();
}
private void Save()
{
if (_machine is not null && _gameKey.Length > 0) TutorialSettings.Save(_gameKey, _machine.Progress);
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (_machine is null || e is not InputEventKey { Pressed: true, Echo: false, Keycode: Key.F1 }) return;
if (_visible)
{
// F1 nasconde soltanto: il tutorial in corso resta salvato
_visible = false;
}
else
{
// riapre dal passo salvato, o dall'inizio se era chiuso o completato
if (_machine.Status != TutorialStatus.Active) _machine.Restart();
_visible = true;
_shownIndex = -1;
Save();
}
Refresh();
GetViewport().SetInputAsHandled();
}
public override void _Process(double delta)
{
if (_machine is null) return;
TrackCameraAndSpeed();
_sinceFacts += delta;
if (_sinceFacts >= FactsInterval)
{
_sinceFacts = 0;
CollectWorldFacts();
if (_visible)
{
string? title = _machine.Current is { } step ? T(step.Title) : null;
if (_machine.Update(_facts))
{
Save();
if (title is not null) _overlay.Flash(title);
// completato l'ultimo passo il riquadro si chiude
if (_machine.Status != TutorialStatus.Active) _visible = false;
}
}
}
Refresh();
}
/// Spostamento della camera (in schermate), zoom (in logaritmi) e cambi di velocità, sommati.
private void TrackCameraAndSpeed()
{
var map = _game.Map;
var camera = map.Camera.Position;
float zoom = map.Zoom;
if (_lastCamera is { } last && zoom > 0 && _lastZoom > 0)
{
if (Math.Abs(zoom - _lastZoom) > 1e-6)
{
// lo zoom attorno al cursore sposta anche la camera: non è uno spostamento
_facts.Add("mapZoom", Math.Abs(Math.Log(zoom / _lastZoom)));
}
else
{
float screen = map.GetViewportRect().Size.X / zoom;
if (screen > 0) _facts.Add("mapPan", camera.DistanceTo(last) / screen);
}
}
_lastCamera = camera;
_lastZoom = zoom;
var w = _game.Session.World;
byte speed = _game.Session.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
if (_lastSpeed is { } s && s != speed) _facts.Add("speedChanges", 1);
_lastSpeed = speed;
}
/// Entità della compagnia nella copia locale, pannello aperto, anteprime del tracciato.
private void CollectWorldFacts()
{
var w = _game.Session.World;
int me = w.Summary?.CompanyId ?? -1;
int edges = 0, active = 0, locos = 0, cars = 0, trains = 0, onLine = 0;
foreach (var e in w.Edges.Values)
{
if (e.Owner != me) continue;
edges++;
if (e.State == (byte)EdgeState.Active) active++;
}
foreach (var v in w.Vehicles.Values)
{
if (v.Owner != me || !_vehicleKinds.TryGetValue(v.Type, out var kind)) continue;
if (kind == VehicleKind.Locomotive) locos++;
else cars++;
}
foreach (var t in w.Trains.Values)
{
if (t.Owner != me) continue;
trains++;
if (t.Line >= 0) onLine++;
}
_facts.Set("stations", w.Stations.Values.Count(s => s.Owner == me));
_facts.Set("depots", w.Depots.Values.Count(d => d.Owner == me));
_facts.Set("edges", edges);
_facts.Set("edgesActive", active);
// i cantieri sono gli archi non ancora in funzione (dismessi compresi: non bloccano un tutorial nuovo)
_facts.Set("edgesBuilding", w.Edges.Values.Count(e => e.Owner == me && e.State == (byte)EdgeState.UnderConstruction));
_facts.Set("locomotives", locos);
_facts.Set("cars", cars);
_facts.Set("trains", trains);
_facts.Set("lines", w.Lines.Values.Count(l => l.Owner == me));
_facts.Set("trainsOnLine", onLine);
_facts.Set("trackPreviews", _game.TrackPreviews);
_facts.Panel = _game.CurrentTool.ToString().ToLowerInvariant();
}
/// Testi del passo corrente, posizione del riquadro ed elemento evidenziato.
private void Refresh()
{
if (_machine is null) return;
bool show = _visible && _machine.Current is not null && !_game.ChronicleVisible && _game.Session.IsOpen;
_overlay.Visible = show;
if (!show) return;
var step = _machine.Current!;
if (_shownIndex != _machine.Index)
{
_shownIndex = _machine.Index;
_overlay.ShowStep(_machine.Index + 1, _machine.Script.Steps.Count, T(step.Title), T(step.Text), step.IsInformative, _machine.IsLast);
}
_overlay.Area = _game.TutorialArea();
Control? target = null;
if (step.Highlight is { } h) target = Shown(_game.TutorialTarget(h));
if (target is null && step.Fallback is { } f) target = Shown(_game.TutorialTarget(f));
_overlay.Target = target?.GetGlobalRect();
}
private static Control? Shown(Control? c) => c is not null && IsInstanceValid(c) && c.IsVisibleInTree() && c.Size.X > 0 ? c : null;
}