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>
This commit is contained in:
1 parent
b258e0858a
commit
1f8da87e51
41 files changed
+1892
-41
No files matched your search
@@ -18,6 +18,8 @@ public enum EventKind : byte
|
||||
Maintenance = 7,
|
||||
Employment = 8,
|
||||
Company = 9,
|
||||
/// <summary>Evento del mondo (events.json, ADR 0017): inizio e fine.</summary>
|
||||
World = 10,
|
||||
}
|
||||
|
||||
/// <summary>Riferimento facoltativo all'entità coinvolta.</summary>
|
||||
|
||||
@@ -16,6 +16,11 @@ public sealed class ScenarioFile
|
||||
public string Difficulty { get; set; } = "imprenditore";
|
||||
/// <summary>Numero di concorrenti IA (sostituisce quello della difficoltà; null = come la difficoltà).</summary>
|
||||
public int? AiCompetitors { get; set; }
|
||||
/// <summary>
|
||||
/// Frequenza degli eventi del mondo (sostituisce quella della difficoltà; null = come la difficoltà,
|
||||
/// 0 = nessun evento casuale): gli scenari di accettazione la mettono a 0 (ADR 0017).
|
||||
/// </summary>
|
||||
public double? EventFrequencyMultiplier { get; set; }
|
||||
public required ScenarioTerrain Terrain { get; init; }
|
||||
public List<ScenarioTown> Towns { get; set; } = [];
|
||||
public List<ScenarioIndustry> Industries { get; set; } = [];
|
||||
|
||||
@@ -29,6 +29,15 @@ public sealed record LoadedScenario(World World, ScenarioFile File)
|
||||
/// <summary>Costruisce un mondo da uno scenario JSON (terreno a mano + entità in posizioni date).</summary>
|
||||
public static class ScenarioLoader
|
||||
{
|
||||
/// <summary>Ritocchi della difficoltà scritti nello scenario (concorrenti IA, frequenza degli eventi).</summary>
|
||||
private static List<(string Key, double Value)> Overrides(ScenarioFile file)
|
||||
{
|
||||
var list = new List<(string Key, double Value)>();
|
||||
if (file.AiCompetitors is { } ai) list.Add(("aiCompetitors", ai));
|
||||
if (file.EventFrequencyMultiplier is { } events) list.Add(("eventFrequencyMultiplier", events));
|
||||
return list;
|
||||
}
|
||||
|
||||
public static LoadedScenario LoadFile(GameData data, string path) => Load(data, File.ReadAllText(path));
|
||||
|
||||
public static LoadedScenario Load(GameData data, string json)
|
||||
@@ -104,8 +113,8 @@ public static class ScenarioLoader
|
||||
StartYear = file.StartYear,
|
||||
DifficultyId = file.Difficulty,
|
||||
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria",
|
||||
DifficultyOverride = file.AiCompetitors is { } ai
|
||||
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), [("aiCompetitors", ai)])
|
||||
DifficultyOverride = Overrides(file) is { Count: > 0 } overrides
|
||||
? DifficultyOverrides.Apply(data.DifficultyPreset(file.Difficulty), overrides)
|
||||
: null,
|
||||
};
|
||||
var world = WorldFactory.FromMap(data, map, settings);
|
||||
|
||||
@@ -42,6 +42,7 @@ public sealed class SystemPipeline(IReadOnlyList<ISimSystem> systems)
|
||||
new FinanceSystem(),
|
||||
new StockMarketSystem(),
|
||||
new AiSystem(),
|
||||
new EventSystem(),
|
||||
new HashSystem(),
|
||||
]);
|
||||
|
||||
|
||||
@@ -158,7 +158,8 @@ public sealed class ConstructionSystem : ISimSystem
|
||||
}
|
||||
var owner = w.Companies[e.Owner.Value];
|
||||
double before = e.Condition;
|
||||
double wear = e.WearToday / tw.K * w.Difficulty.WearMultiplier;
|
||||
// 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
|
||||
|
||||
@@ -43,7 +43,8 @@ public sealed class DemandSystem : ISimSystem
|
||||
market.DemandToday[data.SparePartsGood] += (double)IndustryMath.MonthlyPartsUse(ind, im) / dpm;
|
||||
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
|
||||
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
|
||||
// capacità modificata dagli eventi del mondo (incidente, boom: ADR 0017)
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * w.WorldEvents.IndustryCapacity(ind.Id);
|
||||
var inputs = ind.Def.Recipe.Inputs;
|
||||
for (int i = 0; i < inputs.Count; i++)
|
||||
{
|
||||
@@ -54,14 +55,18 @@ public sealed class DemandSystem : ISimSystem
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Domanda giornaliera di una città per un bene, in unità.</summary>
|
||||
public static double TownDemand(World w, Town town, int good, int year)
|
||||
/// <summary>
|
||||
/// Domanda giornaliera di una città per un bene, in unità, con i moltiplicatori degli eventi del
|
||||
/// mondo in corso (fiera, epidemia, domanda del bene nella zona: ADR 0017) se <paramref name="events"/>.
|
||||
/// </summary>
|
||||
public static double TownDemand(World w, Town town, int good, int year, bool events = true)
|
||||
{
|
||||
var def = w.Data.Goods[good];
|
||||
if (def.Town is not { } td || def.Era > year || (td.UntilYear is { } until && year >= until)) return 0;
|
||||
double ratio = w.Market.GlobalPrice[good] / def.BasePrice;
|
||||
var tb = w.Data.Balance.Town;
|
||||
double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), tb.DemandPriceFactorMin, tb.DemandPriceFactorMax);
|
||||
return town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
|
||||
double d = town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
|
||||
return events ? d * w.WorldEvents.TownDemand(town, good) : d;
|
||||
}
|
||||
}
|
||||
@@ -446,6 +446,8 @@ public sealed class EmploymentSystem : ISimSystem
|
||||
c.Coverage = Ema.Step(c.Coverage, ratio, eb.CoverageEmaDays);
|
||||
if (!c.Walking) c.LowCoverageDays = c.Coverage < eb.DissolveCoverage ? c.LowCoverageDays + 1 : 0;
|
||||
double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
|
||||
// eventi del mondo: epidemia o sciopero in città, sciopero in deposito (ADR 0017)
|
||||
present *= w.WorldEvents.Attendance(c.Town, c.Workplace);
|
||||
var p = Workplace(w, c.Workplace);
|
||||
if (c.Category == PaxClass.Staff) p.StaffPresent += present;
|
||||
else p.WorkersPresent += present;
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo (F6, ADR 0017): ogni giorno chiude quelli scaduti, poi per ogni tipo del
|
||||
/// catalogo (events.json, in ordine) estrae con il flusso dedicato «events» se ne nasce uno, con
|
||||
/// probabilità chancePerYear × difficoltà / giorni dell'anno, e sceglie il bersaglio tra i candidati
|
||||
/// in ordine di id. Nessun doppione dello stesso tipo sullo stesso bersaglio; al massimo maxActive
|
||||
/// eventi insieme. Inizio e fine danno una notizia (<see cref="EventKind.World"/>). Gli effetti sono
|
||||
/// moltiplicatori letti dai sistemi tramite <see cref="WorldEventState"/>.
|
||||
/// Gira dopo le IA e prima dell'hash, quindi dopo i sistemi giornalieri del giorno: un evento estratto
|
||||
/// oggi inizia domani (StartDay) e agisce sui sistemi giornalieri nei giorni [StartDay, EndDay), cioè
|
||||
/// esattamente per la durata estratta; si chiude a fine giornata del suo ultimo giorno (EndDay − 1),
|
||||
/// con la notizia di fine. I treni, che si muovono a ogni tick, lo sentono dal tick successivo.
|
||||
/// </summary>
|
||||
public sealed class EventSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Events";
|
||||
|
||||
private readonly List<(EntityKind Kind, int Target, int Good)> _candidates = [];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
Expire(w, ctx.Day);
|
||||
|
||||
double frequency = w.Difficulty.EventFrequencyMultiplier;
|
||||
if (frequency <= 0) return;
|
||||
var catalog = w.Data.Events;
|
||||
var rng = w.Stream("events");
|
||||
double days = w.Calendar.DaysPerYear;
|
||||
foreach (var def in catalog.Events)
|
||||
{
|
||||
if (ctx.Year < def.MinYear) continue;
|
||||
if (!rng.Chance(def.ChancePerYear * frequency / days)) continue;
|
||||
if (w.WorldEvents.Active.Count >= catalog.MaxActive) continue;
|
||||
Candidates(w, def, _candidates);
|
||||
if (_candidates.Count == 0) continue;
|
||||
var (kind, target, good) = _candidates[rng.NextInt(_candidates.Count)];
|
||||
int duration = rng.NextInt(def.DurationDays[0], def.DurationDays[1] + 1);
|
||||
double intensity = rng.NextDouble();
|
||||
Begin(w, def, kind, target, good, ctx.Day + 1, duration, intensity);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chiude gli eventi scaduti o il cui bersaglio non esiste più (industria chiusa, deposito demolito).</summary>
|
||||
private static void Expire(World w, long day)
|
||||
{
|
||||
var state = w.WorldEvents;
|
||||
for (int i = 0; i < state.Active.Count;)
|
||||
{
|
||||
var e = state.Active[i];
|
||||
bool alive = TargetAlive(w, e.TargetKind, e.Target);
|
||||
// domani è fuori dall'intervallo [StartDay, EndDay): oggi era l'ultimo giorno
|
||||
if (day + 1 < e.EndDay && alive)
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
state.RemoveAt(i);
|
||||
if (alive) Announce(w, e, e.Def.NewsEndIt, NewsSeverity.Info);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fa iniziare subito un evento sul bersaglio indicato (test, scenari e strumenti; in partita li
|
||||
/// estrae il sistema). Restituisce null se il bersaglio non è ammesso dal tipo, se un evento dello
|
||||
/// stesso tipo è già in corso lì o se la durata non è positiva. Non usa numeri casuali e non
|
||||
/// controlla maxActive né l'anno minimo. Chiamato tra un giorno e l'altro (fuori dalla pipeline),
|
||||
/// l'evento agisce già sul giorno che sta per cominciare; a giornata iniziata, da domani.
|
||||
/// </summary>
|
||||
public static ActiveWorldEvent? Force(World w, string typeId, int target, int good = -1, int? durationDays = null, double intensity = 1.0)
|
||||
{
|
||||
var def = w.Data.EventType(typeId) ?? throw new ArgumentException($"Tipo di evento sconosciuto: {typeId}", nameof(typeId));
|
||||
var list = new List<(EntityKind Kind, int Target, int Good)>();
|
||||
Candidates(w, def, list);
|
||||
var kind = KindOf(def.Target);
|
||||
if (!list.Contains((kind, target, def.Target == EventTarget.TownGood ? good : -1))) return null;
|
||||
int duration = durationDays ?? def.DurationDays[0];
|
||||
if (duration <= 0) return null;
|
||||
long start = w.Clock.Tick % w.Calendar.TicksPerDay == 0 ? w.Clock.Day : w.Clock.Day + 1;
|
||||
return Begin(w, def, kind, target, good, start, duration, Math.Clamp(intensity, 0, 1));
|
||||
}
|
||||
|
||||
private static ActiveWorldEvent Begin(World w, WorldEventDef def, EntityKind kind, int target, int good, long start, int duration, double intensity)
|
||||
{
|
||||
var (center, radius2) = Zone(w, def, kind, target);
|
||||
var e = new ActiveWorldEvent
|
||||
{
|
||||
Id = w.WorldEvents.NextId++,
|
||||
Def = def,
|
||||
TargetKind = kind,
|
||||
Target = target,
|
||||
Good = def.Target == EventTarget.TownGood ? good : -1,
|
||||
StartDay = start,
|
||||
EndDay = start + duration,
|
||||
Intensity = intensity,
|
||||
Center = center,
|
||||
RadiusSquaredM = radius2,
|
||||
};
|
||||
w.WorldEvents.Add(e);
|
||||
Announce(w, e, def.NewsIt, def.Severity);
|
||||
return e;
|
||||
}
|
||||
|
||||
/// <summary>Centro e raggio al quadrato della zona di un evento (dal catalogo e dalla città bersaglio).</summary>
|
||||
public static (Vec2 Center, double RadiusSquaredM) Zone(World w, WorldEventDef def, EntityKind kind, int target)
|
||||
{
|
||||
if (kind != EntityKind.Town || def.RadiusKm is not { } km || target < 0 || target >= w.Towns.Count) return (Vec2.Zero, 0);
|
||||
double r = km * 1000;
|
||||
return (w.Towns[target].Position, r * r);
|
||||
}
|
||||
|
||||
public static EntityKind KindOf(EventTarget target) => target switch
|
||||
{
|
||||
EventTarget.Industry => EntityKind.Industry,
|
||||
EventTarget.Depot => EntityKind.Depot,
|
||||
_ => EntityKind.Town,
|
||||
};
|
||||
|
||||
private static bool TargetAlive(World w, EntityKind kind, int target) => kind switch
|
||||
{
|
||||
EntityKind.Industry => target < w.Industries.Count && !w.Industries[target].Closed && w.Industries[target].Level > 0,
|
||||
EntityKind.Depot => target < w.Network.Depots.Count && w.Network.IsAlive(w.Network.Depots[target]),
|
||||
EntityKind.Town => target < w.Towns.Count,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Bersagli ammessi in ordine deterministico (id dell'entità, poi indice del bene).</summary>
|
||||
private static void Candidates(World w, WorldEventDef def, List<(EntityKind, int, int)> into)
|
||||
{
|
||||
into.Clear();
|
||||
var state = w.WorldEvents;
|
||||
switch (def.Target)
|
||||
{
|
||||
case EventTarget.Industry:
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || ind.Level <= 0) continue;
|
||||
if (def.IndustryKinds is { } kinds && !kinds.Contains(ind.Def.Kind)) continue;
|
||||
if (state.IsActive(def, EntityKind.Industry, ind.Id.Value)) continue;
|
||||
into.Add((EntityKind.Industry, ind.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.Depot:
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (!w.Network.IsAlive(d) || state.IsActive(def, EntityKind.Depot, d.Id.Value)) continue;
|
||||
into.Add((EntityKind.Depot, d.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.Town:
|
||||
case EventTarget.Area:
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.Population < def.MinPopulation || state.IsActive(def, EntityKind.Town, t.Id.Value)) continue;
|
||||
into.Add((EntityKind.Town, t.Id.Value, -1));
|
||||
}
|
||||
break;
|
||||
case EventTarget.TownGood:
|
||||
int year = w.Clock.Year;
|
||||
foreach (var t in w.Towns)
|
||||
{
|
||||
if (t.Population < def.MinPopulation || state.IsActive(def, EntityKind.Town, t.Id.Value)) continue;
|
||||
foreach (int g in def.GoodIndices)
|
||||
{
|
||||
// solo i beni che la città consuma quest'anno (era e fine del consumo)
|
||||
if (DemandSystem.TownDemand(w, t, g, year, events: false) <= 0) continue;
|
||||
into.Add((EntityKind.Town, t.Id.Value, g));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Announce(World w, ActiveWorldEvent e, string template, NewsSeverity severity)
|
||||
{
|
||||
string text = Format(w, e, template);
|
||||
w.Events.Add(new GameEvent(w.Clock.Day, EventKind.World, (EventSeverity)(byte)severity, text, e.TargetKind, e.Target));
|
||||
}
|
||||
|
||||
/// <summary>Testo della notizia con i segnaposti {target}, {good}, {pct}, {days}, {until}.</summary>
|
||||
public static string Format(World w, ActiveWorldEvent e, string template) => template
|
||||
.Replace("{target}", TargetName(w, e.TargetKind, e.Target), StringComparison.Ordinal)
|
||||
.Replace("{good}", e.Good >= 0 ? w.Data.Goods[e.Good].NameIt.ToLowerInvariant() : "", StringComparison.Ordinal)
|
||||
.Replace("{pct}", $"{Math.Round(e.Primary * 100):0}%", StringComparison.Ordinal)
|
||||
.Replace("{days}", e.DurationDays.ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.Ordinal)
|
||||
.Replace("{until}", w.Calendar.DateOfDay(e.EndDay).ToString(), StringComparison.Ordinal);
|
||||
|
||||
public static string TargetName(World w, EntityKind kind, int target) => kind switch
|
||||
{
|
||||
EntityKind.Industry when target < w.Industries.Count => w.Industries[target].Name,
|
||||
EntityKind.Depot when target < w.Network.Depots.Count => w.Network.Depots[target].Name,
|
||||
EntityKind.Town when target < w.Towns.Count => w.Towns[target].Name,
|
||||
_ => "?",
|
||||
};
|
||||
}
|
||||
@@ -60,9 +60,11 @@ public sealed class IndustrySystem : ISimSystem
|
||||
if (frac < ib.DepletionStartFraction) depletion = frac / ib.DepletionStartFraction;
|
||||
}
|
||||
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion;
|
||||
// eventi del mondo: incidente (capacità ridotta o nulla) e boom di produzione (ADR 0017)
|
||||
double capacity = w.WorldEvents.IndustryCapacity(ind.Id);
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion * capacity;
|
||||
for (int o = 0; o < recipe.Outputs.Count && !stopped; o++)
|
||||
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * recipe.Outputs[o].PerCycle;
|
||||
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * capacity * recipe.Outputs[o].PerCycle;
|
||||
|
||||
// copertura degli input di oggi: limita la produzione alle scorte disponibili
|
||||
double covInToday = 1.0;
|
||||
@@ -109,7 +111,7 @@ public sealed class IndustrySystem : ISimSystem
|
||||
double extracted = whole * recipe.Outputs[0].PerCycle * data.Difficulty.DepletionMultipliers.For(w.Difficulty.Depletion);
|
||||
site.ReserveTonnes = Math.Max(0, site.ReserveTonnes - extracted);
|
||||
}
|
||||
ind.Efficiency = eLabor * covInToday * depletion;
|
||||
ind.Efficiency = eLabor * covInToday * depletion * capacity;
|
||||
|
||||
// salari giornalieri ai presenti
|
||||
double wages = (ind.WorkersPresent * ib.WagePerWorkerPerMonth + ind.StaffPresent * ib.WagePerStaffPerMonth) / dpm;
|
||||
|
||||
@@ -243,7 +243,8 @@ public sealed class TrainSystem : ISimSystem
|
||||
// 2. velocità obiettivo: limiti presenti e futuri, fine dell'autorizzazione, fermata
|
||||
var step = t.Route[t.RouteIndex];
|
||||
var edge = net.Edges[step.Edge.Value];
|
||||
double cond = ConstructionSystem.ConditionFactor(w, edge);
|
||||
// condizione del binario e maltempo sull'area (ADR 0017)
|
||||
double cond = ConstructionSystem.ConditionFactor(w, edge) * w.WorldEvents.EdgeSpeed(edge);
|
||||
double limit = Math.Min(t.TopSpeedKmh, LimitAt(edge, step.Forward, t.StepPos) * cond) / 3.6;
|
||||
double target = Math.Min(limit, Math.Sqrt(2 * _brake * Math.Max(0, ma - 1)));
|
||||
target = Math.Min(target, LookaheadCap(w, t, needed + 500));
|
||||
@@ -657,7 +658,7 @@ public sealed class TrainSystem : ISimSystem
|
||||
{
|
||||
var step = t.Route[s];
|
||||
var e = net.Edges[step.Edge.Value];
|
||||
double cond = ConstructionSystem.ConditionFactor(w, e);
|
||||
double cond = ConstructionSystem.ConditionFactor(w, e) * w.WorldEvents.EdgeSpeed(e);
|
||||
double start = s == t.RouteIndex ? t.StepPos : 0;
|
||||
int n = e.S.Length;
|
||||
if (step.Forward)
|
||||
|
||||
@@ -95,6 +95,9 @@ public sealed class World
|
||||
public GoodsCounters Goods { get; }
|
||||
public EventLog Events { get; } = new();
|
||||
|
||||
/// <summary>Eventi del mondo in corso con i loro effetti temporanei (ADR 0017).</summary>
|
||||
public WorldEventState WorldEvents { get; } = new();
|
||||
|
||||
/// <summary>Avvisi di manutenzione del giorno (non salvati): il server li inoltra come MaintenanceAlert.</summary>
|
||||
public List<FleetAlert> Alerts { get; } = [];
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation;
|
||||
|
||||
/// <summary>
|
||||
/// Evento del mondo in corso (ADR 0017): tipo del catalogo, bersaglio, bene (per la domanda di un
|
||||
/// bene), giorno d'inizio e di fine e intensità in [0, 1] da cui si ricavano i moltiplicatori.
|
||||
/// </summary>
|
||||
public sealed class ActiveWorldEvent
|
||||
{
|
||||
public required int Id { get; init; }
|
||||
public required WorldEventDef Def { get; init; }
|
||||
/// <summary>Entità bersaglio: industria, città (anche centro di zona e area) o deposito.</summary>
|
||||
public required EntityKind TargetKind { get; init; }
|
||||
public required int Target { get; init; }
|
||||
/// <summary>Bene coinvolto (TownGood), altrimenti −1.</summary>
|
||||
public int Good { get; init; } = -1;
|
||||
public required long StartDay { get; init; }
|
||||
/// <summary>Primo giorno senza l'evento: dura EndDay − StartDay giorni.</summary>
|
||||
public required long EndDay { get; init; }
|
||||
public required double Intensity { get; init; }
|
||||
|
||||
/// <summary>Centro della zona in metri (città bersaglio), per area e domanda di un bene.</summary>
|
||||
public Vec2 Center { get; init; }
|
||||
|
||||
/// <summary>Quadrato del raggio della zona in metri (0 senza zona).</summary>
|
||||
public double RadiusSquaredM { get; init; }
|
||||
|
||||
public int DurationDays => (int)(EndDay - StartDay);
|
||||
|
||||
/// <summary>Moltiplicatore dell'effetto indicato (1 se il tipo non ce l'ha).</summary>
|
||||
public double Effect(EventEffectKind kind)
|
||||
{
|
||||
foreach (var e in Def.Effects)
|
||||
{
|
||||
if (e.Kind == kind) return e.At(Intensity);
|
||||
}
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
public bool Has(EventEffectKind kind)
|
||||
{
|
||||
foreach (var e in Def.Effects)
|
||||
{
|
||||
if (e.Kind == kind) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Moltiplicatore dell'effetto principale (il primo del catalogo).</summary>
|
||||
public double Primary => Def.Effects[0].At(Intensity);
|
||||
|
||||
public bool InZone(Vec2 p) => RadiusSquaredM > 0 && (p - Center).LengthSquared <= RadiusSquaredM;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Eventi del mondo in corso: unica sorgente dei moltiplicatori temporanei letti dai sistemi. Ogni
|
||||
/// interrogazione restituisce il prodotto degli effetti attivi sull'entità (1 senza eventi), così a
|
||||
/// evento scaduto tutto torna come prima. L'elenco è in ordine d'inizio (id crescente).
|
||||
/// </summary>
|
||||
public sealed class WorldEventState
|
||||
{
|
||||
private readonly List<ActiveWorldEvent> _active = [];
|
||||
private int _areaEvents;
|
||||
|
||||
public IReadOnlyList<ActiveWorldEvent> Active => _active;
|
||||
|
||||
/// <summary>Prossimo id libero (mai riutilizzato).</summary>
|
||||
public int NextId { get; set; }
|
||||
|
||||
internal void Add(ActiveWorldEvent e)
|
||||
{
|
||||
_active.Add(e);
|
||||
Recount();
|
||||
}
|
||||
|
||||
internal void RemoveAt(int index)
|
||||
{
|
||||
_active.RemoveAt(index);
|
||||
Recount();
|
||||
}
|
||||
|
||||
internal void Clear()
|
||||
{
|
||||
_active.Clear();
|
||||
Recount();
|
||||
}
|
||||
|
||||
private void Recount()
|
||||
{
|
||||
_areaEvents = 0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def.Target == EventTarget.Area) _areaEvents++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Vero se un evento dello stesso tipo è già in corso sullo stesso bersaglio.</summary>
|
||||
public bool IsActive(WorldEventDef def, EntityKind kind, int target)
|
||||
{
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def == def && e.TargetKind == kind && e.Target == target) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Eventi che riguardano un'entità (bersaglio diretto o città centro di una zona).</summary>
|
||||
public IEnumerable<ActiveWorldEvent> For(EntityKind kind, int index)
|
||||
{
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.TargetKind == kind && e.Target == index) yield return e;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Capacità produttiva dell'industria (IndustrySystem, DemandSystem).</summary>
|
||||
public double IndustryCapacity(IndustryId industry)
|
||||
{
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.TargetKind == EntityKind.Industry && e.Target == industry.Value) f *= e.Effect(EventEffectKind.IndustryCapacity);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Domanda della città per un bene: eventi sulla città e sul bene nella zona.</summary>
|
||||
public double TownDemand(Town town, int good)
|
||||
{
|
||||
if (_active.Count == 0) return 1.0;
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
switch (e.Def.Target)
|
||||
{
|
||||
case EventTarget.Town when e.Target == town.Id.Value:
|
||||
f *= e.Effect(EventEffectKind.TownDemand);
|
||||
break;
|
||||
case EventTarget.TownGood when e.Good == good && (e.Target == town.Id.Value || e.InZone(town.Position)):
|
||||
f *= e.Effect(EventEffectKind.GoodDemand);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quota dei pendolari che si presenta al lavoro: eventi sulla città di provenienza (epidemia,
|
||||
/// sciopero) e sul deposito di destinazione (sciopero del personale).
|
||||
/// </summary>
|
||||
public double Attendance(TownId town, WorkplaceRef workplace)
|
||||
{
|
||||
if (_active.Count == 0) return 1.0;
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
bool hit = e.Def.Target switch
|
||||
{
|
||||
EventTarget.Town => e.Target == town.Value,
|
||||
EventTarget.Depot => workplace.Kind == WorkplaceKind.Depot && e.Target == workplace.Index,
|
||||
_ => false,
|
||||
};
|
||||
if (hit) f *= e.Effect(EventEffectKind.Attendance);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Velocità dei treni sull'arco (TrainSystem): aree di maltempo che contengono il suo punto medio.</summary>
|
||||
public double EdgeSpeed(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrainSpeed);
|
||||
|
||||
/// <summary>Usura del binario dovuta al traffico sull'arco (ConstructionSystem).</summary>
|
||||
public double EdgeWear(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrackWear);
|
||||
|
||||
private double AreaEffect(TrackEdge edge, EventEffectKind kind)
|
||||
{
|
||||
int mid = edge.X.Length / 2;
|
||||
var p = new Vec2(edge.X[mid], edge.Y[mid]);
|
||||
double f = 1.0;
|
||||
foreach (var e in _active)
|
||||
{
|
||||
if (e.Def.Target == EventTarget.Area && e.InZone(p)) f *= e.Effect(kind);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user