using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Scenarios;
using ViaFerrea.Tests.Harness;
using ViaFerrea.Tests.Scenarios;
namespace ViaFerrea.Tests.Rail;
/// Mondo con comandi di comodo per i test ferroviari.
public sealed class RailFixture
{
public World W { get; }
public LoadedScenario? Scenario { get; }
public CompanyId Me => W.Player.Id;
public RailFixture(World w, LoadedScenario? scenario = null)
{
W = w;
Scenario = scenario;
}
public static RailFixture Valdoria() { var s = ScenarioHelper.Load("valdoria"); return new RailFixture(s.World, s); }
public static Vec2 K(double x, double y) => new(x * 1000, y * 1000);
/// Esegue il comando nel prossimo tick e ne restituisce l'esito.
public CommandResult Do(GameCommand c, CompanyId? issuer = null)
{
W.Enqueue(c with { Issuer = issuer ?? Me });
W.RunTicks(1);
return W.DrainResults().Last();
}
public int Ok(GameCommand c, CompanyId? issuer = null)
{
var r = Do(c, issuer);
Assert.True(r.Ok, $"{c.Type}: {r.Error} {r.Message}");
return r.Created.Length > 0 ? r.Created[0] : -1;
}
/// Esegue giorni finché la condizione è vera (o scade il limite).
public bool RunUntil(Func condition, int maxDays)
{
for (int d = 0; d < maxDays * 8; d++)
{
if (condition()) return true;
W.RunTicks(W.Calendar.TicksPerDay / 8);
}
return condition();
}
/// Compra veicoli e compone un treno nel deposito.
public int Train(int depot, string loco, int locos, string car, int cars, string name)
{
var ids = new List();
ids.AddRange(W_Buy(loco, depot, locos));
if (cars > 0) ids.AddRange(W_Buy(car, depot, cars));
return Ok(new ComposeTrainCommand(new DepotId(depot), ids, name));
}
private IEnumerable W_Buy(string type, int depot, int count) =>
Do(new BuyVehicleCommand(type, new DepotId(depot), count)).Created.Select(i => new VehicleId(i));
///
/// Rete merci di Valdoria: stazione delle miniere, stazione dell'acciaieria, deposito e
/// tracciato per il valico; restituisce (miniera, acciaieria, deposito).
///
public (int Mine, int Mill, int Depot) BuildFreightNetwork(bool waitForConstruction = true)
{
int mine = Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
int mill = Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
int depot = Ok(new BuildDepotCommand(K(2.6, 4.4), "small", "Deposito Rocca Bruna"));
Ok(new BuildTrackCommand(Scenario!.Route("valico", Me).Polyline, AllowTunnels: false));
Ok(new BuildTrackCommand(new[] { K(2.6, 4.4), K(2.92, 4.95) }));
if (waitForConstruction)
Assert.True(RunUntil(() => W.Network.Edges.All(e => e.State == EdgeState.Active), 400), "cantieri completati");
return (mine, mill, depot);
}
}