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:
21 files changed
+1558
-16
No files matched your search
@@ -93,6 +93,7 @@
|
||||
"staffMinPopulation": 5000,
|
||||
"staffMinServices": 2,
|
||||
"servicesSatisfactionThreshold": 0.5,
|
||||
"baseServicesPerPopulation": 6000,
|
||||
"serviceJobsShare": 0.12,
|
||||
"satisfactionEmaDays": 30,
|
||||
"initialSatisfaction": 0.5,
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"riverClearanceM": 6,
|
||||
"navigableClearanceM": 12,
|
||||
"navigableMinWidthCells": 3,
|
||||
"riverWidthMByClass": [ 30, 60, 120, 250 ],
|
||||
"snapAngleDeg": 45
|
||||
},
|
||||
"maxGradientByTraction": { "steam": 0.025, "diesel": 0.035, "electric": 0.04, "highspeed": 0.035 },
|
||||
|
||||
@@ -10,13 +10,13 @@ La guida (6.3) fissa le formule ma lascia aperti alcuni punti: come si somma la
|
||||
|
||||
1. **Componente mondiale.** Il resto del mondo scambia ogni giorno con la regione un volume V = max(baseline·giorni, quota·(D + S)/2) al prezzo mondiale Pw = Pb·(1 + A·sin(2πt/T) + shock). Entra nel rapporto come domanda V·(Pw/Pg)^ε e offerta V·(Pg/Pw)^ε: a Pg = Pw è neutra, sopra Pw spinge il prezzo giù e viceversa. Così la formula della guida `Pg' = clamp(Pg·(1 + k·(D/S − 1)))` resta intatta e il prezzo torna verso il ciclo mondiale invece di divergere. Il rapporto D/S è limitato a [0,2; 5]. Gli shock sono per bene, decadono esponenzialmente e la volatilità della difficoltà moltiplica ampiezza e shock.
|
||||
2. **Domanda e offerta.** D = consumo desiderato dalle città (con elasticità al prezzo, limitata a ×0,5…×1,5) + input che le industrie userebbero al loro potenziale di lavoro; S = produzione effettiva. Il trasporto quindi conta: senza consegne gli output dei trasformatori scarseggiano e i loro prezzi salgono.
|
||||
3. **Prezzo locale.** Per un nodo: Dl = domanda giornaliera × giorni di scorta desiderati, Sl = giacenza. Un produttore con magazzino pieno vende a ~0,65·Pg, un consumatore a secco paga ~1,35·Pg (entro ±40 %).
|
||||
4. **Contabilità a partita doppia.** Ogni movimento è un trasferimento tra conti (compagnie, industrie, conto Esterno). Il ritiro di merce paga il produttore al prezzo locale d'origine; la consegna a un'industria la addebita al prezzo locale di destinazione; le famiglie e il mercato mondiale sono il conto Esterno. La somma dei saldi è sempre zero. Le scorte iniziali e quelle create dai test sono contabilizzate come prodotte.
|
||||
3. **Prezzo locale.** Per un nodo: Dl = domanda giornaliera × giorni di scorta desiderati, Sl = giacenza. Un produttore con magazzino pieno vale ~0,65·Pg, un consumatore a secco ~1,35·Pg (entro ±40 %). Serve al commercio delle compagnie (BuyGoods/SellGoods) e ai tooltip, non alla contabilità delle industrie.
|
||||
4. **Contabilità a partita doppia.** Ogni movimento è un trasferimento tra conti (compagnie, industrie, conto Esterno). Il ritiro di merce paga il produttore al prezzo globale; la consegna a un'industria la addebita al prezzo globale (gli hub usano Pg ± dazio). Con i prezzi locali il margine di ogni trasformatore sarebbe negativo per costruzione (compra a 1,35·Pg, vende a 0,65·Pg). Le famiglie e il mercato mondiale sono il conto Esterno. La somma dei saldi è sempre zero. Le scorte iniziali e quelle create dai test sono contabilizzate come prodotte.
|
||||
5. **Lavoro in sede.** Il 30 % dei posti di ogni industria è coperto da chi vive in sede (villaggio operaio): l'efficienza di un'industria isolata parte da circa 0,3 e cresce solo con i pendolari. È il punto di partenza dell'accettazione F2 («dall'acciaieria sotto il 40 %…»).
|
||||
6. **Trasporto locale su strada.** Produttori, consumatori e hub entro 3 km si scambiano piccole quantità (25 % della giacenza, al massimo 6 unità al giorno per bene), senza vettore. I lavoratori vanno a piedi entro 1,5 km dal bordo della città. Tiene vivo il territorio senza rendere superflua la ferrovia; si spegne da `balance.json`.
|
||||
7. **Crescita solo per le industrie servite.** Il punteggio trimestrale si calcola sempre, ma livello, regressione e chiusura si applicano solo alle industrie `Served` (con una stazione di un vettore nel bacino, da F2). Senza questa regola, all'inizio della partita quasi tutte le industrie chiuderebbero entro due anni perché nessuno le serve ancora.
|
||||
8. **Domanda insoddisfatta = capacità mancante.** Un bene è «insoddisfatto» quando la domanda media supera di 1,25 volte la capacità installata (non la produzione effettiva): nascono nuove industrie dove manca capacità, non dove manca il trasporto. Al massimo due nascite all'anno.
|
||||
9. **Servizi cittadini.** I «servizi» di una città sono le categorie di consumo (alimentari, merci, combustibili, edilizia) con soddisfazione ≥ 0,5: il personale qualificato esiste solo nelle città grandi e ben rifornite.
|
||||
9. **Servizi cittadini.** I «servizi» di una città sono uno ogni 6.000 abitanti (scuole, ospedali) più le categorie di consumo (alimentari, merci, combustibili, edilizia) con soddisfazione ≥ 0,5: il personale qualificato (città ≥ 5.000 abitanti e servizi ≥ 2) esiste nelle città grandi o in quelle medie ben rifornite.
|
||||
10. **Distanze dalle città** si misurano dal bordo dell'abitato (distanza dal centro meno il raggio), sia nella generazione sia nel gioco.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
@@ -240,6 +240,8 @@ public sealed class TownBalance
|
||||
public required int StaffMinPopulation { get; init; }
|
||||
public required int StaffMinServices { get; init; }
|
||||
public required double ServicesSatisfactionThreshold { get; init; }
|
||||
/// <summary>Servizi di base (scuole, ospedali…) ogni tanti abitanti, oltre alle categorie soddisfatte.</summary>
|
||||
public required int BaseServicesPerPopulation { get; init; }
|
||||
public required double ServiceJobsShare { get; init; }
|
||||
public required int SatisfactionEmaDays { get; init; }
|
||||
public required double InitialSatisfaction { get; init; }
|
||||
|
||||
@@ -31,6 +31,8 @@ public sealed class ProfileParams
|
||||
public required double RiverClearanceM { get; init; }
|
||||
public required double NavigableClearanceM { get; init; }
|
||||
public required int NavigableMinWidthCells { get; init; }
|
||||
/// <summary>Larghezza reale dell'alveo per classe di fiume 1–4 (la cella da 100 m contiene anche le sponde).</summary>
|
||||
public required double[] RiverWidthMByClass { get; init; }
|
||||
public required double SnapAngleDeg { get; init; }
|
||||
}
|
||||
|
||||
|
||||
@@ -194,6 +194,7 @@ public static class DataValidator
|
||||
}
|
||||
RequireKeys("construction.json", "physics.cxByKind", c.Physics.CxByKind.Keys, ["locomotive", "wagon", "coach"], errors);
|
||||
if (c.Profile.SmoothingWindow % 2 == 0) Err("construction.json", "profile.smoothingWindow deve essere dispari");
|
||||
if (c.Profile.RiverWidthMByClass.Length != 4) Err("construction.json", "profile.riverWidthMByClass deve avere 4 valori (classi 1–4)");
|
||||
|
||||
// --- manutenzione
|
||||
var m = d.Maintenance;
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
|
||||
namespace ViaFerrea.Core.Rail;
|
||||
|
||||
/// <summary>Tratto elementare della linea d'asse: rettilineo o arco di cerchio.</summary>
|
||||
public readonly record struct TrackPiece(Vec2 Start, Vec2 End, double Length, bool IsArc, Vec2 Center, double Radius, double StartAngle, double Sweep)
|
||||
{
|
||||
/// <summary>Punto e direzione a distanza s dall'inizio del tratto.</summary>
|
||||
public (Vec2 Point, Vec2 Direction) At(double s)
|
||||
{
|
||||
if (!IsArc)
|
||||
{
|
||||
var dir = Length > 0 ? (End - Start) / Length : new Vec2(1, 0);
|
||||
return (Start + dir * s, dir);
|
||||
}
|
||||
double a = StartAngle + Sweep * (s / Length);
|
||||
var p = Center + new Vec2(DMath.Cos(a), DMath.Sin(a)) * Radius;
|
||||
// tangente: derivata rispetto all'angolo, orientata nel verso di percorrenza
|
||||
var t = new Vec2(-DMath.Sin(a), DMath.Cos(a)) * Math.Sign(Sweep);
|
||||
return (p, t);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Campione della linea d'asse ogni Δ metri.</summary>
|
||||
public readonly record struct GeometrySample(double S, Vec2 Point, Vec2 Direction, double RadiusM);
|
||||
|
||||
/// <summary>
|
||||
/// Linea d'asse di un binario: la polilinea dell'utente con un raccordo circolare a ogni
|
||||
/// vertice (raggio della classe di velocità). Se un raccordo non entra tra due vertici il
|
||||
/// raggio effettivo si riduce e il pianificatore lo segnala.
|
||||
/// </summary>
|
||||
public sealed class TrackGeometry
|
||||
{
|
||||
public IReadOnlyList<TrackPiece> Pieces { get; }
|
||||
public double Length { get; }
|
||||
|
||||
/// <summary>Raggio minimo effettivamente ottenuto (∞ per un rettilineo).</summary>
|
||||
public double MinRadius { get; }
|
||||
|
||||
private TrackGeometry(List<TrackPiece> pieces, double minRadius)
|
||||
{
|
||||
Pieces = pieces;
|
||||
Length = pieces.Sum(p => p.Length);
|
||||
MinRadius = minRadius;
|
||||
}
|
||||
|
||||
/// <summary>Costruisce la geometria raccordando i vertici con il raggio richiesto.</summary>
|
||||
public static TrackGeometry FromPolyline(IReadOnlyList<Vec2> points, double radius)
|
||||
{
|
||||
var pts = new List<Vec2>();
|
||||
foreach (var p in points)
|
||||
{
|
||||
if (pts.Count == 0 || Vec2.Distance(pts[^1], p) > 1e-6) pts.Add(p);
|
||||
}
|
||||
var pieces = new List<TrackPiece>();
|
||||
if (pts.Count < 2) return new TrackGeometry(pieces, double.PositiveInfinity);
|
||||
|
||||
int n = pts.Count;
|
||||
var segLen = new double[n - 1];
|
||||
for (int i = 0; i < n - 1; i++) segLen[i] = Vec2.Distance(pts[i], pts[i + 1]);
|
||||
|
||||
// tangenti di ogni vertice interno con il raggio richiesto, poi riduzione se non entrano
|
||||
var theta = new double[n];
|
||||
var tangent = new double[n];
|
||||
var radii = new double[n];
|
||||
for (int i = 1; i < n - 1; i++)
|
||||
{
|
||||
var d1 = (pts[i] - pts[i - 1]).Normalized();
|
||||
var d2 = (pts[i + 1] - pts[i]).Normalized();
|
||||
double cos = Math.Clamp(Vec2.Dot(d1, d2), -1, 1);
|
||||
double sin = Vec2.Cross(d1, d2);
|
||||
theta[i] = Math.Abs(DMath.Atan2(sin, cos));
|
||||
radii[i] = radius;
|
||||
tangent[i] = theta[i] < 1e-9 ? 0 : radius * DMath.Tan(theta[i] / 2);
|
||||
}
|
||||
for (int i = 1; i < n - 1; i++)
|
||||
{
|
||||
if (tangent[i] <= 0) continue;
|
||||
// ogni segmento è condiviso tra i raccordi ai suoi due estremi
|
||||
double availPrev = i - 1 == 0 ? segLen[i - 1] : segLen[i - 1] * Share(tangent[i], tangent[i - 1]);
|
||||
double availNext = i + 1 == n - 1 ? segLen[i] : segLen[i] * Share(tangent[i], tangent[i + 1]);
|
||||
double maxT = Math.Min(availPrev, availNext);
|
||||
if (tangent[i] > maxT)
|
||||
{
|
||||
tangent[i] = maxT;
|
||||
radii[i] = theta[i] >= DMath.Pi - 1e-9 ? 0 : maxT / DMath.Tan(theta[i] / 2);
|
||||
}
|
||||
}
|
||||
|
||||
double minRadius = double.PositiveInfinity;
|
||||
var cursor = pts[0];
|
||||
for (int i = 1; i < n; i++)
|
||||
{
|
||||
var dirIn = (pts[i] - pts[i - 1]).Normalized();
|
||||
double t = i < n - 1 ? tangent[i] : 0;
|
||||
var lineEnd = pts[i] - dirIn * t;
|
||||
double lineLen = Vec2.Distance(cursor, lineEnd);
|
||||
if (lineLen > 1e-9) pieces.Add(new TrackPiece(cursor, lineEnd, lineLen, false, default, 0, 0, 0));
|
||||
cursor = lineEnd;
|
||||
if (i < n - 1 && t > 0 && radii[i] > 0)
|
||||
{
|
||||
var dirOut = (pts[i + 1] - pts[i]).Normalized();
|
||||
double turn = Math.Sign(Vec2.Cross(dirIn, dirOut));
|
||||
// centro a sinistra o a destra della direzione d'ingresso
|
||||
var normal = new Vec2(-dirIn.Y, dirIn.X) * turn;
|
||||
var center = lineEnd + normal * radii[i];
|
||||
double startAngle = DMath.Atan2(lineEnd.Y - center.Y, lineEnd.X - center.X);
|
||||
double sweep = theta[i] * turn;
|
||||
var arcEnd = pts[i] + dirOut * t;
|
||||
double arcLen = radii[i] * theta[i];
|
||||
pieces.Add(new TrackPiece(lineEnd, arcEnd, arcLen, true, center, radii[i], startAngle, sweep));
|
||||
minRadius = Math.Min(minRadius, radii[i]);
|
||||
cursor = arcEnd;
|
||||
}
|
||||
}
|
||||
return new TrackGeometry(pieces, minRadius);
|
||||
}
|
||||
|
||||
// quota di un segmento spettante al raccordo «mine» quando l'altro estremo ne chiede «other»
|
||||
private static double Share(double mine, double other) => other <= 0 ? 1.0 : mine / (mine + other);
|
||||
|
||||
/// <summary>Campioni ogni «spacing» metri, più l'estremo finale.</summary>
|
||||
public List<GeometrySample> Sample(double spacing)
|
||||
{
|
||||
var samples = new List<GeometrySample>();
|
||||
if (Pieces.Count == 0) return samples;
|
||||
double s = 0;
|
||||
int piece = 0;
|
||||
double pieceStart = 0;
|
||||
while (true)
|
||||
{
|
||||
while (piece < Pieces.Count - 1 && s > pieceStart + Pieces[piece].Length + 1e-9)
|
||||
{
|
||||
pieceStart += Pieces[piece].Length;
|
||||
piece++;
|
||||
}
|
||||
var p = Pieces[piece];
|
||||
var (point, dir) = p.At(Math.Clamp(s - pieceStart, 0, p.Length));
|
||||
samples.Add(new GeometrySample(s, point, dir, p.IsArc ? p.Radius : double.PositiveInfinity));
|
||||
if (s >= Length - 1e-9) break;
|
||||
s = Math.Min(Length, s + spacing);
|
||||
if (Length - s < 1e-6) s = Length;
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
/// <summary>Punto alla distanza s lungo la linea d'asse.</summary>
|
||||
public (Vec2 Point, Vec2 Direction) At(double s)
|
||||
{
|
||||
double start = 0;
|
||||
for (int i = 0; i < Pieces.Count; i++)
|
||||
{
|
||||
var p = Pieces[i];
|
||||
if (s <= start + p.Length || i == Pieces.Count - 1)
|
||||
return p.At(Math.Clamp(s - start, 0, p.Length));
|
||||
start += p.Length;
|
||||
}
|
||||
return (Vec2.Zero, new Vec2(1, 0));
|
||||
}
|
||||
|
||||
/// <summary>Velocità massima in curva: vMax = 3,6·√(fattore·R) km/h.</summary>
|
||||
public static double CurveSpeedKmh(double radius, double factor) =>
|
||||
double.IsPositiveInfinity(radius) ? double.PositiveInfinity : 3.6 * Math.Sqrt(factor * radius);
|
||||
|
||||
/// <summary>Aggancia la direzione dell'ultimo segmento a multipli di 45° (strumento binari del client).</summary>
|
||||
public static Vec2 SnapDirection(Vec2 from, Vec2 to, double snapDeg = 45)
|
||||
{
|
||||
var d = to - from;
|
||||
double len = d.Length;
|
||||
if (len < 1e-9) return to;
|
||||
double step = snapDeg * DMath.Pi / 180;
|
||||
double a = Math.Round(DMath.Atan2(d.Y, d.X) / step) * step;
|
||||
return from + new Vec2(DMath.Cos(a), DMath.Sin(a)) * len;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Map;
|
||||
|
||||
namespace ViaFerrea.Core.Rail;
|
||||
|
||||
/// <summary>Tipo di opera lungo il tracciato (guida 8.1).</summary>
|
||||
public enum WorkKind : byte { Natural = 0, Embankment = 1, Cutting = 2, Bridge = 3, Tunnel = 4 }
|
||||
|
||||
/// <summary>Opera: tratto contiguo dello stesso tipo, con costo e giorni di cantiere.</summary>
|
||||
public sealed record Work(WorkKind Kind, double StartM, double EndM, double MaxHeightM, long CostCents, int Days, string? BridgeType)
|
||||
{
|
||||
public double LengthM => EndM - StartM;
|
||||
}
|
||||
|
||||
/// <summary>Motivo di rifiuto o avviso del pianificatore.</summary>
|
||||
public enum PlanIssueCode : byte
|
||||
{
|
||||
TooShort = 0,
|
||||
OutOfMap = 1,
|
||||
GradientExceeded = 2,
|
||||
RadiusTooSmall = 3,
|
||||
BridgeNeeded = 4,
|
||||
BridgeTooLong = 5,
|
||||
TunnelNotAllowed = 6,
|
||||
TunnelTooLong = 7,
|
||||
ForbiddenArea = 8,
|
||||
CrossesOwnTrack = 9,
|
||||
UnknownTrackClass = 10,
|
||||
ClassNotAvailable = 11,
|
||||
ElectrificationNotAvailable = 12,
|
||||
EndpointHeight = 13,
|
||||
SteepForTraction = 14,
|
||||
}
|
||||
|
||||
/// <summary>Problema localizzato lungo il tracciato (AtM in metri dall'inizio).</summary>
|
||||
public readonly record struct PlanIssue(PlanIssueCode Code, string Message, double AtM);
|
||||
|
||||
/// <summary>Campione del profilo: terreno, binario, opera, velocità ammessa.</summary>
|
||||
public readonly record struct ProfileSample(double S, Vec2 Point, double TerrainM, double TrackM, WorkKind Kind, CellType Cell, double SpeedLimitKmh);
|
||||
|
||||
/// <summary>Richiesta di pianificazione (comando BuildTrack e anteprima del client).</summary>
|
||||
public sealed record TrackPlanRequest
|
||||
{
|
||||
public required IReadOnlyList<Vec2> Polyline { get; init; }
|
||||
public double HeightOffsetM { get; init; }
|
||||
public bool AllowBridges { get; init; } = true;
|
||||
public bool AllowTunnels { get; init; } = true;
|
||||
public string TrackClass { get; init; } = "c60";
|
||||
public bool DoubleTrack { get; init; }
|
||||
public bool Electrified { get; init; }
|
||||
public CompanyId Company { get; init; }
|
||||
|
||||
/// <summary>Quota imposta all'inizio (aggancio a un nodo esistente); null = quota del terreno.</summary>
|
||||
public double? StartHeightM { get; init; }
|
||||
public double? EndHeightM { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Risultato della pianificazione: profilo, opere, costi, tempi, errori e avvisi.</summary>
|
||||
public sealed class TrackPlan
|
||||
{
|
||||
public required TrackPlanRequest Request { get; init; }
|
||||
public required TrackGeometry Geometry { get; init; }
|
||||
public List<PlanIssue> Errors { get; } = [];
|
||||
public List<PlanIssue> Warnings { get; } = [];
|
||||
public List<ProfileSample> Samples { get; } = [];
|
||||
public List<Work> Works { get; } = [];
|
||||
public bool Valid => Errors.Count == 0;
|
||||
public double LengthM => Geometry.Length;
|
||||
public Money WorksCost { get; set; }
|
||||
public Money LandCost { get; set; }
|
||||
public Money TotalCost => WorksCost + LandCost;
|
||||
public int Days { get; set; }
|
||||
public double MaxGradient { get; set; }
|
||||
public double GradientLimit { get; set; }
|
||||
public double MinRadiusM => Geometry.MinRadius;
|
||||
public double ClassSpeedKmh { get; set; }
|
||||
public string? BridgeType { get; set; }
|
||||
|
||||
/// <summary>Lunghezza totale per tipo di opera.</summary>
|
||||
public double LengthOf(WorkKind kind) => Works.Where(w => w.Kind == kind).Sum(w => w.LengthM);
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Map;
|
||||
|
||||
namespace ViaFerrea.Core.Rail;
|
||||
|
||||
/// <summary>Attraversamento di un binario esistente lungo un segmento (T = frazione 0–1).</summary>
|
||||
public readonly record struct TrackCrossing(double T, double OtherHeightM, bool Foreign);
|
||||
|
||||
/// <summary>Interrogazioni sulla rete esistente necessarie al pianificatore.</summary>
|
||||
public interface ITrackObstacles
|
||||
{
|
||||
/// <summary>Aggiunge a results gli attraversamenti di binari esistenti tra a e b.</summary>
|
||||
void FindCrossings(Vec2 a, Vec2 b, CompanyId company, List<TrackCrossing> results);
|
||||
|
||||
/// <summary>Vero se il punto cade nell'area di una stazione o di un deposito (foreign = di un'altra compagnia).</summary>
|
||||
bool IsStationArea(Vec2 p, CompanyId company, out bool foreign);
|
||||
}
|
||||
|
||||
/// <summary>Contesto del pianificatore: terreno, anno, moltiplicatori, rete e città.</summary>
|
||||
public sealed class TrackPlanContext
|
||||
{
|
||||
public required GameData Data { get; init; }
|
||||
public required TerrainSampler Sampler { get; init; }
|
||||
public required int Year { get; init; }
|
||||
|
||||
/// <summary>Moltiplicatore dei costi (difficoltà, eventuale sconto IA).</summary>
|
||||
public double CostMultiplier { get; init; } = 1.0;
|
||||
|
||||
public ITrackObstacles? Obstacles { get; init; }
|
||||
|
||||
/// <summary>Distanza in km dal bordo della città più vicina (per il costo dei terreni); null = nessuna città.</summary>
|
||||
public Func<Vec2, double>? NearestTownEdgeKm { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pianificatore dei binari (guida 8.1–8.2): campiona il terreno ogni 25 m lungo la linea
|
||||
/// d'asse raccordata, calcola il profilo con le due passate di limitazione della pendenza e la
|
||||
/// smussatura, rispetta franchi sui fiumi e divieti, classifica le opere, ne stima costi e
|
||||
/// giorni di cantiere. Usato identico dal server e dall'anteprima del client.
|
||||
/// </summary>
|
||||
public static class TrackPlanner
|
||||
{
|
||||
public static TrackPlan Plan(TrackPlanContext ctx, TrackPlanRequest req)
|
||||
{
|
||||
var c = ctx.Data.Construction;
|
||||
var eras = ctx.Data.Eras;
|
||||
var terrain = ctx.Sampler.Terrain;
|
||||
|
||||
var trackClass = eras.TrackClasses.FirstOrDefault(t => t.Id == req.TrackClass);
|
||||
var speedClass = c.SpeedClasses.FirstOrDefault(s => s.TrackClass == req.TrackClass);
|
||||
double minRadius = speedClass?.MinRadiusM ?? 200;
|
||||
var geometry = TrackGeometry.FromPolyline(req.Polyline, minRadius);
|
||||
var plan = new TrackPlan { Request = req, Geometry = geometry };
|
||||
|
||||
if (trackClass is null || speedClass is null)
|
||||
{
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.UnknownTrackClass, $"Classe di binario sconosciuta: {req.TrackClass}", 0));
|
||||
return plan;
|
||||
}
|
||||
plan.ClassSpeedKmh = trackClass.SpeedKmh;
|
||||
if (trackClass.From > ctx.Year)
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.ClassNotAvailable, $"{trackClass.NameIt} disponibile dal {trackClass.From}", 0));
|
||||
if (req.Electrified && eras.ElectrificationFrom > ctx.Year)
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.ElectrificationNotAvailable, $"Elettrificazione disponibile dal {eras.ElectrificationFrom}", 0));
|
||||
|
||||
double spacing = c.Profile.SampleSpacingM;
|
||||
if (geometry.Length < spacing * 2)
|
||||
{
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.TooShort, $"Binario troppo corto (minimo {spacing * 2:F0} m)", 0));
|
||||
return plan;
|
||||
}
|
||||
foreach (var pt in req.Polyline)
|
||||
{
|
||||
if (pt.X < 0 || pt.Y < 0 || pt.X > terrain.WidthM || pt.Y > terrain.HeightM)
|
||||
{
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.OutOfMap, "Il tracciato esce dalla mappa", 0));
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
if (geometry.MinRadius < minRadius - 1e-6)
|
||||
{
|
||||
double at = AtOfMinRadius(geometry);
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.RadiusTooSmall,
|
||||
$"Curva di raggio {geometry.MinRadius:F0} m: la classe {trackClass.SpeedKmh:F0} km/h richiede almeno {minRadius:F0} m", at));
|
||||
}
|
||||
|
||||
// pendenza massima: la trazione più permissiva disponibile quest'anno su questo binario
|
||||
double gMax = 0;
|
||||
foreach (var t in eras.Tractions)
|
||||
{
|
||||
if (t.From <= ctx.Year && (!t.NeedsElectrification || req.Electrified))
|
||||
gMax = Math.Max(gMax, c.MaxGradientByTraction.For(t.Id));
|
||||
}
|
||||
plan.GradientLimit = gMax;
|
||||
|
||||
var geo = geometry.Sample(spacing);
|
||||
int n = geo.Count;
|
||||
var terrainH = new double[n];
|
||||
var cells = new CellType[n];
|
||||
var water = new bool[n];
|
||||
var navigable = new bool[n];
|
||||
var riverClass = new int[n];
|
||||
var forcedBridge = new bool[n];
|
||||
var crossingClearance = new double[n];
|
||||
Array.Fill(crossingClearance, double.NegativeInfinity);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var pt = geo[i].Point;
|
||||
terrainH[i] = ctx.Sampler.HeightAt(pt);
|
||||
var (cx, cy) = terrain.CellAt(pt);
|
||||
cells[i] = terrain.TypeAt(cx, cy);
|
||||
water[i] = cells[i] is CellType.Water or CellType.Sea;
|
||||
if (water[i])
|
||||
{
|
||||
int width = terrain.RiverWidth[terrain.Index(cx, cy)];
|
||||
riverClass[i] = cells[i] == CellType.Sea ? 0 : width;
|
||||
navigable[i] = cells[i] == CellType.Sea || width == 0 || width >= c.Profile.NavigableMinWidthCells;
|
||||
// la superficie dell'acqua è la quota della cella, non l'interpolazione con le sponde
|
||||
terrainH[i] = Math.Min(terrainH[i], terrain.CellHeightM(cx, cy));
|
||||
}
|
||||
forcedBridge[i] = water[i] || cells[i] == CellType.Marsh;
|
||||
bool forbidden = (cells[i] == CellType.Town && c.Rules.ForbidTownFootprint)
|
||||
|| (cells[i] == CellType.Industry && c.Rules.ForbidIndustryFootprint);
|
||||
if (forbidden)
|
||||
{
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.ForbiddenArea,
|
||||
cells[i] == CellType.Town ? "Il tracciato attraversa l'abitato di una città" : "Il tracciato attraversa un'industria", geo[i].S));
|
||||
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
|
||||
}
|
||||
if (ctx.Obstacles is { } obs && i > 0 && i < n - 1 && obs.IsStationArea(pt, req.Company, out bool foreign))
|
||||
{
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.ForbiddenArea,
|
||||
foreign ? "Il tracciato attraversa una stazione di un'altra compagnia" : "Il tracciato attraversa una stazione: collegalo all'estremità", geo[i].S));
|
||||
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
|
||||
}
|
||||
}
|
||||
|
||||
// attraversamenti di binari esistenti: altrui → cavalcavia automatico, propri → vietati
|
||||
if (ctx.Obstacles is { } obstacles)
|
||||
{
|
||||
var found = new List<TrackCrossing>();
|
||||
for (int i = 0; i < n - 1; i++)
|
||||
{
|
||||
found.Clear();
|
||||
obstacles.FindCrossings(geo[i].Point, geo[i + 1].Point, req.Company, found);
|
||||
foreach (var x in found)
|
||||
{
|
||||
int k = x.T < 0.5 ? i : i + 1;
|
||||
if (!x.Foreign)
|
||||
{
|
||||
if (k > 0 && k < n - 1)
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.CrossesOwnTrack,
|
||||
"Incrocio a raso con un proprio binario: termina il tracciato sul binario esistente", geo[k].S));
|
||||
continue;
|
||||
}
|
||||
forcedBridge[k] = true;
|
||||
crossingClearance[k] = Math.Max(crossingClearance[k], x.OtherHeightM + c.Rules.OverpassClearanceM);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!req.AllowBridges)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (forcedBridge[i])
|
||||
{
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.BridgeNeeded,
|
||||
water[i] ? "Serve un ponte per attraversare l'acqua" : cells[i] == CellType.Marsh ? "Serve un viadotto sulla palude" : "Serve un cavalcavia", geo[i].S));
|
||||
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- profilo
|
||||
var delta = new double[n - 1];
|
||||
for (int i = 0; i < n - 1; i++) delta[i] = geo[i + 1].S - geo[i].S;
|
||||
double offset = Math.Clamp(req.HeightOffsetM, -c.Profile.HeightOffsetRangeM, c.Profile.HeightOffsetRangeM);
|
||||
double startPin = req.StartHeightM ?? terrainH[0];
|
||||
double endPin = req.EndHeightM ?? terrainH[n - 1];
|
||||
|
||||
var target = new double[n];
|
||||
var lower = new double[n];
|
||||
var upper = new double[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
target[i] = terrainH[i] + offset;
|
||||
lower[i] = double.NegativeInfinity;
|
||||
upper[i] = double.PositiveInfinity;
|
||||
if (water[i])
|
||||
lower[i] = terrainH[i] + (navigable[i] ? c.Profile.NavigableClearanceM : c.Profile.RiverClearanceM);
|
||||
lower[i] = Math.Max(lower[i], crossingClearance[i]);
|
||||
if (!req.AllowTunnels && !water[i]) lower[i] = Math.Max(lower[i], terrainH[i] - c.Profile.CuttingMaxM);
|
||||
if (!req.AllowBridges && !water[i]) upper[i] = Math.Min(upper[i], terrainH[i] + c.Profile.EmbankmentMaxM);
|
||||
}
|
||||
target[0] = lower[0] = upper[0] = startPin;
|
||||
target[n - 1] = lower[n - 1] = upper[n - 1] = endPin;
|
||||
|
||||
var l = MaxEnvelope(lower, delta, gMax);
|
||||
var u = MinEnvelope(upper, delta, gMax);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (l[i] > u[i] + 1e-6)
|
||||
{
|
||||
double needed = RequiredGradient(lower, upper, delta, i);
|
||||
string reason = !req.AllowTunnels
|
||||
? "servirebbe una galleria o un altro tracciato"
|
||||
: "abbassa o alza il tracciato o cambia percorso";
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded,
|
||||
$"Pendenza necessaria {needed * 100:F1}% oltre il massimo {gMax * 100:F1}%: {reason}", geo[i].S));
|
||||
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
|
||||
}
|
||||
}
|
||||
|
||||
// due passate di limitazione della pendenza (guida 8.1), poi i vincoli inferiori
|
||||
var h = new double[n];
|
||||
for (int i = 0; i < n; i++) h[i] = Math.Clamp(target[i], l[i], u[i]);
|
||||
h = MinEnvelope(h, delta, gMax);
|
||||
for (int i = 0; i < n; i++) h[i] = Math.Max(h[i], l[i]);
|
||||
|
||||
// smussatura a finestra mobile, estremi fissi, poi ripristino rigoroso dei vincoli
|
||||
int half = c.Profile.SmoothingWindow / 2;
|
||||
var smooth = new double[n];
|
||||
smooth[0] = h[0];
|
||||
smooth[n - 1] = h[n - 1];
|
||||
for (int i = 1; i < n - 1; i++)
|
||||
{
|
||||
int k = Math.Min(half, Math.Min(i, n - 1 - i));
|
||||
double sum = 0;
|
||||
for (int j = i - k; j <= i + k; j++) sum += h[j];
|
||||
smooth[i] = sum / (2 * k + 1);
|
||||
}
|
||||
for (int i = 0; i < n; i++) smooth[i] = Math.Clamp(smooth[i], l[i], u[i]);
|
||||
h = MinEnvelope(smooth, delta, gMax);
|
||||
for (int i = 0; i < n; i++) h[i] = Math.Max(h[i], l[i]);
|
||||
|
||||
if (Math.Abs(h[0] - startPin) > 0.05 || Math.Abs(h[n - 1] - endPin) > 0.05)
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.EndpointHeight, "Dislivello eccessivo alle estremità del tracciato", 0));
|
||||
|
||||
double maxGrade = 0;
|
||||
for (int i = 0; i < n - 1; i++) maxGrade = Math.Max(maxGrade, Math.Abs(h[i + 1] - h[i]) / delta[i]);
|
||||
plan.MaxGradient = maxGrade;
|
||||
if (maxGrade > gMax + 1e-9)
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded, $"Pendenza {maxGrade * 100:F2}% oltre il massimo {gMax * 100:F1}%", 0));
|
||||
|
||||
// ---- classificazione per campione
|
||||
var kinds = new WorkKind[n];
|
||||
var p = c.Profile;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
double d = h[i] - terrainH[i];
|
||||
if (forcedBridge[i]) kinds[i] = WorkKind.Bridge;
|
||||
else if (Math.Abs(d) <= p.NaturalToleranceM) kinds[i] = WorkKind.Natural;
|
||||
else if (d > 0 && d <= p.EmbankmentMaxM) kinds[i] = WorkKind.Embankment;
|
||||
else if (d < 0 && d >= -p.CuttingMaxM) kinds[i] = WorkKind.Cutting;
|
||||
else if (d > p.EmbankmentMaxM) kinds[i] = WorkKind.Bridge;
|
||||
else kinds[i] = WorkKind.Tunnel;
|
||||
}
|
||||
if (!req.AllowTunnels && kinds.Contains(WorkKind.Tunnel))
|
||||
{
|
||||
int at = Array.IndexOf(kinds, WorkKind.Tunnel);
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.TunnelNotAllowed, "Il profilo richiede una galleria ma le gallerie sono disattivate", geo[at].S));
|
||||
}
|
||||
if (!req.AllowBridges && kinds.Contains(WorkKind.Bridge))
|
||||
{
|
||||
int at = Array.IndexOf(kinds, WorkKind.Bridge);
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.BridgeNeeded, "Il profilo richiede un viadotto ma i ponti sono disattivati", geo[at].S));
|
||||
}
|
||||
|
||||
BuildWorks(plan, ctx, geo, terrainH, h, kinds, cells, water, riverClass);
|
||||
return Finish(plan, ctx, geo, terrainH, h, cells, kinds);
|
||||
}
|
||||
|
||||
private static void BuildWorks(TrackPlan plan, TrackPlanContext ctx, List<GeometrySample> geo, double[] terrainH, double[] h,
|
||||
WorkKind[] kinds, CellType[] cells, bool[] water, int[] riverClass)
|
||||
{
|
||||
var c = ctx.Data.Construction;
|
||||
var eras = ctx.Data.Eras;
|
||||
int n = geo.Count;
|
||||
double classMult = c.SpeedClasses.First(s => s.TrackClass == plan.Request.TrackClass).CostMultiplier;
|
||||
double extra = (plan.Request.DoubleTrack ? c.Costs.DoubleTrackMultiplier : 1.0) * (plan.Request.Electrified ? 1.0 + c.Costs.ElectrificationExtra : 1.0);
|
||||
double tunnelLimit = eras.TunnelLimits.Where(t => t.From <= ctx.Year).Select(t => t.MaxLengthM).DefaultIfEmpty(0).Max();
|
||||
var bridgeTypes = eras.BridgeTypes.Where(b => b.From <= ctx.Year).ToList();
|
||||
|
||||
int start = 0;
|
||||
double totalDays = 0;
|
||||
while (start < n)
|
||||
{
|
||||
int end = start;
|
||||
while (end + 1 < n && kinds[end + 1] == kinds[start]) end++;
|
||||
var kind = kinds[start];
|
||||
double from = start == 0 ? 0 : (geo[start - 1].S + geo[start].S) / 2;
|
||||
double to = end == n - 1 ? geo[n - 1].S : (geo[end].S + geo[end + 1].S) / 2;
|
||||
|
||||
// campata d'acqua più lunga del tratto (per il tipo di ponte): per i fiumi conta la
|
||||
// larghezza dell'alveo della loro classe, per laghi e mare l'estensione attraversata
|
||||
double waterSpan = 0, run = 0;
|
||||
for (int i = start; i <= end; i++)
|
||||
{
|
||||
if (!water[i])
|
||||
{
|
||||
run = 0;
|
||||
continue;
|
||||
}
|
||||
if (riverClass[i] > 0)
|
||||
{
|
||||
waterSpan = Math.Max(waterSpan, c.Profile.RiverWidthMByClass[Math.Min(riverClass[i], 4) - 1]);
|
||||
run = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
run += SampleLength(geo, i);
|
||||
waterSpan = Math.Max(waterSpan, run);
|
||||
}
|
||||
}
|
||||
BridgeTypeDef? bridge = null;
|
||||
if (kind == WorkKind.Bridge)
|
||||
{
|
||||
bridge = bridgeTypes.Where(b => b.MaxSpanM >= waterSpan).OrderBy(b => b.CostMultiplier).ThenBy(b => b.From).FirstOrDefault();
|
||||
if (bridge is null)
|
||||
{
|
||||
double best = bridgeTypes.Count == 0 ? 0 : bridgeTypes.Max(b => b.MaxSpanM);
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.BridgeTooLong,
|
||||
$"Corso d'acqua di {waterSpan:F0} m oltre la campata massima ({best:F0} m) dell'epoca: attraversalo dove è più stretto", from));
|
||||
}
|
||||
else
|
||||
{
|
||||
plan.BridgeType = bridge.Id;
|
||||
}
|
||||
}
|
||||
if (kind == WorkKind.Tunnel && to - from > tunnelLimit)
|
||||
plan.Errors.Add(new PlanIssue(PlanIssueCode.TunnelTooLong,
|
||||
$"Galleria di {to - from:F0} m oltre il limite dell'epoca ({tunnelLimit:F0} m)", from));
|
||||
|
||||
double cost = 0, maxHeight = 0;
|
||||
for (int i = start; i <= end; i++)
|
||||
{
|
||||
double d = h[i] - terrainH[i];
|
||||
maxHeight = Math.Max(maxHeight, Math.Abs(d));
|
||||
double perMeter = c.Costs.BasePerMeter * classMult * TerrainModifier(c, cells[i]) * KindFactor(c, kind, d)
|
||||
* (kind == WorkKind.Bridge ? bridge?.CostMultiplier ?? 1.0 : 1.0);
|
||||
cost += perMeter * SampleLength(geo, i);
|
||||
}
|
||||
cost *= extra * ctx.CostMultiplier;
|
||||
double rate = c.Crews.MetersPerDay[KindKey(kind)];
|
||||
int days = (int)Math.Ceiling((to - from) / rate);
|
||||
totalDays += days;
|
||||
plan.Works.Add(new Work(kind, from, to, maxHeight, (long)Math.Round(cost), days, kind == WorkKind.Bridge ? bridge?.Id : null));
|
||||
start = end + 1;
|
||||
}
|
||||
plan.WorksCost = new Money(plan.Works.Sum(w => w.CostCents));
|
||||
plan.Days = (int)totalDays;
|
||||
|
||||
// terreni: celle sotto il binario (le gallerie non ne occupano)
|
||||
var land = c.Costs.Land;
|
||||
var counted = new HashSet<int>();
|
||||
double landCents = 0;
|
||||
var terrain = ctx.Sampler.Terrain;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (kinds[i] == WorkKind.Tunnel) continue;
|
||||
var (cx, cy) = terrain.CellAt(geo[i].Point);
|
||||
if (!counted.Add(terrain.Index(cx, cy))) continue;
|
||||
double m = 1.0;
|
||||
if (ctx.NearestTownEdgeKm is { } nearest && nearest(geo[i].Point) <= land.NearTownKm) m *= land.NearTownMultiplier;
|
||||
if (cells[i] == CellType.Field) m *= land.FieldMultiplier;
|
||||
landCents += land.BasePerCell * m;
|
||||
}
|
||||
plan.LandCost = Money.FromCentsRounded(landCents * ctx.CostMultiplier);
|
||||
}
|
||||
|
||||
private static TrackPlan Finish(TrackPlan plan, TrackPlanContext ctx, List<GeometrySample> geo, double[] terrainH, double[] h,
|
||||
CellType[] cells, WorkKind[]? kinds = null)
|
||||
{
|
||||
var c = ctx.Data.Construction;
|
||||
double classSpeed = plan.ClassSpeedKmh > 0 ? plan.ClassSpeedKmh : 60;
|
||||
for (int i = 0; i < geo.Count; i++)
|
||||
{
|
||||
double speed = Math.Min(classSpeed, TrackGeometry.CurveSpeedKmh(geo[i].RadiusM, c.CurveSpeedFactor));
|
||||
plan.Samples.Add(new ProfileSample(geo[i].S, geo[i].Point, terrainH[i], h[i], kinds?[i] ?? WorkKind.Natural, cells[i], speed));
|
||||
}
|
||||
if (plan.Valid)
|
||||
{
|
||||
foreach (var t in ctx.Data.Eras.Tractions)
|
||||
{
|
||||
if (t.From > ctx.Year) continue;
|
||||
double g = c.MaxGradientByTraction.For(t.Id);
|
||||
if (plan.MaxGradient > g + 1e-9)
|
||||
plan.Warnings.Add(new PlanIssue(PlanIssueCode.SteepForTraction,
|
||||
$"Pendenza {plan.MaxGradient * 100:F1}% oltre il limite della trazione {t.NameIt.ToLowerInvariant()} ({g * 100:F1}%): servirà la doppia trazione", 0));
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
private static double SampleLength(List<GeometrySample> geo, int i)
|
||||
{
|
||||
double left = i == 0 ? 0 : (geo[i].S - geo[i - 1].S) / 2;
|
||||
double right = i == geo.Count - 1 ? 0 : (geo[i + 1].S - geo[i].S) / 2;
|
||||
return left + right;
|
||||
}
|
||||
|
||||
private static double KindFactor(ConstructionFile c, WorkKind kind, double d) => kind switch
|
||||
{
|
||||
WorkKind.Natural => c.Costs.Natural,
|
||||
WorkKind.Embankment => 1 + c.Costs.EmbankmentPerM * Math.Max(0, d),
|
||||
WorkKind.Cutting => 1 + c.Costs.CuttingPerM * Math.Max(0, -d),
|
||||
WorkKind.Bridge => c.Costs.BridgeBase + c.Costs.BridgePerM * Math.Max(0, d),
|
||||
_ => c.Costs.Tunnel,
|
||||
};
|
||||
|
||||
private static double TerrainModifier(ConstructionFile c, CellType cell) =>
|
||||
c.Costs.TerrainModifiers.TryGetValue(cell.ToString().ToLowerInvariant(), out double m) ? m : 1.0;
|
||||
|
||||
public static string KindKey(WorkKind kind) => kind switch
|
||||
{
|
||||
WorkKind.Natural => "natural",
|
||||
WorkKind.Embankment => "embankment",
|
||||
WorkKind.Cutting => "cutting",
|
||||
WorkKind.Bridge => "bridge",
|
||||
_ => "tunnel",
|
||||
};
|
||||
|
||||
/// <summary>Funzione g-lipschitziana più alta che non supera i limiti (passate avanti e indietro).</summary>
|
||||
public static double[] MinEnvelope(double[] values, double[] delta, double g)
|
||||
{
|
||||
int n = values.Length;
|
||||
var r = (double[])values.Clone();
|
||||
for (int i = 1; i < n; i++) r[i] = Math.Min(r[i], r[i - 1] + g * delta[i - 1]);
|
||||
for (int i = n - 2; i >= 0; i--) r[i] = Math.Min(r[i], r[i + 1] + g * delta[i]);
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>Funzione g-lipschitziana più bassa che non scende sotto i limiti.</summary>
|
||||
public static double[] MaxEnvelope(double[] values, double[] delta, double g)
|
||||
{
|
||||
int n = values.Length;
|
||||
var r = (double[])values.Clone();
|
||||
for (int i = 1; i < n; i++) r[i] = Math.Max(r[i], r[i - 1] - g * delta[i - 1]);
|
||||
for (int i = n - 2; i >= 0; i--) r[i] = Math.Max(r[i], r[i + 1] - g * delta[i]);
|
||||
return r;
|
||||
}
|
||||
|
||||
// pendenza minima che renderebbe compatibili i vincoli attorno al punto di conflitto
|
||||
private static double RequiredGradient(double[] lower, double[] upper, double[] delta, int at)
|
||||
{
|
||||
double worst = 0;
|
||||
int n = lower.Length;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (double.IsNegativeInfinity(lower[i])) continue;
|
||||
double dist = 0;
|
||||
for (int j = i; j < n - 1 && dist < 5000; j++)
|
||||
{
|
||||
dist += delta[j];
|
||||
if (!double.IsPositiveInfinity(upper[j + 1]))
|
||||
worst = Math.Max(worst, (lower[i] - upper[j + 1]) / dist);
|
||||
}
|
||||
dist = 0;
|
||||
for (int j = i; j > 0 && dist < 5000; j--)
|
||||
{
|
||||
dist += delta[j - 1];
|
||||
if (!double.IsPositiveInfinity(upper[j - 1]))
|
||||
worst = Math.Max(worst, (lower[i] - upper[j - 1]) / dist);
|
||||
}
|
||||
}
|
||||
_ = at;
|
||||
return worst;
|
||||
}
|
||||
|
||||
private static double AtOfMinRadius(TrackGeometry g)
|
||||
{
|
||||
double s = 0;
|
||||
foreach (var p in g.Pieces)
|
||||
{
|
||||
if (p.IsArc && Math.Abs(p.Radius - g.MinRadius) < 1e-9) return s;
|
||||
s += p.Length;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Scenarios;
|
||||
|
||||
/// <summary>
|
||||
/// Scenario costruito a mano (tests/scenarios/*.json): terreno da elementi geometrici, città,
|
||||
/// industrie e hub in posizioni precise. Coordinate in km dall'angolo nord-ovest.
|
||||
/// </summary>
|
||||
public sealed class ScenarioFile
|
||||
{
|
||||
[JsonPropertyName("$schema")] public string? Schema { get; init; }
|
||||
public required string Name { get; init; }
|
||||
[JsonPropertyName("description_it")] public string? DescriptionIt { get; init; }
|
||||
public required ulong Seed { get; init; }
|
||||
public int StartYear { get; set; } = 1850;
|
||||
public string Difficulty { get; set; } = "imprenditore";
|
||||
public required ScenarioTerrain Terrain { get; init; }
|
||||
public List<ScenarioTown> Towns { get; set; } = [];
|
||||
public List<ScenarioIndustry> Industries { get; set; } = [];
|
||||
public List<ScenarioHub> Hubs { get; set; } = [];
|
||||
public ScenarioPlayer? Player { get; init; }
|
||||
/// <summary>Tracciati nominati, usati dai test e dallo strumento profile.</summary>
|
||||
public Dictionary<string, ScenarioRoute> Routes { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class ScenarioTerrain
|
||||
{
|
||||
public required int WidthCells { get; init; }
|
||||
public required int HeightCells { get; init; }
|
||||
public double BaseHeightM { get; set; } = 100;
|
||||
/// <summary>Inclinazione generale in metri per km verso est e verso sud.</summary>
|
||||
public double TiltEastMPerKm { get; init; }
|
||||
public double TiltSouthMPerKm { get; init; }
|
||||
/// <summary>Ampiezza del microrilievo (rumore) in metri.</summary>
|
||||
public double NoiseM { get; init; }
|
||||
public List<ScenarioFeature> Features { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Elemento del terreno: hill, river, marsh, forest, lake, sea, field.</summary>
|
||||
public sealed class ScenarioFeature
|
||||
{
|
||||
public required string Kind { get; init; }
|
||||
public double X { get; init; }
|
||||
public double Y { get; init; }
|
||||
public double RadiusKm { get; init; }
|
||||
/// <summary>Semiassi dell'ellisse (palude, bosco, lago); se assenti vale RadiusKm.</summary>
|
||||
public double? RadiusXKm { get; init; }
|
||||
public double? RadiusYKm { get; init; }
|
||||
public double HeightM { get; init; }
|
||||
public List<double[]>? Points { get; init; }
|
||||
public int WidthClass { get; set; } = 1;
|
||||
public double DepthM { get; set; } = 4;
|
||||
/// <summary>Lato per il mare: north, east, south, west.</summary>
|
||||
public string? Side { get; init; }
|
||||
public double WidthKm { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ScenarioTown
|
||||
{
|
||||
public required string Name { get; init; }
|
||||
public required double X { get; init; }
|
||||
public required double Y { get; init; }
|
||||
public required int Population { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ScenarioIndustry
|
||||
{
|
||||
public required string Type { get; init; }
|
||||
public required string Name { get; init; }
|
||||
public required double X { get; init; }
|
||||
public required double Y { get; init; }
|
||||
public int Level { get; set; } = 1;
|
||||
public long? ReserveTonnes { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ScenarioHub
|
||||
{
|
||||
public required string Kind { get; init; }
|
||||
public required string Name { get; init; }
|
||||
public required double X { get; init; }
|
||||
public required double Y { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ScenarioPlayer
|
||||
{
|
||||
public string? Name { get; init; }
|
||||
public long? Cash { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ScenarioRoute
|
||||
{
|
||||
public required List<double[]> Points { get; init; }
|
||||
public double HeightOffsetM { get; init; }
|
||||
public bool AllowBridges { get; set; } = true;
|
||||
public bool AllowTunnels { get; set; } = true;
|
||||
public string TrackClass { get; set; } = "c60";
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true)]
|
||||
[JsonSerializable(typeof(ScenarioFile))]
|
||||
public sealed partial class ScenarioJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,244 @@
|
||||
using System.Text.Json;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
using ViaFerrea.Core.Map;
|
||||
using ViaFerrea.Core.Rail;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Scenarios;
|
||||
|
||||
/// <summary>Scenario caricato: mondo pronto e definizioni originali (per i tracciati nominati).</summary>
|
||||
public sealed record LoadedScenario(World World, ScenarioFile File)
|
||||
{
|
||||
/// <summary>Richiesta di pianificazione per un tracciato nominato dello scenario.</summary>
|
||||
public TrackPlanRequest Route(string name, CompanyId company)
|
||||
{
|
||||
var r = File.Routes[name];
|
||||
return new TrackPlanRequest
|
||||
{
|
||||
Polyline = r.Points.Select(p => new Vec2(p[0] * 1000, p[1] * 1000)).ToList(),
|
||||
HeightOffsetM = r.HeightOffsetM,
|
||||
AllowBridges = r.AllowBridges,
|
||||
AllowTunnels = r.AllowTunnels,
|
||||
TrackClass = r.TrackClass,
|
||||
Company = company,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Costruisce un mondo da uno scenario JSON (terreno a mano + entità in posizioni date).</summary>
|
||||
public static class ScenarioLoader
|
||||
{
|
||||
public static LoadedScenario LoadFile(GameData data, string path) => Load(data, File.ReadAllText(path));
|
||||
|
||||
public static LoadedScenario Load(GameData data, string json)
|
||||
{
|
||||
var file = JsonSerializer.Deserialize(json, ScenarioJsonContext.Default.ScenarioFile)
|
||||
?? throw new InvalidDataException("Scenario vuoto");
|
||||
var terrain = BuildTerrain(file.Terrain, new Rng(file.Seed));
|
||||
double cs = terrain.CellSizeM;
|
||||
(int, int) Cell(double xKm, double yKm) =>
|
||||
(Math.Clamp((int)(xKm * 1000 / cs), 0, terrain.Width - 1), Math.Clamp((int)(yKm * 1000 / cs), 0, terrain.Height - 1));
|
||||
|
||||
var tp = data.Balance.Map.Towns;
|
||||
var towns = new List<TownSeed>();
|
||||
foreach (var t in file.Towns)
|
||||
{
|
||||
var (x, y) = Cell(t.X, t.Y);
|
||||
double radius = tp.RadiusBaseCells + tp.RadiusPerSqrtPop * Math.Sqrt(t.Population);
|
||||
towns.Add(new TownSeed(t.Name, x, y, t.Population, radius));
|
||||
MarkDisc(terrain, x, y, radius, CellType.Town);
|
||||
}
|
||||
|
||||
var sites = new List<ResourceSiteSeed>();
|
||||
var industries = new List<IndustrySeed>();
|
||||
foreach (var ind in file.Industries)
|
||||
{
|
||||
var def = data.Industry(ind.Type);
|
||||
var (x, y) = Cell(ind.X, ind.Y);
|
||||
int footprint = data.Balance.Industry.FootprintCells[def.Footprint.ToString().ToLowerInvariant()];
|
||||
int site = -1;
|
||||
if (def.Placement.Needs == PlacementNeed.Deposit && def.Placement.Resource is { } kind)
|
||||
{
|
||||
site = sites.Count;
|
||||
var range = data.Balance.Map.Deposits.ReserveTonnes[kind.ToString().ToLowerInvariant()];
|
||||
sites.Add(new ResourceSiteSeed(kind, x, y, 4, ind.ReserveTonnes ?? range[1]));
|
||||
}
|
||||
industries.Add(new IndustrySeed(def.Index, ind.Name, x, y, ind.Level, site, footprint));
|
||||
}
|
||||
|
||||
var hubs = new List<HubSeed>();
|
||||
foreach (var h in file.Hubs)
|
||||
{
|
||||
var kind = Enum.Parse<HubKind>(h.Kind, ignoreCase: true);
|
||||
var (x, y) = Cell(h.X, h.Y);
|
||||
int footprint = data.Balance.Industry.FootprintCells[data.Balance.Hubs.For(kind).Footprint.ToString().ToLowerInvariant()];
|
||||
hubs.Add(new HubSeed(kind, h.Name, x, y, footprint));
|
||||
var (x0, y0) = GeneratedMap.FootprintOrigin(x, y, footprint);
|
||||
for (int yy = y0; yy < y0 + footprint; yy++)
|
||||
for (int xx = x0; xx < x0 + footprint; xx++)
|
||||
if (terrain.InBounds(xx, yy)) terrain.SetType(xx, yy, CellType.Industry);
|
||||
}
|
||||
|
||||
var seaSide = file.Terrain.Features.FirstOrDefault(f => f.Kind == "sea")?.Side?.ToLowerInvariant() switch
|
||||
{
|
||||
"north" => MapSide.North,
|
||||
"south" => MapSide.South,
|
||||
"west" => MapSide.West,
|
||||
_ => MapSide.East,
|
||||
};
|
||||
var map = new GeneratedMap
|
||||
{
|
||||
Spec = new MapSpec(file.Seed, (int)Math.Round(terrain.WidthM / 1000), file.StartYear),
|
||||
Terrain = terrain,
|
||||
SeaSide = seaSide,
|
||||
Sites = sites,
|
||||
Towns = towns,
|
||||
Industries = industries,
|
||||
Hubs = hubs,
|
||||
};
|
||||
var settings = new NewGameSettings
|
||||
{
|
||||
Seed = file.Seed,
|
||||
SizeKm = map.Spec.SizeKm,
|
||||
StartYear = file.StartYear,
|
||||
DifficultyId = file.Difficulty,
|
||||
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria",
|
||||
};
|
||||
var world = WorldFactory.FromMap(data, map, settings);
|
||||
if (file.Player?.Cash is { } cash)
|
||||
{
|
||||
var player = world.Player;
|
||||
world.Money.Transfer(Account.Of(player.Id), Account.External, player.Cash, LedgerEntry.Other);
|
||||
world.Money.Transfer(Account.External, Account.Of(player.Id), new Money(cash), LedgerEntry.Other);
|
||||
}
|
||||
return new LoadedScenario(world, file);
|
||||
}
|
||||
|
||||
private static Terrain BuildTerrain(ScenarioTerrain spec, Rng rng)
|
||||
{
|
||||
var t = new Terrain(spec.WidthCells, spec.HeightCells, 100, 64);
|
||||
double cs = t.CellSizeM;
|
||||
var noise = new ValueNoise(rng.NextU64());
|
||||
var heights = new double[t.Width * t.Height];
|
||||
for (int y = 0; y < t.Height; y++)
|
||||
{
|
||||
for (int x = 0; x < t.Width; x++)
|
||||
{
|
||||
double xKm = (x + 0.5) * cs / 1000, yKm = (y + 0.5) * cs / 1000;
|
||||
double h = spec.BaseHeightM + spec.TiltEastMPerKm * xKm + spec.TiltSouthMPerKm * yKm
|
||||
+ (noise.Fbm(x, y, 2, 12, 0.5, 2) - 0.5) * 2 * spec.NoiseM;
|
||||
foreach (var f in spec.Features)
|
||||
{
|
||||
if (f.Kind != "hill") continue;
|
||||
double r = Math.Sqrt((xKm - f.X) * (xKm - f.X) + (yKm - f.Y) * (yKm - f.Y)) / f.RadiusKm;
|
||||
if (r < 1) h += f.HeightM * (1 - r * r) * (1 - r * r);
|
||||
}
|
||||
heights[t.Index(x, y)] = h;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var f in spec.Features)
|
||||
{
|
||||
switch (f.Kind)
|
||||
{
|
||||
case "marsh":
|
||||
case "forest":
|
||||
case "field":
|
||||
case "lake":
|
||||
{
|
||||
var type = f.Kind switch { "marsh" => CellType.Marsh, "forest" => CellType.Forest, "field" => CellType.Field, _ => CellType.Water };
|
||||
double rx = f.RadiusXKm ?? f.RadiusKm, ry = f.RadiusYKm ?? f.RadiusKm;
|
||||
for (int y = 0; y < t.Height; y++)
|
||||
{
|
||||
for (int x = 0; x < t.Width; x++)
|
||||
{
|
||||
double xKm = (x + 0.5) * cs / 1000, yKm = (y + 0.5) * cs / 1000;
|
||||
double e = Sq((xKm - f.X) / rx) + Sq((yKm - f.Y) / ry);
|
||||
if (e > 1) continue;
|
||||
if (t.Types[t.Index(x, y)] is (byte)CellType.Water or (byte)CellType.Sea) continue;
|
||||
t.Types[t.Index(x, y)] = (byte)type;
|
||||
if (type == CellType.Marsh) heights[t.Index(x, y)] -= 1;
|
||||
if (type == CellType.Water) heights[t.Index(x, y)] -= f.DepthM;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "sea":
|
||||
{
|
||||
int band = (int)Math.Round(f.WidthKm * 1000 / cs);
|
||||
for (int y = 0; y < t.Height; y++)
|
||||
{
|
||||
for (int x = 0; x < t.Width; x++)
|
||||
{
|
||||
bool sea = (f.Side ?? "east") switch
|
||||
{
|
||||
"north" => y < band,
|
||||
"south" => y >= t.Height - band,
|
||||
"west" => x < band,
|
||||
_ => x >= t.Width - band,
|
||||
};
|
||||
if (!sea) continue;
|
||||
t.Types[t.Index(x, y)] = (byte)CellType.Sea;
|
||||
heights[t.Index(x, y)] = 0;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fiumi: superficie che scende verso valle lungo la polilinea, alveo largo «widthClass» celle;
|
||||
// la superficie si calcola sul terreno originale, non su quello già scavato
|
||||
var original = (double[])heights.Clone();
|
||||
foreach (var f in spec.Features.Where(f => f.Kind == "river" && f.Points is { Count: >= 2 }))
|
||||
{
|
||||
var pts = f.Points!.Select(p => new Vec2(p[0] * 1000, p[1] * 1000)).ToList();
|
||||
double surface = double.PositiveInfinity;
|
||||
double step = cs / 4;
|
||||
for (int k = 0; k < pts.Count - 1; k++)
|
||||
{
|
||||
double len = Vec2.Distance(pts[k], pts[k + 1]);
|
||||
for (double s = 0; s <= len; s += step)
|
||||
{
|
||||
var p = Vec2.Lerp(pts[k], pts[k + 1], s / len);
|
||||
var (cx, cy) = t.CellAt(p);
|
||||
surface = Math.Min(surface, original[t.Index(cx, cy)] - f.DepthM);
|
||||
int w = Math.Clamp(f.WidthClass, 1, 4);
|
||||
int off = (w - 1) / 2;
|
||||
for (int dy = 0; dy < w; dy++)
|
||||
{
|
||||
for (int dx = 0; dx < w; dx++)
|
||||
{
|
||||
int x = cx + dx - off, y = cy + dy - off;
|
||||
if (!t.InBounds(x, y)) continue;
|
||||
int i = t.Index(x, y);
|
||||
if (t.Types[i] == (byte)CellType.Sea) continue;
|
||||
t.Types[i] = (byte)CellType.Water;
|
||||
t.RiverWidth[i] = (byte)w;
|
||||
heights[i] = Math.Min(heights[i], Math.Max(0.5, surface));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < heights.Length; i++) t.Heights[i] = Terrain.ToDecimeters(Math.Max(0, heights[i]));
|
||||
return t;
|
||||
}
|
||||
|
||||
private static void MarkDisc(Terrain t, int cx, int cy, double radius, CellType type)
|
||||
{
|
||||
int r = (int)Math.Ceiling(radius);
|
||||
for (int y = cy - r; y <= cy + r; y++)
|
||||
{
|
||||
for (int x = cx - r; x <= cx + r; x++)
|
||||
{
|
||||
if (!t.InBounds(x, y) || Sq(x - cx) + Sq(y - cy) > radius * radius || t.IsWater(x, y)) continue;
|
||||
t.SetType(x, y, type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static double Sq(double v) => v * v;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ namespace ViaFerrea.Core.Simulation.Systems;
|
||||
/// <summary>
|
||||
/// Trasporto locale su strada (carrettieri, ADR 0004): piccole quantità tra produttori, consumatori
|
||||
/// e hub vicinissimi, senza vettore. Tiene vivo il territorio senza rendere superflua la ferrovia.
|
||||
/// Vendite e acquisti avvengono ai prezzi locali; le merci passano solo da un magazzino all'altro.
|
||||
/// Vendite e acquisti avvengono al prezzo globale; le merci passano solo da un magazzino all'altro.
|
||||
/// </summary>
|
||||
public sealed class LocalTransportSystem : ISimSystem
|
||||
{
|
||||
@@ -36,7 +36,6 @@ public sealed class LocalTransportSystem : ISimSystem
|
||||
}
|
||||
}
|
||||
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
foreach (var producer in w.Industries)
|
||||
{
|
||||
@@ -47,7 +46,8 @@ public sealed class LocalTransportSystem : ISimSystem
|
||||
int good = outputs[o].GoodIndex;
|
||||
int available = Math.Min(lt.MaxUnitsPerDay, (int)Math.Ceiling(producer.OutputStock[o] * lt.DailyShare));
|
||||
if (available <= 0) continue;
|
||||
double sellPrice = Market.LocalPrice(w.Market.GlobalPrice[good], 0, producer.OutputStock[o], lp);
|
||||
// le industrie comprano e vendono al prezzo globale (ADR 0004)
|
||||
double sellPrice = w.Market.GlobalPrice[good];
|
||||
|
||||
foreach (var (ci, _) in _nearIndustries[producer.Id.Value])
|
||||
{
|
||||
@@ -58,7 +58,7 @@ public sealed class LocalTransportSystem : ISimSystem
|
||||
int free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i];
|
||||
int units = Math.Min(available, free);
|
||||
if (units <= 0) continue;
|
||||
double buyPrice = Market.LocalPrice(w.Market.GlobalPrice[good], consumer.InputDemandToday[i] * consumer.Def.StorageDays, consumer.InputStock[i], lp);
|
||||
double buyPrice = w.Market.GlobalPrice[good];
|
||||
producer.OutputStock[o] -= units;
|
||||
consumer.InputStock[i] += units;
|
||||
available -= units;
|
||||
|
||||
@@ -69,7 +69,7 @@ public sealed class TownSystem : ISimSystem
|
||||
private static void Grow(WorldContext ctx, Town town)
|
||||
{
|
||||
var tb = ctx.Data.Balance.Town;
|
||||
int services = 0;
|
||||
int services = town.Population / Math.Max(1, tb.BaseServicesPerPopulation);
|
||||
for (int c = 0; c < Town.CategoryCount; c++)
|
||||
{
|
||||
if (town.CategoryActive[c] && town.Satisfaction[c] >= tb.ServicesSatisfactionThreshold) services++;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Map;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ViaFerrea.Core.Simulation.Scenarios;
|
||||
|
||||
namespace ViaFerrea.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// profile: pianifica un tracciato e scrive il profilo campionato ogni 25 m in CSV (separatore «;»),
|
||||
/// con il riepilogo delle opere, dei costi e dei giorni.
|
||||
/// </summary>
|
||||
public sealed class ProfileCommand : IToolCommand
|
||||
{
|
||||
public string Name => "profile";
|
||||
|
||||
public string Usage => "profile (--seed <n> [--size 128] | --scenario <file> [--route <nome>]) [--polyline \"x1,y1;x2,y2;…\" (km)] [--offset <m>] [--class c60] [--no-tunnels] [--no-bridges] [--year <anno>] [--out profilo.csv]";
|
||||
|
||||
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
ulong seed = args.ULong("seed", 1);
|
||||
int size = args.Int("size", 64);
|
||||
string? scenarioPath = args.String("scenario");
|
||||
string? routeName = args.String("route");
|
||||
string? polyline = args.String("polyline");
|
||||
double offset = args.Double("offset", 0);
|
||||
string trackClass = args.String("class", "c60");
|
||||
bool noTunnels = args.Flag("no-tunnels");
|
||||
bool noBridges = args.Flag("no-bridges");
|
||||
int? year = args.String("year") is { } y ? int.Parse(y, Inv) : null;
|
||||
string output = args.String("out", "profilo.csv");
|
||||
args.EnsureAllUsed();
|
||||
|
||||
var data = GameData.LoadDefault();
|
||||
World world;
|
||||
TrackPlanRequest request;
|
||||
if (scenarioPath is not null)
|
||||
{
|
||||
var scenario = ScenarioLoader.LoadFile(data, scenarioPath);
|
||||
world = scenario.World;
|
||||
request = routeName is not null
|
||||
? scenario.Route(routeName, world.Player.Id)
|
||||
: new TrackPlanRequest { Polyline = ParsePolyline(polyline ?? throw new ArgumentException("serve --route o --polyline")) };
|
||||
}
|
||||
else
|
||||
{
|
||||
world = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size });
|
||||
request = new TrackPlanRequest { Polyline = ParsePolyline(polyline ?? throw new ArgumentException("serve --polyline")) };
|
||||
}
|
||||
if (polyline is not null || routeName is null)
|
||||
{
|
||||
request = request with
|
||||
{
|
||||
HeightOffsetM = offset,
|
||||
TrackClass = trackClass,
|
||||
AllowTunnels = !noTunnels,
|
||||
AllowBridges = !noBridges,
|
||||
};
|
||||
}
|
||||
|
||||
var ctx = new TrackPlanContext
|
||||
{
|
||||
Data = data,
|
||||
Sampler = world.Sampler,
|
||||
Year = year ?? world.Clock.Year,
|
||||
CostMultiplier = world.Difficulty.ConstructionCostMultiplier,
|
||||
NearestTownEdgeKm = p => world.Towns.Count == 0 ? double.MaxValue : world.Towns.Min(t => world.TownEdgeDistanceKm(t, p)),
|
||||
};
|
||||
var plan = TrackPlanner.Plan(ctx, request);
|
||||
|
||||
var csv = new StringBuilder();
|
||||
csv.AppendLine("s_m;x_m;y_m;terreno_m;binario_m;differenza_m;opera;cella;velocita_kmh");
|
||||
foreach (var s in plan.Samples)
|
||||
{
|
||||
csv.AppendLine(string.Join(';', F(s.S), F(s.Point.X), F(s.Point.Y), F(s.TerrainM), F(s.TrackM), F(s.TrackM - s.TerrainM),
|
||||
s.Kind.ToString(), s.Cell.ToString(), F(s.SpeedLimitKmh)));
|
||||
}
|
||||
File.WriteAllText(output, csv.ToString(), new UTF8Encoding(true));
|
||||
|
||||
Console.WriteLine($"profile: {(plan.Valid ? "VALIDO" : "RIFIUTATO")} — {plan.LengthM / 1000:F2} km, pendenza max {plan.MaxGradient * 100:F2}% (limite {plan.GradientLimit * 100:F1}%), raggio min {(double.IsInfinity(plan.MinRadiusM) ? "∞" : plan.MinRadiusM.ToString("F0", Inv))} m");
|
||||
foreach (var e in plan.Errors) Console.WriteLine($" errore al km {e.AtM / 1000:F2}: {e.Message}");
|
||||
foreach (var w in plan.Warnings) Console.WriteLine($" avviso: {w.Message}");
|
||||
foreach (var w in plan.Works)
|
||||
Console.WriteLine($" {w.Kind,-10} {w.StartM / 1000,6:F2}–{w.EndM / 1000,6:F2} km h max {w.MaxHeightM,5:F1} m {new Money(w.CostCents),14} {w.Days,4} gg{(w.BridgeType is { } b ? " ponte " + b : "")}");
|
||||
double natural = plan.LengthM * data.Construction.Costs.BasePerMeter * ctx.CostMultiplier;
|
||||
Console.WriteLine($" opere {plan.WorksCost}, terreni {plan.LandCost}, totale {plan.TotalCost} ({plan.TotalCost.Cents / Math.Max(1, natural + plan.LandCost.Cents):F2}× la sede naturale), {plan.Days} giorni");
|
||||
Console.WriteLine($" profilo in {output}");
|
||||
return plan.Valid ? 0 : 3;
|
||||
}
|
||||
|
||||
private static string F(double v) => double.IsInfinity(v) ? "" : v.ToString("0.##", Inv).Replace('.', ',');
|
||||
|
||||
private static List<Vec2> ParsePolyline(string text) =>
|
||||
text.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(p => p.Split(','))
|
||||
.Select(p => new Vec2(double.Parse(p[0], Inv) * 1000, double.Parse(p[1], Inv) * 1000))
|
||||
.ToList();
|
||||
}
|
||||
@@ -10,6 +10,7 @@ public static class ToolsProgram
|
||||
new ValidateDataCommand(),
|
||||
new GenMapCommand(),
|
||||
new SimulateCommand(),
|
||||
new ProfileCommand(),
|
||||
];
|
||||
|
||||
public static int Main(string[] args)
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
|
||||
namespace ViaFerrea.Tools.Scenarios;
|
||||
|
||||
/// <summary>Caricamento degli scenari di prova (tests/scenarios/*.json): arriva con la Fase 2.</summary>
|
||||
/// <summary>Accesso agli scenari di Core dagli strumenti.</summary>
|
||||
public static class ScenarioLoader
|
||||
{
|
||||
public sealed record LoadedScenario(World World);
|
||||
|
||||
public static LoadedScenario Load(GameData data, string path) =>
|
||||
throw new ArgumentException($"Gli scenari ({path}) sono supportati dalla Fase 2");
|
||||
public static Core.Simulation.Scenarios.LoadedScenario Load(Core.Data.GameData data, string path) =>
|
||||
Core.Simulation.Scenarios.ScenarioLoader.LoadFile(data, path);
|
||||
}
|
||||
@@ -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 ] ] }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user