using Godot;
using RailEnterprise.Client.Hud;
using RailEnterprise.Client.Map;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Screens;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Client.App;
///
/// Pilota automatico per il collaudo del client (-- --autopilot cartella): nella partita
/// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno,
/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo; poi apre
/// officine e impieghi (F4), la scheda del proprietario di un'industria, «Compagnie e borsa» e la
/// Cronaca provvisoria (F5).
///
public partial class AutoPilot : Node
{
private readonly GameScreen _game;
private readonly string _out;
public AutoPilot(GameScreen game, string outDir)
{
_game = game;
_out = outDir;
}
private GameSession Session => _game.Session;
private ClientWorld World => _game.Session.World;
public override async void _Ready()
{
int code = 0;
try
{
await Run();
GD.Print("autopilot: ok");
}
catch (Exception e)
{
GD.PrintErr($"autopilot: FALLITO {e.Message}\n{e.StackTrace}");
code = 1;
}
GetTree().Quit(code);
}
private async Task Frame() => await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
private async Task Until(Func condition, string what, double timeoutS = 120)
{
ulong start = Time.GetTicksMsec();
while (!condition())
{
if (Time.GetTicksMsec() - start > timeoutS * 1000) throw new TimeoutException(what);
await Frame();
}
}
private Task Do(GameCommand command)
{
var tcs = new TaskCompletionSource();
Session.Command(command, r => tcs.TrySetResult(r));
return tcs.Task;
}
private async Task Ok(GameCommand command)
{
var r = await Do(command);
if (!r.Ok) throw new InvalidOperationException($"{command.Type}: {r.Message}");
GD.Print($"autopilot: {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
/// Attende una condizione al massimo per il tempo indicato, senza fallire.
private async Task Wait(Func condition, double timeoutS)
{
ulong start = Time.GetTicksMsec();
while (!condition())
{
if (Time.GetTicksMsec() - start > timeoutS * 1000) return false;
await Frame();
}
return true;
}
private async Task Shot(string name, int settleFrames = 30)
{
for (int i = 0; i < settleFrames; i++) await Frame();
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
var image = GetViewport().GetTexture().GetImage();
string path = Path.Combine(_out, name + ".jpg");
image.SaveJpg(path, 0.88f);
GD.Print($"autopilot: schermata {path}");
}
private async Task Run()
{
Directory.CreateDirectory(_out);
var summary = World.Summary!;
Session.Send(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 });
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
await Until(() => World.Chunks.Count == chunks && World.Towns.Count > 0, "terreno");
await Shot("01_avvio", 90);
await Ok(new TakeLoanCommand(Money.FromLire(200_000)));
var site = BridgeSiteFinder.Find(World) ?? throw new InvalidOperationException("nessun sito con ponte");
int a = await Ok(new BuildStationCommand(site.A, 2));
int b = await Ok(new BuildStationCommand(site.B, 2));
int depot = await Ok(new BuildDepotCommand(site.Depot, "small"));
await Until(() => World.Stations.ContainsKey(b) && World.Depots.ContainsKey(depot), "stazioni");
var main = new BuildTrackCommand([site.A, site.B]);
var plan = World.PreviewTrack(main);
await Ok(main with { ExpectedCostCents = plan.TotalCost.Cents });
await Until(() => World.Edges.Count > 0, "binario");
var spur = new BuildTrackCommand([site.Depot, site.A]);
await Ok(spur with { ExpectedCostCents = World.PreviewTrack(spur).TotalCost.Cents });
// vista d'insieme del cantiere
var center = MapScale.V((site.A + site.B) / 2);
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("02_cantiere");
Session.SetSpeed(8);
await Until(() => World.Edges.Count >= 2 && World.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri", 240);
var loco = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var wagons = await Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3));
int train = await Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
var loco2 = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
var coaches = await Do(new BuyVehicleCommand("coach_worker", new DepotId(depot), 2));
int train2 = await Ok(new ComposeTrainCommand(new DepotId(depot), loco2.Created.Concat(coaches.Created).Select(i => new VehicleId(i)).ToList(), "Treno 2"));
int line = await Ok(new CreateLineCommand("Linea 1, collaudo", "#e0a526", [new LineStop(new StationId(a)), new LineStop(new StationId(b))]));
await Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
Session.SetSpeed(1);
await Until(() => World.Motions.TryGetValue(train, out var m) && m.Speed > 3, "treno in moto", 120);
await Ok(new AssignTrainCommand(new TrainId(train2), new LineId(line)));
_game.Map.CenterOn(center);
_game.Map.SetZoom(0.22f);
await Shot("03_linea");
// ponte da vicino (immagine 02)
_game.Map.CenterOn(MapScale.V(site.River));
_game.Map.SetZoom(0.9f);
await Shot("04_ponte");
// treno da vicino (immagine 03): la camera lo segue per qualche fotogramma
for (int i = 0; i < 40; i++)
{
if (World.TrainHead(train) is { } head) _game.Map.CenterOn(MapScale.V(head));
_game.Map.SetZoom(1.4f);
await Frame();
}
_game.SelectTrain(train);
await Shot("05_treno", 5);
// scheda del treno con la mappa d'insieme
_game.Map.SetZoom(0.3f);
await Shot("06_scheda_treno", 20);
// strumento binari con il profilo di un tracciato in collina
_game.UseTool(Tool.Track);
var dir = (site.B - site.A).Normalized();
var normal = new Vec2(-dir.Y, dir.X);
var p0 = MapScale.V(site.B);
var p1 = MapScale.V(site.B + normal * 2500);
var p2 = MapScale.V(site.B + normal * 4000 + dir * 1500);
_game.SetTrackPoints([p0, p1], p2);
_game.Map.CenterOn(MapScale.V(site.B + normal * 2000 + dir * 500));
_game.Map.SetZoom(0.2f);
await Shot("07_profilo", 40);
_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);
await IndustriesAndMarket(site.A);
}
/// F5: scheda del proprietario di un'industria, borsa con il libro dei soci, Cronaca provvisoria.
private async Task IndustriesAndMarket(Vec2 near)
{
int me = World.Summary!.CompanyId;
var anchor = MapScale.V(near);
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
_game.OpenIndustry(industry.Id);
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
// al livello iniziale il server rifiuta l'acquisto: il messaggio compare sulla mappa
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
_game.Map.CenterOn(MapScale.V(industry.Position));
_game.Map.SetZoom(0.3f);
await Shot("12_industria", 40);
_game.ScrollPanel(1);
await Shot("12b_industria_scorte", 20);
_game.ScrollPanel(0);
// borsa: azioni di una compagnia IA, qualche mese di prezzi, poi listino e libro dei soci
var ai = World.Companies.Values.Where(c => !c.IsPlayer && c.Listed && !c.Bankrupt).OrderBy(c => c.Id).FirstOrDefault();
if (ai is not null) await Ok(new BuySharesCommand(new CompanyId(ai.Id), 20_000, Money.Zero));
_game.OpenCompanies(ai?.Id ?? me);
Session.SetSpeed(8);
bool history = await Wait(() => ai is null || (World.CompanyCards.TryGetValue(ai.Id, out var card) && card.PriceHistory.Count >= 3), 200);
if (!history) GD.Print("autopilot: storico dei prezzi ancora corto");
Session.SetSpeed(1);
await Until(() => World.Tape is not null, "listino di borsa", 60);
await Shot("13_compagnie", 60);
_game.OpenCompanies(me);
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
await Shot("14_compagnia_giocatore", 40);
// Cronaca provvisoria
_game.OpenChronicle();
await Until(() => _game.ChronicleVisible, "cronaca", 30);
await Shot("15_cronaca", 30);
}
}