A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
B1: Hebrew turn-report causes, first slice (economy, immigration, effects, security) (#1642)
Eyal Golanaa6ec46fb366
diff --git a/changelog.d/b1-hebrew-causes.md b/changelog.d/b1-hebrew-causes.mdnew file mode 100644index 000000000..1ddca589b--- /dev/null+++ b/changelog.d/b1-hebrew-causes.md@@ -0,0 +1,4 @@+### Fixed+- In Hebrew, the turn report, the top-bar tips and the Why screen now give the money, foreign currency, immigration,+ ongoing-effect, situation and security lines in Hebrew. Lines from events, military upkeep and other systems are+ still in English for now (B1, first part).diff --git a/sim/Statecraft.Sim.Tests/CauseKeysTests.cs b/sim/Statecraft.Sim.Tests/CauseKeysTests.csnew file mode 100644index 000000000..ede95445f--- /dev/null+++ b/sim/Statecraft.Sim.Tests/CauseKeysTests.cs@@ -0,0 +1,178 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Linq;+using System.Threading;+using Statecraft.Sim;++/// <summary>B1: the economy, population, effect and security lines carry a key and their values (CauseKeys), so the UI can+/// word them in the player's language. The key is result data only: Message, Delta and the state are what they were, and+/// the values are the same whatever the machine's culture.</summary>+public class CauseKeysTests+{+ static readonly Content Real = ContentLoader.Load(RealContentTests.ContentRoot());+ static readonly Content Fix = ContentLoader.Load(Fixture.Write());+ static readonly string[] Keyed = { "population", "effects", "situations", "security" };++ [Fact]+ public void EveryKeyIsListedOnceAndNoneIsAUnitKey()+ {+ Assert.Equal(CauseKeys.All.Distinct().Count(), CauseKeys.All.Count);+ Assert.Empty(CauseKeys.All.Intersect(WhyKeys.All));+ Assert.Equal(CauseKeys.Purpose.All.Distinct().Count(), CauseKeys.Purpose.All.Count);+ }++ /// <summary>The reference run to the end: every line of the population, effects, situations and security systems has a+ /// known key.</summary>+ [Fact]+ public void TheReferenceRunKeysEveryLineOfTheSlice()+ {+ var lines = Run(Real, 1000);+ Assert.NotEmpty(lines);+ foreach (var w in lines.Where(w => Keyed.Contains(w.System)))+ Assert.True(CauseKeys.All.Contains(w.Key), $"[{w.System}] {w.Message}: no key");+ // Each key the run reaches, at least once (the rest are covered below on the fixture).+ foreach (var key in new[] { CauseKeys.MoneyFlows, CauseKeys.FxFlows, CauseKeys.Borrowed, CauseKeys.FxCrisisBegan, CauseKeys.Arrived,+ CauseKeys.EffectChange, CauseKeys.SituationBegan, CauseKeys.RungChanged, CauseKeys.CallUpRaised, CauseKeys.CallUpLowered })+ Assert.Contains(lines, w => w.Key == key);+ }++ /// <summary>Other files also write "economy" lines, so EconomySystem's own are checked at the producer: its turn step and+ /// the civilian upkeep, on every state of the reference run, as they are, with the Treasury short, and with the currency+ /// crisis starting and easing. Every line they write has a key.</summary>+ [Fact]+ public void EveryLineEconomySystemWritesHasAKey()+ {+ var s = Simulation.NewGame(Real, GoldenRun.Seed, Mode.Historical);+ var lines = new List<Cause>();+ for (int t = 0; t < 1000 && s.GameOver == null; t++)+ {+ foreach (var change in new Action<GameState>[] { _ => { }, x => x.Treasury = -50, x => x.FxReserves = -1e6,+ x => { x.ActiveSituations.Add(EconomySystem.FxCrisis); x.FxReserves = 1e6; } })+ {+ var x = s.Clone(); change(x);+ EconomySystem.Apply(Real, x, 0.25, lines);+ EconomySystem.PayCivilianUpkeep(Real, x, Real.RulesAt(x.Date).Mvp!, 0.25, lines);+ }+ s = Simulation.Step(Real, s, GoldenRun.Orders(Real, s)).State;+ }+ foreach (var w in lines) Assert.True(CauseKeys.All.Contains(w.Key), $"[{w.System}] {w.Message}: no key");+ foreach (var key in new[] { CauseKeys.MoneyFlows, CauseKeys.FxFlows, CauseKeys.Borrowed, CauseKeys.FxCrisisBegan, CauseKeys.FxCrisisEased })+ Assert.Contains(lines, w => w.Key == key);+ Assert.All(lines.Where(w => w.Key == CauseKeys.Borrowed), w => Assert.Contains(w.Args[0], CauseKeys.Purpose.All));+ }++ /// <summary>The values parse back to exactly the numbers the English line printed, as invariant text.</summary>+ [Fact]+ public void TheValuesAreTheNumbersTheLineNames()+ {+ foreach (var w in Run(Real, 1000).Where(w => w.Key != ""))+ switch (w.Key)+ {+ case CauseKeys.MoneyFlows:+ Assert.Equal($"{PlayerText.Change(Real, "treasury", w.Delta)} (tax {Money(w, 0)}, spending {Money(w, 1)}, reserve call-up {Money(w, 2)})", w.Message);+ break;+ case CauseKeys.Arrived:+ Assert.Equal(FormattableString.Invariant($"{w.Delta:N0} immigrants arrived ({PlayerText.Region(Real, w.Target)})"), w.Message);+ break;+ case CauseKeys.EffectChange:+ var names = w.Args.Select(id => Real.Effects.Single(e => e.Id == id).Name).ToList();+ Assert.Equal(PlayerText.Change(Real, w.Target, w.Delta) + (names.Count > 0 ? $" ({string.Join(", ", names)})" : ""), w.Message);+ break;+ case CauseKeys.RungChanged:+ Assert.Equal($"Security level {w.Args[0]} to {w.Args[1]}", w.Message);+ break;+ case CauseKeys.CallUpLowered:+ Assert.Equal($"Reserves sent home: call-up lowered to {PlayerText.Percent(Number(w, 0))}, the minimum for security level {w.Args[1]}", w.Message);+ break;+ }+ }++ /// <summary>Keys and values are the same under a comma-decimal culture: the UI reads them as invariant text.</summary>+ [Fact]+ public void TheValuesDoNotDependOnTheCulture()+ {+ string Lines() => string.Join("\n", Run(Real, 30).Select(w => w.Key + "|" + string.Join(";", w.Args)));+ var invariant = Lines();+ var culture = Thread.CurrentThread.CurrentCulture;+ try+ {+ Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");+ Assert.Equal(invariant, Lines());+ }+ finally { Thread.CurrentThread.CurrentCulture = culture; }+ }++ [Fact]+ public void TheFixtureLinesTheReferenceRunDoesNotReachAreKeyed()+ {+ var s = new GameState { Rung = 1 }; var why = new List<Cause>();+ Assert.Null(SecuritySystem.SetMobilization(Fix, s, 0.9, why));+ Assert.Equal(CauseKeys.CallUpSet, Assert.Single(why).Key);++ s = new GameState(); why = new List<Cause>();+ SecuritySystem.Init(Fix, s, why);+ for (int i = 0; i < 4; i++) SecuritySystem.Apply(Fix, s, TurnLength.Week, why);+ Assert.Equal(CauseKeys.Ceasefire, Assert.Single(why, w => w.Target == "ceasefire").Key);++ // Situation ended: the fixture's hunger turns off above 0.45.+ s = new GameState { Date = new DateTime(1948, 6, 1) };+ EffectsSystem.Init(Fix, s);+ s.ActiveSituations.Add("hunger"); s.Indicators["food_supply"] = 0.5;+ why = new List<Cause>();+ EffectsSystem.UpdateSituations(Fix, s, why);+ var ended = Assert.Single(why);+ Assert.Equal((CauseKeys.SituationEnded, "hunger"), (ended.Key, ended.Target));+ Assert.Equal(new[] { "food_supply", "0.5" }, ended.Args);+ }++ [Fact]+ public void TheCurrencyCrisisLinesAreKeyed()+ {+ var c = ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["rules.yaml"] = Fixture.Files["rules.yaml"] + "fx_crisis_food_per_year: -0.4\n" }));+ var s = new GameState { Date = new DateTime(1948, 6, 1) };+ EffectsSystem.Init(c, s); EconomySystem.Init(c, s);+ s.Population["veterans"] = 1000;+ s.FxReserves = -20;+ var why = new List<Cause>();+ EconomySystem.Apply(c, s, 0.25, why);+ Assert.Equal(CauseKeys.FxCrisisBegan, Assert.Single(why, w => w.Target == EconomySystem.FxCrisis).Key);+ Assert.Equal(CauseKeys.FxCrisisFood, Assert.Single(why, w => w.Target == "food_supply").Key);++ s.FxReserves = 1000; why.Clear();+ EconomySystem.Apply(c, s, 0.25, why);+ Assert.Equal(CauseKeys.FxCrisisEased, Assert.Single(why, w => w.Target == EconomySystem.FxCrisis).Key);+ }++ [Fact]+ public void CivilianUpkeepAndItsBorrowingAreKeyed()+ {+ var s = new GameState { Treasury = 0, Debt = 0 }; var why = new List<Cause>();+ EconomySystem.PayOrBorrow(Fix, s, 3, "for civilian upkeep", why, CauseKeys.Purpose.CivilianUpkeep);+ var line = Assert.Single(why);+ Assert.Equal((CauseKeys.Borrowed, "Borrowed IL 3.0m for civilian upkeep"), (line.Key, line.Message));+ Assert.Equal(new[] { CauseKeys.Purpose.CivilianUpkeep }, line.Args);++ why.Clear();+ EconomySystem.PayOrBorrow(Fix, s, 3, "to build a housing project", why, CauseKeys.Purpose.Project, "housing");+ line = Assert.Single(why);+ Assert.Equal(CauseKeys.Borrowed, line.Key);+ Assert.Equal(new[] { CauseKeys.Purpose.Project, "housing" }, line.Args);+ }++ static string Money(Cause w, int i) => PlayerText.Money(Real, "treasury", Number(w, i));+ static double Number(Cause w, int i) => double.Parse(w.Args[i], NumberStyles.Float, CultureInfo.InvariantCulture);++ static List<Cause> Run(Content c, int turns)+ {+ var lines = new List<Cause>();+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);+ for (int t = 0; t < turns && s.GameOver == null; t++)+ {+ var r = Simulation.Step(c, s, GoldenRun.Orders(c, s));+ lines.AddRange(r.Why);+ s = r.State;+ }+ return lines;+ }+}diff --git a/sim/Statecraft.Sim.Tests/TrainingTests.cs b/sim/Statecraft.Sim.Tests/TrainingTests.csindex 964de9906..ed1c7bca1 100644--- a/sim/Statecraft.Sim.Tests/TrainingTests.cs+++ b/sim/Statecraft.Sim.Tests/TrainingTests.cs@@ -127,7 +127,8 @@ public class TrainingTestsAssert.Equal(0, after.Treasury);Assert.Equal(3.1, after.Debt, 9); // the IL 0.1m the Treasury lackedAssert.Single(after.Cohorts);- Assert.Contains(why, x => x.System == "economy" && x.Target == "debt" && x.Message == "Borrowed IL 0.1m for training");+ var borrowed = Assert.Single(why, x => x.System == "economy" && x.Target == "debt" && x.Message == "Borrowed IL 0.1m for training");+ Assert.Equal((CauseKeys.Borrowed, CauseKeys.Purpose.Training), (borrowed.Key, Assert.Single(borrowed.Args))); // B1: worded in Hebrew toovar none = s.Clone();none.Treasury = 0;Assert.Empty(Step(c, none, new Train("town_a", "recruit", 3)).Rejected); // an empty Treasury trains toodiff --git a/sim/Statecraft.Sim/Cause.cs b/sim/Statecraft.Sim/Cause.csindex eb229f24d..c9220fe75 100644--- a/sim/Statecraft.Sim/Cause.cs+++ b/sim/Statecraft.Sim/Cause.cs@@ -1,5 +1,6 @@using System;using System.Collections.Generic;+using System.Globalization;namespace Statecraft.Sim{@@ -33,4 +34,65 @@ namespace Statecraft.Sim}public override string ToString() => $"[{System}] {Message}";}++ /// <summary>B1: the keys of the resource, population, effect and security lines, so the UI words them in the player's+ /// language (why.cause.<key>) from the line's Target, Delta and Args instead of its English Message. Message stays+ /// as it was, word for word, for the CLI, the tests and every line without a key. These lines name no unit, so they are+ /// apart from <see cref="WhyKeys"/>. A line that is not keyed yet keeps its English Message on screen.</summary>+ public static class CauseKeys+ {+ /// <summary>Target money moved by Delta. Args: tax, spending, reserve call-up (Economy).</summary>+ public const string MoneyFlows = "money_flows";+ /// <summary>Foreign currency moved by Delta. Args: exports, donations and loans, imports.</summary>+ public const string FxFlows = "fx_flows";+ /// <summary>Delta borrowed into the debt. Args: what for (a <see cref="Purpose"/>), then that purpose's values.</summary>+ public const string Borrowed = "borrowed";+ /// <summary>Target money moved by Delta, for civilian upkeep. No args.</summary>+ public const string CivilianUpkeep = "civilian_upkeep";+ public const string FxCrisisBegan = "fx_crisis_began", FxCrisisEased = "fx_crisis_eased";+ /// <summary>Target (food_supply) moved by Delta while the foreign currency crisis cuts food imports. No args.</summary>+ public const string FxCrisisFood = "fx_crisis_food";+ /// <summary>Delta immigrants arrived from the origin group Target. No args.</summary>+ public const string Arrived = "immigrants_arrived";+ /// <summary>Indicator Target moved by Delta. Args: the ids of the effects that moved it, in content order (none: no+ /// effect named).</summary>+ public const string EffectChange = "effect_change";+ /// <summary>Situation Target began or ended. Args: its indicator, the indicator's level.</summary>+ public const string SituationBegan = "situation_began", SituationEnded = "situation_ended";+ /// <summary>The security level changed. Args: from, to.</summary>+ public const string RungChanged = "rung_changed";+ /// <summary>The call-up was set to Delta. No args.</summary>+ public const string CallUpSet = "call_up_set";+ /// <summary>The call-up was raised or lowered to a level's minimum. Args: the new call-up, the security level.</summary>+ public const string CallUpRaised = "call_up_raised", CallUpLowered = "call_up_lowered";+ public const string Ceasefire = "ceasefire";++ /// <summary>What a <see cref="Borrowed"/> line borrowed for (EconomySystem.PayOrBorrow's callers, and the deficit).</summary>+ public static class Purpose+ {+ public const string Deficit = "deficit", CivilianUpkeep = "civilian_upkeep", MilitaryUpkeep = "military_upkeep",+ Corridor = "corridor", Arms = "arms", Training = "training", Prisoners = "prisoners", TrainingCamp = "training_camp",+ Plow = "plow", Drain = "drain", Yishuv = "yishuv", Deport = "deport", Occupation = "occupation";+ /// <summary>Args: the project kind's id.</summary>+ public const string Project = "project";+ /// <summary>Args: the event's id, its English title as shown, and "1" when its title_he names it (no variant title).</summary>+ public const string Event = "event";++ public static readonly IReadOnlyList<string> All = new[]+ {+ Deficit, CivilianUpkeep, MilitaryUpkeep, Corridor, Arms, Training, Prisoners, TrainingCamp, Plow, Drain, Yishuv,+ Deport, Occupation, Project, Event,+ };+ }++ public static readonly IReadOnlyList<string> All = new[]+ {+ MoneyFlows, FxFlows, Borrowed, CivilianUpkeep, FxCrisisBegan, FxCrisisEased, FxCrisisFood, Arrived, EffectChange,+ SituationBegan, SituationEnded, RungChanged, CallUpSet, CallUpRaised, CallUpLowered, Ceasefire,+ };++ /// <summary>A number as an Arg: invariant and round-trip, so the UI rounds exactly the value Message rounded.</summary>+ internal static string Number(double v) => v.ToString("R", CultureInfo.InvariantCulture);+ internal static string Number(int v) => v.ToString(CultureInfo.InvariantCulture);+ }}diff --git a/sim/Statecraft.Sim/Corridors.cs b/sim/Statecraft.Sim/Corridors.csindex dab4fc97c..7f8b6ff71 100644--- a/sim/Statecraft.Sim/Corridors.cs+++ b/sim/Statecraft.Sim/Corridors.cs@@ -57,7 +57,7 @@ namespace Statecraft.Simreturn seg.BuiltOn == null ? $"{name} is already being built" : $"{name} is already built";var r = c.RulesAt(s.Date).Mvp!; // the loader requires it in the GDD loopvar (cost, _) = Projects.Terms(r, action);- EconomySystem.PayOrBorrow(c, s, cost, "to build a corridor segment", why);+ EconomySystem.PayOrBorrow(c, s, cost, "to build a corridor segment", why, CauseKeys.Purpose.Corridor);// As for sites (R-SITE-001): the turn of the order is the first build turn. The segment starts at 0, step 5 of this// turn's resolve gives it its first turn of progress, and with 6 turns an order on turn T is built at the end of T+5.var started = new SegmentWork(unit, 0, null);diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.csindex 405e910f0..aa2626d66 100644--- a/sim/Statecraft.Sim/EconomySystem.cs+++ b/sim/Statecraft.Sim/EconomySystem.cs@@ -36,13 +36,16 @@ namespace Statecraft.Sim/// <summary>Pays <paramref name="cost"/> from the Treasury, borrowing what it lacks: the shortfall goes to Debt and the/// Treasury stops at 0, as for map actions and the deficit. <paramref name="purpose"/> ends the cause ("for training").- /// The GDD orders pay through it (owner decision "Allow borrowing", 2026-10-15; R-TRAIN-001, R-SITE-001).</summary>- public static void PayOrBorrow(Content c, GameState s, double cost, string purpose, List<Cause> why)+ /// The GDD orders pay through it (owner decision "Allow borrowing", 2026-10-15; R-TRAIN-001, R-SITE-001).+ /// <paramref name="purposeKey"/> (a CauseKeys.Purpose) and <paramref name="purposeArgs"/> say the same purpose for the+ /// UI (CauseKeys.Borrowed, B1); <paramref name="purpose"/> stays the English Message.</summary>+ public static void PayOrBorrow(Content c, GameState s, double cost, string purpose, List<Cause> why, string purposeKey, params string[] purposeArgs){s.Treasury -= cost;if (s.Treasury >= 0) return;s.Debt += -s.Treasury;- why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} {purpose}"));+ why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} {purpose}",+ key: CauseKeys.Borrowed, args: new[] { purposeKey }.Concat(purposeArgs).ToList()));s.Treasury = 0;}@@ -51,8 +54,8 @@ namespace Statecraft.Sim{var cost = Cities.AnnualUpkeep(c, s, r) * yearFraction;if (cost == 0) return;- why.Add(new Cause("economy", "treasury", -cost, $"{PlayerText.Change(c, "treasury", -cost)} (civilian upkeep)"));- PayOrBorrow(c, s, cost, "for civilian upkeep", why);+ why.Add(new Cause("economy", "treasury", -cost, $"{PlayerText.Change(c, "treasury", -cost)} (civilian upkeep)", key: CauseKeys.CivilianUpkeep));+ PayOrBorrow(c, s, cost, "for civilian upkeep", why, CauseKeys.Purpose.CivilianUpkeep);}public static void Apply(Content c, GameState s, double yearFraction, List<Cause> why)@@ -62,11 +65,13 @@ namespace Statecraft.Simvar revenue = flows.Tax; var spending = flows.Spending; var mobilization = flows.Mobilization;s.Treasury += revenue - spending - mobilization;why.Add(new Cause("economy", "treasury", revenue - spending - mobilization,- $"{PlayerText.Change(c, "treasury", revenue - spending - mobilization)} (tax {PlayerText.Money(c, "treasury", revenue)}, spending {PlayerText.Money(c, "treasury", spending)}, reserve call-up {PlayerText.Money(c, "treasury", mobilization)})"));+ $"{PlayerText.Change(c, "treasury", revenue - spending - mobilization)} (tax {PlayerText.Money(c, "treasury", revenue)}, spending {PlayerText.Money(c, "treasury", spending)}, reserve call-up {PlayerText.Money(c, "treasury", mobilization)})",+ key: CauseKeys.MoneyFlows, args: new[] { CauseKeys.Number(revenue), CauseKeys.Number(spending), CauseKeys.Number(mobilization) }));if (s.Treasury < 0){s.Debt += -s.Treasury;- why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} to cover the deficit"));+ why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} to cover the deficit",+ key: CauseKeys.Borrowed, args: new[] { CauseKeys.Purpose.Deficit }));s.Treasury = 0;}@@ -75,11 +80,12 @@ namespace Statecraft.Simvar imports = r.ImportsPerCapitaPerYear * pop * yearFraction;var net = exports + inflow - imports;s.FxReserves += net;- why.Add(new Cause("economy", "fx_reserves", net, $"{PlayerText.Change(c, "fx_reserves", net)} (exports {PlayerText.Money(c, "fx_reserves", exports)}, donations and loans {PlayerText.Money(c, "fx_reserves", inflow)}, imports {PlayerText.Money(c, "fx_reserves", imports)})"));+ why.Add(new Cause("economy", "fx_reserves", net, $"{PlayerText.Change(c, "fx_reserves", net)} (exports {PlayerText.Money(c, "fx_reserves", exports)}, donations and loans {PlayerText.Money(c, "fx_reserves", inflow)}, imports {PlayerText.Money(c, "fx_reserves", imports)})",+ key: CauseKeys.FxFlows, args: new[] { CauseKeys.Number(exports), CauseKeys.Number(inflow), CauseKeys.Number(imports) }));bool on = s.ActiveSituations.Contains(FxCrisis);- if (!on && s.FxReserves < 0) { s.ActiveSituations.Add(FxCrisis); why.Add(new Cause("economy", FxCrisis, 1, "Foreign currency reserves are exhausted")); }- else if (on && s.FxReserves > 0.25 * r.FxStart) { s.ActiveSituations.Remove(FxCrisis); why.Add(new Cause("economy", FxCrisis, -1, "Foreign currency crisis eased")); }+ if (!on && s.FxReserves < 0) { s.ActiveSituations.Add(FxCrisis); why.Add(new Cause("economy", FxCrisis, 1, "Foreign currency reserves are exhausted", key: CauseKeys.FxCrisisBegan)); }+ else if (on && s.FxReserves > 0.25 * r.FxStart) { s.ActiveSituations.Remove(FxCrisis); why.Add(new Cause("economy", FxCrisis, -1, "Foreign currency crisis eased", key: CauseKeys.FxCrisisEased)); }// The consequence: with no currency to pay for them, food imports are cut while the crisis lasts. In the GDD loop// the cut falls on the Food stock's imports instead (R-FOOD-002, Q-POOL-4), and food_supply follows the stock.@@ -87,7 +93,7 @@ namespace Statecraft.Sim{var change = EffectsSystem.Shift(c, s, "food_supply", r.FxCrisisFoodPerYear * yearFraction);if (change != 0)- why.Add(new Cause("economy", "food_supply", change, $"{PlayerText.Change(c, "food_supply", change)} (foreign currency crisis: food imports cut)"));+ why.Add(new Cause("economy", "food_supply", change, $"{PlayerText.Change(c, "food_supply", change)} (foreign currency crisis: food imports cut)", key: CauseKeys.FxCrisisFood));}}diff --git a/sim/Statecraft.Sim/EffectsSystem.cs b/sim/Statecraft.Sim/EffectsSystem.csindex 350a6b93a..b47a47c51 100644--- a/sim/Statecraft.Sim/EffectsSystem.cs+++ b/sim/Statecraft.Sim/EffectsSystem.cs@@ -94,9 +94,10 @@ namespace Statecraft.Sim{var delta = s.Indicators[i.Id] - before[i.Id];if (Math.Abs(delta) <= 1e-9) continue;- 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}"));+ var effects = v.Effects.Where(e => e.Target == i.Id && moved.Contains(e.Id)).ToList();+ var from = effects.Count > 0 ? $" ({string.Join(", ", effects.Select(e => e.Name))})" : "";+ why.Add(new Cause("effects", i.Id, delta, $"{PlayerText.Change(c, i.Id, delta)}{from}",+ key: CauseKeys.EffectChange, args: effects.Select(e => e.Id).ToList()));}UpdateSituations(c, s, why);}@@ -152,8 +153,10 @@ namespace Statecraft.Simbool on = s.ActiveSituations.Contains(sit.Id);bool turnOn = sit.OnBelow.HasValue ? v < sit.OnBelow.Value : v > sit.OnAbove!.Value;bool turnOff = sit.OffAbove.HasValue ? v > sit.OffAbove.Value : v < sit.OffBelow!.Value;- if (!on && turnOn) { s.ActiveSituations.Add(sit.Id); why.Add(new Cause("situations", sit.Id, 1, $"{sit.Name} began ({PlayerText.Target(c, sit.Indicator)} at {PlayerText.Percent(v)})")); }- else if (on && turnOff) { s.ActiveSituations.Remove(sit.Id); why.Add(new Cause("situations", sit.Id, -1, $"{sit.Name} ended ({PlayerText.Target(c, sit.Indicator)} at {PlayerText.Percent(v)})")); }+ if (!on && turnOn) { s.ActiveSituations.Add(sit.Id); why.Add(new Cause("situations", sit.Id, 1, $"{sit.Name} began ({PlayerText.Target(c, sit.Indicator)} at {PlayerText.Percent(v)})",+ key: CauseKeys.SituationBegan, args: new[] { sit.Indicator, CauseKeys.Number(v) })); }+ else if (on && turnOff) { s.ActiveSituations.Remove(sit.Id); why.Add(new Cause("situations", sit.Id, -1, $"{sit.Name} ended ({PlayerText.Target(c, sit.Indicator)} at {PlayerText.Percent(v)})",+ key: CauseKeys.SituationEnded, args: new[] { sit.Indicator, CauseKeys.Number(v) })); }}}diff --git a/sim/Statecraft.Sim/EventSystem.cs b/sim/Statecraft.Sim/EventSystem.csindex 54e6f2665..eec1a54b9 100644--- a/sim/Statecraft.Sim/EventSystem.cs+++ b/sim/Statecraft.Sim/EventSystem.cs@@ -75,6 +75,8 @@ namespace Statecraft.Sims.ChosenOptions[eventId] = o.Id;var fillDate = FillDate(Get(c, eventId), s.Date);var title = Title(c, s, Get(c, eventId));+ var variant = Timeline.Variant(c, s, Get(c, eventId));+ var titleHe = variant == null || variant.Title == ""; // the event's title_he names it, as on its card (B1)why.Add(new Cause("events", eventId, 0, $"{how}: {Cabinet.Fill(c, s, o.Text, fillDate)}"));foreach (var fx in o.Effects.Where(fx => Reaches(s, fx.Target))){@@ -84,7 +86,7 @@ namespace Statecraft.Sim{// R-MONEY-003: the cost first, then what was borrowed for it, as every other payment borrows.why.Add(new Cause("events", fx.Target, change, $"{PlayerText.Change(c, fx.Target, change)} ({title})"));- if (delta < 0) EconomySystem.PayOrBorrow(c, s, -delta, $"for {title}", why);+ if (delta < 0) EconomySystem.PayOrBorrow(c, s, -delta, $"for {title}", why, CauseKeys.Purpose.Event, eventId, title, titleHe ? "1" : "0");else s.Treasury += delta;continue;}diff --git a/sim/Statecraft.Sim/Military.cs b/sim/Statecraft.Sim/Military.csindex 490f38c23..1ad9177dc 100644--- a/sim/Statecraft.Sim/Military.cs+++ b/sim/Statecraft.Sim/Military.cs@@ -29,7 +29,7 @@ namespace Statecraft.Simvar cost = count * r.MilitaryUpkeepPerTurn!.Value;if (cost == 0) return;why.Add(new Cause("economy", "treasury", -cost, $"{PlayerText.Change(c, "treasury", -cost)} (military upkeep)"));- EconomySystem.PayOrBorrow(c, s, cost, "for military upkeep", why);+ EconomySystem.PayOrBorrow(c, s, cost, "for military upkeep", why, CauseKeys.Purpose.MilitaryUpkeep);}}}diff --git a/sim/Statecraft.Sim/Pools.cs b/sim/Statecraft.Sim/Pools.csindex 1db1b0bef..825a31632 100644--- a/sim/Statecraft.Sim/Pools.cs+++ b/sim/Statecraft.Sim/Pools.cs@@ -43,7 +43,7 @@ namespace Statecraft.Simif (count < 1) return "Buy at least 1 Arms";if ((long)s.Arms + count > int.MaxValue) return "That is more Arms than the stock can hold";var cost = count * c.RulesAt(s.Date).Mvp!.ArmsPrice!.Value;- EconomySystem.PayOrBorrow(c, s, cost, "for Arms", why);+ EconomySystem.PayOrBorrow(c, s, cost, "for Arms", why, CauseKeys.Purpose.Arms);s.Arms += count;why.Add(new Cause("economy", "arms", count, FormattableString.Invariant($"Bought {count} Arms, cost {PlayerText.Money(c, "treasury", cost)}")));return null;diff --git a/sim/Statecraft.Sim/PopulationSystem.cs b/sim/Statecraft.Sim/PopulationSystem.csindex b644d77ff..6feed4d27 100644--- a/sim/Statecraft.Sim/PopulationSystem.cs+++ b/sim/Statecraft.Sim/PopulationSystem.cs@@ -34,7 +34,7 @@ namespace Statecraft.Simforeach (var kv in Arrivals(c, s.Date, to).OrderBy(k => k.Key, StringComparer.Ordinal)){s.Population[kv.Key] = (s.Population.TryGetValue(kv.Key, out var v) ? v : 0) + kv.Value;- if (kv.Value > 0) why.Add(new Cause("population", kv.Key, kv.Value, FormattableString.Invariant($"{kv.Value:N0} immigrants arrived ({PlayerText.Region(c, kv.Key)})")));+ if (kv.Value > 0) why.Add(new Cause("population", kv.Key, kv.Value, FormattableString.Invariant($"{kv.Value:N0} immigrants arrived ({PlayerText.Region(c, kv.Key)})"), key: CauseKeys.Arrived));}}}diff --git a/sim/Statecraft.Sim/Prisoners.cs b/sim/Statecraft.Sim/Prisoners.csindex 6c8d6d5b3..6e6ed52b5 100644--- a/sim/Statecraft.Sim/Prisoners.cs+++ b/sim/Statecraft.Sim/Prisoners.cs@@ -72,7 +72,7 @@ namespace Statecraft.Simvar held = s.SoldiersHeld.Values.Sum();if (held == 0) return;var cost = held * r.HeldSoldierCostPerTurn!.Value;- if (cost > 0) EconomySystem.PayOrBorrow(c, s, cost, "for our soldiers held by the enemy", why);+ if (cost > 0) EconomySystem.PayOrBorrow(c, s, cost, "for our soldiers held by the enemy", why, CauseKeys.Purpose.Prisoners);}/// <summary>R-POW-004, R-POW-005: <paramref name="front"/>'s exchange card was resolved. Its sides' prisoners go home anddiff --git a/sim/Statecraft.Sim/Projects.cs b/sim/Statecraft.Sim/Projects.csindex 519ee5868..32b1b4408 100644--- a/sim/Statecraft.Sim/Projects.cs+++ b/sim/Statecraft.Sim/Projects.cs@@ -155,7 +155,8 @@ namespace Statecraft.Simvar r = c.RulesAt(s.Date).Mvp!; // the loader requires it in the GDD loop// Owner decision "Allow borrowing" (2026-10-15, #378 question 13): a short Treasury borrows, as map actions do.var (cost, turns) = Terms(r, action);- EconomySystem.PayOrBorrow(c, s, cost, camp ? "to build a training camp" : plow ? "to plow fields" : drain ? "to drain a swamp" : "to build a yishuv", why);+ EconomySystem.PayOrBorrow(c, s, cost, camp ? "to build a training camp" : plow ? "to plow fields" : drain ? "to drain a swamp" : "to build a yishuv", why,+ camp ? CauseKeys.Purpose.TrainingCamp : plow ? CauseKeys.Purpose.Plow : drain ? CauseKeys.Purpose.Drain : CauseKeys.Purpose.Yishuv);// The same reading of D-A6 as training's: the turn of the order is the first build turn, so with// build_yishuv_turns 6 an order on turn T is built at the end of T+5// (ProjectsTests.AnOrderOnTurnTWithSixTurnsIsBuiltAtTheEndOfTurnTPlusFive).@@ -318,7 +319,7 @@ namespace Statecraft.Simif (s.MapActionsTurnDate != s.Date) { s.MapActionsTurnDate = s.Date; s.MapActionsThisTurn = 0; }s.MapActionsThisTurn++;var name = PlayerText.Settlement(c, city);- EconomySystem.PayOrBorrow(c, s, k.Cost, "to build " + k.Name, why);+ EconomySystem.PayOrBorrow(c, s, k.Cost, "to build " + k.Name, why, CauseKeys.Purpose.Project, k.Id);var id = s.NextId++;s.CityProjects.Add(id, new CityProject(id, kind, city, q, r, k.Turns));why.Add(new Cause("city", city, 1, $"{name}: {k.Name} began, cost {PlayerText.Money(c, "treasury", k.Cost)}"));diff --git a/sim/Statecraft.Sim/SecuritySystem.cs b/sim/Statecraft.Sim/SecuritySystem.csindex 849eb1d88..2e2d9ce4a 100644--- a/sim/Statecraft.Sim/SecuritySystem.cs+++ b/sim/Statecraft.Sim/SecuritySystem.cs@@ -45,7 +45,8 @@ namespace Statecraft.Sim{rung = ClampRung(rung);s.CeasefireWeeksLeft = CeasefireWeeksAfter(c, s.Date, s.Rung, s.CeasefireWeeksLeft, rung);- if (rung != s.Rung) why.Add(new Cause("security", "rung", rung - s.Rung, FormattableString.Invariant($"Security level {s.Rung} to {rung}")));+ if (rung != s.Rung) why.Add(new Cause("security", "rung", rung - s.Rung, FormattableString.Invariant($"Security level {s.Rung} to {rung}"),+ key: CauseKeys.RungChanged, args: new[] { CauseKeys.Number(s.Rung), CauseKeys.Number(rung) }));s.Rung = rung;RaiseToFloor(c, s, why);if (c.IsGdd) SendHomeToFloor(c, s, why);@@ -56,7 +57,7 @@ namespace Statecraft.Sim{if (!(level >= 0 && level <= 1)) return "Mobilization must be between 0 and 1";s.Mobilization = level;- why.Add(new Cause("security", "mobilization", level, $"reserve call-up set to {PlayerText.Percent(level)}"));+ why.Add(new Cause("security", "mobilization", level, $"reserve call-up set to {PlayerText.Percent(level)}", key: CauseKeys.CallUpSet));RaiseToFloor(c, s, why);return null;}@@ -67,7 +68,8 @@ namespace Statecraft.Simvar floor = MinMobilization(c, s.Date, rung);if (s.Mobilization < floor){- why.Add(new Cause("security", "mobilization", floor - s.Mobilization, FormattableString.Invariant($"reserve call-up raised to {PlayerText.Percent(floor)}, the minimum for security level {rung}")));+ why.Add(new Cause("security", "mobilization", floor - s.Mobilization, FormattableString.Invariant($"reserve call-up raised to {PlayerText.Percent(floor)}, the minimum for security level {rung}"),+ key: CauseKeys.CallUpRaised, args: new[] { CauseKeys.Number(floor), CauseKeys.Number(rung) }));s.Mobilization = floor;}}@@ -81,7 +83,8 @@ namespace Statecraft.Simvar floor = MinMobilization(c, s.Date, rung);if (s.Mobilization > floor){- why.Add(new Cause("security", "mobilization", floor - s.Mobilization, FormattableString.Invariant($"reserves sent home: call-up lowered to {PlayerText.Percent(floor)}, the minimum for security level {rung}")));+ why.Add(new Cause("security", "mobilization", floor - s.Mobilization, FormattableString.Invariant($"reserves sent home: call-up lowered to {PlayerText.Percent(floor)}, the minimum for security level {rung}"),+ key: CauseKeys.CallUpLowered, args: new[] { CauseKeys.Number(floor), CauseKeys.Number(rung) }));s.Mobilization = floor;}}@@ -103,7 +106,7 @@ namespace Statecraft.Sims.CeasefireWeeksLeft = Math.Max(0, s.CeasefireWeeksLeft - weeks);if (s.CeasefireWeeksLeft == 0){- why.Add(new Cause("security", "ceasefire", 0, "UN ceasefire imposed: full war ends")); // the rung cause SetRung adds carries the -2+ why.Add(new Cause("security", "ceasefire", 0, "UN ceasefire imposed: full war ends", key: CauseKeys.Ceasefire)); // the rung cause SetRung adds carries the -2SetRung(c, s, 3, why);}}diff --git a/sim/Statecraft.Sim/SettlementControl.cs b/sim/Statecraft.Sim/SettlementControl.csindex ab7edb046..28d0e5eb9 100644--- a/sim/Statecraft.Sim/SettlementControl.cs+++ b/sim/Statecraft.Sim/SettlementControl.cs@@ -296,7 +296,7 @@ namespace Statecraft.Sim}// Deport never pays (owner, 22 October 2026, #1327): its Money stays at or below Occupy's and Raid's.why.Add(new Cause("economy", "treasury", -r.DeportMoneyCost!.Value, $"{PlayerText.Change(c, "treasury", -r.DeportMoneyCost.Value)} (Deport of {name})"));- EconomySystem.PayOrBorrow(c, s, r.DeportMoneyCost.Value, $"for the Deport of {name}", why);+ EconomySystem.PayOrBorrow(c, s, r.DeportMoneyCost.Value, $"for the Deport of {name}", why, CauseKeys.Purpose.Deport, id);return null;}@@ -359,7 +359,7 @@ namespace Statecraft.Simwhy.Add(new Cause("map", id, 0, $"{name}: no Israeli unit holds it any more, so the occupation ended as a raid. It is under enemy control again. {Residents(x)}"));continue;}- EconomySystem.PayOrBorrow(c, s, r.OccupationUpkeepPerTurn!.Value, $"for the occupation of {name}", why);+ EconomySystem.PayOrBorrow(c, s, r.OccupationUpkeepPerTurn!.Value, $"for the occupation of {name}", why, CauseKeys.Purpose.Occupation, id);if (x.State == AwaitingEnd) continue;var left = x.Turns - 1;s.Settlements[id] = new SettlementControl(x.Owner, left == 0 ? AwaitingEnd : Occupied, x.Since, x.Depopulated, x.Combatants, x.Buildings, left, x.Fled);diff --git a/sim/Statecraft.Sim/Training.cs b/sim/Statecraft.Sim/Training.csindex 6df5672bb..5c5910c15 100644--- a/sim/Statecraft.Sim/Training.cs+++ b/sim/Statecraft.Sim/Training.cs@@ -126,7 +126,7 @@ namespace Statecraft.Simif (arms > s.Arms) return FormattableString.Invariant($"{name}: not enough Arms for {Course(type)} (need {arms}, have {s.Arms})");var cost = count * type.TrainingCost;// Owner decision "Allow borrowing" (2026-10-15, #468 question 1): a short Treasury borrows, as map actions do.- EconomySystem.PayOrBorrow(c, s, cost, "for training", why);+ EconomySystem.PayOrBorrow(c, s, cost, "for training", why, CauseKeys.Purpose.Training);// R-HOUSE-003: trainees remain housed as a cohort, and recruits keep their home city's housing as formations.// A pioneer unit leaves city housing; a craftsman remains. The employed share also reads the new counts.// R-QUAL-006: the trainees are taken from the unqualified civilians first; a qualified one taken loses itsdiff --git a/tools/tests/test_hebrew_ui.py b/tools/tests/test_hebrew_ui.pyindex b5a1bd732..e090ccb5d 100644--- a/tools/tests/test_hebrew_ui.py+++ b/tools/tests/test_hebrew_ui.py@@ -147,6 +147,23 @@ def test_every_cabinet_refusal_has_both_strings_and_the_english_is_the_sims_wordassert sorted(k for k in en if k.startswith('cabinet.reason.')) == sorted('cabinet.reason.' + k for k, _, _ in paths)+def test_the_cause_line_names_are_contents_names_in_english_and_hebrew_without_latin():+ """B1: CauseText names indicators, money, effects, situations and origin groups from why.name/effect/situation/region.+ English must be content's own name (the line is the sim's Message word for word), every content row has one, and the+ Hebrew has no Latin letters."""+ en, he = strings('strings.en.yaml'), strings('strings.he.yaml')+ model = yaml12.load((ROOT / 'content/model.yaml').read_text(encoding='utf-8'))+ aliyah = yaml12.load((ROOT / 'content/aliyah.yaml').read_text(encoding='utf-8'))+ rows = {'why.name.': model['indicators'] + model['money'], 'why.effect.': model['effects'],+ 'why.situation.': model['situations'], 'why.region.': aliyah['regions']}+ for prefix, items in rows.items():+ assert {k[len(prefix):] for k in en if k.startswith(prefix)} == {r['id'] for r in items}, prefix+ for r in items:+ assert en[prefix + r['id']] == r['name'], prefix + r['id']+ assert not re.search('[A-Za-z]', he[prefix + r['id']]), prefix + r['id']+ assert all(not re.search('[A-Za-z]', re.sub(r'\{[^}]*\}', '', he[k])) for k in he if k.startswith('why.cause.')) # {0:N0} aside++def test_the_hebrew_plural_of_a_turn_is_torot_never_torim():"""The owner's ruling (24 Oct 2026, #1589): the plural of תור (a game turn) is תורות. #1589 changed it to תורים bymistake and #1612 changed it back; this keeps it from drifting again. Every string that counts turns must saydiff --git a/unity/Assets/Scripts/UI/CauseText.cs b/unity/Assets/Scripts/UI/CauseText.csnew file mode 100644index 000000000..709072107--- /dev/null+++ b/unity/Assets/Scripts/UI/CauseText.cs@@ -0,0 +1,93 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Linq;+using Statecraft.Game.Map.Units;+using Statecraft.Sim;++namespace Statecraft.Game.UI+{+ /// <summary>B1: one Why line in the player's language, the one formatter the Why screen, the turn report and the meter+ /// tip share. A line with a CauseKeys key is worded from why.cause.<key> with its Target, Delta and Args, the+ /// numbers rounded by the same PlayerText rules as the sim's English Message, and the names it gives (indicator, money,+ /// effect, situation, origin group) from why.name, why.effect, why.situation and why.region; so the English line is the+ /// sim's Message, word for word. Every other line goes to <see cref="UnitNames.Line"/>: a unit line in the player's+ /// language, and a line with no key yet as the sim's English Message (not yet localized).</summary>+ public static class CauseText+ {+ public static string Line(Cause cause, Content c, IReadOnlyList<UnitEntry> rows, UiText text,+ IReadOnlyDictionary<string, string>? namesHe = null)+ {+ var key = "why.cause." + cause.Key;+ switch (cause.Key)+ {+ case CauseKeys.MoneyFlows:+ case CauseKeys.FxFlows:+ return text.Format(key, Name(text, cause.Target), Change(c, cause.Target, cause.Delta),+ Money(c, cause.Target, cause.Args[0]), Money(c, cause.Target, cause.Args[1]), Money(c, cause.Target, cause.Args[2]));+ case CauseKeys.CivilianUpkeep:+ case CauseKeys.FxCrisisFood:+ return text.Format(key, Name(text, cause.Target), Change(c, cause.Target, cause.Delta));+ case CauseKeys.Borrowed:+ return Borrowed(cause, c, text, namesHe);+ case CauseKeys.FxCrisisBegan:+ case CauseKeys.FxCrisisEased:+ case CauseKeys.Ceasefire:+ return text[key];+ case CauseKeys.Arrived:+ return text.Format(key, cause.Delta, text["why.region." + cause.Target]);+ case CauseKeys.EffectChange:+ return cause.Args.Count == 0+ ? text.Format(key, Name(text, cause.Target), Change(c, cause.Target, cause.Delta))+ : text.Format(key + "_from", Name(text, cause.Target), Change(c, cause.Target, cause.Delta),+ string.Join(", ", cause.Args.Select(id => text["why.effect." + id])));+ case CauseKeys.SituationBegan:+ case CauseKeys.SituationEnded:+ return text.Format(key, text["why.situation." + cause.Target], Name(text, cause.Args[0]), PlayerText.Percent(Number(cause.Args[1])));+ case CauseKeys.RungChanged:+ return text.Format(key, cause.Args[0], cause.Args[1]);+ case CauseKeys.CallUpSet:+ return text.Format(key, PlayerText.Percent(cause.Delta));+ case CauseKeys.CallUpRaised:+ case CauseKeys.CallUpLowered:+ return text.Format(key, PlayerText.Percent(Number(cause.Args[0])), cause.Args[1]);+ default:+ return UnitNames.Line(cause, c, rows, text, namesHe);+ }+ }++ /// <summary>A borrowing line, by its purpose (CauseKeys.Purpose): why.cause.borrowed.<purpose>, with what the+ /// purpose names in the UI's language (a project kind, a settlement, an event's title).</summary>+ static string Borrowed(Cause cause, Content c, UiText text, IReadOnlyDictionary<string, string>? namesHe)+ {+ var key = "why.cause.borrowed." + cause.Args[0];+ var amount = PlayerText.Money(c, cause.Target, cause.Delta);+ switch (cause.Args[0])+ {+ case CauseKeys.Purpose.Project:+ return text.Format(key, amount, ContentNames.Of(text, c.ProjectKinds.First(k => k.Id == cause.Args[1])));+ case CauseKeys.Purpose.Deport:+ case CauseKeys.Purpose.Occupation:+ return text.Format(key, amount, ContentNames.Settlement(text, c, cause.Args[1], namesHe));+ case CauseKeys.Purpose.Event:+ // The title as the card shows it: title_he, unless a variant gives its own (English) title.+ var he = cause.Args[3] == "1" ? c.Events.First(e => e.Id == cause.Args[1]).TitleHe : "";+ return text.Format(key, amount, he != "" && text["ui.lang"] == UiLanguage.Hebrew ? he : cause.Args[2]);+ default:+ return text.Format(key, amount);+ }+ }++ /// <summary>An indicator's or a money's name (model.yaml's name in English).</summary>+ static string Name(UiText text, string id) => text["why.name." + id];++ /// <summary>The change in the target's unit, as PlayerText.Change words it after the name.</summary>+ static string Change(Content c, string id, double delta) =>+ PlayerText.IsMoney(c, id) ? PlayerText.MoneyChange(c, id, delta) : PlayerText.PercentChange(delta);++ static string Money(Content c, string id, string value) => PlayerText.Money(c, id, Number(value));++ static double Number(string value) => double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);+ }+}diff --git a/unity/Assets/Scripts/UI/CauseText.cs.meta b/unity/Assets/Scripts/UI/CauseText.cs.metanew file mode 100644index 000000000..519fed954--- /dev/null+++ b/unity/Assets/Scripts/UI/CauseText.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 8a333d7d62a34985a1801940b5970037diff --git a/unity/Assets/Scripts/UI/HudModel.cs b/unity/Assets/Scripts/UI/HudModel.csindex c929e8fb1..5df643758 100644--- a/unity/Assets/Scripts/UI/HudModel.cs+++ b/unity/Assets/Scripts/UI/HudModel.cs@@ -52,14 +52,15 @@ namespace Statecraft.Game.UI_ => throw new ArgumentOutOfRangeException(nameof(id), id, "not a top-bar meter"),};- /// <summary>The main causes of a meter's change in <paramref name="turn"/> (#1037): the messages of the sim's own causes- /// (StepResult.Why) for the quantity the meter shows, the largest change first (each meter's causes share its unit),+ /// <summary>The main causes of a meter's change in <paramref name="turn"/> (#1037): the sim's own causes+ /// (StepResult.Why) for the quantity the meter shows, each worded by <paramref name="line"/> (CauseText.Line: the+ /// player's language, B1), the largest change first (each meter's causes share its unit),/// the sim's order breaking a tie, at most <see cref="MaxCauses"/>. Nothing is computed or reworded here: a cause is/// matched by its target, as <see cref="From"/> reads the state (Money: the Treasury and the debt; Immigration: the/// population system's arrivals; Social cohesion: morale; International support: intl_standing; Foreign currency:/// fx_reserves; Security: security). Public support is an average the sim computes from the indicators/// (EffectsSystem.Approval) and no cause names it, so it has none.</summary>- public static IReadOnlyList<string> Causes(StepResult? turn, string meter)+ public static IReadOnlyList<string> Causes(StepResult? turn, string meter, Func<Cause, string> line){if (turn == null) return Array.Empty<string>();Func<Cause, bool> match = meter switch@@ -73,7 +74,7 @@ namespace Statecraft.Game.UI_ => w => false,};return turn.Why.Select((w, i) => (w, i)).Where(x => match(x.w) && x.w.Delta != 0)- .OrderByDescending(x => Math.Abs(x.w.Delta)).ThenBy(x => x.i).Take(MaxCauses).Select(x => x.w.Message).ToList();+ .OrderByDescending(x => Math.Abs(x.w.Delta)).ThenBy(x => x.i).Take(MaxCauses).Select(x => line(x.w)).ToList();}public static HudModel From(SimBridge b, UiText t)diff --git a/unity/Assets/Scripts/UI/MeterTip.cs b/unity/Assets/Scripts/UI/MeterTip.csindex 9390f9bbe..58ef0ef0e 100644--- a/unity/Assets/Scripts/UI/MeterTip.cs+++ b/unity/Assets/Scripts/UI/MeterTip.cs@@ -8,19 +8,20 @@ namespace Statecraft.Game.UI{/// <summary>Each top-bar number explains itself (#1037): while the pointer is over a meter, or after a tap on it (a/// touchscreen has no hover), a tip under the bar gives the meter in words (its tooltip, HudModel.Spoken: the value- /// and this turn's change) and the turn's main causes, which are the sim's own messages (HudModel.Causes). A second+ /// and this turn's change) and the turn's main causes, the sim's own causes worded by CauseText (HudModel.Causes). A second/// tap on the same meter closes it, a tap on another moves it, and a tap anywhere else or End Turn closes it; a mouse/// click pins nothing, as the mouse hovers (#1108). It shows only while the meter can take the pointer, so a report or/// an outcome clip over the bar hides it. The tip is centred under the meter and kept inside the window. Nothing is/// computed here; the tip takes no clicks. Its two labels are the meter's words in the UI's language and the causes,- /// which the sim gives in English (#55), so each takes its own direction.</summary>+ /// which are in the UI's language where the line has a key (B1) and in the sim's English where it has none yet (#55),+ /// so each takes its own direction.</summary>public sealed class MeterTip : IDisposable{public const string TipName = "meter-tip";/// <summary>The gap between the tip and the window's edge, and between the meter and the tip.</summary>const float Margin = 8f;- readonly VisualElement layer, tip; readonly Label words, causesLine; readonly SimBridge bridge; readonly UiText text;+ readonly VisualElement layer, tip; readonly Label words; readonly VisualElement causesBox; readonly SimBridge bridge; readonly UiText text;readonly List<VisualElement> meters = new List<VisualElement>();readonly EventCallback<PointerEnterEvent> onEnter; readonly EventCallback<PointerLeaveEvent> onLeave;readonly EventCallback<ClickEvent> onClick; readonly EventCallback<GeometryChangedEvent> onTipGeometry;@@ -32,7 +33,7 @@ namespace Statecraft.Game.UIpublic MeterTip(VisualElement root, SimBridge bridge, UiText text, IEnumerable<VisualElement> meters){tip = root.Q<VisualElement>(TipName); layer = tip.parent; this.bridge = bridge; this.text = text;- words = tip.Q<Label>("meter-tip-words"); causesLine = tip.Q<Label>("meter-tip-causes");+ words = tip.Q<Label>("meter-tip-words"); causesBox = tip.Q<VisualElement>("meter-tip-causes");onEnter = e => { hovered = (VisualElement)e.currentTarget; Refresh(); };onLeave = e => { if (hovered == e.currentTarget) hovered = null; Refresh(); };// #1108: a mouse click pinned the tip, so it outlived the pointer's leave; the mouse has hover, only a tap pins. A@@ -83,12 +84,13 @@ namespace Statecraft.Game.UI/// <summary>The meter the tip is shown for, or null.</summary>public VisualElement? ShownFor => shownFor;- /// <summary>The tip's two lines for <paramref name="meter"/> (an element named "meter-" + a HudModel.MeterIds id): its- /// words, with the causes' heading when there are causes, and the causes ("" when none).</summary>- public (string words, string causes) Lines(VisualElement meter)+ /// <summary>The tip's lines for <paramref name="meter"/> (an element named "meter-" + a HudModel.MeterIds id): its+ /// words, with the causes' heading when there are causes, and the causes, one a line (none when none).</summary>+ public (string words, IReadOnlyList<string> causes) Lines(VisualElement meter){- var causes = HudModel.Causes(bridge.Session.Last, meter.name.Substring("meter-".Length));- return causes.Count == 0 ? (meter.tooltip, "") : (meter.tooltip + "\n" + text["hud.causes"], string.Join("\n", causes));+ var causes = HudModel.Causes(bridge.Session.Last, meter.name.Substring("meter-".Length),+ w => CauseText.Line(w, bridge.Content, Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), text)); // no meter counts a unit line+ return causes.Count == 0 ? (meter.tooltip, causes) : (meter.tooltip + "\n" + text["hud.causes"], causes);}/// <summary>Shows the tip for the hovered meter, else the tapped one, with today's words (HudPresenter.Render calls@@ -98,8 +100,17 @@ namespace Statecraft.Game.UIvar target = hovered ?? pinned;if (target == null || !target.enabledInHierarchy || string.IsNullOrEmpty(target.tooltip) || !(target.worldBound.width > 0)) { Hide(); return; }var (w, c) = Lines(target);- words.text = w; causesLine.text = c;- causesLine.style.display = c.Length == 0 ? DisplayStyle.None : DisplayStyle.Flex;+ words.text = w;+ // One label a cause, each with its own direction (UiDirection): a Hebrew line and a line still in English (B1).+ causesBox.Clear();+ foreach (var line in c)+ {+ var label = new Label { pickingMode = PickingMode.Ignore };+ label.AddToClassList("meter-tip-line");+ causesBox.Add(label);+ label.text = line; // set once in the panel, so UiDirection's change callback gives it its direction+ }+ causesBox.style.display = c.Count == 0 ? DisplayStyle.None : DisplayStyle.Flex;shownFor = target;tip.style.display = DisplayStyle.Flex;Place();diff --git a/unity/Assets/Scripts/UI/ToastPresenter.cs b/unity/Assets/Scripts/UI/ToastPresenter.csindex 3794b47cf..bb66d3ee7 100644--- a/unity/Assets/Scripts/UI/ToastPresenter.cs+++ b/unity/Assets/Scripts/UI/ToastPresenter.cs@@ -27,7 +27,7 @@ namespace Statecraft.Game.UI{label = root.Q<Label>("toast"); this.text = text; this.bridge = bridge;onTurnEnded = r => Show(r.Select(x => text.Format("toast.refused", x.Reason)));- onCommitted = why => Show(why.Where(x => !string.IsNullOrEmpty(x.Key))+ onCommitted = why => Show(why.Where(x => WhyKeys.All.Contains(x.Key)) // unit lines only: a call-up order's line (B1 key) is no toast.Select(x => UnitNames.Line(x, bridge.Content, units, text, TownNamesHe)));onRouteStep = _ =>{diff --git a/unity/Assets/Scripts/UI/TurnReportPresenter.cs b/unity/Assets/Scripts/UI/TurnReportPresenter.csindex fce4df46e..3d3d40b33 100644--- a/unity/Assets/Scripts/UI/TurnReportPresenter.cs+++ b/unity/Assets/Scripts/UI/TurnReportPresenter.cs@@ -11,8 +11,8 @@ namespace Statecraft.Game.UI{/// <summary>The turn report (#1037; the first outside play-test, #1038: "I see the values changing, but I don't really/// understand what's happening"). When a turn has run, a short panel names each top-bar number that changed, with the- /// change the bar shows (HudModel.From) and its main causes, which are the sim's own cause messages- /// (StepResult.Why, through HudModel.Causes). "See all" opens the Why screen with every cause; Close, Esc or Cancel+ /// change the bar shows (HudModel.From) and its main causes, the sim's own causes in the player's language+ /// (StepResult.Why, through HudModel.Causes and CauseText, B1). "See all" opens the Why screen with every cause; Close, Esc or Cancel/// closes it. Nothing is computed or reworded here, so no rule lives in the UI./// <para>While it shows, the root has <see cref="OpenClass"/>: ScreenNav.DisableCovered disables the top bar, the panels/// and the decision layer under it, as under an End Turn outcome clip, which is drawn over the report (Game.uxml order)@@ -102,7 +102,8 @@ namespace Statecraft.Game.UIif (id == "cohesion" && !m.ShowsCohesion) continue;var meter = m.For(id);if (meter.Delta.Length == 0) continue;- lines.Add(new Line(id, text.Format("report.line", text["hud.caption." + id], meter.Delta), HudModel.Causes(bridge.Session.Last, id)));+ lines.Add(new Line(id, text.Format("report.line", text["hud.caption." + id], meter.Delta), HudModel.Causes(bridge.Session.Last, id,+ w => CauseText.Line(w, bridge.Content, units ?? Array.Empty<UnitEntry>(), text))));}var enemy = EnemyOrders(bridge, text, units);if (enemy.Count > 0) lines.Add(new Line(EnemyRow, text["report.enemy"], enemy));@@ -142,8 +143,16 @@ namespace Statecraft.Game.UIrow.Add(heading);if (line.Causes.Count > 0){- var causes = new Label(string.Join("\n", line.Causes)) { name = "turn-report-causes-" + line.Meter };+ // One label a cause, so each takes its own direction (UiDirection): in Hebrew a line with a key (B1) is+ // right to left and a line still in English left to right.+ var causes = new VisualElement { name = "turn-report-causes-" + line.Meter };causes.AddToClassList("turn-report-causes");+ foreach (var cause in line.Causes)+ {+ var label = new Label(cause);+ label.AddToClassList("turn-report-cause");+ causes.Add(label);+ }row.Add(causes);}rows.Add(row);diff --git a/unity/Assets/Scripts/UI/WhyPresenter.cs b/unity/Assets/Scripts/UI/WhyPresenter.csindex e0d866014..82ba8b344 100644--- a/unity/Assets/Scripts/UI/WhyPresenter.cs+++ b/unity/Assets/Scripts/UI/WhyPresenter.cs@@ -67,7 +67,7 @@ namespace Statecraft.Game.UIrows.Add(header);foreach (var w in lines){- var line = new Label(UnitNames.Line(w, bridge.Content, units, text, townNamesHe)) { name = "why-" + i++ };+ var line = new Label(CauseText.Line(w, bridge.Content, units, text, townNamesHe)) { name = "why-" + i++ };line.AddToClassList("why-line");rows.Add(line);}diff --git a/unity/Assets/Tests/EditMode/CauseTextTests.cs b/unity/Assets/Tests/EditMode/CauseTextTests.csnew file mode 100644index 000000000..818dbf8b8--- /dev/null+++ b/unity/Assets/Tests/EditMode/CauseTextTests.cs@@ -0,0 +1,174 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using System.Text.RegularExpressions;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map.Units;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor;+using UnityEngine;++/// <summary>B1: the turn report, the meter tip and the Why screen word the economy, population, effect and security lines+/// (CauseKeys) in the player's language through CauseText. In English every row is the sim's Message, word for word, so+/// the English report is what it was before B1; in Hebrew each keyed line is Hebrew, its amounts the only Latin text.</summary>+public class CauseTextTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static readonly IReadOnlyList<UnitEntry> NoRows = Array.Empty<UnitEntry>();+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);+ static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");++ /// <summary>The golden seed's whole game, played by the reference player, turn by turn.</summary>+ static IEnumerable<StepResult> Turns()+ {+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);+ for (int t = 0; t < 1000 && s.GameOver == null; t++)+ {+ var r = Simulation.Step(C, s, GoldenRun.Orders(C, s));+ yield return r;+ s = r.State;+ }+ }++ /// <summary>Before B1 the report and the tip showed each cause's Message; now CauseText's English. For a seeded game,+ /// every turn and every meter, the rows are the same, character for character, and so is every Why line.</summary>+ [Test]+ public void TheEnglishRowsAreTheSameAsBefore()+ {+ var en = En; int rows = 0, keyed = 0;+ foreach (var turn in Turns())+ {+ foreach (var id in HudModel.MeterIds)+ {+ var before = HudModel.Causes(turn, id, w => w.Message);+ CollectionAssert.AreEqual(before, HudModel.Causes(turn, id, w => CauseText.Line(w, C, NoRows, en)), id);+ rows += before.Count;+ }+ foreach (var w in turn.Why.Where(w => CauseKeys.All.Contains(w.Key)))+ {+ Assert.AreEqual(w.Message, CauseText.Line(w, C, NoRows, en), w.Key);+ keyed++;+ }+ }+ Assert.Greater(rows, 100, "precondition: the game has report rows");+ Assert.Greater(keyed, 400, "precondition: the game has keyed lines (531 at 7ec163c4)");+ }++ /// <summary>In Hebrew every keyed line of the seeded game is Hebrew: right to left, every placeholder filled, and no+ /// Latin letter outside a value UiText marked left to right (an amount such as "IL -6.8m").</summary>+ [Test]+ public void EveryKeyedLineIsHebrewInHebrew()+ {+ var he = He; var seen = new HashSet<string>();+ foreach (var turn in Turns())+ foreach (var w in turn.Why.Where(w => CauseKeys.All.Contains(w.Key)))+ {+ AssertHebrew(CauseText.Line(w, C, NoRows, he), w.Key);+ seen.Add(w.Key);+ }+ Assert.GreaterOrEqual(seen.Count, 8, "precondition: the game reaches most keys: " + string.Join(", ", seen));+ }++ /// <summary>The keyed lines the seeded game does not reach: a call-up order, a situation that ends, civilian upkeep and+ /// its borrowing, the currency crisis on both sides, and the legacy loop's food cut and UN ceasefire.</summary>+ [Test]+ public void TheRareLinesAreWordedInBothLanguages()+ {+ var why = new List<Cause>();+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);+ Assert.IsNull(SecuritySystem.SetMobilization(C, s, 1.0, why));+ s.ActiveSituations.Add("food_crisis"); s.Indicators["food_supply"] = 0.6;+ EffectsSystem.UpdateSituations(C, s, why);+ // Civilian upkeep: the real content's places cost nothing yet, so the line is the sim's own (EconomySystem.PayCivilianUpkeep),+ // and the borrowing comes from PayOrBorrow with that purpose.+ why.Add(new Cause("economy", "treasury", -2, PlayerText.Change(C, "treasury", -2) + " (civilian upkeep)", key: CauseKeys.CivilianUpkeep));+ EconomySystem.PayOrBorrow(C, s, s.Treasury + 3, "for civilian upkeep", why, CauseKeys.Purpose.CivilianUpkeep);+ s.ActiveSituations.Add(EconomySystem.FxCrisis); s.FxReserves = 1e6;+ EconomySystem.Apply(C, s, 0.25, why);+ s.ActiveSituations.Remove(EconomySystem.FxCrisis); s.FxReserves = -1e6;+ EconomySystem.Apply(C, s, 0.25, why);++ var legacy = SimBridgeGddTests.Legacy;+ var l = Simulation.NewGame(legacy, GoldenRun.Seed, Mode.Historical);+ l.ActiveSituations.Add(EconomySystem.FxCrisis); l.FxReserves = -1e6;+ EconomySystem.Apply(legacy, l, 0.25, why);+ l.Rung = 5; l.CeasefireWeeksLeft = 1;+ SecuritySystem.Apply(legacy, l, 1, why);++ var keys = why.Where(w => CauseKeys.All.Contains(w.Key)).Select(w => w.Key).Distinct().ToList();+ foreach (var key in new[] { CauseKeys.CallUpSet, CauseKeys.SituationEnded, CauseKeys.CivilianUpkeep, CauseKeys.Borrowed,+ CauseKeys.FxCrisisEased, CauseKeys.FxCrisisBegan, CauseKeys.FxCrisisFood, CauseKeys.Ceasefire })+ CollectionAssert.Contains(keys, key, "precondition");+ var en = En; var he = He;+ foreach (var w in why.Where(w => CauseKeys.All.Contains(w.Key)))+ {+ var content = w.Target == "food_supply" || w.Key == CauseKeys.Ceasefire ? legacy : C;+ Assert.AreEqual(w.Message, CauseText.Line(w, content, NoRows, en), w.Key);+ AssertHebrew(CauseText.Line(w, content, NoRows, he), w.Key);+ }+ }++ /// <summary>Borrowing for every purpose PayOrBorrow's callers give (the English purpose as each caller words it): English+ /// is the Message, Hebrew is Hebrew, and an event's title is its title_he.</summary>+ [Test]+ public void EveryBorrowingPurposeIsWordedInBothLanguages()+ {+ var place = C.SettlementTargets[0].Id; var placeName = C.SettlementNames[place];+ var housing = C.ProjectKinds.First(k => k.Id == "housing");+ var ev = C.Events.First(e => e.TitleHe != "");+ var purposes = new (string Key, string English, string[] Args)[]+ {+ (CauseKeys.Purpose.CivilianUpkeep, "for civilian upkeep", new string[0]),+ (CauseKeys.Purpose.MilitaryUpkeep, "for military upkeep", new string[0]),+ (CauseKeys.Purpose.Corridor, "to build a corridor segment", new string[0]),+ (CauseKeys.Purpose.Arms, "for Arms", new string[0]),+ (CauseKeys.Purpose.Training, "for training", new string[0]),+ (CauseKeys.Purpose.Prisoners, "for our soldiers held by the enemy", new string[0]),+ (CauseKeys.Purpose.TrainingCamp, "to build a training camp", new string[0]),+ (CauseKeys.Purpose.Plow, "to plow fields", new string[0]),+ (CauseKeys.Purpose.Drain, "to drain a swamp", new string[0]),+ (CauseKeys.Purpose.Yishuv, "to build a yishuv", new string[0]),+ (CauseKeys.Purpose.Project, "to build " + housing.Name, new[] { housing.Id }),+ (CauseKeys.Purpose.Deport, $"for the Deport of {placeName}", new[] { place }),+ (CauseKeys.Purpose.Occupation, $"for the occupation of {placeName}", new[] { place }),+ (CauseKeys.Purpose.Event, $"for {ev.Title}", new[] { ev.Id, ev.Title, "1" }),+ };+ CollectionAssert.AreEquivalent(CauseKeys.Purpose.All.Where(p => p != CauseKeys.Purpose.Deficit), purposes.Select(p => p.Key), "every purpose");+ var en = En; var he = He;+ foreach (var (key, english, args) in purposes)+ {+ var why = new List<Cause>();+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);+ EconomySystem.PayOrBorrow(C, s, s.Treasury + 3, english, why, key, args);+ var line = why.Single();+ Assert.AreEqual(line.Message, CauseText.Line(line, C, NoRows, en), key);+ AssertHebrew(CauseText.Line(line, C, NoRows, he), key);+ }+ var title = new Cause("economy", "debt", 3, "x", key: CauseKeys.Borrowed, args: new[] { CauseKeys.Purpose.Event, ev.Id, ev.Title, "1" });+ StringAssert.Contains(ev.TitleHe, CauseText.Line(title, C, NoRows, he), "the event's Hebrew title");+ StringAssert.Contains(housing.NameHe, CauseText.Line(new Cause("economy", "debt", 3, "x", key: CauseKeys.Borrowed,+ args: new[] { CauseKeys.Purpose.Project, housing.Id }), C, NoRows, he), "the project kind's Hebrew name");+ }++ /// <summary>A line with no key yet keeps the sim's English; a unit line is still UnitNames' (#1399).</summary>+ [Test]+ public void OtherLinesAreUnchanged()+ {+ var plain = new Cause("economy", "treasury", -1, "Money IL -1.0m (military upkeep)");+ Assert.AreEqual(plain.Message, CauseText.Line(plain, C, NoRows, He));+ var turn = Turns().First(t => t.Why.Any(w => WhyKeys.All.Contains(w.Key)));+ foreach (var w in turn.Why.Where(w => WhyKeys.All.Contains(w.Key)))+ Assert.AreEqual(UnitNames.Line(w, C, NoRows, He), CauseText.Line(w, C, NoRows, He));+ }++ static void AssertHebrew(string line, string key)+ {+ Assert.IsTrue(UiDirection.RightToLeft(line), $"{key}: '{line}' reads right to left");+ StringAssert.DoesNotContain("{", line, key);+ var unmarked = Regex.Replace(line, UiText.LeftToRightMark + "[^" + UiText.LeftToRightMark + "]*" + UiText.LeftToRightMark, "");+ Assert.IsFalse(Regex.IsMatch(unmarked, "[A-Za-z]"), $"{key}: '{line}' has Latin text outside a marked value");+ }+}diff --git a/unity/Assets/Tests/EditMode/CauseTextTests.cs.meta b/unity/Assets/Tests/EditMode/CauseTextTests.cs.metanew file mode 100644index 000000000..756a9363e--- /dev/null+++ b/unity/Assets/Tests/EditMode/CauseTextTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 8ccfeab67df08448abb494312d935d4a\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/MeterTipTests.cs b/unity/Assets/Tests/EditMode/MeterTipTests.csindex 14873cd13..c451baeea 100644--- a/unity/Assets/Tests/EditMode/MeterTipTests.cs+++ b/unity/Assets/Tests/EditMode/MeterTipTests.cs@@ -1,6 +1,7 @@#nullable enableusing System.Collections;using System.Collections.Generic;+using System.Linq;using NUnit.Framework;using Statecraft.Game;using Statecraft.Game.UI;@@ -29,7 +30,8 @@ public class MeterTipTests/// <summary>Shown only when MeterTip set it so (an unset inline display reads as Flex, the default).</summary>internal static bool Shown(VisualElement tip) => tip.style.display.keyword == StyleKeyword.Undefined && tip.style.display.value == DisplayStyle.Flex;static string Words(VisualElement root) => root.Q<Label>("meter-tip-words").text;- static string CausesLine(VisualElement root) => root.Q<Label>("meter-tip-causes").text;+ /// <summary>The tip's causes, one label each (B1), joined a line each.</summary>+ static string CausesLine(VisualElement root) => string.Join("\n", root.Q("meter-tip-causes").Query<Label>().ToList().Select(l => l.text));/// <summary>After the fixed opening turn, at 1280x720 and 390x844 in English and Hebrew: hovering the bar's first and/// last numbers shows each one's words and the sim's causes under the bar and inside the window; leaving hides it.</summary>@@ -51,12 +53,13 @@ public class MeterTipTestsvar meter = root.Q("meter-" + id);Enter(meter);for (int i = 0; i < 3; i++) yield return null; // the tip is placed once its width is laid out- var causes = HudModel.Causes(bridge.Session.Last, id);+ var causes = HudModel.Causes(bridge.Session.Last, id, w => CauseText.Line(w, bridge.Content, System.Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), text));if (!Shown(tip)) { problems.Add($"{at} {id}: hovering shows no tip"); continue; }if (Words(root) != meter.tooltip + "\n" + text["hud.causes"]) problems.Add($"{at} {id}: the tip's words are '{Words(root)}', not its tooltip and the causes' heading");if (CausesLine(root) != string.Join("\n", causes)) problems.Add($"{at} {id}: the tip's causes are '{CausesLine(root)}', not the sim's '{string.Join(" | ", causes)}'");if (UiDirection.RightToLeft(Words(root)) != hebrew) problems.Add($"{at} {id}: the words are not in the UI's language");- if (UiDirection.HasRightToLeft(CausesLine(root))) problems.Add($"{at} {id}: the sim's causes are expected in English (#55), in their own label");+ // B1: each of these meters has a keyed line on the opening turn, in the UI's language (#55: lines with no key stay English).+ if (UiDirection.HasRightToLeft(CausesLine(root)) != hebrew) problems.Add($"{at} {id}: the causes '{CausesLine(root)}' are not in the UI's language");if (causes.Count == 0) problems.Add($"{at} {id}: precondition: the opening turn has causes for it");Rect t = tip.worldBound, m = meter.worldBound, win = root.worldBound;if (t.xMin < win.xMin - 0.5f || t.xMax > win.xMax + 0.5f || t.yMax > win.yMax + 0.5f) problems.Add($"{at} {id}: the tip {t} leaves the window {win}");diff --git a/unity/Assets/Tests/EditMode/TurnReportTests.cs b/unity/Assets/Tests/EditMode/TurnReportTests.csindex 8b43e7da0..4229be5b4 100644--- a/unity/Assets/Tests/EditMode/TurnReportTests.cs+++ b/unity/Assets/Tests/EditMode/TurnReportTests.cs@@ -49,6 +49,10 @@ public class TurnReportTests}}+ /// <summary>A row's causes, one label each, in order.</summary>+ static List<string> Causes(UiTestKit ui, string meter) =>+ ui.Q<VisualElement>("turn-report-causes-" + meter).Query<Label>(className: "turn-report-cause").ToList().Select(l => l.text).ToList();+[Test]public void TheFixedTurnReportsEachChangedNumberWithTheSimsOwnCauses(){@@ -70,19 +74,19 @@ public class TurnReportTests// The heading is the bar's caption and the very change the bar shows next to the number.var heading = k.Ui.Q<Label>("turn-report-heading-" + id).text;Assert.AreEqual(En.Format("report.line", En["hud.caption." + id], k.Ui.Q<Label>(id + "-delta").text), heading, id);- var causes = k.Ui.Root.Q<Label>("turn-report-causes-" + id);- var expected = HudModel.Causes(turn, id);+ var causes = k.Ui.Root.Q("turn-report-causes-" + id);+ var expected = HudModel.Causes(turn, id, w => CauseText.Line(w, C, System.Array.Empty<UnitEntry>(), En));if (expected.Count == 0) { Assert.IsNull(causes, id + ": no cause line without a cause"); continue; }- var lines = causes!.text.Split('\n');+ var lines = Causes(k.Ui, id);CollectionAssert.AreEqual(expected, lines, id);- Assert.LessOrEqual(lines.Length, HudModel.MaxCauses, id);+ Assert.LessOrEqual(lines.Count, HudModel.MaxCauses, id);foreach (var line in lines) Assert.IsTrue(messages.Contains(line), $"{id}: '{line}' is a cause of StepResult.Why, word for word");}// The fixed turn's own causes: Security moved by One Army, then by the border villages' effect, the larger first.- var security = k.Ui.Q<Label>("turn-report-causes-security").text.Split('\n');+ var security = Causes(k.Ui, "security");Assert.AreEqual("Security +1.5% (One Army)", security[0]);StringAssert.EndsWith("(Border villages)", security[1]);- StringAssert.StartsWith("Money ", k.Ui.Q<Label>("turn-report-causes-treasury").text, "Money's main cause is the economy's line");+ StringAssert.StartsWith("Money ", Causes(k.Ui, "treasury")[0], "Money's main cause is the economy's line");Assert.IsNull(k.Ui.Root.Q("turn-report-causes-support"), "no cause names Public support (an average of the indicators)");}@@ -107,7 +111,7 @@ public class TurnReportTestsreturn text.Format("report.enemy_" + w.EnemyOrder, hebrew ? row.NameHe : row.Name);}).ToList();Assert.AreEqual(text["report.enemy"], k.Ui.Q<Label>("turn-report-heading-" + TurnReportPresenter.EnemyRow).text);- var lines = k.Ui.Q<Label>("turn-report-causes-" + TurnReportPresenter.EnemyRow).text.Split('\n');+ var lines = Causes(k.Ui, TurnReportPresenter.EnemyRow);CollectionAssert.AreEqual(expected, lines);CollectionAssert.Contains(lines, hebrew ? "הלגיון הערבי עבר לעמדה חדשה" : "Arab Legion moved to a new position", "the Legion's march on Latrun");}@@ -132,7 +136,7 @@ public class TurnReportTestsvar turn = k.Bridge.EndTurn();Assert.IsFalse(turn.Why.Any(w => w.Message.StartsWith($"Unit {ala} will attack")), "the attack stands: no order this turn");Assert.IsTrue(turn.Why.Any(w => w.Message.StartsWith($"The attack on hex {a.Q},{a.R - 1}")), "and it engages");- var lines = k.Ui.Q<Label>("turn-report-causes-" + TurnReportPresenter.EnemyRow).text.Split('\n');+ var lines = Causes(k.Ui, TurnReportPresenter.EnemyRow);CollectionAssert.Contains(lines, hebrew ? "צבא ההצלה פתח בהתקפה על אחת היחידות שלכם" : "Arab Liberation Army launched an attack on one of your units");}}@@ -235,8 +239,14 @@ public class TurnReportTestsStringAssert.StartsWith(He["hud.caption.security"] + ":", heading);// In a right-to-left line the change keeps its sign in front ("+2%", not "2%+"): UiText.Format marks it (#543).StringAssert.Contains(UiText.LeftToRightMark + k.Ui.Q<Label>("security-delta").text + UiText.LeftToRightMark, heading);- CollectionAssert.AreEqual(HudModel.Causes(k.Bridge.Session.Last, "security"), k.Ui.Q<Label>("turn-report-causes-security").text.Split('\n'),- "the causes are the sim's messages, as on the Why screen");+ var causes = Causes(k.Ui, "security");+ CollectionAssert.AreEqual(HudModel.Causes(k.Bridge.Session.Last, "security", w => CauseText.Line(w, C, System.Array.Empty<UnitEntry>(), He)), causes,+ "the causes are the sim's, worded as on the Why screen");+ // B1: the treasury's tax-and-spending line is Hebrew (a line with no key yet, such as an event's, stays English).+ Assert.IsTrue(UiDirection.RightToLeft(Causes(k.Ui, "treasury")[0]), "the money line is in Hebrew");+ // B1: one label a cause, so a Hebrew line and a line still in English each take their own direction.+ Assert.AreEqual(HudModel.Causes(k.Bridge.Session.Last, "security", w => w.Message).Count,+ k.Q("turn-report-causes-security").Query<Label>(className: "turn-report-cause").ToList().Count);}/// <summary>The smoke run plays as a player does: it closes each turn's report before the next turn (GameRoot.Smoke).</summary>diff --git a/unity/Assets/Tests/EditMode/WhyScreenTests.cs b/unity/Assets/Tests/EditMode/WhyScreenTests.csindex a617fbcd3..734af2e8b 100644--- a/unity/Assets/Tests/EditMode/WhyScreenTests.cs+++ b/unity/Assets/Tests/EditMode/WhyScreenTests.cs@@ -42,7 +42,7 @@ public class WhyScreenTestsvar bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);new WhyPresenter(ui.Root, bridge, Text) { Units = Rows };var r = bridge.EndTurn();- var expected = WhyPresenter.Order.SelectMany(sys => r.Why.Where(w => w.System == sys).Select(w => UnitNames.Line(w, C, Rows, Text))).ToList();+ var expected = WhyPresenter.Order.SelectMany(sys => r.Why.Where(w => w.System == sys).Select(w => CauseText.Line(w, C, Rows, Text))).ToList();var shown = ui.Q<ScrollView>("why-rows").Query<Label>(className: "why-line").ToList().Select(l => l.text).ToList();Assert.AreEqual(expected, shown);}diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxmlindex 09bbee2f1..6cbc9b453 100644--- a/unity/Assets/UI/Game.uxml+++ b/unity/Assets/UI/Game.uxml@@ -646,12 +646,12 @@<!-- The name of an icon-only button, beside it on hover and on keyboard focus (HoverTip; UI Toolkit draws `tooltip`only in Editor UI). Last, so it draws over the panels; it takes no clicks. --><ui:Label name="hud-tip" class="hud-tip" picking-mode="Ignore" />- <!-- A top-bar number's explanation under the bar, on hover or after a tap (MeterTip, #1037); it takes no clicks. Two- lines of their own: the meter in the UI's words, then the sim's causes, which are English (#55), so each label- takes its own direction in the Hebrew UI (UiDirection). -->+ <!-- A top-bar number's explanation under the bar, on hover or after a tap (MeterTip, #1037); it takes no clicks. The+ meter in the UI's words, then one label per cause: a cause is in the UI's language where it has a key (B1) and in+ the sim's English where it has none yet (#55), so each label takes its own direction in the Hebrew UI (UiDirection). --><ui:VisualElement name="meter-tip" class="meter-tip" picking-mode="Ignore"><ui:Label name="meter-tip-words" class="meter-tip-line" picking-mode="Ignore" />- <ui:Label name="meter-tip-causes" class="meter-tip-line" picking-mode="Ignore" />+ <ui:VisualElement name="meter-tip-causes" picking-mode="Ignore" /></ui:VisualElement></ui:VisualElement></ui:UXML>diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.ussindex 6aae12372..473ed2680 100644--- a/unity/Assets/UI/Statecraft.uss+++ b/unity/Assets/UI/Statecraft.uss@@ -546,7 +546,9 @@ Button.settings-choice-selected { -unity-font-definition: url("project://databas.turn-report-rows { flex-shrink: 1; min-height: 0; }.turn-report-row { margin-bottom: 10px; }.turn-report-heading { white-space: normal; color: var(--gold-light); -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); }-.turn-report-causes { white-space: normal; padding-left: 12px; }+/* A row's causes: one label each (B1: each takes its own direction), set as one block, as the one label was. */+.turn-report-causes { padding: 4px 2px 4px 14px; margin: 1px 3px; }+.turn-report-cause { white-space: normal; margin: 0; padding: 0; }/* The end screen (#812) reuses the report's backdrop and panel: its outcome in the heading face, one line per part. */.end-screen-outcome { white-space: normal; margin-bottom: 10px; color: var(--gold-light); -unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); }.end-screen-line { white-space: normal; margin-bottom: 6px; }diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex c68164577..bed1b0e45 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -315,6 +315,66 @@ why.line.on_its_way: "{0} is on its way to {1}"why.line.stopped_no_route: "{0} stopped: no route reaches {1}"why.line.stopped_full: "{0} stopped: {1} is full"why.line.arrived: "{0} arrived at {1}"+# B1: the economy, population, effect and security Why lines (CauseKeys, CauseText). English is the sim's own Message,+# word for word: a test compares them, so change the sim and this together. {0} a name below, {1} the change in its unit;+# money and percentages arrive formatted by PlayerText. Lines without a key stay the sim's English (not yet localized).+why.cause.money_flows: "{0} {1} (tax {2}, spending {3}, reserve call-up {4})"+why.cause.fx_flows: "{0} {1} (exports {2}, donations and loans {3}, imports {4})"+why.cause.civilian_upkeep: "{0} {1} (civilian upkeep)"+why.cause.borrowed.deficit: "Borrowed {0} to cover the deficit"+why.cause.borrowed.civilian_upkeep: "Borrowed {0} for civilian upkeep"+why.cause.borrowed.military_upkeep: "Borrowed {0} for military upkeep"+why.cause.borrowed.corridor: "Borrowed {0} to build a corridor segment"+why.cause.borrowed.arms: "Borrowed {0} for Arms"+why.cause.borrowed.training: "Borrowed {0} for training"+why.cause.borrowed.prisoners: "Borrowed {0} for our soldiers held by the enemy"+why.cause.borrowed.training_camp: "Borrowed {0} to build a training camp"+why.cause.borrowed.plow: "Borrowed {0} to plow fields"+why.cause.borrowed.drain: "Borrowed {0} to drain a swamp"+why.cause.borrowed.yishuv: "Borrowed {0} to build a yishuv"+why.cause.borrowed.project: "Borrowed {0} to build {1}"+why.cause.borrowed.deport: "Borrowed {0} for the Deport of {1}"+why.cause.borrowed.occupation: "Borrowed {0} for the occupation of {1}"+why.cause.borrowed.event: "Borrowed {0} for {1}"+why.cause.fx_crisis_began: "Foreign currency reserves are exhausted"+why.cause.fx_crisis_eased: "Foreign currency crisis eased"+why.cause.fx_crisis_food: "{0} {1} (foreign currency crisis: food imports cut)"+why.cause.immigrants_arrived: "{0:N0} immigrants arrived ({1})"+why.cause.effect_change: "{0} {1}"+why.cause.effect_change_from: "{0} {1} ({2})"+why.cause.situation_began: "{0} began ({1} at {2})"+why.cause.situation_ended: "{0} ended ({1} at {2})"+why.cause.rung_changed: "Security level {0} to {1}"+why.cause.call_up_set: "Reserve call-up set to {0}"+why.cause.call_up_raised: "Reserve call-up raised to {0}, the minimum for security level {1}"+why.cause.call_up_lowered: "Reserves sent home: call-up lowered to {0}, the minimum for security level {1}"+why.cause.ceasefire: "UN ceasefire imposed: full war ends"+# The names those lines give: content's own names in English (content/model.yaml, content/aliyah.yaml; a test pins them).+why.name.treasury: "Money"+why.name.debt: "Debt"+why.name.fx_reserves: "Foreign currency"+why.name.morale: "Social cohesion"+why.name.food_supply: "Food supply"+why.name.housing: "Housing"+why.name.security: "Security"+why.name.intl_standing: "International support"+why.effect.rationing_feeds: "Rations share out food"+why.effect.rationing_grates: "Rationing wears on cohesion"+why.effect.building_houses: "New housing"+why.effect.homes_lift_morale: "Homes lift cohesion"+why.effect.border_villages_secure: "Border villages"+why.effect.safety_lifts_morale: "Safety lifts cohesion"+why.effect.work_lifts_cohesion: "Work lifts cohesion"+why.effect.food_lifts_cohesion: "Food lifts cohesion"+why.situation.food_crisis: "Food crisis"+why.situation.housing_crisis: "Housing crisis"+why.situation.low_cohesion: "Low social cohesion"+why.situation.low_intl_support: "Low international support"+why.region.asia: "Asia"+why.region.africa: "Africa"+why.region.europe: "Europe"+why.region.america_oceania: "the Americas and Oceania"+why.region.unknown: "country of origin not recorded"# A hex in the unit lines (HexPlaces): a settlement's hex is its name alone; any other hex is said from the nearest# settlement, {0} the km between the centres (to the nearest 5), {1} the compass point (why.hex.<point>), {2} the settlement.why.hex.away: "a hex {0} km {1} of {2}"diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yamlindex c978e502e..52fa29af7 100644--- a/unity/Assets/UI/strings.he.yaml+++ b/unity/Assets/UI/strings.he.yaml@@ -338,6 +338,67 @@ why.line.on_its_way: "{0} בדרך למשושה {1}"why.line.stopped_no_route: "{0}: עצירה, כי אין מסלול שמגיע למשושה {1}"why.line.stopped_full: "{0}: עצירה, כי משושה {1} מלא"why.line.arrived: "{0}: הגעה למשושה {1}"+# B1: the economy, population, effect and security Why lines (CauseKeys, CauseText). A change reads "{0}: שינוי {1}", as+# event.effect.amount does, so the pattern has Hebrew and UiText marks the amount (#543). Counts as "Label: N" (HE-04);+# no verb agrees with a placeholder (HE-15). Native review: owner, 25 Oct 2026 (recommendations page), for every+# why.cause, why.name, why.effect, why.situation and why.region key below (#1642).+why.cause.money_flows: "{0}: שינוי {1} (מסים {2}, הוצאות {3}, גיוס מילואים {4})"+why.cause.fx_flows: "{0}: שינוי {1} (יצוא {2}, תרומות והלוואות {3}, יבוא {4})"+why.cause.civilian_upkeep: "{0}: שינוי {1} (תחזוקה אזרחית)"+why.cause.borrowed.deficit: "הלוואה של {0} לכיסוי הגירעון"+why.cause.borrowed.civilian_upkeep: "הלוואה של {0} לתחזוקה אזרחית"+why.cause.borrowed.military_upkeep: "הלוואה של {0} לתחזוקה צבאית"+why.cause.borrowed.corridor: "הלוואה של {0} לבניית קטע של כביש או מסילה"+why.cause.borrowed.arms: "הלוואה של {0} לרכישת נשק"+why.cause.borrowed.training: "הלוואה של {0} לאימון ולהכשרה"+why.cause.borrowed.prisoners: "הלוואה של {0} עבור חיילינו המוחזקים בידי האויב"+why.cause.borrowed.training_camp: "הלוואה של {0} להקמת מחנה אימונים"+why.cause.borrowed.plow: "הלוואה של {0} לחריש שדות"+why.cause.borrowed.drain: "הלוואה של {0} לייבוש ביצה"+why.cause.borrowed.yishuv: "הלוואה של {0} להקמת יישוב"+why.cause.borrowed.project: "הלוואה של {0} לבניית {1}"+why.cause.borrowed.deport: "הלוואה של {0} לגירוש ({1})"+why.cause.borrowed.occupation: "הלוואה של {0} לעלות ההחזקה ({1})"+why.cause.borrowed.event: "הלוואה של {0} עבור {1}"+why.cause.fx_crisis_began: "יתרות מטבע החוץ אזלו"+why.cause.fx_crisis_eased: "הקלה במשבר מטבע החוץ"+why.cause.fx_crisis_food: "{0}: שינוי {1} (משבר מטבע חוץ: קיצוץ ביבוא המזון)"+why.cause.immigrants_arrived: "עולים שהגיעו ({1}): {0:N0}"+why.cause.effect_change: "{0}: שינוי {1}"+why.cause.effect_change_from: "{0}: שינוי {1} ({2})"+why.cause.situation_began: "תחילת {0} ({1}: {2})"+why.cause.situation_ended: "סיום {0} ({1}: {2})"+why.cause.rung_changed: "רמת הביטחון: מ־{0} ל־{1}"+why.cause.call_up_set: "גיוס המילואים נקבע ל־{0}"+why.cause.call_up_raised: "גיוס המילואים הועלה ל־{0}, המינימום לרמת ביטחון {1}"+why.cause.call_up_lowered: "אנשי מילואים חוזרים הביתה: גיוס המילואים הורד ל־{0}, המינימום לרמת ביטחון {1}"+why.cause.ceasefire: "הפסקת אש בכפיית האו״ם: סיום המלחמה במלוא עוצמתה"+# The names those lines give. כסף, מטבע חוץ, לכידות חברתית and תמיכה בינלאומית are the adopted resource words (HE-02).+why.name.treasury: "כסף"+why.name.debt: "חוב"+why.name.fx_reserves: "מטבע חוץ"+why.name.morale: "לכידות חברתית"+why.name.food_supply: "אספקת מזון"+why.name.housing: "דיור"+why.name.security: "ביטחון"+why.name.intl_standing: "תמיכה בינלאומית"+why.effect.rationing_feeds: "הקיצוב מחלק את המזון"+why.effect.rationing_grates: "הקיצוב שוחק את הלכידות"+why.effect.building_houses: "דיור חדש"+why.effect.homes_lift_morale: "בתים מחזקים את הלכידות"+why.effect.border_villages_secure: "יישובי ספר"+why.effect.safety_lifts_morale: "ביטחון אישי מחזק את הלכידות"+why.effect.work_lifts_cohesion: "תעסוקה מחזקת את הלכידות"+why.effect.food_lifts_cohesion: "מזון מחזק את הלכידות"+why.situation.food_crisis: "משבר מזון"+why.situation.housing_crisis: "משבר דיור"+why.situation.low_cohesion: "לכידות חברתית נמוכה"+why.situation.low_intl_support: "תמיכה בינלאומית נמוכה"+why.region.asia: "אסיה"+why.region.africa: "אפריקה"+why.region.europe: "אירופה"+why.region.america_oceania: "אמריקה ואוקיאניה"+why.region.unknown: "ארץ המוצא לא נרשמה"# A hex in the unit lines (HexPlaces), after the lines' "משושה": a settlement's hex is its name alone ("משושה חיפה"); any# other hex is said from the nearest settlement, {0} the km (to the nearest 5), {1} the compass point, {2} the settlement,# joined to its prefix ("לחיפה"). Native review: owner, 25 Oct 2026 (recommendations page), #1636: why.hex.away, the