A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Statecraft.Sim
{
/// <summary>The GDD v0.1 cities (docs/GDD.md "Cities and construction"; Phase 1 PR 3): civilians and refugees are counts
/// per city (D-A2), in population units (D-A1). Runs only when eras.yaml systems.loop is gdd.</summary>
public static class Cities
{
public const string Kind = "assign_workers";
/// <summary>R-CITY-001: the most of the city's people AssignWorkers accepts in jobs: its job slots, and no more than its
/// civilians and craftsmen (a craftsman fills an ordinary job slot, R-CRAFT-002). R-CITY-009's default fills to it.</summary>
public static int MaxWorkers(City city) => Math.Min(city.JobSlots, city.Civilians + city.Craftsmen);
/// <summary>R-CITY-001 with R-ARMS-005 and R-CITY-011: <see cref="MaxWorkers(City)"/> less the city's staffed arms
/// workshops and builders, who hold no job. The same number where neither is (always, outside gdd-0.3).</summary>
public static int MaxWorkers(GameState s, City city) =>
Math.Max(0, Math.Min(city.JobSlots, city.Civilians + city.Craftsmen - Workshops.Staffed(s, city.Id) - Projects.Builders(s, city.Id)));
/// <summary>R-CITY-001 with R-TRAIN-001: <see cref="MaxWorkers(City)"/> once the city's Train, Reinforce and Reassign
/// orders in <paramref name="pending"/> (this turn's queue) have taken their civilians, so a count up to it keeps every one
/// of them accepted, whatever order they run in. Every queued reassignment counts in full, craftsmen too (#1548): if the
/// job order runs first, the civilians a reassignment needs are already in work. R-ARMS-005: the staffed arms workshops
/// count as a pending "workshop" order leaves them, when it staffs more (#1722 slice E, as Training.Available does), and
/// the city's builders and the builder each queued gdd-0.3 StartProject there may take (R-CITY-011) are taken off too.</summary>
public static int MaxWorkers(GameState s, string city, IEnumerable<Command> pending)
{
var x = s.Cities[city];
var list = pending as IReadOnlyCollection<Command> ?? pending.ToList();
var staffed = Math.Max(Workshops.Staffed(s, city),
list.OfType<AssignWorkers>().Where(w => w.City == city && w.Role == Workshops.Role).Select(w => w.Count).DefaultIfEmpty(0).Max());
return Math.Max(0, Math.Min(x.JobSlots, x.Civilians + x.Craftsmen - staffed - Projects.Builders(s, city) - Projects.Starting(s, city, list) - Training.Ordered(city, list)));
}
/// <summary>R-CITY-007: a city's start people in units: the nearest unit (a half rounds up), and at least 1 for a city
/// with people (Q-START-2, owner, 15 October 2026), so a small town is not left empty.</summary>
public static int StartUnits(decimal people, int peoplePerUnit) => people > 0 ? Math.Max(1, NearestUnit(people, peoplePerUnit)) : 0;
/// <summary>R-CITY-007: people in units to the nearest unit, a half rounding up. Decimal, so it is exact on every runtime.</summary>
public static int NearestUnit(decimal people, int peoplePerUnit) =>
(int)Math.Round(people / peoplePerUnit, MidpointRounding.AwayFromZero);
/// <summary><see cref="Annex"/>'s refusal, {0} the place's name: a constant for the UI's string (#2707).</summary>
public const string RefusedAlreadyCity = "{0} is already a city";
/// <summary>R-CTRL-016 (OWNER QUESTION 1 (a) on #799, the starting-city rule): a stayed target joins the player's
/// population as one new city: its approved people in units (R-CITY-007), homes equal to them, jobs equal to the
/// employed (people times employed_share to the nearest unit), the usual start condition, and no refugees, recruits or
/// craftsmen. Its approved people join GameState.Population's annexed group (R-CITY-008). Null when added, else the
/// reason with the state unchanged (the id is already a city).</summary>
internal static string? Annex(Content c, GameState s, SettlementTarget t)
{
if (s.Cities.ContainsKey(t.Id)) return string.Format(System.Globalization.CultureInfo.InvariantCulture, RefusedAlreadyCity, c.SettlementNames[t.Id]);
var r = c.RulesAt(s.Date).Mvp!;
var people = t.Annexation!.People!.Value; // the loader requires both values on a stayed row
var units = StartUnits(people, r.PeoplePerUnit);
var employed = NearestUnit(people * t.Annexation.EmployedShare!.Value, r.PeoplePerUnit);
s.Cities[t.Id] = new City(t.Id, units, employed, units, employed, 0, 0, r.HousingStartCondition!.Value);
// R-CITY-008 (owner on #2608, "Yes, add them (Recommended)"): the city's people are part of the nation's record,
// so its approved count joins it. Our design, not the ruling: they get their own group, and an initialized gdd-0.3
// ledger fixture keeps its own record of people (R-POP-001) and is left alone.
if (!s.PopulationLedger.IsInitialized)
s.Population[AnnexedGroup] = (s.Population.TryGetValue(AnnexedGroup, out var had) ? had : 0) + (double)people;
return null;
}
/// <summary>R-CITY-008, R-CTRL-016: the GameState.Population group an annexed town's residents join. Their own key,
/// not an aliyah origin, so the record of who arrived from where stays the sourced series.</summary>
public const string AnnexedGroup = "annexed";
/// <summary>Fills the state's cities from cities.yaml, with no refugees yet and the start housing condition (R-HOUSE-001). Does nothing in the legacy loop.</summary>
public static void Init(Content c, GameState s)
{
PopulationLedger.RefuseAggregate(s);
if (!c.IsGdd) return;
var r = c.RulesAt(s.Date).Mvp!;
foreach (var x in c.Cities) s.Cities[x.Id] = new City(x.Id, x.HousingCapacity, x.JobSlots, x.Civilians, x.Employed, 0, 0, r.HousingStartCondition!.Value);
var housing = c.At(s.Date).Indicators.FirstOrDefault(i => i.Id == HousingIndicator);
if (housing != null) s.Indicators[housing.Id] = EffectsSystem.Level(c, s, housing); // R-HOUSE-004 from the first day
}
/// <summary><see cref="Assign"/>'s refusals that name no city (#2707); the UI maps each to its own string (SimBridge.ReasonText).
/// The English is the reason a turn's Rejected list and a save carry, so it does not change. Workshops.Staff shares RefusedNoRole.</summary>
public const string RefusedNoRole = "There is no such role", RefusedNegativeWorkers = "The number of workers cannot be negative";
// #2530: a count of 1 names the singular, as the UI's helper does.
static string Groups(int n) => n == 1 ? "1 group" : FormattableString.Invariant($"{n} groups");
/// <summary>R-CITY-001: sets the number of the city's people in jobs (a standing order), and turns that city's job
/// default off (R-CITY-009). Refused, state untouched, when the city or role is unknown or the count is negative, above
/// the job slots or above the civilians and craftsmen. Step has already refused it in the legacy loop.</summary>
public static string? Assign(Content c, GameState s, string city, string role, int count, List<Cause> why)
{
// #1725 PR 7, producer 07 (owner, 8 November 2026, Q2 "Keep existing order (Rec.)"): on a Historical ledger game
// only the "workshop" role runs (Workshops.Staff picks the records); every other role is still refused (R-POP-002).
if (!(s.PopulationLedger.IsHistorical && role == Workshops.Role)) PopulationLedger.RefuseAggregate(s);
if (!s.Cities.TryGetValue(city, out var x)) return "There is no such city";
// R-ARMS-005: under gdd-0.3 the "workshop" role staffs the city's arms workshops.
if (role == Workshops.Role && c.Ruleset == SaveGame.Gdd03Ruleset) return Workshops.Staff(c, s, city, count, why);
// R-CITY-011 (#1700): under gdd-0.3 the "build" role puts builders on the city's projects being built.
if (role == Projects.BuildRole && c.Ruleset == SaveGame.Gdd03Ruleset) return Projects.AssignBuilders(c, s, city, count, why);
// Craftsmen fill ordinary job slots (Q-CRAFT-2, R-CRAFT-002), so "job" stays the only role.
if (role != "job") return RefusedNoRole;
if (count < 0) return RefusedNegativeWorkers;
if (count > MaxWorkers(s, x))
return count > x.JobSlots
? FormattableString.Invariant($"{PlayerText.Settlement(c, city)} has {x.JobSlots} jobs")
: string.Format(System.Globalization.CultureInfo.InvariantCulture, Workshops.RefusedPeople, PlayerText.Settlement(c, city), x.Civilians + x.Craftsmen - Workshops.Staffed(s, city) - Projects.Builders(s, city));
s.Cities[city] = x.WithCounts(x.Civilians, count, x.Refugees).WithJobsDefault(false);
why.Add(new Cause("city", city, count - x.Employed, FormattableString.Invariant($"{PlayerText.Settlement(c, city)}: {Groups(count)} in work"), key: CauseKeys.WorkersAssigned, args: new[] { CauseKeys.Number(count) }));
return null;
}
/// <summary>R-CITY-002, R-CRAFT-002: each city's employed units earn income_per_job_per_year for the turn's share of a
/// year. Craftsmen take the jobs first, and each employed craftsman earns craftsman_income_multiple times that.
/// R-CITY-010: a city the enemy holds earns nothing, and gets one line saying so (#1711), in s.Cities' order.</summary>
public static void Produce(Content c, GameState s, MvpRules r, double yearFraction, List<Cause> why)
{
PopulationLedger.RefuseAggregate(s);
var held = Held(c, s);
foreach (var x in s.Cities.Values)
{
if (held.Contains(x.Id))
{
why.Add(new Cause("city", x.Id, 0, $"{PlayerText.Settlement(c, x.Id)}: held by the enemy; no job income or project work this turn", key: CauseKeys.CityHeld));
continue;
}
if (x.Employed == 0) continue;
var craftsmen = Math.Min(x.Craftsmen, x.Employed);
var paid = ((x.Employed - craftsmen) + craftsmen * r.CraftsmanIncomeMultiple) * r.IncomePerJobPerYear * yearFraction;
s.Treasury += paid;
why.Add(new Cause("city", x.Id, paid, $"{PlayerText.Settlement(c, x.Id)}: jobs paid {PlayerText.MoneyChange(c, "treasury", paid)}", key: CauseKeys.WagesPaid));
}
}
/// <summary>R-CITY-010 (D6, owner, 1 November 2026, #1711): under gdd-0.3, the ids of the cities with an enemy military
/// unit on their settlement hex (a halutz has no side and holds nothing, R-UNIT-001; Movement's reading of "the
/// enemy", as R-END-003's). Read in steps 5 and 6: no step after step 3 moves an enemy unit, so this is the turn's end;
/// a formation arriving at step 9 counts from the next turn.
/// Empty under every other ruleset.</summary>
public static HashSet<string> Held(Content c, GameState s)
{
var held = new HashSet<string>(StringComparer.Ordinal);
if (c.Ruleset != SaveGame.Gdd03Ruleset) return held;
var enemy = EnemyHexes(s);
foreach (var h in c.SettlementHexes)
if (s.Cities.ContainsKey(h.Id) && enemy.Contains((h.Q, h.R))) held.Add(h.Id);
return held;
}
/// <summary>The hexes an enemy military unit stands on (a halutz has no side, R-UNIT-001), <see cref="Held"/>'s
/// test; the ledger harvest reads it for fields (#1694).</summary>
internal static HashSet<(int Q, int R)> EnemyHexes(GameState s)
{
var enemy = new HashSet<(int Q, int R)>();
foreach (var u in s.Units.Values)
if (u.Side != "" && u.Side != Movement.PlayerSide) enemy.Add((u.Q, u.R));
return enemy;
}
/// <summary>R-MONEY-002: annual Money upkeep for the civilian places that exist at the start of step 7. Only completed
/// projects and camp sites count. The six rates are explicit content design values; all are 0 in the MVP. It counts
/// places, not people, so it runs on an initialized Historical ledger (the dark start, #1725 PR 7) and reads no
/// record; a synthetic or Open ledger stays refused (R-POP-002).</summary>
public static double AnnualUpkeep(Content c, GameState s, MvpRules r)
{
PopulationLedger.RefuseUnlessHistorical(s);
var total = s.Cities.Count * r.CityUpkeepPerYear!.Value;
foreach (var p in s.CityProjects.Values)
{
if (p.BuiltOn == null) continue;
if (p.Kind == "housing") total += r.HousingUpkeepPerYear!.Value;
else if (p.Kind == "industry") total += r.IndustryUpkeepPerYear!.Value;
else if (p.Kind == "transit_camp") total += r.TransitCampUpkeepPerYear!.Value;
}
var military = c.Cities.Sum(x => x.Facilities.Count(f => f == "military_camp"));
var hakhsharot = c.Cities.Sum(x => x.Facilities.Count(f => f == "hakhshara"));
foreach (var w in s.Sites.Values)
{
if (w.BuiltOn == null) continue;
var site = c.Sites.First(x => x.Id == w.Site);
if (site.Kinds.Contains("military_camp")) military++;
if (site.Kinds.Contains("hakhshara")) hakhsharot++;
}
return total + military * r.MilitaryCampUpkeepPerYear!.Value + hakhsharot * r.HakhsharaUpkeepPerYear!.Value;
}
/// <summary>R-CITY-004 (D-A5; D-D1, Q-HOUSE-1): no hard cap. Every refugee becomes a civilian, without a job, on the
/// housing step - as many as R-MIN-002's absorption scaling houses this turn (all of them at a neutral
/// multiplier); the people beyond the city's housing are its overflow (<see cref="Overflow"/>), still counted in it.
/// Residents are housed automatically (Q-HOUSE-4). Then R-CITY-009 (Q-JOBS-1): in ascending city id, a city whose job
/// default is on fills its free job slots from its people without a job, at no Attention cost.</summary>
public static void House(Content c, GameState s, MvpRules r, List<Cause> why)
{
PopulationLedger.RefuseAggregate(s);
// R-MIN-001, R-MIN-002 (D-H3; Q-MIN-1, Q-MIN-2): the Immigration minister's multiplier scales how many of the
// city's refugees are housed this turn; the count is floored (whole groups only) and the rest wait as
// refugees. At a neutral multiplier every refugee is housed, as R-CITY-004 says.
var m = EffectsSystem.GddSystemMultiplier(c, s, r, EffectsSystem.AbsorptionSystem);
foreach (var x in s.Cities.Values.ToList())
{
var absorbed = x.Refugees == 0 ? 0 : Math.Min(x.Refugees, (int)Math.Floor(x.Refugees * m));
var housed = absorbed == 0 ? x : x.WithCounts(x.Civilians + absorbed, x.Employed, x.Refugees - absorbed);
if (absorbed != 0)
why.Add(new Cause("city", x.Id, absorbed, FormattableString.Invariant($"{PlayerText.Settlement(c, x.Id)}: {Groups(absorbed)} of immigrants housed"), key: CauseKeys.ImmigrantsHoused, args: new[] { CauseKeys.Number(absorbed) }));
var work = MaxWorkers(s, housed);
if (housed.JobsDefault && work != housed.Employed)
{
why.Add(new Cause("city", x.Id, work - housed.Employed, FormattableString.Invariant($"{PlayerText.Settlement(c, x.Id)}: {Groups(work)} in work"), key: CauseKeys.WorkersAssigned, args: new[] { CauseKeys.Number(work) }));
housed = housed.WithCounts(housed.Civilians, work, housed.Refugees);
}
s.Cities[x.Id] = housed;
}
}
/// <summary>R-HOUSE-003 (Q-HOUSE-5): the people who take the city's housing: its civilians, craftsmen, recruits and groups
/// in training (a halutz group too, until it becomes a movable unit and leaves). Refugees wait for housing and are not
/// in it. Under gdd-0.1 Israeli formations retain their home city's housing after graduation, including when they move
/// or become veterans. Under gdd-0.3 they do not (#1703; 27M-18, owner-approved 1 November 2026: "Housed = civilians,
/// craftsmen, recruits and groups in training. Refugees and pioneer units are not housed."). Summed as integers, so the
/// order of the training groups and formations cannot change it.
/// With an initialized Historical ledger (the dark start, #1725 PR 7) it counts the ledger's records instead of these
/// fields: <see cref="LedgerHoused"/>.</summary>
public static int Housed(GameState s, City x)
{
if (s.PopulationLedger.IsHistorical) return LedgerHoused(s, x.Id);
var n = x.Civilians + x.Craftsmen + x.Recruits;
foreach (var k in s.Cohorts.Values) if (k.City == x.Id) n += k.Count;
return s.Ruleset == SaveGame.Gdd03Ruleset ? n : n + Soldiers(s, x);
}
/// <summary>R-HOUSE-003 on an initialized Historical ledger (#1725 PR 7): the city's housed records, one population unit
/// each, located in the city: its free civilians (census people, craftsmen, the opening field farmers in their host and
/// the training centre's teacher) and its trainees, the groups in training. Refugees wait for housing and soldiers are
/// not housed under gdd-0.3 (27M-18). A record with no city, such as a farmer at Nir Am or Nirim, which have no city
/// record, is housed in no city.</summary>
static int LedgerHoused(GameState s, string city)
{
var n = 0;
foreach (var u in s.PopulationLedger.Units)
if ((u.Status == PopulationStatus.FreeCivilian || u.Status == PopulationStatus.Trainee) && u.Location?.City == city) n++;
return n;
}
/// <summary>R-HOUSE-005 on an initialized Historical ledger: the city's refugee records.</summary>
static int LedgerRefugees(GameState s, string city)
{
var n = 0;
foreach (var u in s.PopulationLedger.Units)
if (u.Status == PopulationStatus.Refugee && u.Location?.City == city) n++;
return n;
}
/// <summary>R-HOUSE-003, R-UNIT-004 (Q-HOUSE-5): the Israeli formations the city houses, their strength summed:
/// recruits, veterans, guns and armoured cars whose home it is, wherever they stand (#1345, the panel's soldiers line).</summary>
public static int Soldiers(GameState s, City x)
{
var n = 0;
foreach (var u in s.Units.Values) if (u.Side == "israel" && u.HomeCity == x.Id) n += u.Strength;
return n;
}
/// <summary>R-HOUSE-002 (D-D1): the people beyond the city's housing, one capacity point a unit (Q-HOUSE-1); 0 when
/// they fit.</summary>
public static int Overflow(GameState s, City x) => Math.Max(0, Housed(s, x) - x.HousingCapacity);
/// <summary>The national indicator whose base the cities set (R-HOUSE-004).</summary>
public const string HousingIndicator = "housing";
/// <summary>R-HOUSE-004 (owner, 17 October 2026, Q-PR3-A option (a)): the people-weighted mean of the cities' housing
/// condition, each city weighed by its <see cref="Housed"/> people. It replaces the base of the national `housing`
/// indicator in the GDD loop; policy, map actions and events still act on top (EffectsSystem.Inner). Null when no city
/// with a condition houses anybody, and the indicator then reads model.yaml's base. The sum runs in ordinal city order
/// with integer weights, then one division.</summary>
public static double? HousingLevel(GameState s)
{
long people = 0;
var sum = 0.0;
foreach (var x in s.Cities.Values) // SortedDictionary, ordinal
{
if (x.Condition is not double condition) continue;
var n = Housed(s, x);
people += n;
sum += condition * n;
}
return people == 0 ? (double?)null : sum / people;
}
/// <summary>R-HOUSE-002 (D-D1, Q-HOUSE-1): after the housing step, each city with overflow loses
/// <c>overflow_condition_loss * overflow / housed</c> of its housing condition, never below 0. A city with none keeps
/// its condition; nothing in this rule raises it (housing projects do, Phase 3 PR 4). Each city reads only its own
/// counts (R-HOUSE-001: the condition is per city). Under gdd-0.3 the condition follows <see cref="SettleGdd03"/>'s
/// rules instead (#1703: the surcharge, 5 pp overflow and the cohesion term).</summary>
public static void UpdateCondition(Content c, GameState s, MvpRules r, List<Cause> why)
{
PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: R and P are then the ledger's (Housed, OwnPopulation)
var gdd03 = c.Ruleset == SaveGame.Gdd03Ruleset ? Gdd03HousingFormula.FromCatalogue(c.Gdd03Balance!) : null;
var people = gdd03 == null ? 0 : OwnPopulation(s);
double surcharge = 0.0, cohesion = 0.0;
foreach (var x in s.Cities.Values.ToList())
{
var over = Overflow(s, x);
if (gdd03 != null && x.Condition is double was)
{
// R is the city's housed people after this step's housing arrivals (27M-15; owner, 2 November 2026:
// "After housing arrivals (Recommended)"), for the surcharge, the overflow and the cohesion term alike.
var h = gdd03.EvaluateTurn(Housed(s, x), people, x.HousingCapacity, was);
surcharge += h.Surcharge;
cohesion += h.Cohesion;
if (h.ConditionAfter != was) s.Cities[x.Id] = x.WithCondition(h.ConditionAfter);
}
if (over == 0) continue;
if (gdd03 == null && x.Condition is double now)
s.Cities[x.Id] = x.WithCondition(Math.Max(0.0, now - r.OverflowConditionLoss!.Value * over / Housed(s, x)));
why.Add(new Cause("city", x.Id, over, FormattableString.Invariant($"{PlayerText.Settlement(c, x.Id)}: {Groups(over)} more than its homes hold"), key: CauseKeys.HousingShortage, args: new[] { CauseKeys.Number(over) }));
}
if (gdd03 != null) SettleGdd03(c, s, surcharge, cohesion, why);
}
/// <summary>R-HOUSE-002 and R-HOUSE-005 under gdd-0.3 (#1703), in its order: "Price the surcharge from pre-deterioration
/// condition, then deteriorate once, then apply cohesion once." <see cref="UpdateCondition"/> evaluates each city with a
/// condition by <see cref="Gdd03HousingFormula"/>, with its <see cref="Housed"/> people as R (after this step's arrivals
/// became civilians, 27M-15) and <see cref="OwnPopulation"/> as P:
/// - the surcharge, <c>R * max(0, money_threshold - c) * money_slope</c> Money from the condition before this turn's
/// deterioration. money_slope is 0.1 per population unit (owner, 2 November 2026: "Scale it to unit size
/// (Recommended)"; the option read: "0.1 per unit (as #2112 did for Industry), about 7.6 Money a turn at start.");
/// - overflow deterioration, <c>overflow_deterioration pp * max(0, R - capacity) / R</c> (5 pp), in place of gdd-0.1's
/// overflow_condition_loss, never below 0;
/// - the cohesion loss, <c>max_cohesion_loss * sum((R / P) * max(0, (cohesion_threshold - c') / cohesion_threshold))</c>
/// displayed points of Social cohesion, from the condition c' after deterioration.
/// There is no housing upkeep (27M-17, IL 0m), so no unpaid deterioration. The sums run in ordinal city order, in
/// double, the state type (<see cref="Gdd03HousingFormula.EvaluateTurn"/>). This settles them once: the surcharge as one
/// Money line, borrowed when the Treasury is short (R-MONEY-003), and the cohesion loss once on `morale` through its
/// permanent shift. The legacy `housing` to `morale` link adds nothing under gdd-0.3 (EffectsSystem.Apply).</summary>
static void SettleGdd03(Content c, GameState s, double surcharge, double cohesion, List<Cause> why)
{
if (surcharge > 0.0)
{
why.Add(new Cause("economy", "treasury", -surcharge, $"{PlayerText.Change(c, "treasury", -surcharge)} (housing surcharge)", key: CauseKeys.HousingSurcharge));
EconomySystem.PayNamedOrBorrow(c, s, surcharge, "for the housing surcharge", why, CauseKeys.Purpose.HousingSurcharge);
}
if (cohesion > 0.0)
{
var moved = EffectsSystem.Shift(c, s, CohesionIndicator, -cohesion / 100.0);
if (moved != 0)
why.Add(new Cause("city", CohesionIndicator, moved, $"{PlayerText.Change(c, CohesionIndicator, moved)} (housing condition)", key: CauseKeys.HousingCohesion));
}
}
/// <summary>#1722 (the city panel's housing readout): what <see cref="UpdateCondition"/> would settle for
/// <paramref name="city"/> on the state as it is now, under gdd-0.3 (R-HOUSE-005): the surcharge priced from the
/// current condition, the condition after the overflow deterioration and the cohesion shift on <c>morale</c>
/// (<c>-points / 100</c>, before the indicator's bounds), with the catalogue's two thresholds. It changes no state. The
/// turn's own housing step may differ: arrivals and finished repairs change R and the condition before it runs (step
/// order, R-HOUSE-005), and the cohesion term is settled once for all cities. Null outside gdd-0.3, for a city not in
/// the state or with no condition, and on a population-ledger state that is not Historical (UpdateCondition refuses
/// those).</summary>
public static HousingReadout? HousingOutlook(Content c, GameState s, string city)
{
if (c.Ruleset != SaveGame.Gdd03Ruleset || !s.Cities.TryGetValue(city, out var x) || !(x.Condition is double was)) return null;
if (s.PopulationLedger.IsInitialized && !s.PopulationLedger.IsHistorical) return null;
var gdd03 = Gdd03HousingFormula.FromCatalogue(c.Gdd03Balance!);
var h = gdd03.EvaluateTurn(Housed(s, x), OwnPopulation(s), x.HousingCapacity, was);
return new HousingReadout(h.Surcharge, h.ConditionAfter, -h.Cohesion / 100.0, gdd03.MoneyThreshold, gdd03.CohesionThreshold);
}
/// <summary><see cref="HousingOutlook"/>'s values: Surcharge in Money (Target treasury), ConditionAfter on the 0 to 1
/// scale, CohesionShift as a change of the <c>morale</c> indicator, and the two thresholds on the condition's scale.</summary>
public readonly struct HousingReadout
{
public double Surcharge { get; }
public double ConditionAfter { get; }
public double CohesionShift { get; }
public double MoneyThreshold { get; }
public double CohesionThreshold { get; }
public HousingReadout(double surcharge, double conditionAfter, double cohesionShift, double moneyThreshold, double cohesionThreshold)
{
Surcharge = surcharge; ConditionAfter = conditionAfter; CohesionShift = cohesionShift;
MoneyThreshold = moneyThreshold; CohesionThreshold = cohesionThreshold;
}
}
/// <summary>Social cohesion's indicator id (R-NAT-001), which the gdd-0.3 housing cohesion term moves (R-HOUSE-005).</summary>
public const string CohesionIndicator = "morale";
/// <summary>R-HOUSE-005 (#1703): P, all own population in units: every city's housed people and refugees, and the
/// strength of every player unit, wherever it stands: the Israeli formations and the halutz units, which have no side
/// (R-UNIT-001). Summed as integers. The owner was asked: "Should P be the 12 cities' people plus units (the PR today),
/// or the national population (649,400 at start, which cuts the loss by ~20%)?" and answered, 2 November 2026: "The 12
/// cities' people (Recommended)"; the option read: "As built: only the cities whose housing is tracked."
/// With an initialized Historical ledger (#1725 PR 7) it is the ledger's: every city's housed and refugee records plus
/// the active soldiers, so a record in no tracked city (a farmer at Nir Am or Nirim) is not in it. Halutz units are
/// not handled yet on a ledger game: no record is one at the dark start (R-HOUSE-003, R-HOUSE-005).</summary>
public static int OwnPopulation(GameState s)
{
var n = 0;
if (s.PopulationLedger.IsHistorical)
{
foreach (var x in s.Cities.Values) n += LedgerHoused(s, x.Id) + LedgerRefugees(s, x.Id);
foreach (var u in s.PopulationLedger.Units) if (u.Status == PopulationStatus.ActiveSoldier) n++;
return n;
}
foreach (var x in s.Cities.Values) n += Housed(s, x) + x.Refugees;
foreach (var u in s.Units.Values) if (u.Side == "" || u.Side == Movement.PlayerSide) n += u.Strength;
return n;
}
/// <summary>The effect source id of the cities' employed share (R-CITY-005): a GDD-only source of `morale`, Social
/// cohesion, read by the effects web after the turn's housing (D-A6). Phase 1's separate cohesion value is folded into it.</summary>
public const string EmployedShareSource = "employed_share";
/// <summary>R-CITY-005: employed over civilians and craftsmen, summed over all cities as integers (so city order cannot
/// change it); 1 with none, as nobody is out of work.</summary>
public static double EmployedShare(GameState s)
{
long civilians = 0, employed = 0;
foreach (var x in s.Cities.Values) { civilians += x.Civilians + x.Craftsmen; employed += x.Employed; }
return civilians == 0 ? 1.0 : (double)employed / civilians;
}
/// <summary>R-CITY-003 (D-A5, Q-ARRV-1): the turn's immigrants (the CBS series, aliyah.yaml) arrive as refugees, in whole
/// units, spread over the cities by <see cref="Apportion"/>. The cities count them from mvp.city_arrivals_from, the
/// census day their start values already include (Q-ARRV-3); PopulationSystem adds every arrival to the national head
/// count from the game's start, and the cities are the part of it placed in towns (R-CITY-008, Q-ARRV-2).
/// With an initialized Historical ledger (#1725 PR 7) each arrived unit is one refugee record instead, see
/// <see cref="LedgerArrive"/>; the aggregate city fields are not written.</summary>
public static void Arrive(Content c, GameState s, MvpRules r, DateTime next, List<Cause> why)
{
PopulationLedger.RefuseUnlessHistorical(s); // #1725 PR 7: the ledger's records are then the arrivals
var units = ArrivedUnits(c, s.Date, next, r.PeoplePerUnit);
if (units == 0) return;
var before = UnitsBy(c, s.Date, r.PeoplePerUnit);
var had = Apportion(c, before);
var share = Apportion(c, before + units);
var ledger = s.PopulationLedger.IsHistorical ? LedgerArrive(c, s, r, had, share) : null;
foreach (var kv in share)
{
var added = ledger == null ? kv.Value - had[kv.Key] : ledger.GetValueOrDefault(kv.Key);
if (added == 0) continue;
var x = s.Cities[kv.Key];
if (ledger == null) s.Cities[x.Id] = x.WithCounts(x.Civilians, x.Employed, x.Refugees + added);
why.Add(new Cause("city", x.Id, added, FormattableString.Invariant($"{PlayerText.Settlement(c, x.Id)}: {Groups(added)} of immigrants arrived and wait for homes"), key: CauseKeys.ImmigrantsWaiting, args: new[] { CauseKeys.Number(added) }));
}
}
/// <summary>The source key prefix of a CBS arrival record (#1725 PR 7): this prefix plus the city id. Its ordinal is
/// the unit's place in the city's cumulative <see cref="Apportion"/> share from mvp.city_arrivals_from, so a unit's key
/// depends only on the dates, never on the turn that brings it.</summary>
internal const string ArrivalPrefix = "cbs/";
/// <summary>R-CITY-003 on an initialized Historical ledger (#1725 PR 7; GDD Q11: "arrivals take new ids as refugees in a
/// city"): each of the turn's arrived units in <see cref="Apportion"/>'s split is one refugee record located in its city
/// (the region that lists it, R-POP-004), reception 0, no assignment, profession or tier. Keys are
/// <see cref="ArrivalPrefix"/> plus the city id, ordinals the city's units from <paramref name="had"/> to
/// <paramref name="share"/>, in city id order, so a replay of the turn adds nobody twice: an already registered key is
/// skipped (R-POP-001: a source stays registered after its id is lost). R-CITY-008: the records are the people, so
/// no aggregate city field is written. All or nothing: a refused record, or a city with no city record in the game,
/// adds none. Returns the records added per city.</summary>
static Dictionary<string, int> LedgerArrive(Content c, GameState s, MvpRules r, SortedDictionary<string, int> had, SortedDictionary<string, int> share)
{
var ledger = s.PopulationLedger;
if (ledger.PeoplePerUnit != r.PeoplePerUnit)
throw new InvalidOperationException("A ledger record is " + ledger.PeoplePerUnit.ToString(CultureInfo.InvariantCulture)
+ " people but an arrived unit is " + r.PeoplePerUnit.ToString(CultureInfo.InvariantCulture) + " (R-CITY-003, R-POP-001).");
var rows = new List<PopulationInventoryRow>();
var added = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var kv in share)
{
for (var ordinal = had[kv.Key]; ordinal < kv.Value; ordinal++)
{
if (ledger.HasArrived(ArrivalPrefix + kv.Key, ordinal)) continue;
if (!s.Cities.ContainsKey(kv.Key)) throw new InvalidOperationException("No city record for " + kv.Key + " (R-CITY-003).");
var region = c.PlayerRegions.AtLocation(kv.Key)?.Id
?? throw new InvalidOperationException("No region in regions.yaml for city " + kv.Key + " (R-POP-004).");
rows.Add(new PopulationInventoryRow(ArrivalPrefix + kv.Key, ordinal, new PopulationUnit(0, PopulationStatus.Refugee, 0,
new PopulationLocation(region, city: kv.Key), PopulationAssignment.Unassigned, CivilianProfession.None,
CivilianTier.None, 0, "", 0, PopulationEquipment.None)));
added[kv.Key] = added.GetValueOrDefault(kv.Key) + 1;
}
}
ledger.RegisterArrivals(rows);
return added;
}
/// <summary>R-CITY-003 (Q-ARRV-1): the cities' shares of their first <paramref name="units"/> arrived units, by id. The
/// weights are the cities' census people. Units are handed out one at a time, each to the city whose share of the
/// units so far most exceeds what it holds (the largest remainder), a tie to the lower id (ordinal). A fresh
/// largest-remainder split of each total could take a unit back from a city when the total grows (the Alabama paradox;
/// on the real cities at 7 units), so the split is built up from the first unit. Decimal, so exact on every runtime.</summary>
public static SortedDictionary<string, int> Apportion(Content c, int units)
{
var held = new SortedDictionary<string, int>(StringComparer.Ordinal);
foreach (var x in c.Cities) held[x.Id] = 0;
var weight = c.Cities.ToDictionary(x => x.Id, x => x.People!.Value);
var total = weight.Values.Sum();
for (int n = 1; n <= units; n++)
{
string? best = null;
var most = 0m;
foreach (var kv in held) // ordinal order, and only a larger remainder replaces: a tie stays with the lower id
{
var remainder = n * weight[kv.Key] - kv.Value * total; // (the share minus what it holds) times the total
if (best == null || remainder > most) { best = kv.Key; most = remainder; }
}
held[best!]++;
}
return held;
}
/// <summary>The whole units of <paramref name="peoplePerUnit"/> people that arrive in the cities in [from, to). Counted
/// from mvp.city_arrivals_from, floor(people by to) minus floor(people by from), so over any run of turns no unit is lost
/// or counted twice.</summary>
public static int ArrivedUnits(Content c, DateTime from, DateTime to, int peoplePerUnit) =>
UnitsBy(c, to, peoplePerUnit) - UnitsBy(c, from, peoplePerUnit);
/// <summary>The cities' whole units of arrivals from mvp.city_arrivals_from to <paramref name="t"/> (0 before it).</summary>
static int UnitsBy(Content c, DateTime t, int peoplePerUnit)
{
var origin = c.RulesAt(c.Eras[0].From).Mvp!.CityArrivalsFrom; // the same in every era (the loader checks it)
if (t <= origin) return 0;
var people = 0.0;
foreach (var kv in PopulationSystem.Arrivals(c, origin, t).OrderBy(k => k.Key, StringComparer.Ordinal)) people += kv.Value;
return (int)Math.Floor(people / peoplePerUnit);
}
}
}