Files
Rail_Enterprise/src/RailEnterprise.Core/Data/DataValidator.cs
T
Alby96andClaude Opus 5.5 2992e7cc36 F6: mercato globale, storico prezzi a 24 mesi e previsione
Prima parte della F6: il pannello «Mercato globale» dell'immagine di
riferimento 06, con i dati calcolati dal server.

- Lo storico dei prezzi globali passa da 360 a 720 giorni. I salvataggi
  con lo storico di un anno si migrano al caricamento allungando la
  finestra (RollingWindow.Extended), senza cambiare formato.
- MarketOutlook (Core) è un'analisi in sola lettura del mondo: storico
  mensile, variazione a 30 giorni, offerta e domanda con la quota
  mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi
  dalla componente mondiale con banda, destinazioni di vendita ordinate
  per prezzo con la linea che le collega, hub, evento in corso e
  avanzamento verso la compravendita in proprio. Parametri nuovi in
  balance.json (market.outlook); interpretazioni nell'ADR 0015.
- Protocollo: DetailKind.Market (7) e MarketReport (129); il server
  risponde su richiesta, il client lo mostra in un pannello a tutto
  schermo e il pilota automatico ne fa la schermata 16_mercato.
- Test: finestra allungata e migrazione, storico mensile, previsione
  deterministica ed entro i limiti, evento, analisi su Valdoria,
  round-trip del messaggio e quadro via WebSocket.

La simulazione non cambia: l'analisi non scrive nel mondo e
l'accettazione F4 dà gli stessi numeri di prima.

Closes #29.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 14:25:38 +01:00

297 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace RailEnterprise.Core.Data;
/// <summary>
/// Validazione semantica dei dati, dopo lo schema: id univoci, riferimenti risolti,
/// coerenza tra file e limiti che lo schema non può esprimere.
/// </summary>
public static class DataValidator
{
private static readonly string[] SizeKeys = ["small", "medium", "large"];
private static readonly string[] ResourceKeys = ["coal", "iron", "stone", "oil"];
private static readonly string[] WorkKeys = ["natural", "embankment", "cutting", "bridge", "tunnel"];
private static readonly string[] CellTypeKeys = ["plain", "hill", "mountain", "forest", "field", "water", "sea", "town", "industry", "rock", "marsh"];
public static void Validate(GameData d, List<string> errors)
{
void Err(string file, string message) => errors.Add($"{file}: {message}");
// --- beni
Unique("goods.json", d.Goods.Select(g => g.Id), errors);
if (d.Goods.Count > Rail.LineGraph.MaxGoods) Err("goods.json", $"al massimo {Rail.LineGraph.MaxGoods} beni (maschera dei carichi delle linee)");
var goodIds = d.Goods.Select(g => g.Id).ToHashSet(StringComparer.Ordinal);
foreach (string required in new[] { "spare_parts", "machinery" })
{
if (!goodIds.Contains(required)) Err("goods.json", $"manca il bene di servizio obbligatorio «{required}»");
}
foreach (var g in d.Goods)
{
if (g.Town is { UntilYear: { } until } && until <= g.Era) Err("goods.json", $"{g.Id}: town.untilYear precedente all'era del bene");
}
// --- industrie
Unique("industries.json", d.Industries.Select(i => i.Id), errors);
foreach (var ind in d.Industries)
{
string p = $"{ind.Id}:";
foreach (var item in ind.Recipe.Inputs.Concat(ind.Recipe.Outputs))
{
if (!goodIds.Contains(item.Good)) Err("industries.json", $"{p} bene sconosciuto «{item.Good}»");
}
Unique("industries.json", ind.Recipe.Inputs.Select(x => x.Good), errors, $"{p} input");
Unique("industries.json", ind.Recipe.Outputs.Select(x => x.Good), errors, $"{p} output");
if (ind.Kind == IndustryKind.Primary && ind.Recipe.Inputs.Count > 0) Err("industries.json", $"{p} un'industria primaria non ha input");
if (ind.Kind != IndustryKind.Primary && ind.Recipe.Inputs.Count == 0) Err("industries.json", $"{p} un'industria di trasformazione richiede input");
NonDecreasing("industries.json", $"{p} capacityPerLevel", ind.CapacityPerLevel, errors);
NonDecreasing("industries.json", $"{p} workersPerLevel", ind.WorkersPerLevel, errors);
NonDecreasing("industries.json", $"{p} staffPerLevel", ind.StaffPerLevel, errors);
if (ind.CapacityPerLevel[0] <= 0) Err("industries.json", $"{p} capacità di livello 1 nulla");
if (ind.Placement.Needs == PlacementNeed.Deposit && ind.Placement.Resource is null)
Err("industries.json", $"{p} needs=deposit richiede «resource»");
if (ind.Depletable && ind.Placement.Needs != PlacementNeed.Deposit)
Err("industries.json", $"{p} solo le industrie su giacimento possono esaurirsi");
if (ind.Placement is { MinTownDistanceKm: { } mn, MaxTownDistanceKm: { } mx } && mx < mn)
Err("industries.json", $"{p} maxTownDistanceKm < minTownDistanceKm");
if (d.Balance.Industry.FootprintCells is { } fc && !fc.ContainsKey(ind.Footprint.ToString().ToLowerInvariant()))
Err("balance.json", $"industry.footprintCells non definisce «{ind.Footprint}»");
}
foreach (var g in d.Goods)
{
bool produced = d.Industries.Any(i => i.Recipe.Outputs.Any(o => o.Good == g.Id));
if (!produced) Err("industries.json", $"nessuna industria produce «{g.Id}»");
}
// --- veicoli
Unique("vehicles.json", d.Vehicles.Select(v => v.Id), errors);
var locoComponents = d.Maintenance.Components.Locomotive.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
var carComponents = d.Maintenance.Components.Car.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
foreach (var v in d.Vehicles)
{
string p = $"{v.Id}:";
if (v.EraTo is { } to && to < v.EraFrom) Err("vehicles.json", $"{p} eraTo precedente a eraFrom");
switch (v.Kind)
{
case VehicleKind.Locomotive:
if (v.Traction is null) Err("vehicles.json", $"{p} una locomotiva richiede «traction»");
if (v.PowerKw <= 0 || v.TractiveEffortKn <= 0) Err("vehicles.json", $"{p} potenza e sforzo di trazione devono essere positivi");
foreach (string comp in v.Components.Keys)
{
if (!locoComponents.Contains(comp)) Err("vehicles.json", $"{p} componente sconosciuto «{comp}»");
}
foreach (string comp in locoComponents)
{
if (!v.Components.ContainsKey(comp)) Err("vehicles.json", $"{p} manca il componente «{comp}»");
}
break;
case VehicleKind.Wagon:
if (v.Capacity is null || v.WagonType is null || v.Goods is null)
Err("vehicles.json", $"{p} un carro richiede capacity, wagonType e goods");
foreach (string g in v.Goods ?? [])
{
if (!goodIds.Contains(g)) Err("vehicles.json", $"{p} bene sconosciuto «{g}»");
}
CheckCarComponents(v, carComponents, errors);
break;
case VehicleKind.Coach:
if (v.PaxCapacity is null || v.Class is null) Err("vehicles.json", $"{p} una carrozza richiede paxCapacity e class");
CheckCarComponents(v, carComponents, errors);
break;
}
}
foreach (var g in d.Goods)
{
bool carried = d.Vehicles.Any(v => v.Kind == VehicleKind.Wagon && v.WagonType == g.Wagon && (v.Goods?.Contains(g.Id) ?? false));
if (!carried) Err("vehicles.json", $"nessun carro di tipo «{g.Wagon}» trasporta «{g.Id}»");
}
foreach (PaxClass cls in Enum.GetValues<PaxClass>())
{
if (!d.Vehicles.Any(v => v.Kind == VehicleKind.Coach && v.Class == cls))
Err("vehicles.json", $"nessuna carrozza per la classe «{cls}»");
}
if (!d.Vehicles.Any(v => v.Kind == VehicleKind.Locomotive && v.EraFrom <= d.Balance.Time.DefaultStartYear))
Err("vehicles.json", "nessuna locomotiva disponibile all'anno di inizio predefinito");
// --- ere
Unique("eras.json", d.Eras.Eras.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.TrackClasses.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.BridgeTypes.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.Signals.Select(e => e.Id), errors);
Unique("eras.json", d.Eras.Tractions.Select(e => e.Id.ToString()), errors);
foreach (Traction t in Enum.GetValues<Traction>())
{
if (!d.Eras.Tractions.Any(x => x.Id == t)) Err("eras.json", $"manca la trazione «{t}»");
}
Increasing("eras.json", "eras.from", d.Eras.Eras.Select(e => (double)e.From), errors);
Increasing("eras.json", "bridgeTypes.from", d.Eras.BridgeTypes.Select(e => (double)e.From), errors);
Increasing("eras.json", "bridgeTypes.maxSpanM", d.Eras.BridgeTypes.Select(e => e.MaxSpanM), errors);
Increasing("eras.json", "tunnelLimits.from", d.Eras.TunnelLimits.Select(e => (double)e.From), errors);
Increasing("eras.json", "tunnelLimits.maxLengthM", d.Eras.TunnelLimits.Select(e => e.MaxLengthM), errors);
Increasing("eras.json", "trackClasses.speedKmh", d.Eras.TrackClasses.Select(e => e.SpeedKmh), errors);
int start = d.Balance.Time.DefaultStartYear;
if (d.Eras.BridgeTypes[0].From > start) Err("eras.json", "nessun tipo di ponte all'anno di inizio");
if (d.Eras.TunnelLimits[0].From > start) Err("eras.json", "nessun limite di galleria all'anno di inizio");
if (d.Eras.TrackClasses[0].From > start) Err("eras.json", "nessuna classe di binario all'anno di inizio");
// --- livelli
var levels = d.Tiers.Tiers.Select(t => t.Level).ToList();
if (!levels.SequenceEqual(Enumerable.Range(1, levels.Count))) Err("tiers.json", "i livelli devono essere 1, 2, 3, 4, 5 in ordine");
Increasing("tiers.json", "requirements.netWorth", d.Tiers.Tiers.Select(t => (double)t.Requirements.NetWorth), errors, strictFromSecond: true);
if (!d.Tiers.RatingScale.SequenceEqual(Enum.GetValues<CreditRating>())) Err("tiers.json", "ratingScale deve elencare i rating da AAA a D");
// --- difficoltà
Unique("difficulty.json", d.Difficulty.Presets.Select(p => p.Id), errors);
if (!d.Difficulty.Presets.Any(p => p.Id == d.Difficulty.Default)) Err("difficulty.json", $"preset predefinito «{d.Difficulty.Default}» inesistente");
// --- bilanciamento
var b = d.Balance;
if (!b.Time.Speeds.Contains(0) || !b.Time.Speeds.Contains(1)) Err("balance.json", "time.speeds deve contenere 0 e 1");
if (b.Market.MinPriceFactor >= 1 || b.Market.MaxPriceFactor <= 1) Err("balance.json", "market: i fattori di prezzo devono racchiudere 1");
if (b.Market.Outlook.HistoryMonths * b.Time.DaysPerMonth > b.Market.HistoryDays)
Err("balance.json", "market.outlook.historyMonths: lo storico mensile richiede più giorni di market.historyDays");
if (b.Market.Outlook.ChangeDays >= b.Market.HistoryDays) Err("balance.json", "market.outlook.changeDays deve essere minore di market.historyDays");
foreach (int size in b.Map.SizesKm)
{
string key = size.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (!b.Map.Towns.CountBySize.ContainsKey(key)) Err("balance.json", $"map.towns.countBySize non definisce {key}");
if (!b.Map.Industries.CountBySize.ContainsKey(key)) Err("balance.json", $"map.industries.countBySize non definisce {key}");
}
RequireKeys("balance.json", "map.deposits.perThousandKm2", b.Map.Deposits.PerThousandKm2.Keys, ResourceKeys, errors);
RequireKeys("balance.json", "map.deposits.reserveTonnes", b.Map.Deposits.ReserveTonnes.Keys, ResourceKeys, errors);
RequireKeys("balance.json", "map.deposits.preferredMinPercentile", b.Map.Deposits.PreferredMinPercentile.Keys, ResourceKeys, errors);
RequireKeys("balance.json", "map.deposits.preferredMaxPercentile", b.Map.Deposits.PreferredMaxPercentile.Keys, ResourceKeys, errors);
foreach (var (k, range) in b.Map.Deposits.ReserveTonnes)
{
if (range.Length != 2 || range[0] > range[1] || range[0] <= 0) Err("balance.json", $"map.deposits.reserveTonnes.{k} deve essere [min, max] positivo");
}
if (b.Map.Deposits.RadiusCells.Length != 2) Err("balance.json", "map.deposits.radiusCells deve essere [min, max]");
if (b.Map.Towns.LargestPopulation.Length != 2) Err("balance.json", "map.towns.largestPopulation deve essere [min, max]");
if (b.Map.Hydrology.RiverWidthSteps.Length != 4) Err("balance.json", "map.hydrology.riverWidthSteps deve avere 4 soglie (larghezze 1–4)");
RequireKeys("balance.json", "map.industries.shares", b.Map.Industries.Shares.Keys, ["farm", "logging", "processing", "manufacturing"], errors);
if (Math.Abs(b.Map.Industries.Shares.Values.Sum() - 1.0) > 1e-6) Err("balance.json", "map.industries.shares deve sommare a 1");
if (b.Map.Industries.InitialLevels.Length != 2 || b.Map.Industries.InitialLevels[0] > b.Map.Industries.InitialLevels[1])
Err("balance.json", "map.industries.initialLevels deve essere [min, max]");
RequireKeys("balance.json", "industry.footprintCells", b.Industry.FootprintCells.Keys, SizeKeys, errors);
RequireKeys("balance.json", "tariffs.classMultipliers", b.Tariffs.ClassMultipliers.Keys, ["worker", "staff"], errors);
RequireKeys("balance.json", "finance.ratingSpreads", b.Finance.RatingSpreads.Keys, Enum.GetNames<CreditRating>(), errors);
if (b.Finance.RatingByScore.Length != 9) Err("balance.json", "finance.ratingByScore deve avere 9 soglie (AAA … C)");
Increasing("balance.json", "finance.ratingByScore (decrescente)", Enumerable.Reverse(b.Finance.RatingByScore), errors);
RequireKeys("balance.json", "industryMaintenance.budgets", b.IndustryMaintenance.Budgets.Keys, ["none", "base", "high"], errors);
if (b.IndustryMaintenance.BreakdownDays.Length != 2) Err("balance.json", "industryMaintenance.breakdownDays deve essere [min, max]");
if (b.Growth.MaxLevel > 5 || b.Growth.MaxLevel < 1) Err("balance.json", "growth.maxLevel deve stare tra 1 e 5");
// --- costruzione
var c = d.Construction;
var classIds = d.Eras.TrackClasses.Select(t => t.Id).ToHashSet(StringComparer.Ordinal);
foreach (var sc in c.SpeedClasses)
{
if (!classIds.Contains(sc.TrackClass)) Err("construction.json", $"speedClasses: classe «{sc.TrackClass}» inesistente in eras.json");
}
foreach (string id in classIds)
{
if (!c.SpeedClasses.Any(s => s.TrackClass == id)) Err("construction.json", $"speedClasses non definisce la classe «{id}»");
}
RequireKeys("construction.json", "crews.metersPerDay", c.Crews.MetersPerDay.Keys, WorkKeys, errors);
if (c.Crews.CrewsByTier.Length != 5) Err("construction.json", "crews.crewsByTier deve avere 5 valori");
RequireKeys("construction.json", "costs.depotBySize", c.Costs.DepotBySize.Keys, SizeKeys, errors);
foreach (string k in c.Costs.TerrainModifiers.Keys)
{
if (!CellTypeKeys.Contains(k)) Err("construction.json", $"costs.terrainModifiers: tipo di cella sconosciuto «{k}»");
}
RequireKeys("construction.json", "physics.cxByKind", c.Physics.CxByKind.Keys, ["locomotive", "wagon", "coach"], errors);
RequireKeys("construction.json", "stations.depotUpkeepPerYear", c.Stations.DepotUpkeepPerYear.Keys, SizeKeys, 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;
Unique("maintenance.json", m.Interventions.Select(i => i.Id), errors);
Unique("maintenance.json", m.Components.Locomotive.Select(i => i.Id), errors);
Unique("maintenance.json", m.Components.Car.Select(i => i.Id), errors);
Near1("maintenance.json", "components.locomotive.failureWeight", m.Components.Locomotive.Sum(x => x.FailureWeight), errors);
Near1("maintenance.json", "components.car.failureWeight", m.Components.Car.Sum(x => x.FailureWeight), errors);
Near1("maintenance.json", "failure.*Share", m.Failure.MinorShare + m.Failure.MajorShare + m.Failure.CatastrophicShare, errors);
foreach (string id in new[] { "inspection", "service", "overhaul", "repair_minor", "repair_major", "repair_catastrophic" })
{
if (!m.Interventions.Any(i => i.Id == id)) Err("maintenance.json", $"manca l'intervento «{id}»");
}
foreach (var i in m.Interventions)
{
if (i.Effect == InterventionEffect.Repair && i.RestoreTo is null) Err("maintenance.json", $"{i.Id}: una riparazione richiede restoreTo");
}
RequireKeys("maintenance.json", "depots.stallsBySize", m.Depots.StallsBySize.Keys, SizeKeys, errors);
// --- IA, contratti, regioni
Unique("ai.json", d.Ai.Personalities.Select(p => p.Id), errors);
Unique("contracts.json", d.Contracts.Templates.Select(t => t.Id), errors);
foreach (var t in d.Contracts.Templates)
{
if (t.DurationYears[0] > t.DurationYears[1]) Err("contracts.json", $"{t.Id}: durationYears [min, max] invertito");
if (t.Kind == ContractKind.Connect && t.MaxMinutes is null) Err("contracts.json", $"{t.Id}: un collegamento richiede maxMinutes");
if (t.Kind is ContractKind.Deliver or ContractKind.Service && t.Quantity is null) Err("contracts.json", $"{t.Id}: richiede quantity");
if (t.Kind == ContractKind.GreatWork && t.LengthKm is null) Err("contracts.json", $"{t.Id}: una grande opera richiede lengthKm");
}
Unique("regions.json", d.Regions.Regions.Select(r => r.Id), errors);
Unique("regions.json", d.Regions.NamePools.Select(r => r.Id), errors);
var pools = d.Regions.NamePools.Select(p => p.Id).ToHashSet(StringComparer.Ordinal);
foreach (var r in d.Regions.Regions)
{
if (!pools.Contains(r.NamePool)) Err("regions.json", $"{r.Id}: serbatoio di nomi «{r.NamePool}» inesistente");
}
}
private static void CheckCarComponents(VehicleDef v, HashSet<string> carComponents, List<string> errors)
{
foreach (string c in v.Components.Keys)
{
if (!carComponents.Contains(c)) errors.Add($"vehicles.json: {v.Id}: componente sconosciuto «{c}»");
}
foreach (string c in carComponents)
{
if (!v.Components.ContainsKey(c)) errors.Add($"vehicles.json: {v.Id}: manca il componente «{c}»");
}
}
private static void Unique(string file, IEnumerable<string> ids, List<string> errors, string context = "id")
{
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (string id in ids)
{
if (!seen.Add(id)) errors.Add($"{file}: {context} duplicato «{id}»");
}
}
private static void RequireKeys(string file, string what, IEnumerable<string> keys, IEnumerable<string> required, List<string> errors)
{
var set = keys.ToHashSet(StringComparer.Ordinal);
foreach (string k in required)
{
if (!set.Contains(k)) errors.Add($"{file}: {what} non definisce «{k}»");
}
}
private static void NonDecreasing(string file, string what, IReadOnlyList<int> values, List<string> errors)
{
for (int i = 1; i < values.Count; i++)
{
if (values[i] < values[i - 1]) errors.Add($"{file}: {what} non deve decrescere");
}
}
private static void Increasing(string file, string what, IEnumerable<double> values, List<string> errors, bool strictFromSecond = false)
{
double? prev = null;
int i = 0;
foreach (double v in values)
{
if (prev is { } p && (strictFromSecond && i == 1 ? v < p : v <= p))
errors.Add($"{file}: {what} deve essere crescente");
prev = v;
i++;
}
}
private static void Near1(string file, string what, double sum, List<string> errors)
{
if (Math.Abs(sum - 1.0) > 1e-6) errors.Add($"{file}: la somma di {what} deve essere 1 (è {sum})");
}
}