Files
Rail_Enterprise/src/RailEnterprise.Core/Simulation/Systems/ConstructionSystem.cs
T
Alby96andClaude Opus 5.5 1f8da87e51 F6: eventi del mondo con effetti temporanei e notizie
Aggiunge gli eventi della F6: fatti del mondo che cambiano il gioco per
un periodo limitato, leggibili nel notiziario e reversibili.

- Catalogo data/events.json con schema e validazione: incidente e boom
  di un'industria, fiera ed epidemia, boom e crollo della domanda di un
  bene in una zona, maltempo su un'area, sciopero di città o deposito.
- Effetti come moltiplicatori letti da un'unica sorgente
  (World.WorldEvents) dai sistemi esistenti: capacità delle industrie,
  consumi delle città, presenze dei pendolari, velocità dei treni e usura
  del binario. A evento finito il moltiplicatore torna 1.
- EventSystem tra le IA e l'hash, con flusso Rng dedicato «events»,
  bersaglio in ordine di id, frequenza per mappa scalata dalla difficoltà
  (eventFrequencyMultiplier), tetto di 6, niente doppioni, notizie di
  inizio e fine in italiano (EventKind.World).
- Salvataggio corpo versione 5 con gli eventi nell'hash; le versioni 1-4
  si caricano senza eventi e con la frequenza del preset.
- Protocollo: eventi in corso nel DailyDigest e nel MarketReport; client
  con il riquadro «Eventi in corso», avvisi nelle schede e «evento in
  corso» nel Mercato globale.
- Lo scenario Valdoria disattiva gli eventi: con gli eventi attivi la
  flotta F4 senza linea dei ricambi non scendeva più sotto 40, e
  l'accettazione deve misurare la manutenzione, non la fortuna (ADR 0017).
  Accettazione F4 invariata: 35 / 20 guasti senza linea, 75 / 2 con.

Decisioni in docs/adr/0017-eventi-del-mondo.md; 17 test nuovi.

Refs #33.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:59:48 +01:00

209 lines
8.5 KiB
C#

using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
namespace RailEnterprise.Core.Simulation.Systems;
/// <summary>
/// Cantieri (guida 8.2) e usura dei binari (8.3). Ogni giorno le squadre libere di ogni compagnia
/// prendono i progetti in coda nell'ordine di apertura; un progetto avanza di un giorno per giorno
/// di lavoro. Poi si applica l'usura del traffico, la manutenzione ordinaria e l'invecchiamento
/// di ponti e gallerie.
/// </summary>
public sealed class ConstructionSystem : ISimSystem
{
public string Name => "Construction";
public void Step(WorldContext ctx)
{
if (!ctx.IsNewDay) return;
var w = ctx.World;
Projects(ctx, w);
Wear(ctx, w);
}
/// <summary>Squadre disponibili per una compagnia secondo il livello.</summary>
public static int Crews(World w, Company c)
{
var byTier = w.Data.Construction.Crews.CrewsByTier;
return byTier[Math.Clamp(c.Tier, 1, byTier.Length) - 1];
}
private static void Projects(WorldContext ctx, World w)
{
var net = w.Network;
foreach (var company in w.Companies)
{
int crews = Crews(w, company);
int busy = 0;
foreach (var p in net.Projects)
{
if (!p.Done && p.Owner == company.Id && p.Crew >= 0) busy++;
}
foreach (var p in net.Projects)
{
if (p.Done || p.Owner != company.Id || p.Crew >= 0) continue;
if (busy >= crews) break;
p.Crew = FreeCrew(net, company.Id, crews);
p.StartedDay = ctx.Day;
busy++;
}
}
foreach (var p in net.Projects)
{
if (p.Done || p.Crew < 0) continue;
p.ProgressDays += 1;
if (p.ProgressDays + 1e-9 < p.TotalDays) continue;
Complete(ctx, w, p);
}
}
/// <summary>
/// Completa subito tutti i cantieri aperti. Solo per gli strumenti (banco di prova, collaudi):
/// in partita i cantieri avanzano con le squadre.
/// </summary>
public static void CompleteAllNow(World w)
{
foreach (var p in w.Network.Projects)
{
if (p.Done) continue;
p.ProgressDays = p.TotalDays;
Complete(w.Context, w, p);
}
}
private static int FreeCrew(RailNetwork net, CompanyId company, int crews)
{
for (int c = 0; c < crews; c++)
{
bool used = false;
foreach (var p in net.Projects)
{
if (!p.Done && p.Owner == company && p.Crew == c) { used = true; break; }
}
if (!used) return c;
}
return crews - 1;
}
private static void Complete(WorldContext ctx, World w, ConstructionProject p)
{
var net = w.Network;
p.Done = true;
p.Crew = -1;
foreach (var id in p.Edges)
{
var e = net.Edges[id.Value];
if (e.State == EdgeState.Demolished) continue;
e.Project = -1;
switch (p.Kind)
{
case ProjectKind.NewTrack:
e.BuiltDay = ctx.Day;
e.LastRenewalDay = ctx.Day;
e.LastInspectionDay = ctx.Day;
break;
case ProjectKind.Renewal:
e.Condition = 100;
e.StructureCondition = 100;
e.LastRenewalDay = ctx.Day;
e.LastInspectionDay = ctx.Day;
break;
case ProjectKind.Upgrade:
ApplyUpgrade(w, e, p);
break;
}
e.State = EdgeState.Active;
e.ResetBlocks();
}
net.Touch();
string what = p.Kind switch
{
ProjectKind.NewTrack => "Binario completato",
ProjectKind.Renewal => "Rinnovo completato",
_ => "Ammodernamento completato",
};
double km = p.Edges.Sum(id => net.Edges[id.Value].Length) / 1000;
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Construction, EventSeverity.Info,
$"{what}: {km:F1} km in {p.ProgressDays:F0} giorni", EntityKind.None, -1, p.Owner));
}
private static void ApplyUpgrade(World w, TrackEdge e, ConstructionProject p)
{
var classes = w.Data.Eras.TrackClasses;
double oldSpeed = classes[e.TrackClass].SpeedKmh;
double newSpeed = classes[p.UpgradeClass].SpeedKmh;
for (int i = 0; i < e.SpeedLimitKmh.Length; i++)
{
// i tratti limitati dalle curve restano limitati dal raggio
e.SpeedLimitKmh[i] = e.SpeedLimitKmh[i] < oldSpeed - 1e-9 ? Math.Min(newSpeed, e.SpeedLimitKmh[i]) : newSpeed;
}
e.TrackClass = p.UpgradeClass;
e.DoubleTrack = p.UpgradeDouble;
e.Electrified = p.UpgradeElectrified;
e.Condition = 100;
}
private static void Wear(WorldContext ctx, World w)
{
var tw = w.Data.Construction.TrackWear;
var st = w.Data.Construction.Structures;
int daysPerYear = w.Calendar.DaysPerYear;
foreach (var e in w.Network.Edges)
{
if (e.State is EdgeState.Demolished or EdgeState.UnderConstruction)
{
e.WearToday = 0;
continue;
}
var owner = w.Companies[e.Owner.Value];
double before = e.Condition;
// il maltempo sull'area accelera l'usura del traffico (ADR 0017)
double wear = e.WearToday / tw.K * w.Difficulty.WearMultiplier * w.WorldEvents.EdgeWear(e);
e.TonnesThisYear += e.WearToday;
e.WearToday = 0;
// la manutenzione ordinaria pagata annulla la deriva naturale; senza (bancarotta) il binario deperisce
if (owner.Bankrupt) wear += tw.MaintenanceDriftPerDay;
else
{
var cost = Money.FromCentsRounded(e.Length / 1000 * tw.MaintenanceCostPerKmPerDay * (e.DoubleTrack ? 2 : 1));
w.Money.Transfer(Account.Of(owner.Id), Account.External, cost, LedgerEntry.TrackMaintenance);
}
e.Condition = Math.Max(0, e.Condition - wear);
if (before >= 60 && e.Condition < 60)
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Warning,
$"Binario {e.Id.Value}: condizione sotto 60, velocità ridotta al {tw.LimitBelow60 * 100:F0}%", EntityKind.None, e.Id.Value, owner.Id));
// strutture: ispezione annuale obbligatoria e invecchiamento oltre la vita utile
double structures = e.LengthOf(WorkKind.Bridge) + e.LengthOf(WorkKind.Tunnel);
if (structures <= 0) continue;
if (ctx.Day - e.LastInspectionDay >= st.InspectionIntervalDays && !owner.Bankrupt)
{
double share = structures / Math.Max(1, e.Length);
var cost = Money.FromCentsRounded(e.BuildCostCents * share * st.InspectionCostShare);
w.Money.Transfer(Account.Of(owner.Id), Account.External, cost, LedgerEntry.TrackMaintenance);
e.LastInspectionDay = ctx.Day;
}
double age = (ctx.Day - e.LastRenewalDay) / (double)daysPerYear;
double structureBefore = e.StructureCondition;
if (ctx.Day - e.LastInspectionDay > st.InspectionIntervalDays) e.StructureCondition -= st.MissedInspectionWearPerDay;
if (age > st.RenewalYears) e.StructureCondition -= 100.0 / (st.AgingYearsToZero * daysPerYear);
e.StructureCondition = Math.Max(0, e.StructureCondition);
if (structureBefore >= st.CloseBelow && e.StructureCondition < st.CloseBelow)
w.Events.Add(new GameEvent(ctx.Day, EventKind.Maintenance, EventSeverity.Critical,
$"Binario {e.Id.Value}: ponti e gallerie da rinnovare, velocità minima", EntityKind.None, e.Id.Value, owner.Id));
}
}
/// <summary>Fattore di velocità dovuto alla condizione di binario e strutture (8.3).</summary>
public static double ConditionFactor(World w, TrackEdge e)
{
var tw = w.Data.Construction.TrackWear;
var st = w.Data.Construction.Structures;
double f = e.Condition < 30 ? tw.LimitBelow30 : e.Condition < 60 ? tw.LimitBelow60 : 1.0;
if (e.StructureCondition < st.SpeedLimitBelow) f = Math.Min(f, st.SpeedLimitFactor);
if (e.StructureCondition < st.CloseBelow) f = Math.Min(f, st.ClosedSpeedFactor);
return f;
}
}