Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Add isolated housing formula arithmetic (Refs #1703) (#1960)

Eyal Golan036fae6223ac
diff --git a/changelog.d/1703-housing-formula.md b/changelog.d/1703-housing-formula.md
new file mode 100644
index 000000000..2ce25e3ee
--- /dev/null
+++ b/changelog.d/1703-housing-formula.md
@@ -0,0 +1 @@
+- Add isolated housing formula arithmetic with explicit resident, condition and upkeep inputs for GDD 0.3 synthetic fixtures.
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index 3d4fd4db0..96d878e3f 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -116,10 +116,16 @@ R-CITY-007: A city starts with `civilians` = `people / people_per_unit` to the n
R-HOUSE-001: Each city has a housing condition from 0 to 1, an average over the city (D-D2, Q-HOUSE-2, owner, 15 October 2026). Every city starts at `mvp.housing_start_condition` (Q-START-3: one design value for all the cities, 0.35, `model.yaml`'s `housing` base). The condition is per city: one city's counts never change another's. It is in the state hash (R-LOOP-002).
+For R-HOUSE-001, the preceding legacy/gdd-0.1 wording remains unchanged. The inactive gdd-0.3 cross-reference is `Gdd03HousingFormula`, detached synthetic arithmetic with an explicit condition input, no initial condition or state commit (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:5-6@7ec122145`). It snapshots labelled Agreed/Default catalogue scalars, preserves the Default basis of overflow deterioration, and refuses missing, Deferred, unlabelled or malformed required scalars and incompatible catalogue identity. Condition is bounded to 0..1 after deterioration and each explicit project effect; repair uses the catalogue's condition-pp part without implementing repair cost, work or availability (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:13-62@7ec122145`, `:80-103`; `sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs:78-98@7ec122145`, `:119-141`). Source: `docs/gdd/cities.md:27@605277dfa511dc512562ececeb273b8393b21d35`, `"Project capacity/condition effects live in [balance](balance.md#project-catalogue), clamped to condition bounds."` (quoted verbatim from that pinned file; its balance.md is not in this repository) Initial-condition integration remains pending: the #1703 status comment of 27 October 2026 leaves initial-condition and resident-policy questions with #1668, "rather than becoming fallback values".
+
R-HOUSE-002: A city's overflow is `max(0, housed - housing_capacity)`, one capacity point housing one population unit (D-D1, Q-HOUSE-1, owner, 15 October 2026). On the housing step, after R-CITY-004 and before Social cohesion (D-A6), a city with overflow loses `overflow_condition_loss * overflow / housed` of its condition, never below 0; a city without overflow keeps its condition. `overflow_condition_loss` is 0.15, a design value. The loader requires both values, from 0 to 1. Overflow reaches Social cohesion through R-HOUSE-004 (a lower condition lowers the base of the national `housing` indicator) and the existing `homes_lift_morale` link (k 0.15) from `housing` into `morale`, which is Social cohesion (R-NAT-001); there is no direct overflow term (Q-HOUSE-1, decided by the owner 15 October 2026, plan:165 of `docs/superpowers/plans/2026-10-15-gdd-phase-3.md`: cohesion follows through the existing `housing` to `morale` link, "so it needs no number of its own"; the cohesion half was built after #728, merged as #857, owner 17 October 2026).
+For R-HOUSE-002, inactive gdd-0.3 synthetic arithmetic prices the surcharge as `SurchargeResidents * max(0, money_threshold - ConditionBefore) * money_slope`, then subtracts overflow and unpaid-upkeep losses and clamps condition. Overflow loss is `(overflow_deterioration / 100) * max(0, PreArrivalResidents - Capacity) / PreArrivalResidents`; unpaid loss is `(max_deterioration / 100) * (UpkeepDue - UpkeepPaid) / UpkeepDue`. Zero pre-arrival residents or zero upkeep due gives zero for the respective loss. The returned cohesion contribution is `max_cohesion_loss * (CohesionResidents / OwnPopulation) * max(0, (cohesion_threshold - ConditionAfter) / cohesion_threshold)`, zero with no own population. It is displayed points, not an indicator write or a national summation (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:65-85@7ec122145`; worked-number, distinct-count, post-deterioration and zero-denominator fixtures in `sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs:16-75@7ec122145`). Source: `docs/gdd/cities.md:29-35@605277dfa511dc512562ececeb273b8393b21d35`; #1703 says, "Price the surcharge from pre-deterioration condition, then deteriorate once, then apply cohesion once." These are returned calculations only: Money settlement (#1702), repairs (#1700), national indicator application and removal of duplicate legacy penalties (#1715), and monthly snapshot/commit-once timing (#1716) remain pending under the #1703 status comment; the preceding active rule is unchanged.
+
R-HOUSE-003: The people who take a city's housing (`housed`) are its civilians, its craftsmen, its recruits and its groups in training, a halutz group included until it becomes a movable unit. Halutz units do not (Q-HOUSE-5, owner, 15 October 2026). Refugees wait for housing and are not in it.
+For R-HOUSE-003, the inactive gdd-0.3 helper takes independently supplied surcharge, pre-arrival and cohesion resident counts plus own population; it selects no residents and substitutes none of those counts for another (`sim/Statecraft.Sim/Gdd03HousingFormula.cs:68-85@7ec122145`, `:107-125`; `sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs:39-47@7ec122145`). Negative counts, capacity or upkeep, overpayment, cohesion residents above total own population, and condition outside 0..1 are refused. A zero-population cohesion input therefore requires zero cohesion residents (`docs/gdd/cities.md:27,31@605277dfa511dc512562ececeb273b8393b21d35`). Source: `docs/gdd/cities.md:25@605277dfa511dc512562ececeb273b8393b21d35`, "A civilian resident without dedicated reception, teacher or military-training housing uses ordinary housing."; `docs/gdd/loop-switch.md:33` at that revision says, "use pre-arrival residents for overcrowding deterioration". Those are producer requirements, not resident-selection behavior implemented here. Live status selection (#1689), regions/approved housing locations (#1690/#1691) and which residents to count (#1668) remain pending under the #1703 status comment, which says, "Regional housing settlement is not yet implemented". The preceding legacy/gdd-0.1 resident set remains unchanged.
+
R-HOUSE-004: In the GDD loop the base of the national `housing` indicator is the people-weighted mean of the cities' housing condition, each city weighed by its housed people (R-HOUSE-003): `sum(condition * housed) / sum(housed)`. Policy effects, map actions and events still act on top, as on any indicator. Decided (owner, 17 Oct 2026, option (a) of Q-PR3-A, relayed on [#855 at 06:33Z](https://github.com/eyalgolan/statecraft-israel/pull/855#issuecomment-6230731177)): the national housing base is the people-weighted mean of city condition, with policy, map actions and events still applied on top. When no city houses anybody the mean is undefined, and the base is `model.yaml`'s. Capacity reaches the level through overflow and condition (R-HOUSE-002).
## City projects
diff --git a/sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs b/sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs
new file mode 100644
index 000000000..3f2f6daeb
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/Gdd03HousingFormulaTests.cs
@@ -0,0 +1,238 @@
+using Statecraft.Sim;
+using System.Globalization;
+
+public class Gdd03HousingFormulaTests
+{
+ // All counts, Money amounts and conditions below are TEST-ONLY SYNTHETIC inputs.
+ static Gdd03HousingFormula Formula() => Gdd03HousingFormula.FromCatalogue(
+ ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance ?? throw new InvalidOperationException("GDD 0.3 catalogue required"));
+
+ static Gdd03HousingInput Input(int surcharge = 10, int beforeArrival = 10,
+ int cohesion = 10, int population = 20, decimal capacity = 5m,
+ decimal condition = 0.40m, decimal due = 4m, decimal paid = 2m) =>
+ new Gdd03HousingInput(surcharge, beforeArrival, cohesion, population,
+ capacity, condition, due, paid);
+
+ // Each fixture changes one coefficient before the existing reader validates/snapshots it.
+ static Gdd03HousingFormula FormulaWithSyntheticScalar(string key, decimal value)
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance ?? throw new InvalidOperationException("GDD 0.3 catalogue required");
+ var row = c.Values[key];
+ row.Values[0] = value;
+ row.Note = "TEST-ONLY SYNTHETIC coefficient override: " + value.ToString(CultureInfo.InvariantCulture);
+ return Gdd03HousingFormula.FromCatalogue(c);
+ }
+
+ // Exact decimal arithmetic only; all divisions below terminate, so no tolerance is needed.
+ [Fact] public void SyntheticMoneyThresholdComesFromSuppliedCatalogue()
+ {
+ // R-HOUSE-001: catches moneyThreshold replaced by the shipped literal 0.50m.
+ const decimal threshold = 0.70m;
+ var f = FormulaWithSyntheticScalar("housing.money_threshold", threshold);
+ var expected = 10m * Math.Max(0m, threshold - 0.40m) * 1m;
+ Assert.Equal(expected, f.Evaluate(Input(condition: 0.40m)).SurchargeMoney);
+ }
+
+ [Fact] public void SyntheticMoneySlopeComesFromSuppliedCatalogue()
+ {
+ // R-HOUSE-001: catches moneySlope replaced by the shipped literal 1m.
+ const decimal slope = 2.5m;
+ var f = FormulaWithSyntheticScalar("housing.money_slope", slope);
+ var expected = 10m * Math.Max(0m, 0.50m - 0.40m) * slope;
+ Assert.Equal(expected, f.Evaluate(Input(condition: 0.40m)).SurchargeMoney);
+ }
+
+ [Fact] public void SyntheticCohesionThresholdComesFromSuppliedCatalogue()
+ {
+ // R-HOUSE-002: catches cohesionThreshold replaced by the shipped literal 0.25m.
+ const decimal threshold = 0.50m;
+ var f = FormulaWithSyntheticScalar("housing.cohesion_threshold", threshold);
+ var expected = 2m * (5m / 20m) * Math.Max(0m, (threshold - 0.125m) / threshold);
+ Assert.Equal(expected, f.Evaluate(Input(cohesion: 5, population: 20,
+ capacity: 10m, condition: 0.125m, due: 0m, paid: 0m)).CohesionLossPoints);
+ }
+
+ [Fact] public void SyntheticMaximumCohesionLossComesFromSuppliedCatalogue()
+ {
+ // R-HOUSE-002: catches maxCohesionLoss replaced by the shipped literal 2m.
+ const decimal maximumLoss = 3m;
+ var f = FormulaWithSyntheticScalar("housing.max_cohesion_loss", maximumLoss);
+ var expected = maximumLoss * (5m / 20m) * Math.Max(0m, (0.25m - 0.125m) / 0.25m);
+ Assert.Equal(expected, f.Evaluate(Input(cohesion: 5, population: 20,
+ capacity: 10m, condition: 0.125m, due: 0m, paid: 0m)).CohesionLossPoints);
+ }
+
+ [Fact] public void SyntheticOverflowRateComesFromSuppliedCatalogue()
+ {
+ // R-HOUSE-002: catches overflowPp replaced by the shipped literal 5m.
+ const decimal overflowPp = 12.5m;
+ var f = FormulaWithSyntheticScalar("housing.overflow_deterioration", overflowPp);
+ var expectedLoss = (overflowPp / 100m) * Math.Max(0m, 20m - 8m) / 20m;
+ var r = f.Evaluate(Input(beforeArrival: 20, capacity: 8m,
+ condition: 0.40m, due: 4m, paid: 4m));
+ Assert.Equal(expectedLoss, r.OverflowConditionLoss);
+ Assert.Equal(0.40m - expectedLoss, r.ConditionAfter);
+ }
+
+ [Fact] public void SyntheticUnpaidRateComesFromSuppliedCatalogue()
+ {
+ // R-HOUSE-002: catches unpaidPp replaced by the shipped literal 10m.
+ const decimal unpaidPp = 18m;
+ var f = FormulaWithSyntheticScalar("housing.max_deterioration", unpaidPp);
+ var expectedLoss = (unpaidPp / 100m) * ((10m - 2m) / 10m);
+ var r = f.Evaluate(Input(capacity: 10m, condition: 0.40m, due: 10m, paid: 2m));
+ Assert.Equal(expectedLoss, r.UnpaidConditionLoss);
+ Assert.Equal(0.40m - expectedLoss, r.ConditionAfter);
+ }
+
+ [Fact] public void SyntheticRepairEffectComesFromSuppliedCatalogue()
+ {
+ // R-HOUSE-001: catches repairPp replaced by the shipped literal 10m.
+ const decimal repairPp = 25m;
+ var c = ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance ?? throw new InvalidOperationException("GDD 0.3 catalogue required");
+ var row = c.Values["housing_repair"].Parts["condition_pp"];
+ row.Values[0] = repairPp;
+ row.Note = "TEST-ONLY SYNTHETIC repair effect: " + repairPp.ToString(CultureInfo.InvariantCulture);
+ var f = Gdd03HousingFormula.FromCatalogue(c);
+ var expected = Math.Min(1m, 0.40m + repairPp / 100m);
+ Assert.Equal(expected, f.RepairCondition(0.40m));
+ }
+
+ [Fact] public void PreDeteriorationPriceAndBothLossesHaveWorkedNumbers()
+ {
+ // R-HOUSE-001, R-HOUSE-002: price first, deteriorate once, return arithmetic only.
+ var r = Formula().Evaluate(Input());
+ Assert.Equal(1m, r.SurchargeMoney);
+ Assert.Equal(0.025m, r.OverflowConditionLoss);
+ Assert.Equal(0.05m, r.UnpaidConditionLoss);
+ Assert.Equal(0.325m, r.ConditionAfter);
+ Assert.Equal(0m, r.CohesionLossPoints);
+ Assert.Equal(7.5m, r.TotalConditionLossPp);
+ }
+
+ [Theory]
+ [InlineData("0.499", "0.01")]
+ [InlineData("0.50", "0")]
+ [InlineData("0.60", "0")]
+ public void SurchargeIsContinuous(string condition, string expected)
+ {
+ // R-HOUSE-001
+ Assert.Equal(decimal.Parse(expected, CultureInfo.InvariantCulture),
+ Formula().Evaluate(Input(condition: decimal.Parse(condition, CultureInfo.InvariantCulture))).SurchargeMoney);
+ }
+
+ [Fact] public void ExplicitBoundaryCountsAreNeverSubstitutedForEachOther()
+ {
+ // R-HOUSE-002, R-HOUSE-003: does not select residents or settle timing.
+ var r = Formula().Evaluate(Input(surcharge: 10, beforeArrival: 20,
+ cohesion: 5, population: 20, capacity: 15m, condition: 0.125m, due: 0m, paid: 0m));
+ Assert.Equal(3.75m, r.SurchargeMoney);
+ Assert.Equal(0.0125m, r.OverflowConditionLoss);
+ Assert.Equal(0.1125m, r.ConditionAfter);
+ Assert.Equal(0.275m, r.CohesionLossPoints);
+ }
+
+ [Fact] public void CohesionUsesPostDeteriorationConditionAndOwnPopulation()
+ {
+ // R-HOUSE-002: no extra direct overflow penalty or indicator mutation.
+ var f = Formula();
+ var r = f.Evaluate(Input(population: 10, condition: 0.26m, due: 0m, paid: 0m));
+ Assert.Equal(0.235m, r.ConditionAfter);
+ Assert.Equal(0.12m, r.CohesionLossPoints);
+ var a = f.Evaluate(Input(condition: 0.125m, capacity: 10m, due: 0m, paid: 0m));
+ var b = f.Evaluate(Input(surcharge: 5, beforeArrival: 5, cohesion: 5,
+ condition: 0m, capacity: 5m, due: 0m, paid: 0m));
+ Assert.Equal(1m, a.CohesionLossPoints + b.CohesionLossPoints);
+ }
+
+ [Fact] public void ZeroDenominatorsAndFullPaymentHaveNoLoss()
+ {
+ // R-HOUSE-002
+ var r = Formula().Evaluate(Input(surcharge: 0, beforeArrival: 0, cohesion: 0,
+ population: 0, capacity: 0m, condition: 0m, due: 0m, paid: 0m));
+ Assert.Equal(0m, r.OverflowConditionLoss);
+ Assert.Equal(0m, r.UnpaidConditionLoss);
+ Assert.Equal(0m, r.CohesionLossPoints);
+ Assert.Equal(0m, r.SurchargeMoney);
+ Assert.Equal(0m, Formula().Evaluate(Input(due: 4m, paid: 4m)).UnpaidConditionLoss);
+ Assert.Equal(0.075m, Formula().Evaluate(Input(due: 4m, paid: 1m)).UnpaidConditionLoss);
+ Assert.Equal(0m, Formula().Evaluate(Input(beforeArrival: 0, cohesion: 0, population: 0,
+ condition: 0m)).CohesionLossPoints);
+ }
+
+ [Fact] public void ConditionClampsAfterDeteriorationAndEachExplicitEffect()
+ {
+ // R-HOUSE-001: arithmetic only, no project, payment or initial condition.
+ var f = Formula();
+ Assert.Equal(0m, f.Evaluate(Input(condition: 0.01m, paid: 0m)).ConditionAfter);
+ Assert.Equal(1m, f.RepairCondition(0.95m));
+ Assert.Equal(0m, f.ApplyConditionEffect(0.04m, -0.10m));
+ Assert.Equal(0.90m, f.ApplyConditionEffect(f.RepairCondition(0.95m), -0.10m));
+ Assert.Equal(0.14m, f.RepairCondition(0.04m));
+ }
+
+ [Theory]
+ [InlineData(40, 20)]
+ [InlineData(1, 0)]
+ public void RegionalCohesionResidentsCannotExceedOwnPopulation(int residents, int population)
+ {
+ // R-HOUSE-002: a region's ordinary residents are part of total own population.
+ Assert.Throws<ArgumentOutOfRangeException>(() => Formula().Evaluate(
+ Input(cohesion: residents, population: population, condition: 0m, due: 0m, paid: 0m)));
+ }
+
+ [Fact] public void InvalidExplicitInputsAreRejectedWithoutState()
+ {
+ var f = Formula();
+ foreach (var input in new[] { Input(surcharge: -1), Input(beforeArrival: -1),
+ Input(cohesion: -1), Input(population: -1), Input(capacity: -1m),
+ Input(condition: -0.01m), Input(condition: 1.01m), Input(due: -1m),
+ Input(paid: -1m), Input(paid: 5m), Input(due: 0m, paid: 1m) })
+ Assert.Throws<ArgumentOutOfRangeException>(() => f.Evaluate(input));
+ Assert.Throws<ArgumentNullException>(() => f.Evaluate(null!));
+ Assert.Equal(1m, f.Evaluate(Input()).SurchargeMoney);
+ }
+
+ [Theory]
+ [InlineData("he-IL")][InlineData("en-US")]
+ public void CatalogueReaderAndArithmeticAreCultureIndependent(string culture)
+ {
+ var old = CultureInfo.CurrentCulture;
+ var oldUi = CultureInfo.CurrentUICulture;
+ try
+ {
+ CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
+ CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
+ Assert.Equal("0.325", Formula().Evaluate(Input()).ConditionAfter.ToString(CultureInfo.InvariantCulture));
+ }
+ finally { CultureInfo.CurrentCulture = old; CultureInfo.CurrentUICulture = oldUi; }
+ }
+
+ [Theory]
+ [InlineData("missing")][InlineData("deferred")][InlineData("shape")]
+ [InlineData("zero")][InlineData("negative")][InlineData("basis")]
+ public void ReaderRefusesMissingDeferredOrMalformedScalar(string failure)
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance ?? throw new InvalidOperationException("GDD 0.3 catalogue required");
+ var row = c.Values["housing.cohesion_threshold"];
+ if (failure == "missing") c.Values.Remove("housing.cohesion_threshold");
+ if (failure == "deferred") { row.Basis = "Deferred"; row.Values.Clear(); row.Expression = "unresolved"; }
+ if (failure == "shape") row.Values.Add(1m); // TEST-ONLY SYNTHETIC invalid shape
+ if (failure == "zero") row.Values[0] = 0m;
+ if (failure == "negative") row.Values[0] = -1m;
+ if (failure == "basis") row.Basis = "Unknown";
+ Assert.Throws<ContentException>(() => Gdd03HousingFormula.FromCatalogue(c));
+ }
+
+ [Fact] public void ReaderSnapshotsCatalogueAndPreservesDefaultProvenance()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot()).Gdd03Balance ?? throw new InvalidOperationException("GDD 0.3 catalogue required");
+ var f = Gdd03HousingFormula.FromCatalogue(c);
+ Assert.Equal("Default", f.OverflowBasis);
+ c.Values["housing.overflow_deterioration"].Values[0] = 99m; // TEST-ONLY SYNTHETIC mutation
+ Assert.Equal(0.025m, f.Evaluate(Input()).OverflowConditionLoss);
+ c.Ruleset = SaveGame.GddRuleset;
+ Assert.Throws<ContentException>(() => Gdd03HousingFormula.FromCatalogue(c));
+ Assert.Throws<ArgumentNullException>(() => Gdd03HousingFormula.FromCatalogue(null!));
+ }
+}
diff --git a/sim/Statecraft.Sim/Gdd03HousingFormula.cs b/sim/Statecraft.Sim/Gdd03HousingFormula.cs
new file mode 100644
index 000000000..c0430de73
--- /dev/null
+++ b/sim/Statecraft.Sim/Gdd03HousingFormula.cs
@@ -0,0 +1,146 @@
+using System;
+
+namespace Statecraft.Sim
+{
+ /// <summary>Unwired arithmetic for #1703 synthetic fixtures. No state, resident selection,
+ /// initial condition, snapshot timing, Money settlement or indicator commit.</summary>
+ internal sealed class Gdd03HousingFormula
+ {
+ readonly decimal conditionMax, moneyThreshold, moneySlope, cohesionThreshold;
+ readonly decimal maxCohesionLoss, overflowPp, unpaidPp, repairPp;
+ internal string OverflowBasis { get; }
+
+ Gdd03HousingFormula(Gdd03BalanceCatalogue c)
+ {
+ // content/gdd03-balance.yaml:226-253; GDD balance.md:100-105 at 605277df.
+ conditionMax = Scalar(c, "housing.condition_max", true);
+ moneyThreshold = Scalar(c, "housing.money_threshold", true);
+ moneySlope = Scalar(c, "housing.money_slope", false);
+ cohesionThreshold = Scalar(c, "housing.cohesion_threshold", true);
+ maxCohesionLoss = Scalar(c, "housing.max_cohesion_loss", false);
+ overflowPp = Scalar(c, "housing.overflow_deterioration", false);
+ unpaidPp = Scalar(c, "housing.max_deterioration", false);
+ OverflowBasis = c.Values["housing.overflow_deterioration"].Basis;
+ if (conditionMax != 1m || moneyThreshold > conditionMax || cohesionThreshold > conditionMax)
+ throw Invalid("housing.condition_max", "condition is a fraction in [0,1]; thresholds must lie within it");
+ if (!c.Values.TryGetValue("housing_repair", out var repair) || repair == null
+ || repair.Basis != "Agreed" || repair.Parts == null || repair.Values == null
+ || repair.Values.Count != 0 || !string.IsNullOrEmpty(repair.Expression)
+ || !repair.Parts.TryGetValue("condition_pp", out var effect))
+ throw Invalid("housing_repair", "requires agreed repair condition part");
+ // content/gdd03-balance.yaml:683-687. No repair cost/work/availability policy here.
+ repairPp = Number(effect, "housing_repair.parts.condition_pp", false);
+ }
+
+ internal static Gdd03HousingFormula FromCatalogue(Gdd03BalanceCatalogue catalogue)
+ {
+ if (catalogue == null) throw new ArgumentNullException(nameof(catalogue));
+ if (catalogue.Ruleset != SaveGame.Gdd03Ruleset || catalogue.Values == null)
+ throw Invalid("housing", "requires explicit gdd-0.3 catalogue");
+ return new Gdd03HousingFormula(catalogue);
+ }
+
+ static ContentException Invalid(string key, string reason) =>
+ new ContentException(Gdd03BalanceCatalogue.FileName, "values." + key, reason);
+
+ static decimal Scalar(Gdd03BalanceCatalogue c, string key, bool positive)
+ {
+ if (!c.Values.TryGetValue(key, out var row)) throw Invalid(key, "required housing scalar");
+ return Number(row, key, positive);
+ }
+
+ static decimal Number(Gdd03DesignValue row, string key, bool positive)
+ {
+ if (row == null || (row.Basis != "Agreed" && row.Basis != "Default")
+ || row.Values == null || row.Values.Count != 1 || row.Parts == null
+ || row.Parts.Count != 0 || !string.IsNullOrEmpty(row.Expression)
+ || string.IsNullOrWhiteSpace(row.Note))
+ throw Invalid(key, "requires one labelled Agreed/Default scalar; Deferred is not a number");
+ var value = row.Values[0];
+ if (positive ? value <= 0m : value < 0m)
+ throw Invalid(key, positive ? "must be positive" : "must be nonnegative");
+ return value;
+ }
+
+ internal Gdd03HousingResult Evaluate(Gdd03HousingInput input)
+ {
+ if (input == null) throw new ArgumentNullException(nameof(input));
+ if (input.SurchargeResidents < 0 || input.PreArrivalResidents < 0
+ || input.CohesionResidents < 0 || input.OwnPopulation < 0
+ || input.CohesionResidents > input.OwnPopulation || input.Capacity < 0m
+ || input.UpkeepDue < 0m || input.UpkeepPaid < 0m || input.UpkeepPaid > input.UpkeepDue)
+ throw new ArgumentOutOfRangeException(nameof(input), "counts/capacity/upkeep must be nonnegative; regional residents cannot exceed own population; paid cannot exceed due");
+ ValidateCondition(input.ConditionBefore);
+ // GDD cities.md:29,33,35; loop-switch.md:29,33 at 605277df.
+ // Counts are independently supplied; this helper makes no timing/status decision.
+ var surcharge = input.SurchargeResidents * Math.Max(0m, moneyThreshold - input.ConditionBefore) * moneySlope;
+ var overflow = input.PreArrivalResidents == 0 ? 0m :
+ (overflowPp / 100m) * Math.Max(0m, input.PreArrivalResidents - input.Capacity) / input.PreArrivalResidents;
+ var unpaid = input.UpkeepDue == 0m ? 0m :
+ (unpaidPp / 100m) * ((input.UpkeepDue - input.UpkeepPaid) / input.UpkeepDue);
+ var after = Clamp(input.ConditionBefore - overflow - unpaid);
+ // GDD cities.md:31,33. Contribution in displayed points, not indicator storage.
+ var cohesion = input.OwnPopulation == 0 ? 0m : maxCohesionLoss
+ * ((decimal)input.CohesionResidents / input.OwnPopulation)
+ * Math.Max(0m, (cohesionThreshold - after) / cohesionThreshold);
+ return new Gdd03HousingResult(surcharge, overflow, unpaid, after, cohesion);
+ }
+
+ // Explicit single project-effect arithmetic; caller owns command/payment/application-once.
+ internal decimal ApplyConditionEffect(decimal condition, decimal deltaFraction)
+ {
+ ValidateCondition(condition);
+ // Avoid overflow even for extreme explicit effects before clamping.
+ if (deltaFraction >= conditionMax - condition) return conditionMax;
+ if (deltaFraction <= -condition) return 0m;
+ return condition + deltaFraction;
+ }
+
+ internal decimal RepairCondition(decimal condition) => ApplyConditionEffect(condition, repairPp / 100m);
+ decimal Clamp(decimal condition) => Math.Max(0m, Math.Min(conditionMax, condition));
+ void ValidateCondition(decimal condition)
+ {
+ if (condition < 0m || condition > conditionMax)
+ throw new ArgumentOutOfRangeException(nameof(condition), "explicit condition must be within catalogue bounds");
+ }
+ }
+
+ /// <summary>Caller-selected boundary counts. No field has a gameplay default.</summary>
+ internal sealed class Gdd03HousingInput
+ {
+ internal int SurchargeResidents { get; }
+ internal int PreArrivalResidents { get; }
+ internal int CohesionResidents { get; }
+ internal int OwnPopulation { get; }
+ internal decimal Capacity { get; }
+ internal decimal ConditionBefore { get; }
+ internal decimal UpkeepDue { get; }
+ internal decimal UpkeepPaid { get; }
+
+ internal Gdd03HousingInput(int surchargeResidents, int preArrivalResidents, int cohesionResidents,
+ int ownPopulation, decimal capacity, decimal conditionBefore, decimal upkeepDue, decimal upkeepPaid)
+ {
+ SurchargeResidents = surchargeResidents; PreArrivalResidents = preArrivalResidents;
+ CohesionResidents = cohesionResidents; OwnPopulation = ownPopulation; Capacity = capacity;
+ ConditionBefore = conditionBefore; UpkeepDue = upkeepDue; UpkeepPaid = upkeepPaid;
+ }
+ }
+
+ internal sealed class Gdd03HousingResult
+ {
+ internal decimal SurchargeMoney { get; }
+ internal decimal OverflowConditionLoss { get; }
+ internal decimal UnpaidConditionLoss { get; }
+ internal decimal TotalConditionLossPp => (OverflowConditionLoss + UnpaidConditionLoss) * 100m;
+ internal decimal ConditionAfter { get; }
+ internal decimal CohesionLossPoints { get; }
+
+ internal Gdd03HousingResult(decimal surchargeMoney, decimal overflowConditionLoss,
+ decimal unpaidConditionLoss, decimal conditionAfter, decimal cohesionLossPoints)
+ {
+ SurchargeMoney = surchargeMoney; OverflowConditionLoss = overflowConditionLoss;
+ UnpaidConditionLoss = unpaidConditionLoss; ConditionAfter = conditionAfter;
+ CohesionLossPoints = cohesionLossPoints;
+ }
+ }
+}