F2: pianificatore dei binari, profilo altimetrico e scenario Valdoria

- TrackGeometry: polilinea raccordata con il raggio della classe
- TrackPlanner: campioni ogni 25 m, due passate di pendenza, smussatura,
  franchi sui fiumi, classificazione delle opere, costi, giorni, vincoli
  per era (campate per classe di fiume, lunghezza delle gallerie)
- Scenari a mano (ScenarioLoader) e tests/scenarios/valdoria.json
- viaferrea-tools profile; industrie al prezzo globale; servizi di base

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-01 22:54:57 +00:00
1 parent 7cb98fa206
commit 259e6ab65f
21 files changed
+1558 -16

No files matched your search

@@ -0,0 +1,44 @@
using ViaFerrea.Core.Map;
namespace ViaFerrea.Tests.Rail;
/// <summary>Terreni costruiti a mano per i test del pianificatore (celle da 100 m).</summary>
public static class SyntheticTerrain
{
public static Terrain Build(int width, int height, Func<double, double, double> heightAtMeters, Func<int, int, CellType>? type = null)
{
var t = new Terrain(width, height, 100, 64);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double hx = (x + 0.5) * 100, hy = (y + 0.5) * 100;
t.Heights[t.Index(x, y)] = Terrain.ToDecimeters(heightAtMeters(hx, hy));
t.Types[t.Index(x, y)] = (byte)(type?.Invoke(x, y) ?? CellType.Plain);
}
}
return t;
}
public static Terrain Flat(int size = 60, double h = 100) => Build(size, size, (_, _) => h);
/// <summary>Collina a cupola centrata in (cx, cy) metri.</summary>
public static Func<double, double, double> Hill(double cx, double cy, double radiusM, double heightM, double baseM = 100) =>
(x, y) =>
{
double r = Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / radiusM;
return baseM + (r >= 1 ? 0 : heightM * (1 - r * r) * (1 - r * r));
};
/// <summary>Pianura con un fiume nord-sud largo «widthCells» celle intorno a x = riverX metri.</summary>
public static Terrain River(int size, double riverXm, int widthCells, double baseM = 100, double waterM = 96)
{
int x0 = (int)(riverXm / 100) - widthCells / 2;
var t = Build(size, size, (x, _) => (int)(x / 100) >= x0 && (int)(x / 100) < x0 + widthCells ? waterM : baseM,
(x, _) => x >= x0 && x < x0 + widthCells ? CellType.Water : CellType.Plain);
for (int y = 0; y < size; y++)
for (int x = x0; x < x0 + widthCells; x++)
t.RiverWidth[t.Index(x, y)] = (byte)Math.Min(4, widthCells);
return t;
}
}
@@ -0,0 +1,170 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Rail;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Rail;
public static class TrackPlannerTests
{
private static TrackPlanContext Ctx(Terrain t, int year = 1850, double costMultiplier = 1.0) =>
new() { Data = TestData.Data, Sampler = new TerrainSampler(t), Year = year, CostMultiplier = costMultiplier };
private static TrackPlanRequest Line(params (double X, double Y)[] pts) =>
new() { Polyline = pts.Select(p => new Vec2(p.X, p.Y)).ToList(), AllowBridges = true, AllowTunnels = true };
[Test]
public static void FlatStraightLineIsAllNaturalWithExpectedCostAndDays()
{
var plan = TrackPlanner.Plan(Ctx(SyntheticTerrain.Flat()), Line((1000, 3000), (3000, 3000)));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
Assert.Equal(1, plan.Works.Count);
Assert.Equal(WorkKind.Natural, plan.Works[0].Kind);
Assert.Approx(2000, plan.LengthM, 1e-6);
Assert.Equal(81, plan.Samples.Count, "un campione ogni 25 m");
var c = TestData.Data.Construction;
Assert.Equal((long)Math.Round(2000 * c.Costs.BasePerMeter), plan.WorksCost.Cents);
Assert.Equal(10, plan.Days, "200 m al giorno su sede naturale");
Assert.Approx(0, plan.MaxGradient, 1e-12);
}
[Test(Description = "Le due passate rispettano gMax ovunque e lasciano gli estremi alla quota del terreno")]
public static void ProfileRespectsMaxGradientOnRandomTerrain()
{
var rng = new Rng(77);
for (int trial = 0; trial < 25; trial++)
{
var noise = new ValueNoise(rng.NextU64());
double amp = rng.NextDouble(20, 200);
var t = SyntheticTerrain.Build(80, 80, (x, y) => 300 + amp * noise.Fbm(x, y, 4, 3000, 0.5, 2));
var req = Line((500, rng.NextDouble(500, 7500)), (4000, rng.NextDouble(500, 7500)), (7500, rng.NextDouble(500, 7500)))
with { HeightOffsetM = rng.NextDouble(-20, 20) };
var plan = TrackPlanner.Plan(Ctx(t), req);
if (!plan.Valid && plan.Errors.All(e => e.Code is PlanIssueCode.TunnelTooLong or PlanIssueCode.RadiusTooSmall)) continue;
Assert.True(plan.Valid, $"prova {trial}: {string.Join("; ", plan.Errors.Select(e => e.Message))}");
double g = plan.GradientLimit;
for (int i = 1; i < plan.Samples.Count; i++)
{
double grade = Math.Abs(plan.Samples[i].TrackM - plan.Samples[i - 1].TrackM) / (plan.Samples[i].S - plan.Samples[i - 1].S);
Assert.True(grade <= g + 1e-9, $"prova {trial}: pendenza {grade:P3} al km {plan.Samples[i].S / 1000:F2}");
}
Assert.Approx(plan.Samples[0].TerrainM, plan.Samples[0].TrackM, 0.05);
Assert.Approx(plan.Samples[^1].TerrainM, plan.Samples[^1].TrackM, 0.05);
}
}
[Test(Description = "Collina ripida senza gallerie: il tracciato viola gMax e viene rifiutato")]
public static void SteepHillWithoutTunnelsIsRejected()
{
var t = SyntheticTerrain.Build(60, 30, SyntheticTerrain.Hill(3000, 1500, 1200, 120));
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 1500), (5500, 1500)) with { AllowTunnels = false });
Assert.False(plan.Valid);
Assert.Equal(PlanIssueCode.GradientExceeded, plan.Errors[0].Code);
}
[Test]
public static void HillWithTunnelsProducesCuttingsAndATunnel()
{
var t = SyntheticTerrain.Build(60, 30, SyntheticTerrain.Hill(3000, 1500, 700, 50));
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 1500), (5500, 1500)));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
Assert.True(plan.LengthOf(WorkKind.Tunnel) > 0, "galleria");
Assert.True(plan.LengthOf(WorkKind.Cutting) > 0, "trincee agli imbocchi");
Assert.True(plan.LengthOf(WorkKind.Tunnel) <= 1000, "entro il limite del 1850");
// la galleria costa 12 volte la sede naturale al metro
var tunnel = plan.Works.First(w => w.Kind == WorkKind.Tunnel);
Assert.Approx(12 * TestData.Data.Construction.Costs.BasePerMeter * tunnel.LengthM, tunnel.CostCents, tunnel.CostCents * 1e-9 + 1);
Assert.Equal((int)Math.Ceiling(tunnel.LengthM / 8), tunnel.Days, "8 m al giorno in galleria");
}
[Test]
public static void LongTunnelIsLimitedByEra()
{
var t = SyntheticTerrain.Build(80, 30, SyntheticTerrain.Hill(4000, 1500, 2600, 160));
var req = Line((300, 1500), (7700, 1500));
var early = TrackPlanner.Plan(Ctx(t, 1850), req);
Assert.True(early.Errors.Any(e => e.Code == PlanIssueCode.TunnelTooLong), "nel 1850 la galleria supera 1 km");
var later = TrackPlanner.Plan(Ctx(t, 1900), req);
Assert.True(later.Valid, string.Join("; ", later.Errors.Select(e => e.Message)));
}
[Test(Description = "Ponte obbligatorio sull'acqua, con luce libera e rampe entro gMax")]
public static void RiverRequiresBridgeWithClearance()
{
var t = SyntheticTerrain.River(60, 3000, 2);
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
var bridge = plan.Works.Single(w => w.Kind == WorkKind.Bridge);
Assert.True(bridge.StartM < 2500 && bridge.EndM > 2500, "il ponte scavalca il fiume (x = 3 km, cioè s = 2,5 km)");
foreach (var s in plan.Samples.Where(s => s.Cell == CellType.Water))
Assert.True(s.TrackM >= s.TerrainM + TestData.Data.Construction.Profile.RiverClearanceM - 1e-6, "luce libera di 6 m");
Assert.True(plan.LengthOf(WorkKind.Embankment) > 0, "rampe in rilevato verso il ponte");
Assert.Equal("wood", plan.BridgeType);
var noBridges = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)) with { AllowBridges = false });
Assert.Equal(PlanIssueCode.BridgeNeeded, noBridges.Errors[0].Code);
}
[Test(Description = "Campata massima per era: un fiume di classe 3 (120 m) non si passa in legno (60 m) ma sì in ferro (150 m)")]
public static void WideRiverNeedsLongerSpanEra()
{
var t = SyntheticTerrain.River(60, 3000, 3, waterM: 96);
var plan1850 = TrackPlanner.Plan(Ctx(t, 1850), Line((500, 3000), (5500, 3000)));
Assert.True(plan1850.Errors.Any(e => e.Code == PlanIssueCode.BridgeTooLong), "nel 1850 il legno non basta");
var plan1870 = TrackPlanner.Plan(Ctx(t, 1870), Line((500, 3000), (5500, 3000)));
Assert.True(plan1870.Valid, string.Join("; ", plan1870.Errors.Select(e => e.Message)));
Assert.Equal("iron", plan1870.BridgeType);
}
[Test]
public static void ClassificationFollowsHeightDifference()
{
// valle leggera: con lo scostamento +6 m il binario corre in rilevato
var t = SyntheticTerrain.Flat(60);
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)) with { HeightOffsetM = 6 });
Assert.True(plan.Valid);
Assert.True(plan.LengthOf(WorkKind.Embankment) > 3000, "rilevato di 6 m nel mezzo");
Assert.True(plan.Works.Where(w => w.Kind == WorkKind.Embankment).All(w => w.MaxHeightM <= 8 + 1e-9));
// con −6 m in trincea
var cut = TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000)) with { HeightOffsetM = -6 });
Assert.True(cut.LengthOf(WorkKind.Cutting) > 3000);
// il costo del rilevato cresce con l'altezza: ×(1 + 0,25·d)
Assert.True(plan.WorksCost.Cents > TrackPlanner.Plan(Ctx(t), Line((500, 3000), (5500, 3000))).WorksCost.Cents * 1.5);
}
[Test]
public static void SharpCurvesAreRejectedAndCurveSpeedIsLimited()
{
var t = SyntheticTerrain.Flat(60);
var tight = TrackPlanner.Plan(Ctx(t), Line((1000, 1000), (1100, 1000), (1100, 1100)));
Assert.True(tight.Errors.Any(e => e.Code == PlanIssueCode.RadiusTooSmall));
var ok = TrackPlanner.Plan(Ctx(t), Line((1000, 1000), (3000, 1000), (3000, 3000)));
Assert.True(ok.Valid, string.Join("; ", ok.Errors.Select(e => e.Message)));
Assert.Approx(200, ok.MinRadiusM, 1e-6);
double curveSpeed = 3.6 * Math.Sqrt(0.65 * 200);
Assert.Approx(curveSpeed, ok.Samples.Min(s => s.SpeedLimitKmh), 1e-6);
Assert.Approx(2000 + 2000 - 2 * 200 + Math.PI / 2 * 200, ok.LengthM, 1e-6, "lunghezza con il raccordo");
}
[Test]
public static void TownsAndIndustriesCannotBeCrossed()
{
var t = SyntheticTerrain.Build(60, 60, (_, _) => 100, (x, y) => x == 30 && y == 30 ? CellType.Town : CellType.Plain);
var plan = TrackPlanner.Plan(Ctx(t), Line((500, 3050), (5500, 3050)));
Assert.Equal(PlanIssueCode.ForbiddenArea, plan.Errors[0].Code);
}
[Test]
public static void ClassMultipliesCostAndDifficultyToo()
{
var t = SyntheticTerrain.Flat();
var basePlan = TrackPlanner.Plan(Ctx(t, 1990), Line((500, 3000), (4500, 3000)));
var fast = TrackPlanner.Plan(Ctx(t, 1990), Line((500, 3000), (4500, 3000)) with { TrackClass = "c160", DoubleTrack = true, Electrified = true });
Assert.True(fast.Valid, string.Join("; ", fast.Errors.Select(e => e.Message)));
Assert.Approx(2.2 * 1.8 * 1.35, (double)fast.WorksCost.Cents / basePlan.WorksCost.Cents, 1e-6);
var hard = TrackPlanner.Plan(Ctx(t, 1990, 1.5), Line((500, 3000), (4500, 3000)));
Assert.Approx(1.5, (double)hard.TotalCost.Cents / basePlan.TotalCost.Cents, 1e-6);
var early = TrackPlanner.Plan(Ctx(t, 1850), Line((500, 3000), (4500, 3000)) with { TrackClass = "c160" });
Assert.Equal(PlanIssueCode.ClassNotAvailable, early.Errors[0].Code);
}
}
@@ -0,0 +1,34 @@
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Scenarios;
namespace ViaFerrea.Tests.Scenarios;
/// <summary>Accesso agli scenari di riferimento copiati accanto ai test.</summary>
public static class ScenarioHelper
{
public static string PathOf(string name)
{
string beside = Path.Combine(AppContext.BaseDirectory, "scenarios", name + ".json");
if (File.Exists(beside)) return beside;
var dir = new DirectoryInfo(Directory.GetCurrentDirectory());
while (dir is not null)
{
string candidate = Path.Combine(dir.FullName, "tests", "ViaFerrea.Tests", "scenarios", name + ".json");
if (File.Exists(candidate)) return candidate;
dir = dir.Parent;
}
throw new FileNotFoundException($"Scenario {name} non trovato");
}
public static LoadedScenario Load(string name) => ScenarioLoader.LoadFile(TestData.Data, PathOf(name));
public static TrackPlanContext PlanContext(World w) => new()
{
Data = w.Data,
Sampler = w.Sampler,
Year = w.Clock.Year,
CostMultiplier = w.Difficulty.ConstructionCostMultiplier,
NearestTownEdgeKm = p => w.Towns.Min(t => w.TownEdgeDistanceKm(t, p)),
};
}
@@ -0,0 +1,55 @@
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Rail;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Scenarios;
public static class ValdoriaTests
{
[Test]
public static void ScenarioLoadsWithExpectedEntities()
{
var s = ScenarioHelper.Load("valdoria");
var w = s.World;
Assert.Equal(160, w.Terrain.Width);
Assert.Equal(3, w.Towns.Count);
Assert.Equal("Valdoria", w.Towns[0].Name);
Assert.Equal(12400, w.Towns[0].Population);
Assert.True(w.Industries.Any(i => i.Def.Id == "steel_mill"));
Assert.Equal(2, w.Sites.Count);
Assert.True(w.Terrain.Types.Count(t => t == (byte)CellType.Water) > 50, "fiume");
Assert.True(w.Terrain.Types.Count(t => t == (byte)CellType.Marsh) > 50, "palude");
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Accettazione F2: il tracciato diretto sulla collina viola gMax ed è rifiutato")]
public static void DirectRouteOverTheHillIsRejected()
{
var s = ScenarioHelper.Load("valdoria");
var plan = TrackPlanner.Plan(ScenarioHelper.PlanContext(s.World), s.Route("diretto", s.World.Player.Id));
Assert.False(plan.Valid);
Assert.Equal(PlanIssueCode.GradientExceeded, plan.Errors[0].Code);
// anche con le gallerie la collina richiede trafori oltre il limite del 1850
var tunnel = TrackPlanner.Plan(ScenarioHelper.PlanContext(s.World), s.Route("diretto_galleria", s.World.Player.Id));
Assert.True(tunnel.Errors.Any(e => e.Code == PlanIssueCode.TunnelTooLong));
}
[Test(Description = "Accettazione F2: il tracciato per il valico con trincea e ponte è accettato e costa più del doppio")]
public static void PassRouteWithCuttingAndBridgeIsAcceptedAndExpensive()
{
var s = ScenarioHelper.Load("valdoria");
var w = s.World;
var ctx = ScenarioHelper.PlanContext(w);
var plan = TrackPlanner.Plan(ctx, s.Route("valico", w.Player.Id));
Assert.True(plan.Valid, string.Join("; ", plan.Errors.Select(e => e.Message)));
Assert.True(plan.LengthOf(WorkKind.Cutting) > 0, "trincea nel valico");
Assert.True(plan.LengthOf(WorkKind.Bridge) > 0, "ponte sul fiume");
Assert.True(plan.MaxGradient <= plan.GradientLimit + 1e-9);
double naturalCost = plan.LengthM * w.Data.Construction.Costs.BasePerMeter * ctx.CostMultiplier + plan.LandCost.Cents;
Assert.True(plan.TotalCost.Cents > 2 * naturalCost, $"costo {plan.TotalCost} contro {naturalCost / 100:F0} lire in piano");
// tempi coerenti: somma delle opere alle velocità delle squadre
double expected = plan.Works.Sum(x => Math.Ceiling(x.LengthM / w.Data.Construction.Crews.MetersPerDay[TrackPlanner.KindKey(x.Kind)]));
Assert.Equal((int)expected, plan.Days);
Assert.InRange(plan.Days, 60, 400);
}
}
@@ -0,0 +1,48 @@
{
"name": "Valdoria",
"description_it": "Scenario di riferimento (guida, F2): tra le miniere di Rocca Bruna e l'acciaieria di Valdoria ci sono una collina e un fiume con la sua palude. Il tracciato diretto sulla collina viola la pendenza massima; quello per il valico, con trincea e viadotto, è accettato.",
"seed": 1872,
"startYear": 1850,
"difficulty": "imprenditore",
"terrain": {
"widthCells": 160,
"heightCells": 120,
"baseHeightM": 110,
"tiltEastMPerKm": -2.0,
"noiseM": 1.5,
"features": [
{ "kind": "sea", "side": "east", "widthKm": 0.8 },
{ "kind": "hill", "x": 5.0, "y": 3.5, "radiusKm": 2.4, "heightM": 130 },
{ "kind": "hill", "x": 5.0, "y": 10.0, "radiusKm": 2.2, "heightM": 110 },
{ "kind": "hill", "x": 5.0, "y": 6.8, "radiusKm": 1.2, "heightM": 32 },
{ "kind": "marsh", "x": 8.9, "y": 6.8, "radiusXKm": 1.1, "radiusYKm": 1.2 },
{ "kind": "river", "points": [ [ 8.6, 0.0 ], [ 8.8, 4.0 ], [ 9.0, 7.0 ], [ 9.6, 9.5 ], [ 12.0, 11.2 ], [ 16.0, 11.6 ] ], "widthClass": 2, "depthM": 4 },
{ "kind": "forest", "x": 2.4, "y": 9.4, "radiusKm": 1.0 },
{ "kind": "forest", "x": 13.0, "y": 10.0, "radiusXKm": 1.2, "radiusYKm": 0.6 },
{ "kind": "field", "x": 12.4, "y": 6.6, "radiusKm": 0.7 }
]
},
"towns": [
{ "name": "Valdoria", "x": 13.6, "y": 4.6, "population": 12400 },
{ "name": "Borgo Ceresio", "x": 12.8, "y": 8.6, "population": 3100 },
{ "name": "Sant'Elia", "x": 10.2, "y": 1.2, "population": 2200 }
],
"industries": [
{ "type": "iron_mine", "name": "Miniera di ferro Rocca Bruna", "x": 1.2, "y": 3.0, "level": 2, "reserveTonnes": 600000 },
{ "type": "coal_mine", "name": "Miniera di carbone Monteferro", "x": 1.8, "y": 1.4, "level": 2, "reserveTonnes": 600000 },
{ "type": "steel_mill", "name": "Acciaieria di Valdoria", "x": 10.8, "y": 4.4, "level": 1 },
{ "type": "tool_factory", "name": "Fabbrica di attrezzi", "x": 12.6, "y": 3.0, "level": 1 },
{ "type": "farm", "name": "Fattoria Piana Verde", "x": 12.0, "y": 6.6, "level": 1 }
],
"hubs": [
{ "kind": "port", "name": "Porto di Levante", "x": 15.0, "y": 6.0 }
],
"player": { "name": "Società Ferroviaria Valdoria", "cash": 100000000 },
"routes": {
"diretto": { "points": [ [ 2.2, 2.6 ], [ 10.6, 5.4 ] ], "allowTunnels": false },
"diretto_galleria": { "points": [ [ 2.2, 2.6 ], [ 10.6, 5.4 ] ] },
"valico": { "points": [ [ 2.2, 2.6 ], [ 3.4, 6.4 ], [ 6.8, 6.9 ], [ 9.6, 6.6 ], [ 10.6, 5.4 ] ], "allowTunnels": false },
"borgo": { "points": [ [ 12.4, 8.0 ], [ 11.2, 6.2 ], [ 10.6, 5.4 ] ] },
"valdoria": { "points": [ [ 12.8, 4.9 ], [ 10.6, 5.4 ] ] }
}
}