A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
sim: dated windows for model records (refs #57) (#313)
agamrafaeli-instinct52b26816a15f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b2cef2cf..615bbcf7e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,11 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB## [Unreleased]### Added+- Indicators, policies, effects, situations, voter groups and actors can carry `from`/`to` dates (chapters spec 3.2, refs+ #57). The sim reads the records active on the game date; the state gains a record at its start and drops it at its end,+ and a `set_policy` outside the window is refused. The loader refuses a reference to a record that is not active for the+ whole window of the record using it; an event that fires after its window leaves out records that have ended. With no+ dates nothing changes (goldens unchanged). Offices and regions come later.- Map: today's name of a 1948 locality by tap and in the info panel. A tap on a locality pill toggles its tooltip, a tapelsewhere hides it, and a mouse still hovers as before. The info panel lists the selected hex's 1948 localities withtoday's name where a living place carries on, by the same rule as the tooltip. Keyboard players reach the panel listdiff --git a/docs/determinism.md b/docs/determinism.mdindex eeb49656a..e6c8c29cb 100644--- a/docs/determinism.md+++ b/docs/determinism.md@@ -139,6 +139,16 @@ content in `content/`, or the hash format. When it happens, update the manifestthe history below, and say in the commit message why the hash moved. If a hash changes and you did not mean to changerules or content, treat it as a determinism bug.+## Content windows++Records with `from`/`to` (chapters spec 3.2) are resolved by date through `Content.At(date)`. The active lists are built+once at load, one per segment between cut dates, so a turn does a binary search and no allocation. When the date crosses+a cut, `ContentWindows.Update` adds starting records at their defaults and removes ending ones, in ordinal id order, right+after the date moves (before the cabinet, attention and events; the turn's effects already ran on the turn's start date).+The hash reads the state keys, so it never sees a record outside its window. An event that fires late (after its window,+`EventSystem.Trigger`) can find a record it names already gone: a condition on it is not met, and an option's effect or+`set_policy` on it is left out. With no windows there is one segment and the same view everywhere.+## Rebaseline history| Plan task | Run | New hash (first 8) | Why |diff --git a/sim/Statecraft.Sim.Tests/ContentWindowsTests.cs b/sim/Statecraft.Sim.Tests/ContentWindowsTests.csnew file mode 100644index 000000000..f8ef5c069--- /dev/null+++ b/sim/Statecraft.Sim.Tests/ContentWindowsTests.cs@@ -0,0 +1,278 @@+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.Sim;++/// <summary>Dated windows for model records (#57, chapters design 3.2): the active view, the state following it, the command+/// check and the loader's reference checks. Records with no window behave as before (the goldens pin that).</summary>+public class ContentWindowsTests+{+ static readonly DateTime D0 = new DateTime(1948, 5, 15);+ static readonly DateTime Cut = new DateTime(1948, 8, 1);++ static string Model(Func<string, string>? edit = null) => edit == null ? Fixture.Files["model.yaml"] : edit(Fixture.Files["model.yaml"]);+ static string Offices(Func<string, string> edit) => edit(Fixture.Files["offices.yaml"]);++ static Content Load(string model, string? offices = null, Dictionary<string, string>? events = null)+ {+ var o = new Dictionary<string, string> { ["model.yaml"] = model };+ if (offices != null) o["offices.yaml"] = offices;+ return ContentLoader.Load(Fixture.Write(o, events));+ }++ static string Window(string text, string anchor, string window) => text.Replace(anchor, anchor + "\n " + window);++ static void Refused(string model, string expected, string? offices = null, Dictionary<string, string>? events = null)+ {+ var e = Assert.Throws<ContentException>(() => Load(model, offices, events));+ Assert.Contains(expected, e.Message);+ }++ // ---- the active view++ [Fact]+ public void WithNoWindowEveryDateHasTheSameFullView()+ {+ var c = Load(Model());+ Assert.Same(c.At(D0), c.At(new DateTime(1956, 1, 1)));+ Assert.Equal(c.Policies.Count, c.At(D0).Policies.Count);+ Assert.Equal(c.Indicators.Count, c.At(D0).Indicators.Count);+ }++ [Fact]+ public void ARecordIsActiveOnItsFromAndNotOnItsTo()+ {+ var c = Load(Model(m => Window(m, " - id: maabarot\n default: 0.0", "from: 1948-08-01\n to: 1948-11-01")));+ Assert.DoesNotContain(c.At(Cut.AddDays(-1)).Policies, p => p.Id == "maabarot");+ Assert.Contains(c.At(Cut).Policies, p => p.Id == "maabarot");+ Assert.Contains(c.At(new DateTime(1948, 10, 31)).Policies, p => p.Id == "maabarot");+ Assert.DoesNotContain(c.At(new DateTime(1948, 11, 1)).Policies, p => p.Id == "maabarot");+ }++ [Fact]+ public void TheActiveListsAreBuiltOncePerSegmentAtLoadNotPerCall()+ {+ var c = Load(Model(m => Window(m, " - id: maabarot\n default: 0.0", "from: 1948-08-01")));+ Assert.Same(c.At(D0), c.At(Cut.AddDays(-30))); // one segment before the cut+ Assert.Same(c.At(Cut), c.At(new DateTime(1950, 1, 1))); // one segment after it+ Assert.NotSame(c.At(D0), c.At(Cut));+ var first = c.At(D0);+ for (int i = 0; i < 100; i++) Assert.Same(first, c.At(D0.AddDays(i % 60)));+ }++ // ---- the state follows the windows++ // The fixture's turns run weekly to 12 June, then every quarter (the ceasefire ends the war rung): 5/15 ... 6/12, 9/12.+ static Content Windowed() => Load(Model(m => Window(Window(m, " - id: maabarot\n default: 0.0", "from: 1948-06-20"), " - id: housing\n base: 0.3", "to: 1948-08-01")));++ [Fact]+ public void ANewGameHoldsOnlyTheRecordsActiveOnTheStartDate()+ {+ var c = Windowed();+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.DoesNotContain("maabarot", s.Policies.Keys);+ Assert.Contains("housing", s.Indicators.Keys);+ }++ static GameState Play(Content c, DateTime until)+ {+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ while (s.Date < until && s.GameOver == null) s = Simulation.Step(c, s, new Command[0]).State;+ return s;+ }++ [Fact]+ public void ARecordThatBeginsIsAddedAtItsDefaultAndOneThatEndsIsRemoved()+ {+ var c = Windowed();+ var early = Play(c, new DateTime(1948, 6, 10));+ Assert.DoesNotContain("maabarot", early.Policies.Keys);+ Assert.Contains("housing", early.Indicators.Keys);+ var later = Play(c, new DateTime(1948, 9, 10));+ Assert.Equal(0.0, later.Policies["maabarot"]); // added as Init would add it+ Assert.DoesNotContain("housing", later.Indicators.Keys); // removed with its shift+ Assert.DoesNotContain("housing", later.IndicatorShifts.Keys);+ Assert.NotEmpty(later.Hash()); // the hash never reads a missing key+ Assert.NotEmpty(later.Describe());+ }++ [Fact]+ public void ARecordThatBeginsEntersWithAZeroContributionAndTheStateStaysConsistent()+ {+ var m = Model(x => x.Replace(" - id: rationing_food\n source: rationing", " - id: rationing_food\n from: 1948-08-01\n source: rationing"));+ var c = Load(m);+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.DoesNotContain("rationing_food", s.EffectContributions.Keys);+ s = Play(c, new DateTime(1948, 8, 10));+ Assert.Equal(0.0, s.EffectContributions["rationing_food"]);+ Assert.Equal(c.Effects.Count, s.EffectContributions.Count);+ }++ [Fact]+ public void ASituationThatEndsLeavesTheActiveSet()+ {+ var m = Model(x => x.Replace(" on_below: 0.3", " to: 1948-09-01\n on_below: 0.3").Replace("base: 0.4\n name: Food supply", "base: 0.1\n name: Food supply"));+ var c = Load(m);+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ s = Simulation.Step(c, s, new Command[0]).State;+ Assert.Contains("hunger", s.ActiveSituations);+ s = Play(c, new DateTime(1948, 9, 10));+ Assert.DoesNotContain("hunger", s.ActiveSituations);+ }++ // ---- commands++ [Fact]+ public void SetPolicyOutsideItsWindowIsRefusedAndChangesNothing()+ {+ var c = Windowed();+ var s = Simulation.NewGame(c, 1, Mode.Historical);+ var before = s.Hash();+ var r = Simulation.Step(c, s, new Command[] { new SetPolicy("maabarot", 1.0) });+ Assert.Contains("not available", r.Rejected.Single().Reason);+ Assert.DoesNotContain("maabarot", r.State.Policies.Keys);+ Assert.Equal(s.Attention, Simulation.NewGame(c, 1, Mode.Historical).Attention);+ Assert.Equal(before, s.Hash()); // Step never mutates its input+ }++ [Fact]+ public void SetPolicyInsideItsWindowWorksAndAnUnknownPolicyKeepsItsOwnReason()+ {+ var c = Windowed();+ var s = Play(c, new DateTime(1948, 8, 10));+ var r = Simulation.Step(c, s, new Command[] { new SetPolicy("maabarot", 1.0), new SetPolicy("nope", 1.0) });+ Assert.Equal(1.0, r.State.Policies["maabarot"]);+ Assert.Contains("does not exist", r.Rejected.Single().Reason);+ }++ // ---- the loader refuses a reference to a record that is not active for the whole window of the record using it++ [Theory]+ [InlineData(" - id: maabarot\n default: 0.0", "policies[maabarot]")]+ [InlineData(" - id: housing\n base: 0.3", "indicators[housing]")]+ [InlineData(" - id: rationing_morale\n source: rationing", "effects[rationing_morale]")]+ [InlineData(" - id: hunger\n indicator: food_supply", "situations[hunger]")]+ [InlineData(" - id: everyone", "voter_groups[everyone]")]+ [InlineData(" - id: usa", "actors[usa]")]+ public void AWindowMustRunForward(string anchor, string field)+ {+ foreach (var window in new[] { "from: 1948-09-01\n to: 1948-08-01", "from: 1948-09-01\n to: 1948-09-01" }) // backwards, and empty+ {+ var e = Assert.Throws<ContentException>(() => Load(Model(m => Window(m, anchor, window))));+ Assert.Equal("model.yaml", e.File);+ Assert.Equal(field, e.Field);+ Assert.Contains("from must be before to", e.Message);+ }+ }++ [Fact]+ public void AnEffectSourceThatIsNotActiveThroughTheEffectIsRefused()+ {+ var e = Assert.Throws<ContentException>(() => Load(Model(m => Window(m, " - id: rationing\n default: 0.0", "from: 1948-08-01"))));+ Assert.Equal("model.yaml", e.File); // the error names the file and the key+ Assert.Equal("effects[rationing_food].source", e.Field);+ Assert.Contains("source 'rationing' is not active", e.Message);+ }++ [Fact]+ public void AnEffectTargetThatIsNotActiveThroughTheEffectIsRefused() =>+ Refused(Model(m => Window(m, " - id: food_supply\n base: 0.4", "to: 1948-09-01")), "target 'food_supply' is not active");++ [Fact]+ public void ASituationOnAnIndicatorThatEndsEarlyIsRefused() =>+ Refused(Model(m => Window(m, " - id: food_supply\n base: 0.4", "to: 1948-09-01")+ .Replace(" - id: rationing_food\n", " - id: rationing_food\n to: 1948-09-01\n")), "indicator 'food_supply' is not active");++ [Fact]+ public void AVoterGroupWeightOnAnIndicatorThatBeginsLateIsRefused() =>+ Refused(Model(m => Window(m, " - id: morale\n base: 0.5", "from: 1948-08-01")), "is not active for the whole window");++ [Fact]+ public void AWindowedRecordMayUseARecordWithAWiderWindow()+ {+ var m = Model(x => Window(x, " - id: rationing\n default: 0.0", "from: 1948-06-01")+ .Replace(" - id: rationing_food\n", " - id: rationing_food\n from: 1948-07-01\n").Replace(" - id: rationing_morale\n", " - id: rationing_morale\n from: 1948-07-01\n"));+ Assert.NotNull(Load(m));+ }++ [Fact]+ public void ARecordMayUseOneWithExactlyTheSameWindow()+ {+ // Both edges are inclusive for the check: the same from and the same to cover the user's whole window.+ const string w = "from: 1948-07-01\n to: 1949-01-01";+ var m = Model(x => Window(x, " - id: rationing\n default: 0.0", w)+ .Replace(" - id: rationing_food\n", " - id: rationing_food\n " + w + "\n").Replace(" - id: rationing_morale\n", " - id: rationing_morale\n " + w + "\n"));+ Assert.NotNull(Load(m));+ Refused(m.Replace(" - id: rationing_food\n from: 1948-07-01", " - id: rationing_food\n from: 1948-06-30"), "source 'rationing' is not active");+ Refused(m.Replace(" - id: rationing_food\n from: 1948-07-01\n to: 1949-01-01", " - id: rationing_food\n from: 1948-07-01\n to: 1949-01-02"), "source 'rationing' is not active");+ }++ const string Event = "id: probe\ntitle: Probe\ntext: A probe.\nanchor: soft\nfrom: 1948-06-01\nto: 1948-12-01\n{0}options:\n - id: a\n text: Do a\n{1}";++ [Fact]+ public void AnEventConditionOnAnIndicatorThatBeginsInsideItsWindowIsRefused() =>+ Refused(Model(m => Window(m, " - id: housing\n base: 0.3", "from: 1948-07-01")), "not active for the whole window of this event",+ events: new Dictionary<string, string> { ["probe.yaml"] = string.Format(Event, "conditions: [{ indicator: housing, min: 0.1 }]\n", "") });++ [Fact]+ public void AnEventOptionThatSetsAPolicyOrMovesAnIndicatorOutsideItsWindowIsRefused()+ {+ var model = Model(m => Window(m, " - id: maabarot\n default: 0.0", "from: 1948-07-01"));+ Refused(model, "not active for the whole window of this event",+ events: new Dictionary<string, string> { ["probe.yaml"] = string.Format(Event, "", " set_policy: { maabarot: 1.0 }\n") });+ Refused(Model(m => Window(m, " - id: housing\n base: 0.3", "to: 1948-09-01")), "not active for the whole window of this event",+ events: new Dictionary<string, string> { ["probe.yaml"] = string.Format(Event, "", " effects: [{ target: housing, delta: 0.1 }]\n") });+ }++ // ---- a late fire (EventSystem.Trigger) can come after the window of a record the event reaches has ended++ // The event's window [20 June, 1 July) falls inside the fixture's quarterly turn 12 June to 12 September, so it fires late,+ // on 12 September, after housing (and maabarot) have left the state on 1 July.+ static Content LateFire(string conditions, string option) => Load(+ Model(m => Window(Window(m, " - id: housing\n base: 0.3", "to: 1948-07-01"), " - id: maabarot\n default: 0.0", "to: 1948-07-01")),+ events: new Dictionary<string, string> { ["probe.yaml"] = "id: probe\ntitle: Probe\ntext: A probe.\nanchor: soft\nfrom: 1948-06-20\nto: 1948-07-01\n" + conditions + "options:\n - id: a\n text: Do a\n" + option });++ [Fact]+ public void ALateFireDoesNotReadAnIndicatorWhoseWindowHasEnded()+ {+ var c = LateFire("conditions: [{ indicator: housing, min: 0.0 }]\n", "");+ var s = Play(c, new DateTime(1948, 9, 1));+ Assert.Equal(new DateTime(1948, 9, 12), s.Date);+ Assert.DoesNotContain("probe", s.FiredEvents); // its condition reads a record that no longer exists, so it is not met+ }++ [Fact]+ public void ALateFiredEventResolvedAfterTheWindowLeavesEndedRecordsOut()+ {+ var c = LateFire("", " effects: [{ target: housing, delta: 0.1 }, { target: treasury, delta: 5 }]\n set_policy: { maabarot: 1.0 }\n");+ var s = Play(c, new DateTime(1948, 9, 1));+ Assert.Contains("probe", s.PendingEvents);+ var r = Simulation.Step(c, s, new Command[] { new ChooseEventOption("probe", "a") });+ Assert.Empty(r.Rejected);+ Assert.DoesNotContain("housing", r.State.Indicators.Keys);+ Assert.DoesNotContain("housing", r.State.IndicatorShifts.Keys);+ Assert.DoesNotContain("maabarot", r.State.Policies.Keys); // not added back by the option+ Assert.Contains("probe", r.State.ChosenOptions.Keys);+ Assert.Contains(r.Why, w => w.Target == "treasury" && w.Delta == 5); // treasury is not a dated record: the option still pays it+ }++ [Fact]+ public void ARecordWithAWindowNeedsItsOfficeForThatWholeWindow()+ {+ var offices = Offices(o => o + " - id: trade_minister\n title: Trade\n from: 1948-09-01\n");+ string OnTrade(string m) => m.Replace(" - id: maabarot\n default: 0.0\n office: finance_minister", " - id: maabarot\n default: 0.0\n office: trade_minister");+ Refused(Window(OnTrade(Model()), " - id: maabarot\n default: 0.0", "from: 1948-07-01"), "office 'trade_minister' does not exist for the whole window", offices);+ Assert.NotNull(Load(OnTrade(Model()), offices)); // with no window the existing rule stands: the office may be created later+ }++ [Fact]+ public void AnEffectWithAWindowNeedsItsOfficeForThatWholeWindow()+ {+ var offices = Offices(o => o + " - id: trade_minister\n title: Trade\n from: 1948-09-01\n");+ var m = Model(x => x.Replace(" - id: rationing_food\n source: rationing", " - id: rationing_food\n from: 1948-07-01\n source: rationing")+ .Replace(" inertia: 2\n office: finance_minister", " inertia: 2\n office: trade_minister"));+ var e = Assert.Throws<ContentException>(() => Load(m, offices));+ Assert.Equal("effects[rationing_food].office", e.Field);+ Assert.Contains("office 'trade_minister' does not exist for the whole window", e.Message);+ }+}diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex 9d8eae0df..a9516ee29 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -151,6 +151,12 @@ namespace Statecraft.Simpublic double Base { get; set; }/// <summary>Display name shown to the player (Cause text); required.</summary>public string Name { get; set; } = "";+ /// <summary>First day the record exists (inclusive); null when it exists from the start (chapters design 3.2).</summary>+ public DateTime? From { get; set; }+ /// <summary>Day the record stops existing (exclusive); null while it still exists.</summary>+ public DateTime? To { get; set; }+ public bool ActiveOn(DateTime date) => Window.Active(From, To, date);+}public sealed class Policy@@ -160,6 +166,12 @@ namespace Statecraft.Simpublic string Office { get; set; } = "";/// <summary>Display name shown to the player (Cause text); required.</summary>public string Name { get; set; } = "";+ /// <summary>First day the record exists (inclusive); null when it exists from the start (chapters design 3.2).</summary>+ public DateTime? From { get; set; }+ /// <summary>Day the record stops existing (exclusive); null while it still exists.</summary>+ public DateTime? To { get; set; }+ public bool ActiveOn(DateTime date) => Window.Active(From, To, date);+}/// <summary>Additive effect: its contribution to Target moves toward K * source value over Inertia turns.</summary>@@ -173,6 +185,12 @@ namespace Statecraft.Simpublic string Office { get; set; } = "";/// <summary>Short display name shown to the player (Cause text); required.</summary>public string Name { get; set; } = "";+ /// <summary>First day the record exists (inclusive); null when it exists from the start (chapters design 3.2).</summary>+ public DateTime? From { get; set; }+ /// <summary>Day the record stops existing (exclusive); null while it still exists.</summary>+ public DateTime? To { get; set; }+ public bool ActiveOn(DateTime date) => Window.Active(From, To, date);+}/// <summary>Turns on past one threshold and off past another (hysteresis), so it does not flicker.</summary>@@ -186,11 +204,56 @@ namespace Statecraft.Simpublic double? OffBelow { get; set; }/// <summary>Display name shown to the player (Cause text); required.</summary>public string Name { get; set; } = "";+ /// <summary>First day the record exists (inclusive); null when it exists from the start (chapters design 3.2).</summary>+ public DateTime? From { get; set; }+ /// <summary>Day the record stops existing (exclusive); null while it still exists.</summary>+ public DateTime? To { get; set; }+ public bool ActiveOn(DateTime date) => Window.Active(From, To, date);+}- public sealed class VoterGroup { public string Id { get; set; } = ""; public Dictionary<string, double> Weights { get; set; } = new Dictionary<string, double>(); }+ public sealed class VoterGroup+ {+ public string Id { get; set; } = ""; public Dictionary<string, double> Weights { get; set; } = new Dictionary<string, double>();+ /// <summary>First day the record exists (inclusive); null when it exists from the start (chapters design 3.2).</summary>+ public DateTime? From { get; set; }+ /// <summary>Day the record stops existing (exclusive); null while it still exists.</summary>+ public DateTime? To { get; set; }+ public bool ActiveOn(DateTime date) => Window.Active(From, To, date);+ }- public sealed class Actor { public string Id { get; set; } = ""; public string Name { get; set; } = ""; public double Standing { get; set; } }+ public sealed class Actor+ {+ public string Id { get; set; } = ""; public string Name { get; set; } = ""; public double Standing { get; set; }+ /// <summary>First day the record exists (inclusive); null when it exists from the start (chapters design 3.2).</summary>+ public DateTime? From { get; set; }+ /// <summary>Day the record stops existing (exclusive); null while it still exists.</summary>+ public DateTime? To { get; set; }+ public bool ActiveOn(DateTime date) => Window.Active(From, To, date);+ }++ /// <summary>Half-open windows [from, to) with null for "no bound" (chapters design 3.2).</summary>+ public static class Window+ {+ public static bool Active(DateTime? from, DateTime? to, DateTime date) => (!from.HasValue || date >= from.Value) && (!to.HasValue || date < to.Value);++ /// <summary>True when a record with window [rFrom, rTo) exists on every day of [from, to): the window of whatever uses it.</summary>+ public static bool Covers(DateTime? rFrom, DateTime? rTo, DateTime? from, DateTime? to) =>+ (!rFrom.HasValue || (from.HasValue && rFrom.Value <= from.Value)) && (!rTo.HasValue || (to.HasValue && rTo.Value >= to.Value));+ }++ /// <summary>The model records that exist on one day (<see cref="Content.At"/>). Built once at load, never changed.</summary>+ public sealed class ModelView+ {+ public IReadOnlyList<Indicator> Indicators { get; }+ public IReadOnlyList<Policy> Policies { get; }+ public IReadOnlyList<Effect> Effects { get; }+ public IReadOnlyList<Situation> Situations { get; }+ public IReadOnlyList<VoterGroup> VoterGroups { get; }+ public IReadOnlyList<Actor> Actors { get; }+ public ModelView(IReadOnlyList<Indicator> i, IReadOnlyList<Policy> p, IReadOnlyList<Effect> e, IReadOnlyList<Situation> s, IReadOnlyList<VoterGroup> v, IReadOnlyList<Actor> a)+ { Indicators = i; Policies = p; Effects = e; Situations = s; VoterGroups = v; Actors = a; }+ }public sealed class Rules{@@ -365,6 +428,41 @@ namespace Statecraft.Simpublic List<Situation> Situations = new List<Situation>();public List<VoterGroup> VoterGroups = new List<VoterGroup>();public List<Actor> Actors = new List<Actor>();+ ModelView[] _views = new ModelView[0];+ DateTime[] _cuts = new DateTime[0];+ /// <summary>Computes the windows' segments (chapters design 3.2): a sorted array of the days a model record begins or ends, and+ /// the records active in each segment. Called once by the loader; <see cref="At"/> then only does a binary search, so tests+ /// that run in parallel share nothing mutable. With no window anywhere there is one segment, the full lists.</summary>+ internal void BuildWindows()+ {+ var cuts = new SortedSet<DateTime>();+ void Cut(DateTime? a, DateTime? b) { if (a.HasValue) cuts.Add(a.Value); if (b.HasValue) cuts.Add(b.Value); }+ foreach (var x in Indicators) Cut(x.From, x.To);+ foreach (var x in Policies) Cut(x.From, x.To);+ foreach (var x in Effects) Cut(x.From, x.To);+ foreach (var x in Situations) Cut(x.From, x.To);+ foreach (var x in VoterGroups) Cut(x.From, x.To);+ foreach (var x in Actors) Cut(x.From, x.To);+ _cuts = cuts.ToArray();+ if (_cuts.Length == 0) { _views = new[] { new ModelView(Indicators, Policies, Effects, Situations, VoterGroups, Actors) }; return; }+ _views = new ModelView[_cuts.Length + 1];+ for (int k = 0; k < _views.Length; k++)+ {+ var d = k == 0 ? DateTime.MinValue : _cuts[k - 1];+ _views[k] = new ModelView(Indicators.Where(x => x.ActiveOn(d)).ToArray(), Policies.Where(x => x.ActiveOn(d)).ToArray(),+ Effects.Where(x => x.ActiveOn(d)).ToArray(), Situations.Where(x => x.ActiveOn(d)).ToArray(),+ VoterGroups.Where(x => x.ActiveOn(d)).ToArray(), Actors.Where(x => x.ActiveOn(d)).ToArray());+ }+ }++ /// <summary>The model records that exist on <paramref name="date"/>. A record with no window is in every view.</summary>+ public ModelView At(DateTime date)+ {+ int lo = 0, hi = _cuts.Length; // the number of cuts on or before the date+ while (lo < hi) { int mid = (lo + hi) / 2; if (_cuts[mid] <= date) lo = mid + 1; else hi = mid; }+ return _views[lo];+ }+public Rules Rules = new Rules();/// <summary>The complete rules of each era that has an override file (content/rules/<era>.yaml): rules.yaml with that/// file's keys merged in. Built once at load and never changed. An era without a file is not in this map.</summary>diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 863cfb82a..266a31ac6 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -245,6 +245,7 @@ namespace Statecraft.Simc.Events.Add(e);}Validate(c, settlementIds);+ c.BuildWindows();c.Hash = HashOf(read);return c;}@@ -453,6 +454,64 @@ namespace Statecraft.Simif (r.BudgetStart.Count > 0 && Math.Abs(r.BudgetStart.Values.Sum() - 1.0) > 1e-6) throw new ContentException(file, "budget_start", "shares must sum to 1");}+ /// <summary>Chapters design 3.2: a window must run forward, and nothing may reach a record that is not active for the+ /// whole window of whatever uses it (effect sources and targets, situations, voter-group weights, policy and effect offices).</summary>+ static void ValidateWindows(Content c)+ {+ void Order(string where, DateTime? from, DateTime? to)+ {+ if (from.HasValue && to.HasValue && from.Value >= to.Value) throw new ContentException("model.yaml", where, "from must be before to");+ }+ foreach (var x in c.Indicators) Order($"indicators[{x.Id}]", x.From, x.To);+ foreach (var x in c.Policies) Order($"policies[{x.Id}]", x.From, x.To);+ foreach (var x in c.Effects) Order($"effects[{x.Id}]", x.From, x.To);+ foreach (var x in c.Situations) Order($"situations[{x.Id}]", x.From, x.To);+ foreach (var x in c.VoterGroups) Order($"voter_groups[{x.Id}]", x.From, x.To);+ foreach (var x in c.Actors) Order($"actors[{x.Id}]", x.From, x.To);++ void Reach(string where, DateTime? from, DateTime? to, string kind, string id, DateTime? rFrom, DateTime? rTo)+ {+ if (!Window.Covers(rFrom, rTo, from, to))+ throw new ContentException("model.yaml", where, $"{kind} '{id}' is not active for the whole window of this record (give both the same from/to, or a wider one on '{id}')");+ }+ // The reached record's window, or null when the id is a record kind with none: (null, null) means "always".+ (DateTime?, DateTime?) Win(string id)+ {+ var ind = c.Indicators.FirstOrDefault(x => x.Id == id);+ if (ind != null) return (ind.From, ind.To);+ var pol = c.Policies.FirstOrDefault(x => x.Id == id);+ return pol != null ? (pol.From, pol.To) : ((DateTime?)null, (DateTime?)null);+ }+ foreach (var e in c.Effects)+ {+ var s = Win(e.Source); var t = Win(e.Target);+ Reach($"effects[{e.Id}].source", e.From, e.To, "source", e.Source, s.Item1, s.Item2);+ Reach($"effects[{e.Id}].target", e.From, e.To, "target", e.Target, t.Item1, t.Item2);+ }+ foreach (var s in c.Situations)+ {+ var w = Win(s.Indicator);+ Reach($"situations[{s.Id}].indicator", s.From, s.To, "indicator", s.Indicator, w.Item1, w.Item2);+ }+ foreach (var g in c.VoterGroups)+ foreach (var k in g.Weights.Keys)+ {+ var w = Win(k);+ Reach($"voter_groups[{g.Id}].weights.{k}", g.From, g.To, "indicator", k, w.Item1, w.Item2);+ }+ // A record with a window of its own must have its office for that whole window. Records with no window keep the+ // existing rule (a policy may name an office that is created later: it has no holder until then).+ void OfficeFor(string where, string office, DateTime? from, DateTime? to)+ {+ if (office == "" || (!from.HasValue && !to.HasValue)) return;+ var o = c.Offices.FirstOrDefault(x => x.Id == office);+ if (o != null && !Window.Covers(o.From, o.Until, from, to))+ throw new ContentException("model.yaml", where, $"office '{office}' does not exist for the whole window of this record");+ }+ foreach (var p in c.Policies) OfficeFor($"policies[{p.Id}].office", p.Office, p.From, p.To);+ foreach (var e in c.Effects) OfficeFor($"effects[{e.Id}].office", e.Office, e.From, e.To);+ }+static void Validate(Content c, List<string> settlementIds){var offices = new HashSet<string>(c.Offices.Select(o => o.Id));@@ -687,6 +746,7 @@ namespace Statecraft.SimCount("population.yaml", path + ".jews", a.Jews);}ValidateMap(c, settlementIds);+ ValidateWindows(c);EventRules.Validate(c, offices, indicators);}diff --git a/sim/Statecraft.Sim/ContentWindows.cs b/sim/Statecraft.Sim/ContentWindows.csnew file mode 100644index 000000000..ed2f08752--- /dev/null+++ b/sim/Statecraft.Sim/ContentWindows.cs@@ -0,0 +1,33 @@+using System;+using System.Collections.Generic;+using System.Linq;++namespace Statecraft.Sim+{+ /// <summary>Keeps the state's model records in step with their windows (chapters design 3.2). Called once per turn, after the+ /// date moves. A record that begins is added as <see cref="EffectsSystem.Init"/> would add it (an indicator at its base with+ /// shift 0, a policy at its default, an effect's contribution at 0); one that ends is removed. Records go in and out in+ /// ordinal id order. With no window anywhere the two views are the same object and nothing happens.</summary>+ public static class ContentWindows+ {+ public static void Update(Content c, GameState s, DateTime turnStart)+ {+ var before = c.At(turnStart);+ var after = c.At(s.Date);+ if (ReferenceEquals(before, after)) return;++ var gone = new HashSet<string>(before.Indicators.Select(x => x.Id).Except(after.Indicators.Select(x => x.Id)), StringComparer.Ordinal);+ foreach (var id in gone.OrderBy(x => x, StringComparer.Ordinal)) { s.Indicators.Remove(id); s.IndicatorShifts.Remove(id); }+ foreach (var id in before.Policies.Select(x => x.Id).Except(after.Policies.Select(x => x.Id)).OrderBy(x => x, StringComparer.Ordinal)) s.Policies.Remove(id);+ foreach (var id in before.Effects.Select(x => x.Id).Except(after.Effects.Select(x => x.Id)).OrderBy(x => x, StringComparer.Ordinal)) s.EffectContributions.Remove(id);+ foreach (var id in before.Situations.Select(x => x.Id).Except(after.Situations.Select(x => x.Id)).OrderBy(x => x, StringComparer.Ordinal)) s.ActiveSituations.Remove(id);++ var had = new HashSet<string>(before.Indicators.Select(x => x.Id), StringComparer.Ordinal);+ foreach (var i in after.Indicators.Where(x => !had.Contains(x.Id)).OrderBy(x => x.Id, StringComparer.Ordinal)) { s.Indicators[i.Id] = i.Base; s.IndicatorShifts[i.Id] = 0.0; }+ var hadPolicies = new HashSet<string>(before.Policies.Select(x => x.Id), StringComparer.Ordinal);+ foreach (var p in after.Policies.Where(x => !hadPolicies.Contains(x.Id)).OrderBy(x => x.Id, StringComparer.Ordinal)) s.Policies[p.Id] = p.Default;+ var hadEffects = new HashSet<string>(before.Effects.Select(x => x.Id), StringComparer.Ordinal);+ foreach (var e in after.Effects.Where(x => !hadEffects.Contains(x.Id)).OrderBy(x => x.Id, StringComparer.Ordinal)) s.EffectContributions[e.Id] = 0;+ }+ }+}diff --git a/sim/Statecraft.Sim/EffectsSystem.cs b/sim/Statecraft.Sim/EffectsSystem.csindex 2a65f8109..7ffde41cb 100644--- a/sim/Statecraft.Sim/EffectsSystem.cs+++ b/sim/Statecraft.Sim/EffectsSystem.cs@@ -8,9 +8,10 @@ namespace Statecraft.Sim{public static void Init(Content c, GameState s){- foreach (var i in c.Indicators) { s.Indicators[i.Id] = i.Base; s.IndicatorShifts[i.Id] = 0.0; }- foreach (var p in c.Policies) s.Policies[p.Id] = p.Default;- foreach (var e in c.Effects) s.EffectContributions[e.Id] = 0;+ var v = c.At(s.Date); // the records that exist on the start date (all of them when none has a window)+ foreach (var i in v.Indicators) { s.Indicators[i.Id] = i.Base; s.IndicatorShifts[i.Id] = 0.0; }+ foreach (var p in v.Policies) s.Policies[p.Id] = p.Default;+ foreach (var e in v.Effects) s.EffectContributions[e.Id] = 0;}/// <summary>Competence (0.5 + competence/20) of the office holder (player appointments included) times budget@@ -43,24 +44,25 @@ namespace Statecraft.Simpublic static void Apply(Content c, GameState s, List<Cause> why){// Read every source before writing anything, so effect order cannot change results.- var targets = c.Effects.ToDictionary(e => e.Id, e =>+ var v = c.At(s.Date);+ var targets = v.Effects.ToDictionary(e => e.Id, e =>e.K * (s.Policies.TryGetValue(e.Source, out var p) ? p : s.Indicators[e.Source]) * Multiplier(c, s, e.Office));var moved = new HashSet<string>();- foreach (var e in c.Effects)+ foreach (var e in v.Effects){var old = s.EffectContributions[e.Id];var now = old + (targets[e.Id] - old) / e.Inertia;s.EffectContributions[e.Id] = now;if (Math.Abs(now - old) > 1e-9) moved.Add(e.Id);}- var before = c.Indicators.ToDictionary(i => i.Id, i => s.Indicators[i.Id]);- foreach (var i in c.Indicators) s.Indicators[i.Id] = Level(c, s, i);+ var before = v.Indicators.ToDictionary(i => i.Id, i => s.Indicators[i.Id]);+ foreach (var i in v.Indicators) s.Indicators[i.Id] = Level(c, s, i);// One cause per indicator that actually changed (a clamped indicator reports nothing).- foreach (var i in c.Indicators)+ foreach (var i in v.Indicators){var delta = s.Indicators[i.Id] - before[i.Id];if (Math.Abs(delta) <= 1e-9) continue;- var names = c.Effects.Where(e => e.Target == i.Id && moved.Contains(e.Id)).Select(e => e.Name).ToList();+ var names = v.Effects.Where(e => e.Target == i.Id && moved.Contains(e.Id)).Select(e => e.Name).ToList();var from = names.Count > 0 ? $" ({string.Join(", ", names)})" : "";why.Add(new Cause("effects", i.Id, delta, $"{PlayerText.Change(c, i.Id, delta)}{from}"));}@@ -69,7 +71,7 @@ namespace Statecraft.Sim/// <summary>clamp(base + effect contributions) to [0, 1], before event shifts.</summary>internal static double Inner(Content c, GameState s, Indicator i) =>- Math.Max(0, Math.Min(1, i.Base + c.Effects.Where(e => e.Target == i.Id).Sum(e => s.EffectContributions[e.Id])));+ Math.Max(0, Math.Min(1, i.Base + c.At(s.Date).Effects.Where(e => e.Target == i.Id).Sum(e => s.EffectContributions[e.Id])));/// <summary>clamp(inner + event shift) to [0, 1].</summary>internal static double Level(Content c, GameState s, Indicator i) =>@@ -80,7 +82,7 @@ namespace Statecraft.Sim/// Returns the change actually applied (0 when the indicator was already at the clamp).</summary>public static double Shift(Content c, GameState s, string indicator, double delta){- var ind = c.Indicators.First(i => i.Id == indicator);+ var ind = c.At(s.Date).Indicators.First(i => i.Id == indicator);var level = Level(c, s, ind);var newLevel = Math.Max(0, Math.Min(1, level + delta));s.IndicatorShifts[ind.Id] = newLevel - Inner(c, s, ind);@@ -90,7 +92,7 @@ namespace Statecraft.Simpublic static void UpdateSituations(Content c, GameState s, List<Cause> why){- foreach (var sit in c.Situations)+ foreach (var sit in c.At(s.Date).Situations){var v = s.Indicators[sit.Indicator];bool on = s.ActiveSituations.Contains(sit.Id);@@ -102,7 +104,7 @@ namespace Statecraft.Sim}public static double Approval(Content c, GameState s) =>- c.VoterGroups.Count == 0 ? 0.5 :- c.VoterGroups.Average(g => Math.Max(0, Math.Min(1, g.Weights.Sum(w => w.Value * s.Indicators[w.Key]))));+ c.At(s.Date).VoterGroups.Count == 0 ? 0.5 :+ c.At(s.Date).VoterGroups.Average(g => Math.Max(0, Math.Min(1, g.Weights.Sum(w => w.Value * s.Indicators[w.Key]))));}}diff --git a/sim/Statecraft.Sim/EventRules.cs b/sim/Statecraft.Sim/EventRules.csindex 5a29dd5da..657cd4f06 100644--- a/sim/Statecraft.Sim/EventRules.cs+++ b/sim/Statecraft.Sim/EventRules.cs@@ -27,8 +27,17 @@ namespace Statecraft.Simthrow new ContentException(e.File, F("office"), "historical-only titles cannot be delegated events");CheckPlaceholders(c, e, F("title"), e.Title, offices);CheckPlaceholders(c, e, F("text"), e.Text, offices);+ // Chapters design 3.2: an event may only name model records that are active for its whole window.+ void Active(string field, string id)+ {+ var ind = c.Indicators.FirstOrDefault(x => x.Id == id);+ var pol = c.Policies.FirstOrDefault(x => x.Id == id);+ var (rf, rt) = ind != null ? (ind.From, ind.To) : pol != null ? (pol.From, pol.To) : ((DateTime?)null, (DateTime?)null);+ if (!Window.Covers(rf, rt, e.From, e.To)) throw new ContentException(e.File, field, $"'{id}' is not active for the whole window of this event");+ }foreach (var cond in e.Conditions){+ Active(F($"conditions.{cond.Indicator}"), cond.Indicator);if (!indicators.Contains(cond.Indicator)) throw new ContentException(e.File, F($"conditions.{cond.Indicator}"), "unknown indicator");// Indicators live in [0,1], so a bound outside it (or min above max) could never be met.if (cond.Min.HasValue) { ContentLoader.Finite(e.File, F($"conditions.{cond.Indicator}.min"), cond.Min.Value); ContentLoader.Unit(e.File, F($"conditions.{cond.Indicator}.min"), cond.Min.Value); }@@ -57,12 +66,14 @@ namespace Statecraft.Sim{if (c.Policies.All(p => p.Id != kv.Key)) throw new ContentException(e.File, F($"options[{o.Id}].set_policy.{kv.Key}"), "unknown policy");ContentLoader.Unit(e.File, F($"options[{o.Id}].set_policy.{kv.Key}"), kv.Value);+ Active(F($"options[{o.Id}].set_policy.{kv.Key}"), kv.Key);}if (o.SetRung.HasValue && (o.SetRung < 1 || o.SetRung > 5)) throw new ContentException(e.File, F($"options[{o.Id}].set_rung"), "must be 1-5");foreach (var fx in o.Effects){if (!indicators.Contains(fx.Target) && !SpecialTargets.Contains(fx.Target))throw new ContentException(e.File, F($"options[{o.Id}].effects.{fx.Target}"), "unknown target");+ Active(F($"options[{o.Id}].effects.{fx.Target}"), fx.Target);ContentLoader.Finite(e.File, F($"options[{o.Id}].effects.{fx.Target}.delta"), fx.Delta);if (sensitive && (fx.Target == "treasury" || fx.Target == "fx_reserves") && fx.Delta > 0)throw new ContentException(e.File, F($"options[{o.Id}].effects.{fx.Target}"), $"sensitive events cannot reward {fx.Target}");diff --git a/sim/Statecraft.Sim/EventSystem.cs b/sim/Statecraft.Sim/EventSystem.csindex 9ab23a428..a9059bf84 100644--- a/sim/Statecraft.Sim/EventSystem.cs+++ b/sim/Statecraft.Sim/EventSystem.cs@@ -24,8 +24,9 @@ namespace Statecraft.Simvar eligible = c.Events.Where(e => !s.FiredEvents.Contains(e.Id) && e.From <= s.Date && (e.To == null || start < e.To.Value)).Where(e => e.Requires == null || (s.ChosenOptions.TryGetValue(e.Requires.Event, out var picked) && picked == e.Requires.Option))- .Where(e => e.Conditions.All(k => (!k.Min.HasValue || s.Indicators[k.Indicator] >= k.Min.Value)- && (!k.Max.HasValue || s.Indicators[k.Indicator] <= k.Max.Value)))+ // A late fire can come after a dated indicator's window has ended (chapters design 3.2): a condition on it is not met.+ .Where(e => e.Conditions.All(k => s.Indicators.TryGetValue(k.Indicator, out var v)+ && (!k.Min.HasValue || v >= k.Min.Value) && (!k.Max.HasValue || v <= k.Max.Value))).OrderBy(e => e.From).ThenBy(e => e.Id, StringComparer.Ordinal).ToList();var hardCount = eligible.Count(e => e.Anchor == "hard");@@ -60,7 +61,8 @@ namespace Statecraft.Simvar fillDate = FillDate(Get(c, eventId), s.Date);var title = Cabinet.Fill(c, s, Get(c, eventId).Title, fillDate);why.Add(new Cause("events", eventId, 0, $"{how}: {Cabinet.Fill(c, s, o.Text, fillDate)}"));- foreach (var fx in o.Effects)+ // A late-fired event can be resolved after a dated record's window has ended (chapters design 3.2): nothing reaches it.+ foreach (var fx in o.Effects.Where(fx => EventRules.SpecialTargets.Contains(fx.Target) || s.Indicators.ContainsKey(fx.Target))){var change = fx.Delta;if (fx.Target == "treasury") s.Treasury += fx.Delta;@@ -68,7 +70,7 @@ namespace Statecraft.Simelse change = EffectsSystem.Shift(c, s, fx.Target, fx.Delta);why.Add(new Cause("events", fx.Target, change, $"{PlayerText.Change(c, fx.Target, change)} ({title})"));}- foreach (var kv in o.SetPolicy.OrderBy(k => k.Key, StringComparer.Ordinal))+ foreach (var kv in o.SetPolicy.Where(k => s.Policies.ContainsKey(k.Key)).OrderBy(k => k.Key, StringComparer.Ordinal)){s.Policies[kv.Key] = kv.Value;why.Add(new Cause("events", kv.Key, kv.Value, $"{PlayerText.Target(c, kv.Key)} set to {PlayerText.Percent(kv.Value)} ({title})"));diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csindex 934e9ab5d..a73755963 100644--- a/sim/Statecraft.Sim/Simulation.cs+++ b/sim/Statecraft.Sim/Simulation.cs@@ -75,6 +75,7 @@ namespace Statecraft.Sims.GameOver = GameOverCodes.EraEnded; // the legacy report (#19) will come before this once it existswhy.Add(new Cause("era", "era_ended", 0, PlayerText.GameOver(s.GameOver)));}+ ContentWindows.Update(c, s, turnStart);Cabinet.ExpireOnGovernmentChange(c, s, why);AttentionSystem.Refill(c, s);if (s.GameOver == null) EventSystem.Trigger(c, s, why, turnStart); // a game that just ended raises no new events@@ -90,6 +91,7 @@ namespace Statecraft.Sim{case SetPolicy p:if (c.Policies.All(x => x.Id != p.Policy)) return "That policy does not exist in this game";+ if (c.At(s.Date).Policies.All(x => x.Id != p.Policy)) return "That policy is not available at this time";if (!(p.Level >= 0 && p.Level <= 1)) return "Policy level must be between 0 and 1";var legislature = Offices.Legislature(c, s.Date);if (legislature == null) return "No legislature is sitting";