using System.Text.Json.Nodes; using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Core.Data; using RailEnterprise.Core.Economy; using RailEnterprise.Core.Persistence; using RailEnterprise.Core.Rail; using RailEnterprise.Core.Simulation; using RailEnterprise.Core.Simulation.Systems; using RailEnterprise.Protocol; using RailEnterprise.Protocol.Messages; using RailEnterprise.Tests.Harness; using RailEnterprise.Tests.Rail; using static RailEnterprise.Tests.Rail.RailFixture; namespace RailEnterprise.Tests.Simulation; /// Eventi del mondo con effetti temporanei e notizie (F6, issue #33, ADR 0017). public static class EventTests { private static void AssertInvariants(World w, string when) { Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro {when}"); for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} {when}"); } /// Copia esatta del mondo (salvataggio e caricamento del corpo): stesso stato e stesso futuro. private static World Clone(World w) { var s = new SaveWriter(1 << 20); WorldSerializer.Write(w, s); return WorldSerializer.Read(TestData.Data, new SaveReader(s.WrittenSpan.ToArray())); } /// Mondo generato di 64 km senza IA, con la frequenza degli eventi indicata. private static World Generated(ulong seed, double frequency, int ai = 0) => TestWorlds.Small(seed, "imprenditore", ("eventFrequencyMultiplier", frequency), ("aiCompetitors", ai)); private static Town TownNamed(World w, string name) => w.Towns.Single(t => t.Name == name); private static Industry IndustryOfType(World w, string type) => w.Industries.First(i => i.Def.Id == type); private static List WorldNews(World w) => w.Events.Recent.Where(e => e.Kind == EventKind.World).ToList(); // ------------------------------------------------------------------ catalogo [Test(Description = "Il catalogo events.json è valido e copre industria, città, bene, maltempo e sciopero con effetti nel verso atteso")] public static void CatalogIsValidAndCoversEveryKind() { var d = TestData.Data; var events = d.Events.Events; Assert.True(d.Events.MaxActive > 0, "maxActive positivo"); foreach (EventTarget t in Enum.GetValues()) Assert.True(events.Any(e => e.Target == t), $"manca un evento con bersaglio {t}"); foreach (var e in events) { Assert.True(e.DurationDays[0] >= 1 && e.DurationDays[0] <= e.DurationDays[1], $"{e.Id}: durata"); Assert.True(e.ChancePerYear > 0, $"{e.Id}: probabilità"); Assert.True(e.NewsIt.Contains("{target}", StringComparison.Ordinal), $"{e.Id}: la notizia nomina il bersaglio"); Assert.True(e.Effects.All(x => DataValidator.EffectFits(e.Target, x.Kind)), $"{e.Id}: effetti compatibili"); Assert.Equal(e, d.EventType(e.Id)); } double Primary(string id, bool max) => max ? d.EventType(id)!.Effects[0].Max : d.EventType(id)!.Effects[0].Min; Assert.True(Primary("industry_accident", true) < 1 && Primary("industry_accident", false) >= 0, "incidente: capacità ridotta o nulla"); Assert.True(Primary("industry_boom", false) > 1, "boom: capacità aumentata"); Assert.True(Primary("town_fair", false) > 1, "fiera: consumi aumentati"); Assert.True(Primary("epidemic", true) < 1 && d.EventType("epidemic")!.Effects.Any(x => x.Kind == EventEffectKind.Attendance && x.Max < 1), "epidemia: consumi e presenze ridotti"); Assert.True(Primary("good_demand_boom", false) > 1 && Primary("good_demand_slump", true) < 1, "boom e crollo della domanda di un bene"); var storm = d.EventType("storm")!; Assert.True(storm.Effects.Single(x => x.Kind == EventEffectKind.TrainSpeed).Max < 1 && storm.Effects.Single(x => x.Kind == EventEffectKind.TrackWear).Min > 1, "maltempo: treni lenti e usura"); Assert.True(Primary("strike_town", true) < 1 && Primary("strike_depot", true) < 1, "scioperi: presenze ridotte"); Assert.True(d.EventType("good_demand_boom")!.GoodIndices.Length > 0, "beni ammessi risolti"); Assert.True(d.Difficulty.Presets.All(p => p.EventFrequencyMultiplier > 0), "eventi attivi in ogni preset"); } [Test(Description = "Il validatore rifiuta un effetto incompatibile con il bersaglio, un bene sconosciuto, min > max, il raggio mancante e un bersaglio fuori elenco")] public static void CatalogValidationRejectsInconsistentEvents() { static IReadOnlyList Errors(Action mutate) { var files = MemoryDataSource.Snapshot(TestData.Source); var root = JsonNode.Parse(files["events.json"])!; mutate(root); files["events.json"] = root.ToJsonString(); try { GameData.Load(new MemoryDataSource(files)); } catch (DataValidationException ex) { return ex.Errors; } Assert.Fail("il catalogo alterato doveva essere rifiutato"); return []; } var semantic = Errors(root => { var list = root["events"]!.AsArray(); list[0]!["effects"]![0]!["kind"] = "trainSpeed"; list[1]!["effects"]![0]!["min"] = 2.0; list[1]!["effects"]![0]!["max"] = 1.5; list[4]!["goods"] = new JsonArray("unobtainium"); list[6]!.AsObject().Remove("radiusKm"); }); Assert.True(semantic.Any(e => e.Contains("non si applica al bersaglio", StringComparison.Ordinal)), "effetto incompatibile"); Assert.True(semantic.Any(e => e.Contains("min > max", StringComparison.Ordinal)), "min > max"); Assert.True(semantic.Any(e => e.Contains("unobtainium", StringComparison.Ordinal)), "bene sconosciuto"); Assert.True(semantic.Any(e => e.Contains("richiede radiusKm", StringComparison.Ordinal)), "raggio mancante"); var schema = Errors(root => root["events"]![0]!["target"] = "planet"); Assert.True(schema.Any(e => e.Contains("events.json", StringComparison.Ordinal)), "bersaglio fuori elenco"); } // ------------------------------------------------------------------ effetti [Test(Description = "Incidente e boom: la capacità dell'industria segue il moltiplicatore e a evento scaduto torna 1")] public static void IndustryEventsScaleCapacityAndThenStop() { foreach (var (type, intensity, expected) in new[] { ("industry_accident", 0.5, 0.25), ("industry_boom", 1.0, 1.5) }) { var f = Valdoria(); f.W.RunDays(2); var a = f.W; var b = Clone(a); var mine = IndustryOfType(a, "iron_mine"); var ev = EventSystem.Force(a, type, mine.Id.Value, durationDays: 5, intensity: intensity); Assert.NotNull(ev, $"{type} sulla miniera"); Assert.Approx(expected, a.WorldEvents.IndustryCapacity(mine.Id), 1e-12, $"{type}: moltiplicatore"); a.RunDays(1); b.RunDays(1); var mineB = b.Industries[mine.Id.Value]; Assert.True(mineB.Efficiency > 0, "la miniera lavora"); Assert.Approx(expected * mineB.Efficiency, mine.Efficiency, 1e-12, $"{type}: efficienza scalata dalla capacità"); Assert.Approx(1.0, a.WorldEvents.IndustryCapacity(a.Industries.First(i => i.Def.Id == "coal_mine").Id), 0, "le altre industrie non cambiano"); a.RunDays(5); Assert.Equal(0, a.WorldEvents.Active.Count, $"{type}: scaduto"); Assert.Approx(1.0, a.WorldEvents.IndustryCapacity(mine.Id), 0, $"{type}: capacità tornata normale"); Assert.Equal(2, WorldNews(a).Count(e => e.EntityIndex == mine.Id.Value && e.Entity == EntityKind.Industry), $"{type}: notizia d'inizio e di fine"); AssertInvariants(a, type); } } [Test(Description = "Fiera ed epidemia: la domanda della città segue il moltiplicatore, l'epidemia riduce anche le presenze dei suoi lavoratori")] public static void TownEventsScaleDemandAndAttendance() { foreach (var (type, intensity) in new[] { ("town_fair", 1.0), ("epidemic", 0.0) }) { var f = Valdoria(); f.W.RunDays(3); var a = f.W; var b = Clone(a); var town = TownNamed(a, "Valdoria"); var ev = EventSystem.Force(a, type, town.Id.Value, durationDays: 4, intensity: intensity)!; double demand = ev.Effect(EventEffectKind.TownDemand); double attendance = ev.Effect(EventEffectKind.Attendance); a.RunDays(1); b.RunDays(1); int goods = 0; for (int g = 0; g < a.Data.GoodCount; g++) { double db = b.Towns[town.Id.Value].DemandToday[g]; if (db <= 0) continue; goods++; Assert.Approx(db * demand, town.DemandToday[g], 1e-9 * db, $"{type}: domanda di {a.Data.Goods[g].Id}"); } Assert.True(goods > 0, "la città consuma"); var other = TownNamed(a, "Borgo Ceresio"); Assert.SequenceEqual(b.Towns[other.Id.Value].DemandToday, other.DemandToday, "le altre città non cambiano"); // presenze: i lavoratori di Valdoria nei posti vicini (a piedi) si presentano in quota CheckAttendance(a, b, town, attendance, type); a.RunDays(4); Assert.Equal(0, a.WorldEvents.Active.Count); Assert.Approx(1.0, a.WorldEvents.TownDemand(town, 0), 0, "domanda tornata normale"); AssertInvariants(a, type); } } /// Presenze dei posti di lavoro con pendolari della città: ricalcolate con il moltiplicatore e confrontate con il gemello senza evento. private static void CheckAttendance(World a, World b, Town town, double attendance, string what) { var ib = a.Data.Balance.Industry; int checkedPlaces = 0; foreach (var ind in a.Industries) { if (ind.Closed || ind.Level <= 0) continue; var contracts = a.Commutes.Where(c => c.Workplace == ind.Ref && c.Category == PaxClass.Worker).ToList(); if (!contracts.Any(c => c.Town == town.Id)) continue; double expected = EmploymentSystem.OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare); foreach (var c in contracts) { double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage); expected += present * (c.Town == town.Id ? attendance : 1.0); } expected = Math.Min(expected, ind.JobsWorkers); Assert.Approx(expected, ind.WorkersPresent, 1e-9, $"{what}: presenze a {ind.Name}"); if (attendance < 1) Assert.True(ind.WorkersPresent < b.Industries[ind.Id.Value].WorkersPresent, $"{what}: meno presenti a {ind.Name}"); checkedPlaces++; } Assert.True(checkedPlaces > 0, $"{what}: un posto di lavoro con pendolari della città"); } [Test(Description = "Sciopero dei lavoratori di una città: presenze ridotte solo per chi viene da quella città, poi tutto come prima")] public static void TownStrikeCutsAttendanceOfItsWorkers() { var f = Valdoria(); f.W.RunDays(3); var a = f.W; var b = Clone(a); var town = TownNamed(a, "Valdoria"); var ev = EventSystem.Force(a, "strike_town", town.Id.Value, durationDays: 3, intensity: 0)!; Assert.Approx(0.2, ev.Primary, 1e-12); a.RunDays(1); b.RunDays(1); CheckAttendance(a, b, town, 0.2, "sciopero"); // le stime dell'IA (ADR 0017 §9) contano i presenti senza lo sciopero: come nel gemello foreach (var ind in a.Industries) { var twin = b.Industries[ind.Id.Value]; Assert.Approx(twin.WorkersPresent, EmploymentSystem.PresentWithoutEvents(a, ind, PaxClass.Worker), 1e-9, $"presenti senza eventi a {ind.Name}"); Assert.Approx(twin.StaffPresent, EmploymentSystem.PresentWithoutEvents(a, ind, PaxClass.Staff), 1e-9, $"personale senza eventi a {ind.Name}"); Assert.Equal(twin.WorkersPresent, EmploymentSystem.PresentWithoutEvents(b, twin, PaxClass.Worker), "senza eventi è il valore del giorno"); } var sb = b.Towns[town.Id.Value]; Assert.SequenceEqual(sb.DemandToday, town.DemandToday, "lo sciopero non cambia i consumi"); a.RunDays(3); Assert.Equal(0, a.WorldEvents.Active.Count); Assert.Approx(1.0, a.WorldEvents.Attendance(town.Id, new WorkplaceRef(WorkplaceKind.Industry, 0)), 0); } [Test(Description = "Boom e crollo della domanda di un bene: moltiplicano il consumo di quel bene solo nelle città della zona")] public static void GoodDemandEventsActOnTheZoneOnly() { foreach (var (type, intensity, expected) in new[] { ("good_demand_boom", 1.0, 2.0), ("good_demand_slump", 0.0, 0.3) }) { var a = Generated(31, 0); a.RunDays(1); var b = Clone(a); var def = a.Data.EventType(type)!; var center = a.Towns.OrderByDescending(t => t.Population).First(); int good = def.GoodIndices.First(g => DemandSystem.TownDemand(a, center, g, a.Clock.Year) > 0); var ev = EventSystem.Force(a, type, center.Id.Value, good, durationDays: 2, intensity: intensity)!; Assert.Approx(expected, ev.Primary, 1e-12); a.RunDays(1); b.RunDays(1); double r2 = def.RadiusKm!.Value * 1000 * def.RadiusKm.Value * 1000; int inside = 0, outside = 0; foreach (var t in a.Towns) { var tb = b.Towns[t.Id.Value]; bool zone = (t.Position - center.Position).LengthSquared <= r2; for (int g = 0; g < a.Data.GoodCount; g++) { double f = zone && g == good ? expected : 1.0; Assert.Approx(tb.DemandToday[g] * f, t.DemandToday[g], 1e-9 * Math.Max(1, tb.DemandToday[g]), $"{type}: {t.Name}, {a.Data.Goods[g].Id}"); } if (zone) inside++; else outside++; } Assert.True(inside >= 1 && outside >= 1, $"città dentro ({inside}) e fuori ({outside}) dalla zona"); a.RunDays(2); Assert.Equal(0, a.WorldEvents.Active.Count); Assert.Approx(1.0, a.WorldEvents.TownDemand(center, good), 0); AssertInvariants(a, type); } } [Test(Description = "Maltempo: gli archi dell'area hanno velocità ridotta e il traffico li consuma di più; fuori dall'area e dopo l'evento nessun effetto")] public static void StormSlowsAndWearsTheTrackInItsArea() { var f = Valdoria(); f.BuildFreightNetwork(); var a = f.W; var b = Clone(a); var town = TownNamed(a, "Valdoria"); var ev = EventSystem.Force(a, "storm", town.Id.Value, durationDays: 3, intensity: 1.0)!; double speed = ev.Effect(EventEffectKind.TrainSpeed), wear = ev.Effect(EventEffectKind.TrackWear); Assert.Approx(0.8, speed, 1e-12); Assert.Approx(4.0, wear, 1e-12); Assert.False(ev.InZone(new Vec2(1e7, 1e7)), "lontano dall'area"); // il maltempo è in vigore da oggi: l'usura del traffico di oggi si applica domattina, moltiplicata; // stessa usura del traffico nei due mondi: con il maltempo l'arco perde «wear» volte di più a.RunDays(1); b.RunDays(1); var edges = a.Network.Edges.Where(e => e.State == EdgeState.Active).ToList(); var before = new Dictionary(); foreach (var e in edges) { before[e.Id.Value] = (e.Condition, b.Network.Edges[e.Id.Value].Condition); e.WearToday = 2000; b.Network.Edges[e.Id.Value].WearToday = 2000; } a.RunDays(1); b.RunDays(1); int affected = 0; foreach (var e in edges) { double factor = a.WorldEvents.EdgeWear(e); Assert.True(factor == 1.0 || Math.Abs(factor - wear) < 1e-12, "fattore dell'arco"); Assert.Approx(factor == 1.0 ? 1.0 : speed, a.WorldEvents.EdgeSpeed(e), 1e-12, "velocità dell'arco"); double dropA = before[e.Id.Value].A - e.Condition, dropB = before[e.Id.Value].B - b.Network.Edges[e.Id.Value].Condition; Assert.True(dropB > 0, "il traffico consuma il binario"); Assert.Approx(dropB * factor, dropA, 1e-9, $"usura dell'arco {e.Id.Value}"); if (factor > 1) affected++; } Assert.True(affected > 0, "archi nell'area"); a.RunDays(3); Assert.Equal(0, a.WorldEvents.Active.Count); Assert.True(edges.All(e => a.WorldEvents.EdgeSpeed(e) == 1.0 && a.WorldEvents.EdgeWear(e) == 1.0), "nessun effetto dopo l'evento"); } [Test(Description = "Maltempo: un treno nell'area non supera il limite ridotto ed è più lento del gemello senza evento")] public static void StormSlowsTheTrains() { var f = Valdoria(); var (mine, mill, depot) = f.BuildFreightNetwork(); int train = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 4, "Merci 1"); int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) })); f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line))); f.W.RunDays(2); var a = f.W; var b = Clone(a); // intensità 0: velocità al 50 %, su tutta la rete (centro nel mezzo del tracciato) var center = a.Towns.OrderBy(t => (t.Position - a.Network.Stations[mine].Position).LengthSquared).First(); var ev = EventSystem.Force(a, "storm", center.Id.Value, durationDays: 20, intensity: 0)!; double factor = ev.Effect(EventEffectKind.TrainSpeed); Assert.Approx(0.5, factor, 1e-12); double maxA = 0, maxB = 0, maxLimitA = 0; int ticks = 6 * a.Calendar.TicksPerDay; for (int k = 0; k < ticks; k++) { a.RunTicks(1); b.RunTicks(1); if (k < a.Calendar.TicksPerDay) continue; // un giorno per frenare al nuovo limite var ta = a.Trains[train]; var tb = b.Trains[train]; if (ta.Route.Count > 0 && ta.RouteIndex < ta.Route.Count) { var e = a.Network.Edges[ta.Route[ta.RouteIndex].Edge.Value]; if (a.WorldEvents.EdgeSpeed(e) < 1) { maxA = Math.Max(maxA, ta.Speed * 3.6); maxLimitA = Math.Max(maxLimitA, e.SpeedLimitKmh.Max() * factor); } } maxB = Math.Max(maxB, tb.Speed * 3.6); } Assert.True(maxA > 0, "il treno si muove nell'area"); Assert.True(maxA <= maxLimitA + 0.5, $"velocità {maxA:F1} km/h oltre il limite ridotto {maxLimitA:F1}"); Assert.True(maxB > maxA + 1, $"senza maltempo il treno va più forte ({maxB:F1} contro {maxA:F1} km/h)"); AssertInvariants(a, "maltempo"); } [Test(Description = "Sciopero in deposito: il personale non si presenta, l'officina resta senza tecnici fino alla fine")] public static void DepotStrikeEmptiesTheWorkshop() { var f = Valdoria(); var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1); var a = f.W; var depot = a.Network.Depots[net.Officina]; Assert.True(f.RunUntil(() => depot.StaffPresent > 0, 120), "personale in officina"); var b = Clone(a); var ev = EventSystem.Force(a, "strike_depot", depot.Id.Value, durationDays: 5, intensity: 0)!; Assert.Approx(0.0, ev.Primary, 0); a.RunDays(1); b.RunDays(1); Assert.Equal(0.0, depot.StaffPresent, "nessun tecnico presente durante lo sciopero"); Assert.True(b.Network.Depots[net.Officina].StaffPresent > 0, "senza sciopero il personale c'è"); Assert.True(WorldNews(a).Any(e => e.Entity == EntityKind.Depot && e.EntityIndex == depot.Id.Value), "notizia sul deposito"); a.RunDays(5); Assert.Equal(0, a.WorldEvents.Active.Count); Assert.True(f.RunUntil(() => depot.StaffPresent > 0, 30), "il personale torna dopo lo sciopero"); AssertInvariants(a, "sciopero in deposito"); } // ------------------------------------------------------------------ regole [Test(Description = "La durata è rispettata al giorno: l'evento agisce per i giorni estratti, poi la notizia di fine")] public static void DurationIsRespected() { var f = Valdoria(); var w = f.W; w.RunDays(1); var mine = IndustryOfType(w, "iron_mine"); long start = w.Clock.Day; var ev = EventSystem.Force(w, "industry_accident", mine.Id.Value, durationDays: 10, intensity: 0)!; Assert.Equal(start, ev.StartDay); Assert.Equal(start + 10, ev.EndDay); var news = WorldNews(w).Single(); Assert.Equal(EventSeverity.Warning, news.Severity); Assert.Equal(EntityKind.Industry, news.Entity); Assert.True(news.Text.Contains(mine.Name, StringComparison.Ordinal) && news.Text.Contains("10 giorni", StringComparison.Ordinal) && news.Text.Contains("0%", StringComparison.Ordinal), news.Text); Assert.Equal(w.Calendar.DateOfDay(ev.EndDay - 1).ToString(), EventSystem.Format(w, ev, "{until}"), "{until} è l'ultimo giorno dell'evento"); int stoppedDays = 0; for (int d = 0; d < 12; d++) { w.RunDays(1); if (mine.Efficiency == 0) stoppedDays++; Assert.Equal(d < 10, w.WorldEvents.Active.Contains(ev), $"giorno {d}: evento in elenco"); } Assert.Equal(10, stoppedDays, "dieci giorni di produzione nulla"); var end = WorldNews(w).Last(); Assert.Equal(start + 10, end.Day, "la notizia di fine arriva il mattino del primo giorno libero"); Assert.True(end.Text.Contains("riprende", StringComparison.Ordinal), end.Text); Assert.Equal(2, WorldNews(w).Count); } [Test(Description = "Niente due eventi dello stesso tipo sullo stesso bersaglio; un bersaglio non ammesso si rifiuta")] public static void NoDuplicateOnTheSameTarget() { var w = Valdoria().W; var mine = IndustryOfType(w, "iron_mine"); Assert.NotNull(EventSystem.Force(w, "industry_accident", mine.Id.Value)); Assert.True(EventSystem.Force(w, "industry_accident", mine.Id.Value) is null, "doppione rifiutato"); Assert.NotNull(EventSystem.Force(w, "industry_boom", mine.Id.Value), "un altro tipo sullo stesso bersaglio è ammesso"); Assert.NotNull(EventSystem.Force(w, "industry_accident", IndustryOfType(w, "coal_mine").Id.Value), "lo stesso tipo su un altro bersaglio è ammesso"); Assert.True(EventSystem.Force(w, "town_fair", 99) is null, "città inesistente"); Assert.True(EventSystem.Force(w, "town_fair", TownNamed(w, "Valdoria").Id.Value, durationDays: 0) is null, "durata nulla"); Assert.True(EventSystem.Force(w, "good_demand_boom", TownNamed(w, "Valdoria").Id.Value, w.Data.GoodIndex("iron_ore")) is null, "bene non di consumo"); Assert.Throws(() => EventSystem.Force(w, "meteor", 0)); Assert.Equal(3, w.WorldEvents.Active.Count); Assert.Approx(0.5 * 1.5, w.WorldEvents.IndustryCapacity(mine.Id), 1e-12, "incidente e boom insieme: la capacità è il prodotto dei due"); } [Test(Description = "Zone: niente due maltempi né due eventi sulla domanda dello stesso bene su zone sovrapposte; zone lontane o beni diversi sono ammessi")] public static void OverlappingZonesAreRefused() { var w = Generated(31, 0); w.RunDays(1); var boom = w.Data.EventType("good_demand_boom")!; double r = boom.RadiusKm!.Value * 1000; // due città abbastanza vicine da condividere la zona e un bene consumato da entrambe var (x, y, good) = (from p in w.Towns from q in w.Towns where p.Id.Value < q.Id.Value && (p.Position - q.Position).LengthSquared <= 4 * r * r from g in boom.GoodIndices where DemandSystem.TownDemand(w, p, g, w.Clock.Year) > 0 && DemandSystem.TownDemand(w, q, g, w.Clock.Year) > 0 select (p, q, g)).First(); var first = EventSystem.Force(w, "good_demand_boom", x.Id.Value, good, durationDays: 30)!; Assert.True(EventSystem.Force(w, "good_demand_boom", y.Id.Value, good, durationDays: 30) is null, "boom dello stesso bene su una zona sovrapposta"); Assert.True(EventSystem.Force(w, "good_demand_slump", y.Id.Value, good, durationDays: 30) is null, "boom e crollo dello stesso bene insieme"); int other = boom.GoodIndices.FirstOrDefault(g => g != good && DemandSystem.TownDemand(w, y, g, w.Clock.Year) > 0, -1); if (other >= 0) Assert.NotNull(EventSystem.Force(w, "good_demand_boom", y.Id.Value, other, durationDays: 30), "un altro bene è ammesso"); foreach (var t in w.Towns) { double expected = (t.Position - x.Position).LengthSquared <= r * r ? first.Primary : 1.0; Assert.Approx(expected, w.WorldEvents.TownDemand(t, good), 1e-12, $"un solo moltiplicatore a {t.Name}"); } var storm = w.Data.EventType("storm")!; double rs = storm.RadiusKm!.Value * 1000; var near = w.Towns.First(t => t.Id != x.Id && (t.Position - x.Position).LengthSquared <= 4 * rs * rs); var far = w.Towns.FirstOrDefault(t => (t.Position - x.Position).LengthSquared > 4 * rs * rs); Assert.NotNull(EventSystem.Force(w, "storm", x.Id.Value, durationDays: 5)); Assert.True(EventSystem.Force(w, "storm", near.Id.Value, durationDays: 5) is null, "due maltempi su zone sovrapposte"); if (far is not null) Assert.NotNull(EventSystem.Force(w, "storm", far.Id.Value, durationDays: 5), "maltempo lontano ammesso"); } /// Porta il mondo al primo tick del giorno dopo, già eseguito (come quando il server manda il resoconto). private static void NextDayAfterFirstTick(World w) { do w.RunTicks(1); while (w.Clock.TickOfDay != 0); w.RunTicks(1); } [Test(Description = "Maltempo estratto a giornata iniziata: treni, usura e resoconto al client seguono i giorni annunciati, con il conto alla rovescia da n a 1")] public static void StormWindowMatchesTheAnnouncedDays() { var f = Valdoria(); f.BuildFreightNetwork(); var w = f.W; w.RunDays(1); w.RunTicks(1); // giorno D, dopo i sistemi giornalieri: l'evento inizia domani long draw = w.Clock.Day; var town = TownNamed(w, "Valdoria"); var ev = EventSystem.Force(w, "storm", town.Id.Value, durationDays: 3, intensity: 1.0)!; Assert.Equal(draw + 1, ev.StartDay); var edge = w.Network.Edges.First(e => e.State == EdgeState.Active && ev.InZone(new Vec2(e.X[e.X.Length / 2], e.Y[e.Y.Length / 2]))); double speed = ev.Effect(EventEffectKind.TrainSpeed), wear = ev.Effect(EventEffectKind.TrackWear); Assert.Equal(1.0, w.WorldEvents.EdgeSpeed(edge), "il giorno dell'estrazione i treni non rallentano"); WorldEventInfo Listed() => RailEnterprise.Server.Projection.Digest(w, w.Player, [], false, 1, 0).WorldEvents.Single(); Assert.True(Listed().StartDay > w.Clock.Day, "il resoconto del giorno dell'estrazione lo mostra in partenza"); int Ends() => WorldNews(w).Count(n => n.Text.Contains("sereno", StringComparison.Ordinal)); for (int k = 0; k < 3; k++) { NextDayAfterFirstTick(w); Assert.Equal(speed, w.WorldEvents.EdgeSpeed(edge), $"giorno {k + 1}: treni rallentati"); // l'usura applicata oggi è del traffico di ieri: moltiplicata dal secondo giorno Assert.Equal(k == 0 ? 1.0 : wear, w.WorldEvents.EdgeWear(edge), $"giorno {k + 1}: usura"); Assert.Equal(3L - k, Listed().EndDay - w.Clock.Day, $"giorno {k + 1}: giorni che restano"); Assert.Equal(0, Ends(), "nessuna notizia di fine prima del tempo"); } // primo giorno libero, prima del suo primo tick: l'usura dell'ultimo giorno di maltempo è ancora moltiplicata do w.RunTicks(1); while (w.Clock.TickOfDay != 0); Assert.Equal(ev.EndDay, w.Clock.Day); Assert.Equal(wear, w.WorldEvents.EdgeWear(edge), "usura del traffico dell'ultimo giorno"); Assert.Equal(1.0, w.WorldEvents.EdgeSpeed(edge), "il primo giorno libero i treni vanno normali"); w.RunTicks(1); Assert.Equal(0, RailEnterprise.Server.Projection.Digest(w, w.Player, [], false, 1, 0).WorldEvents.Count, "fuori dal resoconto"); var end = WorldNews(w).Last(); Assert.Equal(ev.EndDay, end.Day, "la notizia di fine il primo giorno libero"); Assert.Equal(1, Ends(), end.Text); AssertInvariants(w, "maltempo"); } [Test(Description = "Con la frequenza a zero (scenari di accettazione) non nasce nessun evento; la difficoltà scala la frequenza")] public static void FrequencyZeroMeansNoEvents() { var w = Generated(5, 0); w.RunDays(360); Assert.Equal(0, w.WorldEvents.NextId, "nessun evento in un anno"); Assert.Equal(0.0, Valdoria().W.Difficulty.EventFrequencyMultiplier, "valdoria.json disattiva gli eventi"); var d = TestData.Data; Assert.True(d.DifficultyPreset("apprendista").EventFrequencyMultiplier < d.DifficultyPreset("ferro_e_sangue").EventFrequencyMultiplier, "più eventi alle difficoltà alte"); } // ------------------------------------------------------------------ determinismo e salvataggi private static (World World, List News) FrequentYear(ulong seed, int days, Func? midway = null) { var w = Generated(seed, 10); w.RunDays(days / 2); if (midway is not null) w = midway(w); w.RunDays(days - days / 2); return (w, w.Events.Recent.Where(e => e.Kind == EventKind.World).Select(e => $"{e.Day} {e.Text}").ToList()); } [Test(Description = "Determinismo: stesso seme, stessi eventi e stesso hash; un altro seme dà altri eventi")] public static void SameSeedSameEvents() { var (a, newsA) = FrequentYear(11, 180); var (b, newsB) = FrequentYear(11, 180); var (_, newsC) = FrequentYear(12, 180); Assert.True(newsA.Count >= 10, $"eventi frequenti: {newsA.Count} notizie"); Assert.SequenceEqual(newsA, newsB, "stesse notizie"); Assert.Equal(a.LastStateHash, b.LastStateHash, "stesso hash"); Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b)); Assert.False(newsA.SequenceEqual(newsC), "un altro seme cambia gli eventi"); } [Test(Description = "Salvataggio e caricamento con eventi in corso: stessi eventi, stesso hash e stesso futuro")] public static void SaveAndLoadWithActiveEvents() { int activeAtSave = 0; World ThroughSave(World w) { if (w.WorldEvents.Active.Count == 0) EventSystem.Force(w, "town_fair", w.Towns.OrderByDescending(t => t.Population).First().Id.Value, durationDays: 30); activeAtSave = w.WorldEvents.Active.Count; var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test")); Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso stato dinamico"); Assert.SequenceEqual(w.WorldEvents.Active.Select(e => (e.Id, e.Def.Id, e.Target, e.Good, e.StartDay, e.EndDay, e.Intensity)), loaded.WorldEvents.Active.Select(e => (e.Id, e.Def.Id, e.Target, e.Good, e.StartDay, e.EndDay, e.Intensity)), "eventi ricaricati"); Assert.Equal(w.WorldEvents.NextId, loaded.WorldEvents.NextId); Assert.Equal(w.Difficulty.EventFrequencyMultiplier, loaded.Difficulty.EventFrequencyMultiplier, "frequenza salvata"); foreach (var e in loaded.WorldEvents.Active.Where(e => e.Def.Target is EventTarget.Area or EventTarget.TownGood)) Assert.True(e.RadiusSquaredM > 0, "zona ricostruita"); return loaded; } var (direct, newsDirect) = FrequentYear(17, 120, w => { if (w.WorldEvents.Active.Count == 0) EventSystem.Force(w, "town_fair", w.Towns.OrderByDescending(t => t.Population).First().Id.Value, durationDays: 30); return w; }); var (saved, newsSaved) = FrequentYear(17, 120, ThroughSave); Assert.True(activeAtSave > 0, "eventi in corso al salvataggio"); Assert.Equal(direct.LastStateHash, saved.LastStateHash, "salvare e ricaricare non cambia il futuro"); Assert.SequenceEqual(newsDirect, newsSaved, "stesse notizie"); } [Test(Description = "Un salvataggio della versione 4 si carica senza eventi attivi e con la frequenza del preset; la partita prosegue con gli invarianti")] public static void VersionFourSavesLoadWithoutEvents() { var w = Generated(23, 1); w.RunDays(3); if (w.WorldEvents.NextId == 0) { var body = new SaveWriter(1 << 20); WorldSerializer.Write(w, body, 4); var same = WorldSerializer.Read(TestData.Data, new SaveReader(body.WrittenSpan.ToArray())); Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(same), "senza eventi lo stato è identico"); } EventSystem.Force(w, "town_fair", w.Towns[0].Id.Value, durationDays: 20); var v4 = new SaveWriter(1 << 20); WorldSerializer.Write(w, v4, 4); var loaded = WorldSerializer.Read(TestData.Data, new SaveReader(v4.WrittenSpan.ToArray())); Assert.Equal(0, loaded.WorldEvents.Active.Count, "nessun evento attivo dopo la migrazione"); Assert.Equal(0, loaded.WorldEvents.NextId); Assert.Equal(TestData.Data.DifficultyPreset("imprenditore").EventFrequencyMultiplier, loaded.Difficulty.EventFrequencyMultiplier, "frequenza dal preset"); Assert.Approx(1.0, loaded.WorldEvents.TownDemand(loaded.Towns[0], 0), 0); loaded.RunDays(60); AssertInvariants(loaded, "dopo la migrazione"); } [Test(Slow = true, Description = "Un anno con eventi frequenti (e IA): invarianti di denaro e merci, mai doppioni né oltre maxActive, quasi tutti i tipi")] public static void InvariantsHoldThroughAYearOfFrequentEvents() { var w = Generated(3, 10, ai: 2); var types = new HashSet(StringComparer.Ordinal); int max = 0; for (int d = 0; d < w.Calendar.DaysPerYear; d++) { w.RunDays(1); var active = w.WorldEvents.Active; max = Math.Max(max, active.Count); Assert.True(active.Count <= w.Data.Events.MaxActive, $"giorno {d}: {active.Count} eventi"); var keys = active.Select(e => (e.Def.Id, e.TargetKind, e.Target)).ToList(); Assert.Equal(keys.Count, keys.Distinct().Count(), $"giorno {d}: doppioni"); for (int i = 0; i < active.Count; i++) { for (int j = i + 1; j < active.Count; j++) { var (x, y) = (active[i], active[j]); if (x.Def.Target != y.Def.Target || x.Good != y.Good || x.Def.RadiusKm is not { } rx || y.Def.RadiusKm is not { } ry) continue; double reach = (rx + ry) * 1000; Assert.True((x.Center - y.Center).LengthSquared > reach * reach, $"giorno {d}: zone sovrapposte di {x.Def.Id} e {y.Def.Id}"); } } // giorno appena giocato: Clock.Day − 1; quelli estratti ieri iniziano oggi long last = w.Clock.Day - 1; foreach (var e in active) { types.Add(e.Def.Id); Assert.True(e.DurationDays >= e.Def.DurationDays[0] && e.DurationDays <= e.Def.DurationDays[1], $"{e.Def.Id}: durata"); Assert.True(e.InForce(last) || e.StartDay == last + 1, $"{e.Def.Id}: in vigore ieri o in partenza oggi"); Assert.InRange(e.Intensity, 0, 1, "intensità"); } if (d % 30 == 29) AssertInvariants(w, $"giorno {d}"); } Console.WriteLine($" {w.WorldEvents.NextId} eventi in un anno, al massimo {max} insieme, tipi: {string.Join(", ", types.Order(StringComparer.Ordinal))}"); Assert.True(types.Count >= 7, $"tipi visti: {string.Join(", ", types)}"); Assert.Equal(max, w.Data.Events.MaxActive, "con la frequenza alta si arriva al tetto"); Assert.True(w.Events.Recent.Count(e => e.Kind == EventKind.World) >= Math.Min(w.WorldEvents.NextId, 250), "notizie degli eventi"); } // ------------------------------------------------------------------ protocollo e mercato [Test(Description = "Protocollo: gli eventi in corso arrivano nel resoconto giornaliero e quelli sul bene nel quadro del mercato, con round-trip")] public static void EventsReachTheClient() { var f = Valdoria(); var w = f.W; var town = TownNamed(w, "Valdoria"); var def = w.Data.EventType("good_demand_boom")!; int good = def.GoodIndices.First(g => DemandSystem.TownDemand(w, town, g, w.Clock.Year) > 0); var boom = EventSystem.Force(w, "good_demand_boom", town.Id.Value, good, durationDays: 90, intensity: 0.5)!; var storm = EventSystem.Force(w, "storm", town.Id.Value, durationDays: 5, intensity: 0.25)!; var digest = RailEnterprise.Server.Projection.Digest(w, w.Player, [], false, 1, 0); Assert.Equal(2, digest.WorldEvents.Count); var decoded = (DailyDigest)Frame.Decode(Frame.Encode(digest)); Assert.Equal(2, decoded.WorldEvents.Count); var s = decoded.WorldEvents.Single(e => e.Type == "storm"); Assert.Equal(storm.Id, s.Id); Assert.Equal((byte)EntityKind.Town, s.Entity); Assert.Equal(town.Id.Value, s.EntityIndex); Assert.Equal(-1, s.Good); Assert.Equal(storm.StartDay, s.StartDay); Assert.Equal(storm.EndDay, s.EndDay); Assert.Equal((byte)NewsSeverity.Warning, s.Severity); Assert.Equal(2, s.Effects.Length); Assert.Approx(storm.Effect(EventEffectKind.TrainSpeed), s.Effects[0], 1e-6); Assert.Approx(storm.Effect(EventEffectKind.TrackWear), s.Effects[1], 1e-6); var g = decoded.WorldEvents.Single(e => e.Type == "good_demand_boom"); Assert.Equal(good, g.Good); Assert.Approx(1.7, g.Effects[0], 1e-6); // il quadro del mercato mostra l'evento sul bene come «evento in corso» var outlook = MarketOutlook.Build(w, f.Me); Assert.Equal(boom, outlook.GoodEvents.Single()); var report = RailEnterprise.Server.Projection.Market(w, f.Me); var back = (MarketReport)Frame.Decode(Frame.Encode(report)); Assert.Equal(boom.Id, back.GoodEvents.Single().Id); Assert.Equal(good, back.GoodEvents.Single().Good); Assert.Equal(report.Warehouses.Count, back.Warehouses.Count); // senza eventi i blocchi non viaggiano e il resoconto resta compatibile var empty = RailEnterprise.Server.Projection.Digest(Valdoria().W, w.Player, [], false, 1, 0); Assert.Equal(0, ((DailyDigest)Frame.Decode(Frame.Encode(empty))).WorldEvents.Count); } }