A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Release v0.3.2: version 0.3.2 and the changelog (#2071)
Eyal Goland23fa67cefc7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4cb33c3bf..af1e41cee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,7 +8,281 @@ checks this (see `CONTRIBUTING.md`).## [Unreleased]+## [0.3.2] - 2026-10-31++### Added- Add the two owner-approved follow-up cards for the Jerusalem demilitarisation and Rafah roads, in English and Hebrew; both remain drafts pending human review (Refs #939).+- The HUD holds at the Settings screen's 125% and 150% UI scales (#40): below the smallest window the 100% layout is+ tested at (HudPresenter's new hud-tight, set from the panel's logical size; small phone windows reach it too) the+ bar's rows, the icon column and the panels tighten; on the tight three-row window the icon column becomes a row of the+ phone's 60 px discs under the bar (at least 24 px on screen down to 375x667) and a screen takes the window like a+ mobile modal, with the card's backdrop leaving the row's discs clear. The decision card starts right of the tight+ column; the info panel is a scrolling panel capped clear of the bar and the column, and on a phone at 125% or 150% it+ stands above the minimap at the window's width; the Cabinet's side column slims so+ the seats list keeps its room; and the small text keeps its 12 px on-screen floor at every size. The seven layout+ suites that failed at 125%/150% now run at all three scales.+- At 150% on short windows the Cabinet scroll shows seat cards before the house and legend; on phones at 150% the+ half circle fits its column. Desktop half circles and the 100%/125% Cabinet order keep their existing layout.+- The decision card's body scrolls as one (#1853): the text and the options with their effect lines sit in one scroll+ between the pinned head and the pinned foot, so Hide stays inside the card at 150%. A card that fits shows no scroll+ bar, Tab onto an option scrolls it into view, and a new card opens at the top of its text.+- The unit card's subtitle now shows a sourced Hebrew number line beside the English one (#1219 item 2): the 12+ Israeli brigades ("חטיבה 1" … "חטיבה 12", the Palmach trio marked "הפלמ״ח"), the 101 fighter squadron, INS+ Haganah and INS Wedgwood ("קורבטה, הוכנסה לשירות ב־1948") and the five other armies each carry a `number_he`+ line from a checked he.wiki source (agent-checked 2026-10-26, quoted in the file). Two rows are skipped with+ reasons: `iraqi` (he.wiki composition conflict) and `lebanese` (English phrasing rests on an unread Glubb+ snippet). The new strings join the native-speaker queue in `docs/review-queue.md` (#564). Goldens did not move.+- Select pioneer groups from a hex list or project link to see their track, location and work, and return idle groups to civilian life. Existing project and city row actions remain available.+- A hard event card, `reparations_vote` (#1564): the Knesset's vote of 9 January 1952 on direct talks with West+ Germany over reparations, tagged `holocaust`. It reaches the player on 15 December 1951, with three options, the+ historical vote to negotiate and two debated alternatives (reject any talks; a referendum first), each with a small+ design cost. Its header photograph is Benno Rothenberg's police barriers near the Knesset, January 1952 (CC BY 4.0,+ sensitive). The owner approved the card and options, the photograph and the costs on 25 October 2026 ("Approve all+ three"), so it is sensitivity-reviewed (refs #1564, #1575).+ `Hash1952`, `mvp-end` and `scenario-mvp-defeat` move.+- New event card: the defence of Degania and where the guns go, 19-20 May 1948 (the recorded choice: the 65 mm+ mountain guns to the Jordan Valley), with Moshe Marlin Levin's frame from Degania Alef (catalogue-dated 20 May 1948, CC BY 4.0,+ sensitive: true; the vehicle's identification is flagged for review). The owner approved the card and its+ photograph on 24 October 2026, so it is sensitivity-reviewed (refs #1565, #1568, #28).+- Events: an optional `order` (default 0) decides between the cards of the same date on one turn, before the id+ (R-EVT-006). `degania_defence` has `order: 1`, so One Army still opens the game and Degania comes second (owner,+ 24 October 2026, #1568: "One Army first").+- A language offered to the player must name itself: `Translations.CheckDeclaredLanguage` refuses a+ `translations/<lang>/ui.yaml` with no `ui.lang`, and one whose `ui.lang` names a different language from its+ directory (#1606). The second is the case worth the check — a `ui.yaml` copied from another language with its code+ left behind passes every shape check, and `ui.lang` is what the player reads to pick the Hebrew face and the+ language branches in `EventCardPresenter` and `SharePresenter`, so the failure is silently the wrong language+ rather than an error. Documented in `docs/translations.md`; no player code changes yet.+- A fast one finger swipe now pans the map once by its travel past the tap threshold, even if it ends before the next frame. Ella's tap fix already keeps the swipe from selecting anything. A swipe that goes out past the threshold and back before the next frame is a pan too, and selects nothing.+- A confirm step for ordering a unit onto a friendly unit or a city by touch or keyboard (#1661, owner's ruling of+ 26 October 2026). With a unit selected, picking a hex that holds another of your units, or a city, still selects it+ as before, and also offers "Send <unit> to <place>" for the unit you had selected; taking it moves that unit. The+ offer goes away once it is stale: another selection, a new turn, or a screen opening. Mouse right-click ordering is+ unchanged. The Hebrew wording is native-review-pending.+- Left-button map drags now use the camera's per-press 30 px onset and UI-origin latch, matching right-button drags without replaying held travel (#1661, #998). This builds on Ella Sharakanski's left-drag support in #1791.+- Skip the Attention lesson in the gdd-0.3 opening tour while preserving its remaining steps and the full legacy/gdd-0.1 tour.+- Add the gdd-0.3 population identity foundation: immutable records, a validated ledger, identity-aware scale, canonical state and synthetic fixture initialization. Production population, Food and command/replay integration remain held; legacy and gdd-0.1 behavior and shipped content are unchanged.+- Add the gdd-0.3 gameplay-region geography contract, effective-map validation and immutable regional fixture pools using the existing population ledger. Keep production initialization inactive and preserve the legacy/gdd-0.1 content boundary. Regional commands, replay and production authoring remain separate work.+- Add isolated population fixture assignments with atomic capacity checks and typed Industry rate quotations.+- Refs #1693: add internal, fixture-only civilian profession helpers for actual-work XP, next-turn promotion, matching-course preservation and Agreed catalogue quotes. Production integration and payments remain held; legacy/gdd-0.1 behavior and content are unchanged.+- Add typed farming rates and a detached synthetic staffed-field output evaluator for GDD 0.3 groundwork.+- Add a synthetic immigration manifest model and content validation contract for GDD 0.3 fixtures.+- Refuse synthetic reception evaluation when the supplied duration differs from the initialized population ledger, including civilian eligibility checks.+- Add isolated synthetic reception fixtures for dedicated bed allocation, ordinary progress and civilian eligibility.+- Refs #1697: add an internal, fixture-only gdd-0.3 training centre course lifecycle (start, counted course turns, cancel) on the population ledger. Graduation timing and the other open design points are refused as Deferred; no real centre, payment or game caller is added, and legacy/gdd-0.1 behaviour and content are unchanged.+- Add isolated GDD 0.3 craftsman catalogue and course/work tick arithmetic for synthetic fixtures.+- Add a typed military balance catalogue contract and a synthetic equipment-conservation specification for GDD 0.3.+- Add a typed GDD 0.3 catalogue view for settled city project costs, work, effects and upkeep, isolated from gameplay.+- Add an isolated synthetic arms workshop cycle contract with catalogue pricing and explicit reservations.+- Add isolated housing formula arithmetic with explicit resident, condition and upkeep inputs for GDD 0.3 synthetic fixtures.+- Refs #1704: add an internal pure Food arithmetic foundation with synthetic unit tests. No shipping call site or turn integration; existing Food paths remain unchanged.+- Add inactive synthetic combat catalogue validation and contract fixtures for #1706 (slices 0/1 only). No strength calculation or combat activation; runtime rules and shipped content remain unchanged.+- Add an isolated synthetic captivity identity and surrender-provenance record contract.+- Add an inactive synthetic absorption boundary contract using catalogue thresholds and explicit settled facts.+- Add an internal synthetic monthly-context contract for #1716; no game activation or resolver integration.+- Add isolated gdd-0.3 map authoring schema, source document and blocking diagnostics infrastructure (refs #1721). Domain integration and canonical export remain unavailable; legacy map files are unchanged.+- The default map shows the calm "under attack" look (grey smoke, a low fire glow, a slowly pulsing red border) on every+ hex the turn's attacks hit, for as long as the turn report is open (#1878). It reads the sim's engagement lines and+ changes nothing in the rules.+- The start screen offers the language before you play: "English" and "עברית", each in its own language, with the one+ in use marked. A choice switches the game at once, keeps the start screen up and is the same choice Settings shows and+ keeps; "?lang=he" still wins for that visit (#2054).+- Keep the top bar as main; show Arms in Defence and Food/Arms stocks, turn changes and existing causes in the report and Why. Preserve queued Arms purchases. Refs #731.+- The two alternate cards from #939, `jerusalem_demilitarisation_guard` and `rafah_force_pressure`, are signed off by the+ owner (`reviewed_by`, 28 October 2026), so the release gate no longer refuses them. Their status stays `draft`; native+ Hebrew approval is not asserted. No text, effect or date changed.+- Dragging the map with the left mouse button pans it, the way map apps do (#998; owner's ruling of 22 October 2026).+ A plain left click still selects the hex and gives its orders. The pan starts only once the press leaves the click's+ 30 px slop, so a click never nudges the map, and a drag selects nothing. The click is decided on the release rather+ than the press — a press cannot be known to be a drag until it moves — and is still queued once per physical press,+ so each click acts exactly once. Right-drag, the touch gestures and the keyboard are unchanged.+- Ignore a camera-render callback retained after its unit flag has been destroyed.+- Add fixture regression coverage for workshop worker identity across paid cycles and the unresolved housing-repair parent gate; live rules stay unchanged.+- Generate the nine inactive GDD 0.3 design-region hex lists deterministically from their approved Mandate sub-district coverage, while retaining unresolved place bindings for human review.+- Added synthetic monthly-context regressions rejecting captured and transit pre-arrival residents while preserving constructible opening records.+- Props for the opt-in hex-tile map, still presentation only and off by default: 20 AI-made 3D props by Tal Heuberger+ (Higgsfield, Tripo H3.1) fill the stand-ins of the Arab village (minaret, prickly pear), Jaffa (clock tower, sea+ minaret, belfry), the coastal dunes (scrub), the desert edge (Bedouin tent) and the Judean highlands (garrigue), and+ three new tiles use the rest: a railway halt with a packing house, coastal ruins with a landing stage, and a village+ mill with threshing floors and terraces. The props stream after the first frame from a bundle of their own, only+ with `?hex-tiles` on, so the default download does not grow. `HexSandboxImport.RunHiggsfield` imports a manifest of+ such props (refs #18).+- Each option on an event card lists what it does under its label, in English and Hebrew: one line per effect, from the+ simulation's preview (#1125, Refs #811). The option's label, price and selection are unchanged.+- The end report carries the score's parts (objective points, timing bonuses, prisoner points) beside the total, read from the final state; no screen shows them yet (Refs #812).+- The end screen can show a cause's sourced history note under its line (Q-DEF-4 (b)); a cause without a note goes+ straight from its line to the score. The armistice note for a war loss is held out of the strings until the person's+ check of the history note is recorded, so no ending shows a note yet (Refs #812).+- The end screen shows the prisoners returned (Q-END-3): one line, "Prisoners returned:" and the count in people as the+ Defence screen counts them, only when some prisoners went home. The end report carries the count (#812).+- Keep nightly managed gates and compiler shutdown under the shared machine lock, with node reuse and shared+ compilation disabled.+- Record the nightly draft release ID before uploads, refuse cleanup of a different release, and retry a recorded failed Latest recovery before the next run proceeds.+- Nightly builds: every night at 03:00 (Israel time) the newest `main` is built, checked against the build that is live+ and, only if every check passes, published as a GitHub pre-release that the website's demo serves (`docs/RELEASING.md`,+ "Nightly builds"). itch.io uploads follow once the automated save test passes.+- Preserve the completed gzip player before Unity builds the Pages variant, so Bee cannot retire files needed by packaging and browser gates. Existing release, source-cleanliness and publication gates remain in place.+- Record the approved regional design associations and capital choices separately from historical evidence. Retain unresolved geometry, control and camp-footprint checks; stage schema adaptation and named-place acceptance fixtures while regional activation remains off under gdd-0.3.+- Add production-command regression coverage for qualification localization keys and arguments; game behavior is unchanged.+- The Arab Liberation Army's token shows Tal Heuberger's ALA infantry as its third figure, beside two of the original+ irregulars (C09), as the owner chose on 27 October 2026 after signing off all 19 of Tal Heuberger's generated models+ (#756). The figure streams after the first frame in a bundle of its own, opened after the people's; the token still+ waits only for C09, and keeps two figures if the new bundle is missing. Goldens did not move.+- Tal Heuberger's Bedouin civilian and enclosed striped Bedouin tent stand in the Bedouin camp areas (the owner signed+ off all 19 of Tal Heuberger's generated models on 27 October 2026, #756): the figure at up to three of the camels'+ served camp areas, the tent at up to three Bedouin-area anchors on clear ground apart from the code-built camps'+ plots, whose tents stay as they are. Both models stream after the first frame, each in a bundle of its own. Goldens+ did not move.+- The Egyptian Expeditionary Force is on the map, wearing Tal Heuberger's Egyptian infantry figure (the owner signed+ off all 19 of Tal Heuberger's generated models on 27 October 2026, #756). It is one token: in the normal game the+ force's sim unit, from Gaza on 15 May 1948; in the legacy loop its row's dated anchors, at the first truce the forward+ base at Isdud (the rear base at Majdal stays in the row and on the card). The figure streams after the first frame in+ a bundle of its own, opened after the people's, so the first download does not grow. Goldens did not move.+- The Lebanese army is on the map at al-Malikiyya from 6 June to 8 July 1948, drawn with Tal Heuberger's Lebanese regular+ (owner, 28 October 2026: "6 Jun to 8 Jul (Recommended)"; sources: Dupuy p. 47 and the JTA bulletins of 7 and 8 June).+ It has no sim unit: its token is map-only in both loops (owner, 27 October 2026: "Map-only token (Recommended)") and+ never moves or fights. The figure streams after the first frame in a bundle of its own. Goldens did not move.+- Keep internal decision references out of the Lebanese unit card in English and Hebrew; retain the source and unresolved checks in its data record.+- Refresh unit figure keep-clear bounds after model streaming or retirement, including when the camera stays still, and avoid reading retired mesh components.+- Hebrew wording: a captured place that Israel holds reads "מוחזק" and "תקופת ההחזקה" in the Why panel and the turn+ report, never כיבוש or שחרור, as the strings file's own rule says; the Jerusalem demilitarisation and Rafah cards ask+ "על {prime_minister} להחליט" like the other cards; a finished city project reads "סיום"; the pioneer card says+ "משושה" like every other hex string; and the Degania card writes מ״מ with gershayim.++### Fixed+- Stream Tal Heuberger’s original models for the map views that need them, retire generated consumers before releasing sources, and reacquire on a revisit. Preserve fallback while loading and retained shared road, train, wildlife and hex-board ownership. (Refs #1273)+- Use explicit owner-approved production policy with diagnostics off by default; keep the existing unit appearance rules and correct large-coordinate ground-focus projection without widening admission distances.+- Restore 73 Tal original FBX files and their JPEGs with source-hash provenance (54 FBX contain only owner-approved same-length author-path blanking). Keep fresh-main generated Syrian/Iraqi figures and people-first download ordering intact.+- Keep the sea and air craft out of residency (owner ruling, 26 October 2026): they are asked for once in view and show at the 60 km gameplay view, as before.+- Tiberias, Safed and Hanita are no longer coloured Arab-held in 1948, and the city panel's "Held by" line agrees+ (#1659). A mapped settlement's hex now takes the control at the settlement's own point rather than at the hex's+ centre, which could sit the other side of the traced line; Tiberias is placed on a substitute hex whose own hex is+ lake, so its centre said nothing about the town. Rosh Pinna gains the Hula valley's contested opening (15 May to+ 11 June 1948) for the same reason, its point falling inside that cited overlay where its hex centre did not. Four of+ the 410 hexes change in all. The contested, pin and Jerusalem rules still apply on top, and two settlements sharing+ a hex must agree about its control or the bake fails rather than picking a winner. Display only: the sim never reads+ the control layer. Owner's rulings of 25 October 2026 (option (a)) and 26 October 2026 ("as Ella built it").+- A very fast one-finger swipe no longer selects a hex (#1661 item 4; owner's ruling of 26 October 2026). A finger is+ sampled once a frame, so a press, a long travel and a lift inside one input update left the press and the sample at+ the same point: the slop saw nothing move, however far the finger went, and the swipe came back as a tap at the+ release point. The press now also carries the finger's travel within the frame, so the slop sees it and the gesture+ is a drag. The mouse's right button is stepped from its action callbacks and reports no travel, so right-click+ ordering is unchanged.+- Key the remaining 68 report Cause producers for Hebrew rendering while preserving English messages and simulation rules.+ Hebrew drafts await native review; sensitive capture and displacement wording awaits sensitivity review (#1682, #564).+- How to play omits Attention and uses ruleset-specific event, top-bar and End-turn help under gdd-0.3. Earlier rulesets keep their original guide. New Hebrew help is a draft pending native review. (Refs #1688)+- Under gdd-0.3, an enemy holding a city no longer ends the game. Economic and dated ends still apply; legacy and gdd-0.1 keep their existing rules. (Refs #1711)+- The empty map panel's English and Hebrew hints say to drag to move the map,+ covering either mouse button and one-finger touch panning.+- The Hebrew city panel no longer shows "a winery" and "vineyards" in English inside a Hebrew line (#1781). The+ `winery` project kind gets a `name_he` like its three siblings, and the resource it requires is named by a+ `city.resource.<id>` UI string in both languages. The resource's name lives in the strings rather than in+ `content/`, because a resource is a record nested inside a city and the translation contract binds only a+ `<file>#<list>.<id>.<field>` key (`HebrewOverlay.Bindings`). Both wordings are `agent-checked`, for the native read+ under #564.+- The city panel's Jobs line ("Jobs: 106 of 106 filled") stays on one line at 1024x768 in English (#1789). Layout+ could round its box one raster pixel narrower than its text, so "filled" dropped onto the Refugees line below.+ The paired counts (Jobs and Craftsmen, Refugees waiting and Overflow) no longer break across two lines.+- A very fast pinch no longer pans the map or selects a hex: a second finger that touches and lifts between two+ input samples is now counted.+- Hex map: a unit or placed figure whose model carries its own root rotation (the Collection vehicles' import fix) keeps+ it when it turns, so the Willys jeep, the Sandwich truck, the horse wagon and the citrus truck will stand on their+ wheels instead of lying on their side. Players see it once the alias rows that draw those vehicles land (#1955) (#2006).+- A Hebrew locality tooltip no longer repeats the pill's own name (#2022): where the Hebrew today name is the Hebrew+ 1948 name (Umm el Fahm and Umm al-Fahm are both אום אל-פחם - 48 rows), `Localities.TodayName` returns no today name+ in Hebrew, so the tooltip the pill already gives is not restated. The info panel's Hebrew line is unchanged (it+ already dropped the repeat) and English tooltips keep the today name.+- `tools/advisor_clips.py ingest` now checks the new picture in a temporary folder before it replaces the shipped clip, so a+ picture that fails the checks leaves the old one in place, and `--lang he` refuses a picture that differs from the+ shared `<message>.mp4`.+- Region borders no longer stop in mid-air where they meet land the 1948 lines leave without colour. On the south+ coast at the game's start, Shoval's blue hex drew a lone edge against the Hebron hills, and the 9 July front ended+ abruptly at the uncoloured Gaza sub-district. Land without colour now works like the land beyond the frontier: it+ draws no band of its own, and each side's band runs along its edge. Every pinned settlement hex (Negba, Yad+ Mordechai, Nir Am, Shoval and the rest) now gets a closed blue ring, and every front closes, in every period from+ 15 May 1948 to the 1949 armistice lines. Display only: the sim never reads the control layer. Owner's ruling of+ 27 October 2026 ("Close the borders").+- Restored each Collection category's v0.3.1 map-wide representation (including Near specials and road vehicles), kept added Near detail camera-gated, and retired streamed originals by key without blinking unrelated models.+- Keep rostered unit figures and vehicles visible at strategic zoom and when their token's placement is outside the+ camera-residency footprint, while continuing to unload close-detail models on leave.+- Keep detailed town models visible when the camera is centred on the town label or kit footprint, retain the previous town+ only while it owns the focus or remains in its instance-bounds exit band, and match the game-town generator's footprint+ ownership while preserving instance-bounds fallback for malformed or non-covering detailed footprints.+- The detached GDD 0.3 assignment fixture refuses a reception-completion catalogue limit that differs from its initialized population ledger, matching the reception fixture. Refusal preserves the state. Shipping rules, catalogue values and save formats are unchanged.+- Bound synthetic GDD 0.3 Industry and Workshop assignments by their initialized regional job pools, preserving atomic refusals and independent work kinds. The fixture remains internal with no playable or production hookup.+- Refuse a detached GDD 0.3 training fixture whose reception duration disagrees with its initialized population ledger, before any course action or state change.+- `scripts/check.sh`'s Unity compile step now finds a Linux editor (`~/Unity/Hub/Editor/<version>/Editor/Data`), and+ `scripts/unity_compile/compile.sh` accepts that layout, so the check no longer always skips on Linux. macOS is unchanged.+- A trackpad pinch zooms the map in the macOS player, as it does in the browser: the player passed the pinch to+ nothing, so it did not zoom at all. The wheel, a two-finger scroll and the zoom keys already zoomed there.+- Preserve earlier rejected autosaves when another unreadable autosave or temporary save is set aside, keeping each file for diagnosis.+- An enemy token whose side figure fails to load (a missing or damaged Collection bundle) is now drawn anyway, on its+ plinth under its side's flag with the plain built-in rifleman, at the same anchor and figure count, and the failure is+ logged once per side (owner, 31 October 2026: "Yes, fallback in v0.3.2"; the only exception to #740's "no placeholder+ art"). Before, no enemy unit appeared for the whole session (seen on a CrazyGames-hosted v0.3.1). While a figure is+ still loading the token waits as before; loaded figures and Israeli tokens are unchanged.+- Villages and neighbouring towns at 12-30 km show Tal Heuberger's building models again, as in v0.3.1, instead of+ large plain kit houses, and Nazareth no longer shows its one oversized whole-town house up close. Below 40 km the+ building models of every town and village in view (+3 km) load, nearest first, and unload when you zoom out (owner+ ruling, 31 Oct 2026, "Load all in view").++### Changed+- The objective 3 railway card, `railway_complete`, is `fact-checked` (#1410): a person read its two newspaper pages+ (HaBoker, 14 September 1949; Maariv, 22 September 1949) and the Israel Railways booklet, and all three claims hold.+- A map drag still starts only past 30 px, and now pans only by the distance beyond it, with no catch-up jump (#1661,+ owner's ruling of 26 October 2026). Each press measures from where it landed, so a quick release and a new press+ between two frames can no longer pan inside the 30 px.+- Apply the owner's Hebrew review of the remaining report Cause strings (27 October 2026; #1682, #564). The Hebrew+ occupation countdown now reads "תורות שחרור שנותרו", and a capture left undecided at the end now says the game ended,+ in English ("before the game ended") and Hebrew ("עד סוף המשחק"). The per-string native-review markers are removed;+ sensitivity review of the capture and displacement wording is still open.+- Under the separate gdd-0.3 identity, use catalogue infantry/armour movement allowances and terrain costs, and additive permanent-fort defence from existing fort locations. Keep legacy/gdd-0.1 rules and content unchanged. Artillery movement remains blocked pending approved values; existing fire rules remain unchanged. Refs #1708 (bounded slice; full cutover and release gates remain).+- Under the gdd-0.3 ruleset, keep eight event cards legacy-only through an explicit availability manifest,+ and reject retired event targets and unaccounted structured effects. Preserve shared event records and+ legacy/gdd-0.1 loading; explicit Money costs retain borrowing.+- Keep the gdd-0.3 gameplay camera facing north while retaining pan and the existing 6 to 250 km zoom. Legacy and gdd-0.1 retain orbit.+- An EditMode guard that the capture dialog does not stay in its invisible start state (#1728). `ScreenNav.Show`+ opens a window in `window-opening`, which pins `opacity: 0` and `scale: 0.8`, and that class is taken off in one+ place only — on a `GeometryChangedEvent` — so a dialog that never gets one sits in the layout taking every press+ while invisible. `HudTests` covers the screens and the decision card this way; the capture dialog was not covered,+ and edit mode leaves `ScreenNav.Moves` off, so no test entered the transition path for it at all. No player code+ changes.+- Two EditMode guards for the Hebrew decision-card path (#1728): answering one card, and answering two in sequence,+ must leave the backdrop gone, `event-open` off the root, and the info panel's area pickable. The existing coverage+ only collapsed the card with Hide, and only in English. No player code changes.+- `?navlog` now also prints each modal card's own classes, resolved opacity, box and enabled state on a pointer down+ (#1728). Neither the capture dialog nor the decision card is an ancestor of the backdrop, so the pressed element's+ ancestor chain cannot show them: a press outside a card lands on the scrim, and the chain above the scrim says+ nothing about the card the scrim is protecting. A card held in `window-opening` stays in the layout and takes+ presses at `opacity: 0`, which is a modal the player cannot see; the class and the opacity together say whether+ that is what happened. Diagnostic only, behind the existing flag.+- `?navlog` now prints the pressed element and every ancestor above it, each with its classes, on every UI pointer+ down (#1728). A press that lands on an element nobody expected is usually a full-screen layer in front of the+ panels, and the rules that show those layers are descendant selectors, so the class that displays one can sit on+ any ancestor rather than only the HUD root. Diagnostic only, behind the existing flag.+- One spelling for the Hebrew terms in English text (#1760): **ma'abara** and **ma'abarot** with a straight+ apostrophe, by the owner's ruling of 26 October 2026, now written down in `docs/WRITING_GUIDE.md` section 10 with+ the spellings observed in the game for the terms the owner has not ruled on (yishuv, halutz, aliyah, hakhshara+ with kh, Knesset), marked as observed rather than ruled. The glossary's+ `transliteration` convention moves from `decision-needed` to `preferred`. An identifier is not display text, so ids,+ YAML keys, filenames and C# names keep their apostrophe-free spelling, and a quoted source form or a URL keeps what+ it prints.+- Region borders are stronger and more Civ-like (refs #196; owner ruling 27 Oct 2026, "A2: stronger bands+ (Recommended)"): the bands keep their weight when the camera pulls out (floors of 6 px colour, 1 px light, 12 px+ wash), both sides wash alike at 0.45 to a quarter of the hex, a light territory tint grows from 0.12 up close to+ 0.25 at the overview, and the neutral dashes stay at least 8 px. The earlier look stays selectable with+ `bordervariant=legacy` in the WebGL URL (or `-bordervariant legacy` on desktop), and the prototype's other variants+ with `a`, `b`, `c`, `b2` or `c2`: B adds a dark outer rim, C an Okabe-Ito blue, and A is the lighter tier of A2.+- The detached GDD 0.3 assignment fixture reports a same-job assignment as a no-op, matching the adopted owner ruling, instead of calling its already unchanged state Deferred.+- `QualitySettings.asset` and `URPProjectSettings.asset` are saved in the format the Unity 6000.3.25f1 editor writes,+ so a Unity run no longer leaves them changed in the working tree. The game looks and plays the same.++### Docs+- Record the owner's 30 Oct 2026 play-time ruling: a full session targets 120 minutes, matching `gdd03-balance.yaml` (#1687).++### Tests+- Cover invariant economic cause arguments, political cause argument ordering and IDs, and map-editor digest validation boundaries.+## [0.3.1] - 2026-10-26### Addeddiff --git a/changelog.d/1135-ui-large-scales.md b/changelog.d/1135-ui-large-scales.mddeleted file mode 100644index 3e806aa5d..000000000--- a/changelog.d/1135-ui-large-scales.md+++ /dev/null@@ -1,14 +0,0 @@-- The HUD holds at the Settings screen's 125% and 150% UI scales (#40): below the smallest window the 100% layout is- tested at (HudPresenter's new hud-tight, set from the panel's logical size; small phone windows reach it too) the- bar's rows, the icon column and the panels tighten; on the tight three-row window the icon column becomes a row of the- phone's 60 px discs under the bar (at least 24 px on screen down to 375x667) and a screen takes the window like a- mobile modal, with the card's backdrop leaving the row's discs clear. The decision card starts right of the tight- column; the info panel is a scrolling panel capped clear of the bar and the column, and on a phone at 125% or 150% it- stands above the minimap at the window's width; the Cabinet's side column slims so- the seats list keeps its room; and the small text keeps its 12 px on-screen floor at every size. The seven layout- suites that failed at 125%/150% now run at all three scales.-- At 150% on short windows the Cabinet scroll shows seat cards before the house and legend; on phones at 150% the- half circle fits its column. Desktop half circles and the 100%/125% Cabinet order keep their existing layout.-- The decision card's body scrolls as one (#1853): the text and the options with their effect lines sit in one scroll- between the pinned head and the pinned foot, so Hide stays inside the card at 150%. A card that fits shows no scroll- bar, Tab onto an option scrolls it into view, and a new card opens at the top of its text.diff --git a/changelog.d/1219-unit-subtitles-he.md b/changelog.d/1219-unit-subtitles-he.mddeleted file mode 100644index 1d7ebede6..000000000--- a/changelog.d/1219-unit-subtitles-he.md+++ /dev/null@@ -1,6 +0,0 @@-- The unit card's subtitle now shows a sourced Hebrew number line beside the English one (#1219 item 2): the 12- Israeli brigades ("חטיבה 1" … "חטיבה 12", the Palmach trio marked "הפלמ״ח"), the 101 fighter squadron, INS- Haganah and INS Wedgwood ("קורבטה, הוכנסה לשירות ב־1948") and the five other armies each carry a `number_he`- line from a checked he.wiki source (agent-checked 2026-10-26, quoted in the file). Two rows are skipped with- reasons: `iraqi` (he.wiki composition conflict) and `lebanese` (English phrasing rests on an unread Glubb- snippet). The new strings join the native-speaker queue in `docs/review-queue.md` (#564). Goldens did not move.diff --git a/changelog.d/1273-production-residency.md b/changelog.d/1273-production-residency.mddeleted file mode 100644index 47523e5c2..000000000--- a/changelog.d/1273-production-residency.md+++ /dev/null@@ -1,6 +0,0 @@-### Fixed--- Stream Tal Heuberger’s original models for the map views that need them, retire generated consumers before releasing sources, and reacquire on a revisit. Preserve fallback while loading and retained shared road, train, wildlife and hex-board ownership. (Refs #1273)-- Use explicit owner-approved production policy with diagnostics off by default; keep the existing unit appearance rules and correct large-coordinate ground-focus projection without widening admission distances.-- Restore 73 Tal original FBX files and their JPEGs with source-hash provenance (54 FBX contain only owner-approved same-length author-path blanking). Keep fresh-main generated Syrian/Iraqi figures and people-first download ordering intact.-- Keep the sea and air craft out of residency (owner ruling, 26 October 2026): they are asked for once in view and show at the 60 km gameplay view, as before.diff --git a/changelog.d/1410.md b/changelog.d/1410.mddeleted file mode 100644index a22b3ff81..000000000--- a/changelog.d/1410.md+++ /dev/null@@ -1,3 +0,0 @@-### Changed-- The objective 3 railway card, `railway_complete`, is `fact-checked` (#1410): a person read its two newspaper pages- (HaBoker, 14 September 1949; Maariv, 22 September 1949) and the Israel Railways booklet, and all three claims hold.diff --git a/changelog.d/1549.md b/changelog.d/1549.mddeleted file mode 100644index 4d2e3fcda..000000000--- a/changelog.d/1549.md+++ /dev/null@@ -1 +0,0 @@-- Select pioneer groups from a hex list or project link to see their track, location and work, and return idle groups to civilian life. Existing project and city row actions remain available.diff --git a/changelog.d/1564.md b/changelog.d/1564.mddeleted file mode 100644index 45088b65a..000000000--- a/changelog.d/1564.md+++ /dev/null@@ -1,7 +0,0 @@-- A hard event card, `reparations_vote` (#1564): the Knesset's vote of 9 January 1952 on direct talks with West- Germany over reparations, tagged `holocaust`. It reaches the player on 15 December 1951, with three options, the- historical vote to negotiate and two debated alternatives (reject any talks; a referendum first), each with a small- design cost. Its header photograph is Benno Rothenberg's police barriers near the Knesset, January 1952 (CC BY 4.0,- sensitive). The owner approved the card and options, the photograph and the costs on 25 October 2026 ("Approve all- three"), so it is sensitivity-reviewed (refs #1564, #1575).- `Hash1952`, `mvp-end` and `scenario-mvp-defeat` move.diff --git a/changelog.d/1565.md b/changelog.d/1565.mddeleted file mode 100644index 34a3bd233..000000000--- a/changelog.d/1565.md+++ /dev/null@@ -1,7 +0,0 @@-- New event card: the defence of Degania and where the guns go, 19-20 May 1948 (the recorded choice: the 65 mm- mountain guns to the Jordan Valley), with Moshe Marlin Levin's frame from Degania Alef (catalogue-dated 20 May 1948, CC BY 4.0,- sensitive: true; the vehicle's identification is flagged for review). The owner approved the card and its- photograph on 24 October 2026, so it is sensitivity-reviewed (refs #1565, #1568, #28).-- Events: an optional `order` (default 0) decides between the cards of the same date on one turn, before the id- (R-EVT-006). `degania_defence` has `order: 1`, so One Army still opens the game and Degania comes second (owner,- 24 October 2026, #1568: "One Army first").diff --git a/changelog.d/1606-ui-lang-declared.md b/changelog.d/1606-ui-lang-declared.mddeleted file mode 100644index e6ae74fb8..000000000--- a/changelog.d/1606-ui-lang-declared.md+++ /dev/null@@ -1,8 +0,0 @@-### Added--- A language offered to the player must name itself: `Translations.CheckDeclaredLanguage` refuses a- `translations/<lang>/ui.yaml` with no `ui.lang`, and one whose `ui.lang` names a different language from its- directory (#1606). The second is the case worth the check — a `ui.yaml` copied from another language with its code- left behind passes every shape check, and `ui.lang` is what the player reads to pick the Hebrew face and the- language branches in `EventCardPresenter` and `SharePresenter`, so the failure is silently the wrong language- rather than an error. Documented in `docs/translations.md`; no player code changes yet.diff --git a/changelog.d/1659-city-point-control.md b/changelog.d/1659-city-point-control.mddeleted file mode 100644index eecbb84bf..000000000--- a/changelog.d/1659-city-point-control.md+++ /dev/null@@ -1,10 +0,0 @@-### Fixed--- Tiberias, Safed and Hanita are no longer coloured Arab-held in 1948, and the city panel's "Held by" line agrees- (#1659). A mapped settlement's hex now takes the control at the settlement's own point rather than at the hex's- centre, which could sit the other side of the traced line; Tiberias is placed on a substitute hex whose own hex is- lake, so its centre said nothing about the town. Rosh Pinna gains the Hula valley's contested opening (15 May to- 11 June 1948) for the same reason, its point falling inside that cited overlay where its hex centre did not. Four of- the 410 hexes change in all. The contested, pin and Jerusalem rules still apply on top, and two settlements sharing- a hex must agree about its control or the bake fails rather than picking a winner. Display only: the sim never reads- the control layer. Owner's rulings of 25 October 2026 (option (a)) and 26 October 2026 ("as Ella built it").diff --git a/changelog.d/1661-fast-swipe-pans.md b/changelog.d/1661-fast-swipe-pans.mddeleted file mode 100644index e658a5618..000000000--- a/changelog.d/1661-fast-swipe-pans.md+++ /dev/null@@ -1,8 +0,0 @@-### Fixed--- A very fast one-finger swipe no longer selects a hex (#1661 item 4; owner's ruling of 26 October 2026). A finger is- sampled once a frame, so a press, a long travel and a lift inside one input update left the press and the sample at- the same point: the slop saw nothing move, however far the finger went, and the swipe came back as a tap at the- release point. The press now also carries the finger's travel within the frame, so the slop sees it and the gesture- is a drag. The mouse's right button is stepped from its action callbacks and reports no travel, so right-click- ordering is unchanged.diff --git a/changelog.d/1661-flick-pan.md b/changelog.d/1661-flick-pan.mddeleted file mode 100644index 1ddeed6ba..000000000--- a/changelog.d/1661-flick-pan.md+++ /dev/null@@ -1 +0,0 @@-- A fast one finger swipe now pans the map once by its travel past the tap threshold, even if it ends before the next frame. Ella's tap fix already keeps the swipe from selecting anything. A swipe that goes out past the threshold and back before the next frame is a pan too, and selects nothing.diff --git a/changelog.d/1661-friendly-confirm-drag.md b/changelog.d/1661-friendly-confirm-drag.mddeleted file mode 100644index e9598360e..000000000--- a/changelog.d/1661-friendly-confirm-drag.md+++ /dev/null@@ -1,11 +0,0 @@-- A confirm step for ordering a unit onto a friendly unit or a city by touch or keyboard (#1661, owner's ruling of- 26 October 2026). With a unit selected, picking a hex that holds another of your units, or a city, still selects it- as before, and also offers "Send <unit> to <place>" for the unit you had selected; taking it moves that unit. The- offer goes away once it is stale: another selection, a new turn, or a screen opening. Mouse right-click ordering is- unchanged. The Hebrew wording is native-review-pending.--### Changed--- A map drag still starts only past 30 px, and now pans only by the distance beyond it, with no catch-up jump (#1661,- owner's ruling of 26 October 2026). Each press measures from where it landed, so a quick release and a new press- between two frames can no longer pan inside the 30 px.diff --git a/changelog.d/1661-left-button-observer.md b/changelog.d/1661-left-button-observer.mddeleted file mode 100644index 35d504690..000000000--- a/changelog.d/1661-left-button-observer.md+++ /dev/null@@ -1 +0,0 @@-- Left-button map drags now use the camera's per-press 30 px onset and UI-origin latch, matching right-button drags without replaying held travel (#1661, #998). This builds on Ella Sharakanski's left-drag support in #1791.diff --git a/changelog.d/1682-cause-keys.md b/changelog.d/1682-cause-keys.mddeleted file mode 100644index 8e26ebc65..000000000--- a/changelog.d/1682-cause-keys.md+++ /dev/null@@ -1,4 +0,0 @@-### Fixed--- Key the remaining 68 report Cause producers for Hebrew rendering while preserving English messages and simulation rules.- Hebrew drafts await native review; sensitive capture and displacement wording awaits sensitivity review (#1682, #564).diff --git a/changelog.d/1682-he-review.md b/changelog.d/1682-he-review.mddeleted file mode 100644index c39c6e3f9..000000000--- a/changelog.d/1682-he-review.md+++ /dev/null@@ -1,6 +0,0 @@-### Changed--- Apply the owner's Hebrew review of the remaining report Cause strings (27 October 2026; #1682, #564). The Hebrew- occupation countdown now reads "תורות שחרור שנותרו", and a capture left undecided at the end now says the game ended,- in English ("before the game ended") and Hebrew ("עד סוף המשחק"). The per-string native-review markers are removed;- sensitivity review of the capture and displacement wording is still open.diff --git a/changelog.d/1688-gdd03-help.md b/changelog.d/1688-gdd03-help.mddeleted file mode 100644index 2407457d1..000000000--- a/changelog.d/1688-gdd03-help.md+++ /dev/null@@ -1,3 +0,0 @@-### Fixed--- How to play omits Attention and uses ruleset-specific event, top-bar and End-turn help under gdd-0.3. Earlier rulesets keep their original guide. New Hebrew help is a draft pending native review. (Refs #1688)diff --git a/changelog.d/1688-tour-slice2.md b/changelog.d/1688-tour-slice2.mddeleted file mode 100644index 8578a74ab..000000000--- a/changelog.d/1688-tour-slice2.md+++ /dev/null@@ -1 +0,0 @@-- Skip the Attention lesson in the gdd-0.3 opening tour while preserving its remaining steps and the full legacy/gdd-0.1 tour.diff --git a/changelog.d/1689.md b/changelog.d/1689.mddeleted file mode 100644index c1a6a7114..000000000--- a/changelog.d/1689.md+++ /dev/null@@ -1,3 +0,0 @@-### Added--- Add the gdd-0.3 population identity foundation: immutable records, a validated ledger, identity-aware scale, canonical state and synthetic fixture initialization. Production population, Food and command/replay integration remain held; legacy and gdd-0.1 behavior and shipped content are unchanged.diff --git a/changelog.d/1690.md b/changelog.d/1690.mddeleted file mode 100644index 915176f5e..000000000--- a/changelog.d/1690.md+++ /dev/null@@ -1 +0,0 @@-- Add the gdd-0.3 gameplay-region geography contract, effective-map validation and immutable regional fixture pools using the existing population ledger. Keep production initialization inactive and preserve the legacy/gdd-0.1 content boundary. Regional commands, replay and production authoring remain separate work.diff --git a/changelog.d/1692-fixture-assignments.md b/changelog.d/1692-fixture-assignments.mddeleted file mode 100644index 0a5e3b585..000000000--- a/changelog.d/1692-fixture-assignments.md+++ /dev/null@@ -1 +0,0 @@-- Add isolated population fixture assignments with atomic capacity checks and typed Industry rate quotations.diff --git a/changelog.d/1693-profession-helpers.md b/changelog.d/1693-profession-helpers.mddeleted file mode 100644index 9a5b99897..000000000--- a/changelog.d/1693-profession-helpers.md+++ /dev/null@@ -1 +0,0 @@-- Refs #1693: add internal, fixture-only civilian profession helpers for actual-work XP, next-turn promotion, matching-course preservation and Agreed catalogue quotes. Production integration and payments remain held; legacy/gdd-0.1 behavior and content are unchanged.diff --git a/changelog.d/1694-synthetic-fields.md b/changelog.d/1694-synthetic-fields.mddeleted file mode 100644index e429717c6..000000000--- a/changelog.d/1694-synthetic-fields.md+++ /dev/null@@ -1 +0,0 @@-- Add typed farming rates and a detached synthetic staffed-field output evaluator for GDD 0.3 groundwork.diff --git a/changelog.d/1695-fixture-contract.md b/changelog.d/1695-fixture-contract.mddeleted file mode 100644index 0ffd6199a..000000000--- a/changelog.d/1695-fixture-contract.md+++ /dev/null@@ -1 +0,0 @@-- Add a synthetic immigration manifest model and content validation contract for GDD 0.3 fixtures.diff --git a/changelog.d/1696-reception-catalogue-consistency.md b/changelog.d/1696-reception-catalogue-consistency.mddeleted file mode 100644index 6061fe697..000000000--- a/changelog.d/1696-reception-catalogue-consistency.md+++ /dev/null@@ -1 +0,0 @@-- Refuse synthetic reception evaluation when the supplied duration differs from the initialized population ledger, including civilian eligibility checks.diff --git a/changelog.d/1696-reception-fixtures.md b/changelog.d/1696-reception-fixtures.mddeleted file mode 100644index 9356ee709..000000000--- a/changelog.d/1696-reception-fixtures.md+++ /dev/null@@ -1 +0,0 @@-- Add isolated synthetic reception fixtures for dedicated bed allocation, ordinary progress and civilian eligibility.diff --git a/changelog.d/1697-training-centre-fixture.md b/changelog.d/1697-training-centre-fixture.mddeleted file mode 100644index 7928a14be..000000000--- a/changelog.d/1697-training-centre-fixture.md+++ /dev/null@@ -1 +0,0 @@-- Refs #1697: add an internal, fixture-only gdd-0.3 training centre course lifecycle (start, counted course turns, cancel) on the population ledger. Graduation timing and the other open design points are refused as Deferred; no real centre, payment or game caller is added, and legacy/gdd-0.1 behaviour and content are unchanged.diff --git a/changelog.d/1698-craft-arithmetic.md b/changelog.d/1698-craft-arithmetic.mddeleted file mode 100644index 8327c198d..000000000--- a/changelog.d/1698-craft-arithmetic.md+++ /dev/null@@ -1 +0,0 @@-- Add isolated GDD 0.3 craftsman catalogue and course/work tick arithmetic for synthetic fixtures.diff --git a/changelog.d/1699-military-catalogue.md b/changelog.d/1699-military-catalogue.mddeleted file mode 100644index 650faa36e..000000000--- a/changelog.d/1699-military-catalogue.md+++ /dev/null@@ -1 +0,0 @@-- Add a typed military balance catalogue contract and a synthetic equipment-conservation specification for GDD 0.3.diff --git a/changelog.d/1700-project-catalogue.md b/changelog.d/1700-project-catalogue.mddeleted file mode 100644index 0c9d5cf4e..000000000--- a/changelog.d/1700-project-catalogue.md+++ /dev/null@@ -1 +0,0 @@-- Add a typed GDD 0.3 catalogue view for settled city project costs, work, effects and upkeep, isolated from gameplay.diff --git a/changelog.d/1701-workshop-cycle.md b/changelog.d/1701-workshop-cycle.mddeleted file mode 100644index c525d2e0c..000000000--- a/changelog.d/1701-workshop-cycle.md+++ /dev/null@@ -1 +0,0 @@-- Add an isolated synthetic arms workshop cycle contract with catalogue pricing and explicit reservations.diff --git a/changelog.d/1703-housing-formula.md b/changelog.d/1703-housing-formula.mddeleted file mode 100644index 2ce25e3ee..000000000--- a/changelog.d/1703-housing-formula.md+++ /dev/null@@ -1 +0,0 @@-- Add isolated housing formula arithmetic with explicit resident, condition and upkeep inputs for GDD 0.3 synthetic fixtures.diff --git a/changelog.d/1704-food-arithmetic.md b/changelog.d/1704-food-arithmetic.mddeleted file mode 100644index 234ca9859..000000000--- a/changelog.d/1704-food-arithmetic.md+++ /dev/null@@ -1 +0,0 @@-- Refs #1704: add an internal pure Food arithmetic foundation with synthetic unit tests. No shipping call site or turn integration; existing Food paths remain unchanged.diff --git a/changelog.d/1706-c303.md b/changelog.d/1706-c303.mddeleted file mode 100644index 30b65047f..000000000--- a/changelog.d/1706-c303.md+++ /dev/null@@ -1 +0,0 @@-- Add inactive synthetic combat catalogue validation and contract fixtures for #1706 (slices 0/1 only). No strength calculation or combat activation; runtime rules and shipped content remain unchanged.diff --git a/changelog.d/1708.md b/changelog.d/1708.mddeleted file mode 100644index 2bd3d4414..000000000--- a/changelog.d/1708.md+++ /dev/null@@ -1,3 +0,0 @@-### Changed--- Under the separate gdd-0.3 identity, use catalogue infantry/armour movement allowances and terrain costs, and additive permanent-fort defence from existing fort locations. Keep legacy/gdd-0.1 rules and content unchanged. Artillery movement remains blocked pending approved values; existing fire rules remain unchanged. Refs #1708 (bounded slice; full cutover and release gates remain).diff --git a/changelog.d/1710-captivity-records.md b/changelog.d/1710-captivity-records.mddeleted file mode 100644index c1656af95..000000000--- a/changelog.d/1710-captivity-records.md+++ /dev/null@@ -1 +0,0 @@-- Add an isolated synthetic captivity identity and surrender-provenance record contract.diff --git a/changelog.d/1711-no-city-loss-defeat.md b/changelog.d/1711-no-city-loss-defeat.mddeleted file mode 100644index 78ff22140..000000000--- a/changelog.d/1711-no-city-loss-defeat.md+++ /dev/null@@ -1,3 +0,0 @@-### Fixed--- Under gdd-0.3, an enemy holding a city no longer ends the game. Economic and dated ends still apply; legacy and gdd-0.1 keep their existing rules. (Refs #1711)diff --git a/changelog.d/1714-synthetic-absorption-boundary.md b/changelog.d/1714-synthetic-absorption-boundary.mddeleted file mode 100644index 20b616968..000000000--- a/changelog.d/1714-synthetic-absorption-boundary.md+++ /dev/null@@ -1 +0,0 @@-- Add an inactive synthetic absorption boundary contract using catalogue thresholds and explicit settled facts.diff --git a/changelog.d/1716-c301-synthetic-contract.md b/changelog.d/1716-c301-synthetic-contract.mddeleted file mode 100644index 16378aec2..000000000--- a/changelog.d/1716-c301-synthetic-contract.md+++ /dev/null@@ -1 +0,0 @@-- Add an internal synthetic monthly-context contract for #1716; no game activation or resolver integration.diff --git a/changelog.d/1718-gdd03-event-effects.md b/changelog.d/1718-gdd03-event-effects.mddeleted file mode 100644index 00a92c088..000000000--- a/changelog.d/1718-gdd03-event-effects.md+++ /dev/null@@ -1,5 +0,0 @@-### Changed--- Under the gdd-0.3 ruleset, keep eight event cards legacy-only through an explicit availability manifest,- and reject retired event targets and unaccounted structured effects. Preserve shared event records and- legacy/gdd-0.1 loading; explicit Money costs retain borrowing.diff --git a/changelog.d/1720-camera.md b/changelog.d/1720-camera.mddeleted file mode 100644index d9db1baf7..000000000--- a/changelog.d/1720-camera.md+++ /dev/null@@ -1,3 +0,0 @@-### Changed--- Keep the gdd-0.3 gameplay camera facing north while retaining pan and the existing 6 to 250 km zoom. Legacy and gdd-0.1 retain orbit.diff --git a/changelog.d/1720-map-drag-hint.md b/changelog.d/1720-map-drag-hint.mddeleted file mode 100644index e668aa04f..000000000--- a/changelog.d/1720-map-drag-hint.md+++ /dev/null@@ -1,4 +0,0 @@-### Fixed--- The empty map panel's English and Hebrew hints say to drag to move the map,- covering either mouse button and one-finger touch panning.diff --git a/changelog.d/1721.md b/changelog.d/1721.mddeleted file mode 100644index 7a208a52f..000000000--- a/changelog.d/1721.md+++ /dev/null@@ -1 +0,0 @@-- Add isolated gdd-0.3 map authoring schema, source document and blocking diagnostics infrastructure (refs #1721). Domain integration and canonical export remain unavailable; legacy map files are unchanged.diff --git a/changelog.d/1728-capture-open-transition.md b/changelog.d/1728-capture-open-transition.mddeleted file mode 100644index 20209e20b..000000000--- a/changelog.d/1728-capture-open-transition.md+++ /dev/null@@ -1,8 +0,0 @@-### Changed--- An EditMode guard that the capture dialog does not stay in its invisible start state (#1728). `ScreenNav.Show`- opens a window in `window-opening`, which pins `opacity: 0` and `scale: 0.8`, and that class is taken off in one- place only — on a `GeometryChangedEvent` — so a dialog that never gets one sits in the layout taking every press- while invisible. `HudTests` covers the screens and the decision card this way; the capture dialog was not covered,- and edit mode leaves `ScreenNav.Moves` off, so no test entered the transition path for it at all. No player code- changes.diff --git a/changelog.d/1728-hebrew-scrim-guards.md b/changelog.d/1728-hebrew-scrim-guards.mddeleted file mode 100644index 5ec343091..000000000--- a/changelog.d/1728-hebrew-scrim-guards.md+++ /dev/null@@ -1,5 +0,0 @@-### Changed--- Two EditMode guards for the Hebrew decision-card path (#1728): answering one card, and answering two in sequence,- must leave the backdrop gone, `event-open` off the root, and the info panel's area pickable. The existing coverage- only collapsed the card with Hide, and only in English. No player code changes.diff --git a/changelog.d/1728-navlog-modal-state.md b/changelog.d/1728-navlog-modal-state.mddeleted file mode 100644index b412dce45..000000000--- a/changelog.d/1728-navlog-modal-state.md+++ /dev/null@@ -1,8 +0,0 @@-### Changed--- `?navlog` now also prints each modal card's own classes, resolved opacity, box and enabled state on a pointer down- (#1728). Neither the capture dialog nor the decision card is an ancestor of the backdrop, so the pressed element's- ancestor chain cannot show them: a press outside a card lands on the scrim, and the chain above the scrim says- nothing about the card the scrim is protecting. A card held in `window-opening` stays in the layout and takes- presses at `opacity: 0`, which is a modal the player cannot see; the class and the opacity together say whether- that is what happened. Diagnostic only, behind the existing flag.diff --git a/changelog.d/1728-navlog-root-classes.md b/changelog.d/1728-navlog-root-classes.mddeleted file mode 100644index 521f2dff6..000000000--- a/changelog.d/1728-navlog-root-classes.md+++ /dev/null@@ -1,6 +0,0 @@-### Changed--- `?navlog` now prints the pressed element and every ancestor above it, each with its classes, on every UI pointer- down (#1728). A press that lands on an element nobody expected is usually a full-screen layer in front of the- panels, and the rules that show those layers are descendant selectors, so the class that displays one can sit on- any ancestor rather than only the HUD root. Diagnostic only, behind the existing flag.diff --git a/changelog.d/1760-hebrew-transliteration.md b/changelog.d/1760-hebrew-transliteration.mddeleted file mode 100644index 66d674a53..000000000--- a/changelog.d/1760-hebrew-transliteration.md+++ /dev/null@@ -1,9 +0,0 @@-### Changed--- One spelling for the Hebrew terms in English text (#1760): **ma'abara** and **ma'abarot** with a straight- apostrophe, by the owner's ruling of 26 October 2026, now written down in `docs/WRITING_GUIDE.md` section 10 with- the spellings observed in the game for the terms the owner has not ruled on (yishuv, halutz, aliyah, hakhshara- with kh, Knesset), marked as observed rather than ruled. The glossary's- `transliteration` convention moves from `decision-needed` to `preferred`. An identifier is not display text, so ids,- YAML keys, filenames and C# names keep their apostrophe-free spelling, and a quoted source form or a URL keeps what- it prints.diff --git a/changelog.d/1781-winery-vineyards-he.md b/changelog.d/1781-winery-vineyards-he.mddeleted file mode 100644index 87942add6..000000000--- a/changelog.d/1781-winery-vineyards-he.md+++ /dev/null@@ -1,8 +0,0 @@-### Fixed--- The Hebrew city panel no longer shows "a winery" and "vineyards" in English inside a Hebrew line (#1781). The- `winery` project kind gets a `name_he` like its three siblings, and the resource it requires is named by a- `city.resource.<id>` UI string in both languages. The resource's name lives in the strings rather than in- `content/`, because a resource is a record nested inside a city and the translation contract binds only a- `<file>#<list>.<id>.<field>` key (`HebrewOverlay.Bindings`). Both wordings are `agent-checked`, for the native read- under #564.diff --git a/changelog.d/1789.md b/changelog.d/1789.mddeleted file mode 100644index 75d8bb8a8..000000000--- a/changelog.d/1789.md+++ /dev/null@@ -1,5 +0,0 @@-### Fixed--- The city panel's Jobs line ("Jobs: 106 of 106 filled") stays on one line at 1024x768 in English (#1789). Layout- could round its box one raster pixel narrower than its text, so "filled" dropped onto the Refugees line below.- The paired counts (Jobs and Craftsmen, Refugees waiting and Overflow) no longer break across two lines.diff --git a/changelog.d/1792-pinch-one-update.md b/changelog.d/1792-pinch-one-update.mddeleted file mode 100644index 5fe45fe7e..000000000--- a/changelog.d/1792-pinch-one-update.md+++ /dev/null@@ -1,4 +0,0 @@-### Fixed--- A very fast pinch no longer pans the map or selects a hex: a second finger that touches and lifts between two- input samples is now counted.diff --git a/changelog.d/1878.md b/changelog.d/1878.mddeleted file mode 100644index 669b3b725..000000000--- a/changelog.d/1878.md+++ /dev/null@@ -1,3 +0,0 @@-- The default map shows the calm "under attack" look (grey smoke, a low fire glow, a slowly pulsing red border) on every- hex the turn's attacks hit, for as long as the turn report is open (#1878). It reads the sim's engagement lines and- changes nothing in the rules.diff --git a/changelog.d/196-civ-borders-prototype.md b/changelog.d/196-civ-borders-prototype.mddeleted file mode 100644index 5dff686e8..000000000--- a/changelog.d/196-civ-borders-prototype.md+++ /dev/null@@ -1,7 +0,0 @@-### Changed-- Region borders are stronger and more Civ-like (refs #196; owner ruling 27 Oct 2026, "A2: stronger bands- (Recommended)"): the bands keep their weight when the camera pulls out (floors of 6 px colour, 1 px light, 12 px- wash), both sides wash alike at 0.45 to a quarter of the hex, a light territory tint grows from 0.12 up close to- 0.25 at the overview, and the neutral dashes stay at least 8 px. The earlier look stays selectable with- `bordervariant=legacy` in the WebGL URL (or `-bordervariant legacy` on desktop), and the prototype's other variants- with `a`, `b`, `c`, `b2` or `c2`: B adds a dark outer rim, C an Okabe-Ito blue, and A is the lighter tier of A2.diff --git a/changelog.d/2006-prefab-root-rotation.md b/changelog.d/2006-prefab-root-rotation.mddeleted file mode 100644index a604b8e63..000000000--- a/changelog.d/2006-prefab-root-rotation.md+++ /dev/null@@ -1,4 +0,0 @@-### Fixed-- Hex map: a unit or placed figure whose model carries its own root rotation (the Collection vehicles' import fix) keeps- it when it turns, so the Willys jeep, the Sandwich truck, the horse wagon and the citrus truck will stand on their- wheels instead of lying on their side. Players see it once the alias rows that draw those vehicles land (#1955) (#2006).diff --git a/changelog.d/2022.md b/changelog.d/2022.mddeleted file mode 100644index e8eadc5c4..000000000--- a/changelog.d/2022.md+++ /dev/null@@ -1,5 +0,0 @@-### Fixed-- A Hebrew locality tooltip no longer repeats the pill's own name (#2022): where the Hebrew today name is the Hebrew- 1948 name (Umm el Fahm and Umm al-Fahm are both אום אל-פחם - 48 rows), `Localities.TodayName` returns no today name- in Hebrew, so the tooltip the pill already gives is not restated. The info panel's Hebrew line is unchanged (it- already dropped the repeat) and English tooltips keep the today name.diff --git a/changelog.d/2027.md b/changelog.d/2027.mddeleted file mode 100644index 7f155076c..000000000--- a/changelog.d/2027.md+++ /dev/null@@ -1,5 +0,0 @@-### Fixed--- `tools/advisor_clips.py ingest` now checks the new picture in a temporary folder before it replaces the shipped clip, so a- picture that fails the checks leaves the old one in place, and `--lang he` refuses a picture that differs from the- shared `<message>.mp4`.diff --git a/changelog.d/2054-start-language.md b/changelog.d/2054-start-language.mddeleted file mode 100644index 238f379f8..000000000--- a/changelog.d/2054-start-language.md+++ /dev/null@@ -1,3 +0,0 @@-- The start screen offers the language before you play: "English" and "עברית", each in its own language, with the one- in use marked. A choice switches the game at once, keeps the start screen up and is the same choice Settings shows and- keeps; "?lang=he" still wins for that visit (#2054).diff --git a/changelog.d/731.md b/changelog.d/731.mddeleted file mode 100644index 901e2c0bd..000000000--- a/changelog.d/731.md+++ /dev/null@@ -1 +0,0 @@-- Keep the top bar as main; show Arms in Defence and Food/Arms stocks, turn changes and existing causes in the report and Why. Preserve queued Arms purchases. Refs #731.diff --git a/changelog.d/939-alternate-cards-signoff.md b/changelog.d/939-alternate-cards-signoff.mddeleted file mode 100644index 8858f8ffd..000000000--- a/changelog.d/939-alternate-cards-signoff.md+++ /dev/null@@ -1,3 +0,0 @@-- The two alternate cards from #939, `jerusalem_demilitarisation_guard` and `rafah_force_pressure`, are signed off by the- owner (`reviewed_by`, 28 October 2026), so the release gate no longer refuses them. Their status stays `draft`; native- Hebrew approval is not asserted. No text, effect or date changed.diff --git a/changelog.d/998-left-drag-pan.md b/changelog.d/998-left-drag-pan.mddeleted file mode 100644index da55f517c..000000000--- a/changelog.d/998-left-drag-pan.md+++ /dev/null@@ -1,7 +0,0 @@-### Added--- Dragging the map with the left mouse button pans it, the way map apps do (#998; owner's ruling of 22 October 2026).- A plain left click still selects the hex and gives its orders. The pan starts only once the press leaves the click's- 30 px slop, so a click never nudges the map, and a drag selects nothing. The click is decided on the release rather- than the press — a press cannot be known to be a drag until it moves — and is still queued once per physical press,- so each click acts exactly once. Right-drag, the touch gestures and the keyboard are unchanged.diff --git a/changelog.d/close-borders-uncoloured.md b/changelog.d/close-borders-uncoloured.mddeleted file mode 100644index 05fadd133..000000000--- a/changelog.d/close-borders-uncoloured.md+++ /dev/null@@ -1,9 +0,0 @@-### Fixed--- Region borders no longer stop in mid-air where they meet land the 1948 lines leave without colour. On the south- coast at the game's start, Shoval's blue hex drew a lone edge against the Hebron hills, and the 9 July front ended- abruptly at the uncoloured Gaza sub-district. Land without colour now works like the land beyond the frontier: it- draws no band of its own, and each side's band runs along its edge. Every pinned settlement hex (Negba, Yad- Mordechai, Nir Am, Shoval and the rest) now gets a closed blue ring, and every front closes, in every period from- 15 May 1948 to the 1949 armistice lines. Display only: the sim never reads the control layer. Owner's ruling of- 27 October 2026 ("Close the borders").diff --git a/changelog.d/flag-render-callback.md b/changelog.d/flag-render-callback.mddeleted file mode 100644index 161ce0023..000000000--- a/changelog.d/flag-render-callback.md+++ /dev/null@@ -1 +0,0 @@-Ignore a camera-render callback retained after its unit flag has been destroyed.diff --git a/changelog.d/gdd-fixture-regression-contracts.md b/changelog.d/gdd-fixture-regression-contracts.mddeleted file mode 100644index 8e68d3d0c..000000000--- a/changelog.d/gdd-fixture-regression-contracts.md+++ /dev/null@@ -1 +0,0 @@-- Add fixture regression coverage for workshop worker identity across paid cycles and the unresolved housing-repair parent gate; live rules stay unchanged.diff --git a/changelog.d/gdd-play-time-120.md b/changelog.d/gdd-play-time-120.mddeleted file mode 100644index 7ab08d321..000000000--- a/changelog.d/gdd-play-time-120.md+++ /dev/null@@ -1,2 +0,0 @@-### Docs-- Record the owner's 30 Oct 2026 play-time ruling: a full session targets 120 minutes, matching `gdd03-balance.yaml` (#1687).diff --git a/changelog.d/gdd-regions-from-subdistricts.md b/changelog.d/gdd-regions-from-subdistricts.mddeleted file mode 100644index 9d8d25afc..000000000--- a/changelog.d/gdd-regions-from-subdistricts.md+++ /dev/null@@ -1 +0,0 @@-- Generate the nine inactive GDD 0.3 design-region hex lists deterministically from their approved Mandate sub-district coverage, while retaining unresolved place bindings for human review.diff --git a/changelog.d/gdd-resident-status-contract.md b/changelog.d/gdd-resident-status-contract.mddeleted file mode 100644index 2169f29a4..000000000--- a/changelog.d/gdd-resident-status-contract.md+++ /dev/null@@ -1 +0,0 @@-Added synthetic monthly-context regressions rejecting captured and transit pre-arrival residents while preserving constructible opening records.diff --git a/changelog.d/gdd03-assignment-reception-limit.md b/changelog.d/gdd03-assignment-reception-limit.mddeleted file mode 100644index a106fcabe..000000000--- a/changelog.d/gdd03-assignment-reception-limit.md+++ /dev/null@@ -1,3 +0,0 @@-### Fixed--- The detached GDD 0.3 assignment fixture refuses a reception-completion catalogue limit that differs from its initialized population ledger, matching the reception fixture. Refusal preserves the state. Shipping rules, catalogue values and save formats are unchanged.diff --git a/changelog.d/gdd03-regional-fixture-occupancy.md b/changelog.d/gdd03-regional-fixture-occupancy.mddeleted file mode 100644index 0f7b10d44..000000000--- a/changelog.d/gdd03-regional-fixture-occupancy.md+++ /dev/null@@ -1,3 +0,0 @@-### Fixed--- Bound synthetic GDD 0.3 Industry and Workshop assignments by their initialized regional job pools, preserving atomic refusals and independent work kinds. The fixture remains internal with no playable or production hookup.diff --git a/changelog.d/gdd03-same-slot-noop.md b/changelog.d/gdd03-same-slot-noop.mddeleted file mode 100644index b646c30a5..000000000--- a/changelog.d/gdd03-same-slot-noop.md+++ /dev/null@@ -1,3 +0,0 @@-### Changed--- The detached GDD 0.3 assignment fixture reports a same-job assignment as a no-op, matching the adopted owner ruling, instead of calling its already unchanged state Deferred.diff --git a/changelog.d/gdd03-training-reception-limit.md b/changelog.d/gdd03-training-reception-limit.mddeleted file mode 100644index f01e3b795..000000000--- a/changelog.d/gdd03-training-reception-limit.md+++ /dev/null@@ -1,2 +0,0 @@-### Fixed-- Refuse a detached GDD 0.3 training fixture whose reception duration disagrees with its initialized population ledger, before any course action or state change.diff --git a/changelog.d/hex-props-1155.md b/changelog.d/hex-props-1155.mddeleted file mode 100644index 77896894f..000000000--- a/changelog.d/hex-props-1155.md+++ /dev/null@@ -1,7 +0,0 @@-- Props for the opt-in hex-tile map, still presentation only and off by default: 20 AI-made 3D props by Tal Heuberger- (Higgsfield, Tripo H3.1) fill the stand-ins of the Arab village (minaret, prickly pear), Jaffa (clock tower, sea- minaret, belfry), the coastal dunes (scrub), the desert edge (Bedouin tent) and the Judean highlands (garrigue), and- three new tiles use the rest: a railway halt with a packing house, coastal ruins with a landing stage, and a village- mill with threshing floors and terraces. The props stream after the first frame from a bundle of their own, only- with `?hex-tiles` on, so the default download does not grow. `HexSandboxImport.RunHiggsfield` imports a manifest of- such props (refs #18).diff --git a/changelog.d/laneKT-1125.md b/changelog.d/laneKT-1125.mddeleted file mode 100644index 71bae3d13..000000000--- a/changelog.d/laneKT-1125.md+++ /dev/null@@ -1,2 +0,0 @@-- Each option on an event card lists what it does under its label, in English and Hebrew: one line per effect, from the- simulation's preview (#1125, Refs #811). The option's label, price and selection are unchanged.diff --git a/changelog.d/laneMF-812.md b/changelog.d/laneMF-812.mddeleted file mode 100644index f1561f589..000000000--- a/changelog.d/laneMF-812.md+++ /dev/null@@ -1 +0,0 @@-- The end report carries the score's parts (objective points, timing bonuses, prisoner points) beside the total, read from the final state; no screen shows them yet (Refs #812).diff --git a/changelog.d/laneMG-812.md b/changelog.d/laneMG-812.mddeleted file mode 100644index 265f2b114..000000000--- a/changelog.d/laneMG-812.md+++ /dev/null@@ -1,3 +0,0 @@-- The end screen can show a cause's sourced history note under its line (Q-DEF-4 (b)); a cause without a note goes- straight from its line to the score. The armistice note for a war loss is held out of the strings until the person's- check of the history note is recorded, so no ending shows a note yet (Refs #812).diff --git a/changelog.d/laneMH-812.md b/changelog.d/laneMH-812.mddeleted file mode 100644index f6ce89ed4..000000000--- a/changelog.d/laneMH-812.md+++ /dev/null@@ -1,2 +0,0 @@-- The end screen shows the prisoners returned (Q-END-3): one line, "Prisoners returned:" and the count in people as the- Defence screen counts them, only when some prisoners went home. The end report carries the count (#812).diff --git a/changelog.d/laneNP-1970.md b/changelog.d/laneNP-1970.mddeleted file mode 100644index b606cfb99..000000000--- a/changelog.d/laneNP-1970.md+++ /dev/null@@ -1,3 +0,0 @@-### Fixed-- `scripts/check.sh`'s Unity compile step now finds a Linux editor (`~/Unity/Hub/Editor/<version>/Editor/Data`), and- `scripts/unity_compile/compile.sh` accepts that layout, so the check no longer always skips on Linux. macOS is unchanged.diff --git a/changelog.d/mac-trackpad-pinch-zoom.md b/changelog.d/mac-trackpad-pinch-zoom.mddeleted file mode 100644index 485ff9341..000000000--- a/changelog.d/mac-trackpad-pinch-zoom.md+++ /dev/null@@ -1,4 +0,0 @@-### Fixed--- A trackpad pinch zooms the map in the macOS player, as it does in the browser: the player passed the pinch to- nothing, so it did not zoom at all. The wheel, a two-finger scroll and the zoom keys already zoomed there.diff --git a/changelog.d/nightly-managed-lock.md b/changelog.d/nightly-managed-lock.mddeleted file mode 100644index 629ba9e19..000000000--- a/changelog.d/nightly-managed-lock.md+++ /dev/null@@ -1,2 +0,0 @@-- Keep nightly managed gates and compiler shutdown under the shared machine lock, with node reuse and shared- compilation disabled.diff --git a/changelog.d/nightly-release-id-recovery.md b/changelog.d/nightly-release-id-recovery.mddeleted file mode 100644index ee8f9c4b9..000000000--- a/changelog.d/nightly-release-id-recovery.md+++ /dev/null@@ -1 +0,0 @@-Record the nightly draft release ID before uploads, refuse cleanup of a different release, and retry a recorded failed Latest recovery before the next run proceeds.diff --git a/changelog.d/nightly-release.md b/changelog.d/nightly-release.mddeleted file mode 100644index a5de9a9f8..000000000--- a/changelog.d/nightly-release.md+++ /dev/null@@ -1,3 +0,0 @@-- Nightly builds: every night at 03:00 (Israel time) the newest `main` is built, checked against the build that is live- and, only if every check passes, published as a GitHub pre-release that the website's demo serves (`docs/RELEASING.md`,- "Nightly builds"). itch.io uploads follow once the automated save test passes.diff --git a/changelog.d/nightly-web-artifact-preservation.md b/changelog.d/nightly-web-artifact-preservation.mddeleted file mode 100644index c046a5918..000000000--- a/changelog.d/nightly-web-artifact-preservation.md+++ /dev/null@@ -1 +0,0 @@-Preserve the completed gzip player before Unity builds the Pages variant, so Bee cannot retire files needed by packaging and browser gates. Existing release, source-cleanliness and publication gates remain in place.diff --git a/changelog.d/regions-design-adaptation.md b/changelog.d/regions-design-adaptation.mddeleted file mode 100644index fb36a4b1c..000000000--- a/changelog.d/regions-design-adaptation.md+++ /dev/null@@ -1 +0,0 @@-- Record the approved regional design associations and capital choices separately from historical evidence. Retain unresolved geometry, control and camp-footprint checks; stage schema adaptation and named-place acceptance fixtures while regional activation remains off under gdd-0.3.diff --git a/changelog.d/release-cause-parser-coverage.md b/changelog.d/release-cause-parser-coverage.mddeleted file mode 100644index 3d11c1f60..000000000--- a/changelog.d/release-cause-parser-coverage.md+++ /dev/null@@ -1,2 +0,0 @@-### Tests-- Cover invariant economic cause arguments, political cause argument ordering and IDs, and map-editor digest validation boundaries.diff --git a/changelog.d/release-qualification-cause-tests.md b/changelog.d/release-qualification-cause-tests.mddeleted file mode 100644index 97f6a3bcf..000000000--- a/changelog.d/release-qualification-cause-tests.md+++ /dev/null@@ -1 +0,0 @@-- Add production-command regression coverage for qualification localization keys and arguments; game behavior is unchanged.diff --git a/changelog.d/release-save-preservation.md b/changelog.d/release-save-preservation.mddeleted file mode 100644index c5a1aab6b..000000000--- a/changelog.d/release-save-preservation.md+++ /dev/null@@ -1,3 +0,0 @@-### Fixed--- Preserve earlier rejected autosaves when another unreadable autosave or temporary save is set aside, keeping each file for diagnosis.diff --git a/changelog.d/tal-ala-third-figure.md b/changelog.d/tal-ala-third-figure.mddeleted file mode 100644index b348dd101..000000000--- a/changelog.d/tal-ala-third-figure.md+++ /dev/null@@ -1,4 +0,0 @@-- The Arab Liberation Army's token shows Tal Heuberger's ALA infantry as its third figure, beside two of the original- irregulars (C09), as the owner chose on 27 October 2026 after signing off all 19 of Tal Heuberger's generated models- (#756). The figure streams after the first frame in a bundle of its own, opened after the people's; the token still- waits only for C09, and keeps two figures if the new bundle is missing. Goldens did not move.diff --git a/changelog.d/tal-bedouin-camps.md b/changelog.d/tal-bedouin-camps.mddeleted file mode 100644index ec5b93f40..000000000--- a/changelog.d/tal-bedouin-camps.md+++ /dev/null@@ -1,5 +0,0 @@-- Tal Heuberger's Bedouin civilian and enclosed striped Bedouin tent stand in the Bedouin camp areas (the owner signed- off all 19 of Tal Heuberger's generated models on 27 October 2026, #756): the figure at up to three of the camels'- served camp areas, the tent at up to three Bedouin-area anchors on clear ground apart from the code-built camps'- plots, whose tents stay as they are. Both models stream after the first frame, each in a bundle of its own. Goldens- did not move.diff --git a/changelog.d/tal-egypt-on-map.md b/changelog.d/tal-egypt-on-map.mddeleted file mode 100644index eac4b68fd..000000000--- a/changelog.d/tal-egypt-on-map.md+++ /dev/null@@ -1,5 +0,0 @@-- The Egyptian Expeditionary Force is on the map, wearing Tal Heuberger's Egyptian infantry figure (the owner signed- off all 19 of Tal Heuberger's generated models on 27 October 2026, #756). It is one token: in the normal game the- force's sim unit, from Gaza on 15 May 1948; in the legacy loop its row's dated anchors, at the first truce the forward- base at Isdud (the rear base at Majdal stays in the row and on the card). The figure streams after the first frame in- a bundle of its own, opened after the people's, so the first download does not grow. Goldens did not move.diff --git a/changelog.d/tal-lebanon-on-map.md b/changelog.d/tal-lebanon-on-map.mddeleted file mode 100644index 9e91345dc..000000000--- a/changelog.d/tal-lebanon-on-map.md+++ /dev/null@@ -1,4 +0,0 @@-- The Lebanese army is on the map at al-Malikiyya from 6 June to 8 July 1948, drawn with Tal Heuberger's Lebanese regular- (owner, 28 October 2026: "6 Jun to 8 Jul (Recommended)"; sources: Dupuy p. 47 and the JTA bulletins of 7 and 8 June).- It has no sim unit: its token is map-only in both loops (owner, 27 October 2026: "Map-only token (Recommended)") and- never moves or fights. The figure streams after the first frame in a bundle of its own. Goldens did not move.diff --git a/changelog.d/tal-lebanon-unit-card-copy.md b/changelog.d/tal-lebanon-unit-card-copy.mddeleted file mode 100644index 5137eff47..000000000--- a/changelog.d/tal-lebanon-unit-card-copy.md+++ /dev/null@@ -1 +0,0 @@-- Keep internal decision references out of the Lebanese unit card in English and Hebrew; retain the source and unresolved checks in its data record.diff --git a/changelog.d/unit-figure-residency-bounds.md b/changelog.d/unit-figure-residency-bounds.mddeleted file mode 100644index aedbe0c67..000000000--- a/changelog.d/unit-figure-residency-bounds.md+++ /dev/null@@ -1 +0,0 @@-- Refresh unit figure keep-clear bounds after model streaming or retirement, including when the camera stays still, and avoid reading retired mesh components.diff --git a/changelog.d/unity-settings-upgrade.md b/changelog.d/unity-settings-upgrade.mddeleted file mode 100644index eb23b8149..000000000--- a/changelog.d/unity-settings-upgrade.md+++ /dev/null@@ -1,3 +0,0 @@-### Changed-- `QualitySettings.asset` and `URPProjectSettings.asset` are saved in the format the Unity 6000.3.25f1 editor writes,- so a Unity run no longer leaves them changed in the working tree. The game looks and plays the same.diff --git a/changelog.d/v032-hebrew-wording.md b/changelog.d/v032-hebrew-wording.mddeleted file mode 100644index 617100848..000000000--- a/changelog.d/v032-hebrew-wording.md+++ /dev/null@@ -1,4 +0,0 @@-- Hebrew wording: a captured place that Israel holds reads "מוחזק" and "תקופת ההחזקה" in the Why panel and the turn- report, never כיבוש or שחרור, as the strings file's own rule says; the Jerusalem demilitarisation and Rafah cards ask- "על {prime_minister} להחליט" like the other cards; a finished city project reads "סיום"; the pioneer card says- "משושה" like every other hex string; and the Degania card writes מ״מ with gershayim.diff --git a/sim/Statecraft.Sim.Tests/SmokeTests.cs b/sim/Statecraft.Sim.Tests/SmokeTests.csindex 56c8fab4a..d983fc7b7 100644--- a/sim/Statecraft.Sim.Tests/SmokeTests.cs+++ b/sim/Statecraft.Sim.Tests/SmokeTests.cs@@ -3,5 +3,5 @@ using Statecraft.Sim;public class SmokeTests{[Fact]- public void SimLibraryIsReferenced() => Assert.Equal("0.3.1", SimInfo.Version);+ public void SimLibraryIsReferenced() => Assert.Equal("0.3.2", SimInfo.Version);}diff --git a/sim/Statecraft.Sim/SimInfo.cs b/sim/Statecraft.Sim/SimInfo.csindex 7743ca67f..da72d833c 100644--- a/sim/Statecraft.Sim/SimInfo.cs+++ b/sim/Statecraft.Sim/SimInfo.cs@@ -2,6 +2,6 @@ namespace Statecraft.Sim{public static class SimInfo{- public const string Version = "0.3.1";+ public const string Version = "0.3.2";}}diff --git a/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs b/unity/Assets/Scripts/Map/Collection/CivilianPeople.csindex 01e9cc598..fb4776a7e 100644--- a/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs+++ b/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs@@ -320,14 +320,37 @@ namespace Statecraft.Game.Map.Collectionif (Request != DefaultRequest) { Request(id, detail, done); return new TestSeamLease(); }return CollectionStream.Acquire(id, detail, done);}- void RefreshResidency()+ void RefreshResidency() => RefreshResidencyCore(true);+ void RefreshResidencyCore(bool redraw){if (!isActiveAndEnabled) return;residency ??= new CollectionResidency(AcquireOriginal, ClearForRetirement, OnModel,(instances, owners, keys, complete) => CollectionResidencyMetrics.AfterDestroyed("people", instances, owners, complete,- Application.isPlaying && ownedAcquire == null && Request == DefaultRequest ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys));- residency.Replace(Admitted().SelectMany(w => desiredDetails.Select(d => (w.Model, d))));- Rebuild();+ Application.isPlaying && ownedAcquire == null && Request == DefaultRequest ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys), true);+ // v0.3.1 Ask(Far) requested every wanted model, while Near was first requested by Choose at close zoom.+ var far = wanted.Select(w => (w.Model, CollectionDetail.Far));+ var near = desiredDetails.Contains(CollectionDetail.Near)+ ? Admitted().Select(w => (w.Model, CollectionDetail.Near))+ : Enumerable.Empty<(string, CollectionDetail)>();+ residency.Replace(far.Concat(near));+ if (redraw) Rebuild();+ }+ IReadOnlyList<UnityEngine.Object> ClearForRetirement(IReadOnlyCollection<(string id, CollectionDetail detail)> keys)+ {+ var removed = new List<UnityEngine.Object>();+ foreach (var key in keys)+ {+ prefabs.Remove((key.id, key.detail)); asked.Remove((key.id, key.detail));+ if (!originals.TryGetValue((key.id, key.detail), out var list)) continue;+ foreach (var go in list) if (go != null)+ {+ removed.Add(go);+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) go.transform.SetParent(null); Destroy(go); } else DestroyImmediate(go);+ }+ originals.Remove((key.id, key.detail));+ }+ pairs.RemoveAll(pair => pair.Person == null || pair.Person.Find("Far") == null);+ return removed;}IReadOnlyList<UnityEngine.Object> ClearForRetirement(){@@ -341,7 +364,7 @@ namespace Statecraft.Game.Map.Collection}void LateUpdate(){- if (residencyView != null && residencyView.Prune(Time.frameCount)) RefreshResidency();+ if (residencyView != null && residencyView.Prune(Time.frameCount)) { RefreshResidencyCore(false); SyncNearVisuals(); Apply(lastClose); }}IEnumerable<Want> Admitted(){@@ -353,10 +376,11 @@ namespace Statecraft.Game.Map.Collectionfor (int i = transform.childCount - 1; i >= 0; i--){var old = transform.GetChild(i).gameObject; destroyedOriginals.Add(old);- if (Application.isPlaying) { old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);}destroyedOriginals.RemoveAll(o => o == null);- pairs.Clear(); Placed.Clear(); Missing.Clear();+ originals.Clear();+ peopleByKey.Clear(); pairs.Clear(); Placed.Clear(); Missing.Clear();}MapScene? map;@@ -365,7 +389,10 @@ namespace Statecraft.Game.Map.Collectionnew Dictionary<(string, CollectionDetail), GameObject?>();readonly HashSet<(string Model, CollectionDetail Detail)> asked = new HashSet<(string, CollectionDetail)>();readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();- readonly List<(Renderer[] Far, Renderer[] Near, Animator[] NearAnimators, bool Animate)> pairs = new List<(Renderer[], Renderer[], Animator[], bool)>();+ readonly Dictionary<(string Model, CollectionDetail Detail), List<GameObject>> originals =+ new Dictionary<(string, CollectionDetail), List<GameObject>>();+ readonly Dictionary<string, Transform> peopleByKey = new Dictionary<string, Transform>(StringComparer.Ordinal);+ readonly List<(Transform Person, bool Animate)> pairs = new List<(Transform, bool)>();bool lastClose;public readonly List<PlacedFigure> Placed = new List<PlacedFigure>();@@ -409,7 +436,8 @@ namespace Statecraft.Game.Map.Collectionif (prefab == null)Debug.LogWarning($"PEOPLE: {model} {detail.ToString().ToLowerInvariant()} did not stream; "+ (detail == CollectionDetail.Far ? "its civilians are not drawn" : "its far civilians remain") + ", and the map plays on.");- Rebuild();+ if (detail == CollectionDetail.Near) { SyncNearVisuals(); Apply(lastClose); }+ else Rebuild();}void Rebuild()@@ -417,7 +445,8 @@ namespace Statecraft.Game.Map.CollectionCollectionResidencyMetrics.MarkDirty();ClearVisuals();var parents = new Dictionary<string, Transform>(StringComparer.Ordinal);- foreach (var want in Admitted())+ var nearKeys = residencyView?.Keys;+ foreach (var want in wanted){bool farKnown = prefabs.TryGetValue((want.Model, CollectionDetail.Far), out var farPrefab);if (!farKnown) continue;@@ -433,20 +462,43 @@ namespace Statecraft.Game.Map.Collection}var person = new GameObject(personKey).transform;person.SetParent(parent, false);- var far = Make(person, "Far", farPrefab, want);- Renderer[] near = Array.Empty<Renderer>();- if (prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var nearPrefab) && nearPrefab != null)- near = Make(person, "Near", nearPrefab, want);- pairs.Add((far, near, person.Find("Near")?.GetComponentsInChildren<Animator>(true) ?? Array.Empty<Animator>(), !OriginalModelPose.Required(want.Model)));+ peopleByKey[want.Key] = person;+ Make(person, "Far", farPrefab, want, CollectionDetail.Far);+ if ((nearKeys == null || nearKeys.Contains(want.Key))+ && prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var nearPrefab) && nearPrefab != null)+ Make(person, "Near", nearPrefab, want, CollectionDetail.Near);+ pairs.Add((person, !OriginalModelPose.Required(want.Model)));Placed.Add(new PlacedFigure(want));}Apply(lastClose);Debug.Log($"PEOPLE: {Placed.Count} civilian figures placed, {Missing.Count} not drawn");}- static Renderer[] Make(Transform parent, string name, GameObject prefab, Want want)+ void SyncNearVisuals()+ {+ var admitted = residencyView?.Keys;+ foreach (var want in wanted)+ {+ if (!peopleByKey.TryGetValue(want.Key, out var person) || person == null) continue;+ bool wantsNear = admitted == null || admitted.Contains(want.Key);+ var near = person.Find("Near");+ if (!wantsNear && near != null)+ {+ if (originals.TryGetValue((want.Model, CollectionDetail.Near), out var owned)) owned.Remove(near.gameObject);+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) near.SetParent(null); Destroy(near.gameObject); } else DestroyImmediate(near.gameObject);+ }+ else if (wantsNear && near == null+ && prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var prefab) && prefab != null)+ Make(person, "Near", prefab, want, CollectionDetail.Near);+ }+ }++ Renderer[] Make(Transform parent, string name, GameObject prefab, Want want, CollectionDetail detail){var go = Instantiate(prefab, parent, false);+ if (!originals.TryGetValue((want.Model, detail), out var owned))+ originals[(want.Model, detail)] = owned = new List<GameObject>();+ owned.Add(go);go.name = name;OriginalModelPose.Sample(go); // both aliases are measured in frame-zero pose; Apply starts only visible near idle// Compose the seeded yaw on top of the prefab root's FBX -90-degree X conversion (#979).@@ -497,7 +549,7 @@ namespace Statecraft.Game.Map.Collection{var previousDemand = residencyView.Keys;residencyView.Observe(camera, wanted.Select(w => (w.Key, w.At, FigureClearanceM)), Time.frameCount);- if (!previousDemand.SetEquals(residencyView.Keys)) RefreshResidency();+ if (!previousDemand.SetEquals(residencyView.Keys)) { RefreshResidencyCore(false); SyncNearVisuals(); Apply(lastClose); }}int id = camera.GetInstanceID();bool close = CloseAt(TownLandmarks.ViewDistance(camera), closeFor.TryGetValue(id, out var previous) ? previous : (bool?)null);@@ -510,10 +562,15 @@ namespace Statecraft.Game.Map.Collection{foreach (var pair in pairs){- bool near = close && pair.Near.Length > 0;- foreach (var renderer in pair.Far) renderer.forceRenderingOff = near;- foreach (var renderer in pair.Near) renderer.forceRenderingOff = !near;- foreach (var animator in pair.NearAnimators) animator.enabled = near && pair.Animate;+ if (pair.Person == null) continue;+ var far = pair.Person.Find("Far"); var nearRoot = pair.Person.Find("Near");+ bool near = close && nearRoot != null;+ if (far != null) foreach (var renderer in far.GetComponentsInChildren<Renderer>(true)) if (renderer != null) renderer.forceRenderingOff = near;+ if (nearRoot != null)+ {+ foreach (var renderer in nearRoot.GetComponentsInChildren<Renderer>(true)) if (renderer != null) renderer.forceRenderingOff = !near;+ foreach (var animator in nearRoot.GetComponentsInChildren<Animator>(true)) if (animator != null) animator.enabled = near && pair.Animate;+ }}}}diff --git a/unity/Assets/Scripts/Map/Collection/CollectionResidency.cs b/unity/Assets/Scripts/Map/Collection/CollectionResidency.csindex ca53aaf7b..33c761f07 100644--- a/unity/Assets/Scripts/Map/Collection/CollectionResidency.cs+++ b/unity/Assets/Scripts/Map/Collection/CollectionResidency.cs@@ -28,73 +28,165 @@ namespace Statecraft.Game.Map.Collectioninternal delegate void Retire(IReadOnlyList<UnityEngine.Object> instances, IReadOnlyList<IDisposable> owners,IReadOnlyList<(string id, CollectionDetail detail)> keys, Action complete);readonly Func<string, CollectionDetail, Action<GameObject?>, IDisposable> acquire;- readonly Func<IReadOnlyList<UnityEngine.Object>> destroyAndClear;+ readonly Func<IReadOnlyCollection<(string id, CollectionDetail detail)>, IReadOnlyList<UnityEngine.Object>> destroyAndClear;readonly Action<string, CollectionDetail, GameObject?> answer;readonly Retire retire;- readonly List<IDisposable> owners = new List<IDisposable>();+ readonly bool keyedRetirement;+ readonly Dictionary<(string id, CollectionDetail detail), IDisposable> owners =+ new Dictionary<(string, CollectionDetail), IDisposable>();+ readonly Dictionary<(string id, CollectionDetail detail), int> requestVersions =+ new Dictionary<(string, CollectionDetail), int>();+ readonly Dictionary<(string id, CollectionDetail detail), GameObject?> answeredPrefabs =+ new Dictionary<(string, CollectionDetail), GameObject?>();+ readonly HashSet<(string id, CollectionDetail detail)> retiringKeys =+ new HashSet<(string, CollectionDetail)>();HashSet<(string id, CollectionDetail detail)> active = new HashSet<(string, CollectionDetail)>(),latest = new HashSet<(string, CollectionDetail)>();- int generation;+ int nextRequestVersion;bool retiring, disposed;readonly HashSet<(string id, CollectionDetail detail)> answered = new HashSet<(string, CollectionDetail)>();internal int PendingCount => active.Count(k => !answered.Contains(k));internal int OwnerCount => owners.Count;- internal bool IsRetiring => retiring;+ internal bool IsRetiring => retiring || retiringKeys.Count != 0;+ internal IReadOnlyCollection<(string id, CollectionDetail detail)> ActiveKeys => active.ToArray();+ internal bool ActiveAndAnswered((string id, CollectionDetail detail) key) =>+ active.Contains(key) && answered.Contains(key);public CollectionResidency(Func<string, CollectionDetail, Action<GameObject?>, IDisposable> acquire,Func<IReadOnlyList<UnityEngine.Object>> destroyAndClear, Action<string, CollectionDetail, GameObject?> answer, Retire retire)- { this.acquire = acquire; this.destroyAndClear = destroyAndClear; this.answer = answer; this.retire = retire; }+ : this(acquire, _ => destroyAndClear(), answer, retire, false) { }+ internal CollectionResidency(Func<string, CollectionDetail, Action<GameObject?>, IDisposable> acquire,+ Func<IReadOnlyCollection<(string id, CollectionDetail detail)>, IReadOnlyList<UnityEngine.Object>> destroyAndClear,+ Action<string, CollectionDetail, GameObject?> answer, Retire retire, bool keyedRetirement)+ { this.acquire = acquire; this.destroyAndClear = destroyAndClear; this.answer = answer; this.retire = retire; this.keyedRetirement = keyedRetirement; }internal void Replace(IEnumerable<(string id, CollectionDetail detail)> demand){if (disposed) return;latest = new HashSet<(string, CollectionDetail)>(demand); CollectionResidencyMetrics.MarkDirty();- if (retiring || active.SetEquals(latest)) return;- // Adding a near alias does not retire a still-needed far consumer.- if (active.IsSubsetOf(latest))- {- var added = latest.Except(active).ToArray();- active = new HashSet<(string, CollectionDetail)>(latest);- AcquireKeys(added); return;- }- Leave();+ if (keyedRetirement) ReconcileKeyed();+ else if (!retiring) ReconcileLegacy();+ }+ void ReconcileLegacy()+ {+ var removed = active.Except(latest).ToArray();+ if (removed.Length != 0) { LeaveLegacy(active.ToArray()); return; }+ var added = latest.Except(active).ToArray();+ active.UnionWith(added);+ AcquireKeys(added);}- void Leave()+ void LeaveLegacy(IReadOnlyCollection<(string id, CollectionDetail detail)> oldKeys){- generation++; // No old answer may rebuild the departed view.- var oldKeys = active.ToArray(); active.Clear(); answered.Clear();- var oldOwners = owners.ToArray(); owners.Clear();- var instances = destroyAndClear(); // Must restore fallback/destroy and clear all prefab/renderer references first.+ foreach (var key in oldKeys)+ { active.Remove(key); answered.Remove(key); answeredPrefabs.Remove(key); requestVersions.Remove(key); }+ var oldOwners = oldKeys.Where(owners.ContainsKey).Select(key => owners[key]).ToArray();+ foreach (var key in oldKeys) owners.Remove(key);+ var instances = destroyAndClear(oldKeys); // Destroy/clear references before allowing a bundle unload.retiring = true;- retire(instances, oldOwners, oldKeys, () =>+ retire(instances, oldOwners, oldKeys.ToArray(), () =>{retiring = false;- if (!disposed) Admit();+ ReconcileLegacy();});}- void Admit()++ sealed class HeldLease : IDisposable+ {+ // CollectionRetirement calls Dispose only after every instance is gone. The coordinator makes the+ // final release/reuse decision in the completion callback, when the latest demand is known.+ public void Dispose() { }+ }+ sealed class RetiringKey+ {+ internal readonly (string id, CollectionDetail detail) Key;+ internal readonly IDisposable Owner;+ internal readonly bool HadAnswer;+ internal readonly GameObject? Prefab;+ internal RetiringKey((string id, CollectionDetail detail) key, IDisposable owner, bool hadAnswer, GameObject? prefab)+ { Key = key; Owner = owner; HadAnswer = hadAnswer; Prefab = prefab; }+ }+ void ReconcileKeyed()+ {+ var removed = active.Except(latest).ToArray();+ if (removed.Length != 0) RetireKeys(removed);+ // An unrelated retirement never freezes admission. A key already retiring waits for its own completion,+ // where its lease and answered prefab are reused without a bundle refcount 1 -> 0 -> 1 transition.+ var added = latest.Except(active).Where(key => !retiringKeys.Contains(key)).ToArray();+ active.UnionWith(added);+ AcquireKeys(added);+ }+ void RetireKeys(IReadOnlyCollection<(string id, CollectionDetail detail)> keys){- active = new HashSet<(string, CollectionDetail)>(latest);- AcquireKeys(active);+ var batch = new List<RetiringKey>();+ foreach (var key in keys)+ {+ active.Remove(key); requestVersions.Remove(key);+ bool hadAnswer = answered.Remove(key);+ answeredPrefabs.TryGetValue(key, out var prefab); answeredPrefabs.Remove(key);+ if (owners.TryGetValue(key, out var owner))+ {+ owners.Remove(key);+ batch.Add(new RetiringKey(key, owner, hadAnswer, prefab));+ retiringKeys.Add(key);+ }+ }+ var instances = destroyAndClear(keys); // Destroy/clear references before allowing a bundle unload.+ retire(instances, batch.Select(_ => (IDisposable)new HeldLease()).ToArray(), keys.ToArray(), () => CompleteRetirement(batch));+ }+ void CompleteRetirement(IReadOnlyList<RetiringKey> batch)+ {+ var reacquire = new List<(string id, CollectionDetail detail)>();+ foreach (var item in batch)+ {+ retiringKeys.Remove(item.Key);+ if (!disposed && latest.Contains(item.Key))+ {+ active.Add(item.Key);+ if (item.HadAnswer)+ {+ owners[item.Key] = item.Owner;+ answered.Add(item.Key); answeredPrefabs[item.Key] = item.Prefab;+ answer(item.Key.id, item.Key.detail, item.Prefab);+ }+ else reacquire.Add(item.Key);+ }+ else item.Owner.Dispose();+ }+ // A pending source had no prefab to replay. Acquire its replacement before releasing the old lease, so the+ // bundle remains referenced throughout the hand-off.+ if (reacquire.Count != 0)+ {+ AcquireKeys(reacquire);+ foreach (var item in batch) if (reacquire.Contains(item.Key)) item.Owner.Dispose();+ }+ if (!disposed) ReconcileKeyed();}void AcquireKeys(IEnumerable<(string id, CollectionDetail detail)> keys){- int version = generation;foreach (var key in keys.OrderBy(k => k.id, StringComparer.Ordinal).ThenBy(k => k.detail).ToArray()){- if (disposed || version != generation) return;+ if (disposed) return;+ // A synchronous answer can re-enter Replace and retire or re-acquire later keys of this snapshot. Acquire a+ // key only while it is still active and unowned: a second lease would overwrite (and leak) the first.+ if (!active.Contains(key) || owners.ContainsKey(key)) continue;+ int version = ++nextRequestVersion;+ requestVersions[key] = version;var lease = acquire(key.id, key.detail, prefab =>{- if (!disposed && version == generation && active.Contains(key)) { answered.Add(key); answer(key.id, key.detail, prefab); CollectionResidencyMetrics.MarkDirty(); }+ if (!disposed && active.Contains(key) && requestVersions.TryGetValue(key, out int current) && current == version)+ { answered.Add(key); answeredPrefabs[key] = prefab; answer(key.id, key.detail, prefab); CollectionResidencyMetrics.MarkDirty(); }});// Synchronous fake/editor answers may tear down the owner.- if (disposed || version != generation) lease.Dispose(); else owners.Add(lease);+ if (disposed || !active.Contains(key) || !requestVersions.TryGetValue(key, out int current) || current != version)+ lease.Dispose();+ else owners[key] = lease;}}public void Dispose(){if (disposed) return;disposed = true; latest.Clear();- if (!retiring) Leave(); else generation++;+ if (keyedRetirement) ReconcileKeyed();+ else if (!retiring) ReconcileLegacy();}}diff --git a/unity/Assets/Scripts/Map/Collection/CollectionResidencyMetrics.cs b/unity/Assets/Scripts/Map/Collection/CollectionResidencyMetrics.csindex 1f398f175..735676f14 100644--- a/unity/Assets/Scripts/Map/Collection/CollectionResidencyMetrics.cs+++ b/unity/Assets/Scripts/Map/Collection/CollectionResidencyMetrics.cs@@ -17,7 +17,10 @@ namespace Statecraft.Game.Map.Collectionpublic string category = "";public int uniqueDetails;public string[] detailIds = Array.Empty<string>();- public int demandedAnchors, liveInstances, ownedLeases, pendingRequests, retiringLeases, pendingDestroy;+ /// <summary>Active ownership demand. A category may retain an anchor without current camera demand; its+ /// category snapshot documents that distinction.</summary>+ public int demandedAnchors;+ public int liveInstances, ownedLeases, pendingRequests, retiringLeases, pendingDestroy;public int prefabCacheRefs, rendererCacheRefs, waiterCacheRefs, strongCacheRefs, missing, uniqueIds, bundleOwners, pins;public string[] originalIds = Array.Empty<string>(), bundleScopeIds = Array.Empty<string>();}diff --git a/unity/Assets/Scripts/Map/Collection/RuralLife.cs b/unity/Assets/Scripts/Map/Collection/RuralLife.csindex 2b3471cdc..0fa4ae4ac 100644--- a/unity/Assets/Scripts/Map/Collection/RuralLife.cs+++ b/unity/Assets/Scripts/Map/Collection/RuralLife.cs@@ -186,14 +186,44 @@ namespace Statecraft.Game.Map.Collectionif (Request != DefaultRequest) { Request(id, detail, done); return new TestSeamLease(); }return CollectionStream.Acquire(id, detail, done);}- void RefreshResidency()+ IEnumerable<(string id, CollectionDetail detail)> ResidencyDemand()+ {+ // v0.3.1 requested Far and Near for every wanted model. The 30 October ruling keeps that Far set map-wide,+ // but gates Near to the successfully placed v0.3.1 pairings (Scenes), never unplaced/failed/capped wants.+ var far = wants.Select(w => (w.Model, CollectionDetail.Far));+ var keys = residencyView?.Keys;+ var near = Scenes.Where(w => keys == null || keys.Contains(w.Key + "|" + w.Model))+ .Select(w => (w.Model, CollectionDetail.Near));+ return far.Concat(near);+ }+ void RefreshResidency() => RefreshResidencyCore(true);+ void RefreshResidencyCore(bool redraw){if (!isActiveAndEnabled) return;residency ??= new CollectionResidency(AcquireOriginal, ClearForRetirement, OnModel,(instances, owners, keys, complete) => CollectionResidencyMetrics.AfterDestroyed("rural", instances, owners, complete,- Application.isPlaying && ownedAcquire == null && Request == DefaultRequest ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys));- residency.Replace(Admitted().SelectMany(w => desiredDetails.Select(d => (w.Model, d))));- Rebuild();+ Application.isPlaying && ownedAcquire == null && Request == DefaultRequest ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys), true);+ residency.Replace(ResidencyDemand());+ if (redraw)+ {+ Rebuild();+ // Rebuild is what proves a pairing survived MaxAnchorsPerModel and Spot; admit Near only afterwards.+ residency.Replace(ResidencyDemand());+ }+ }+ IReadOnlyList<UnityEngine.Object> ClearForRetirement(IReadOnlyCollection<(string id, CollectionDetail detail)> keys)+ {+ var removed = new List<UnityEngine.Object>();+ foreach (var key in keys)+ {+ prefabs.Remove((key.id, key.detail)); asked.Remove((key.id, key.detail));+ if (!originals.TryGetValue((key.id, key.detail), out var list)) continue;+ foreach (var go in list) if (go != null) { removed.Add(go); DestroyNow(go); }+ originals.Remove((key.id, key.detail));+ Placed.RemoveAll(p => p.Model == key.id && p.Detail == key.detail);+ }+ renderers.RemoveAll(p => p.Renderer == null); animators.RemoveAll(p => p.Animator == null);+ return removed;}IReadOnlyList<UnityEngine.Object> ClearForRetirement(){@@ -207,7 +237,7 @@ namespace Statecraft.Game.Map.Collection}void LateUpdate(){- if (residencyView != null && residencyView.Prune(Time.frameCount)) RefreshResidency();+ if (residencyView != null && residencyView.Prune(Time.frameCount)) { RefreshResidencyCore(false); SyncNearVisuals(); }}IEnumerable<Want> Admitted(){@@ -217,6 +247,7 @@ namespace Statecraft.Game.Map.Collectionvoid ClearVisuals(){for (int i = transform.childCount - 1; i >= 0; i--) DestroyNow(transform.GetChild(i).gameObject);+ originals.Clear();renderers.Clear(); animators.Clear(); Placed.Clear(); Scenes.Clear(); Missing.Clear();if (map != null) Units.UnitShowcase.HideTrees(map, Name, Array.Empty<(Vector2 centre, float radius)>());}@@ -225,8 +256,10 @@ namespace Statecraft.Game.Map.Collectionreadonly Dictionary<(string Model, CollectionDetail Detail), GameObject?> prefabs = new Dictionary<(string, CollectionDetail), GameObject?>();readonly HashSet<(string Model, CollectionDetail Detail)> asked = new HashSet<(string, CollectionDetail)>();readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();- readonly List<(Renderer Renderer, CollectionDetail Detail)> renderers = new List<(Renderer, CollectionDetail)>();+ readonly List<(Renderer Renderer, CollectionDetail Detail, string Instance)> renderers = new List<(Renderer, CollectionDetail, string)>();readonly List<(Animator Animator, CollectionDetail Detail)> animators = new List<(Animator, CollectionDetail)>();+ readonly Dictionary<(string Model, CollectionDetail Detail), List<GameObject>> originals =+ new Dictionary<(string, CollectionDetail), List<GameObject>>();List<Want> wants = new List<Want>();public readonly List<(string Key, string Model, CollectionDetail Detail, Vector3 At, string Name, int Member)> Placed =@@ -284,7 +317,44 @@ namespace Statecraft.Game.Map.Collectionif (this == null) return;prefabs[(model, detail)] = prefab;if (prefab == null) Debug.LogWarning($"RURAL: {model} {detail.ToString().ToLowerInvariant()} did not stream; that rural detail stays off the map.");- Rebuild();+ if (detail == CollectionDetail.Near) SyncNearVisuals();+ else { Rebuild(); residency?.Replace(ResidencyDemand()); }+ }++ void SyncNearVisuals()+ {+ var admitted = residencyView?.Keys;+ var far = Placed.Where(p => p.Detail == CollectionDetail.Far).ToArray();+ foreach (var placed in far)+ {+ string instanceKey = placed.Key + ":" + placed.Model + (placed.Member == 0 ? "" : "#" + placed.Member);+ string nearName = instanceKey + ":near";+ var near = transform.Find(nearName);+ bool wantsNear = admitted == null || admitted.Contains(placed.Key + "|" + placed.Model);+ if (!wantsNear && near != null)+ {+ if (originals.TryGetValue((placed.Model, CollectionDetail.Near), out var owned)) owned.Remove(near.gameObject);+ DestroyNow(near.gameObject);+ Placed.RemoveAll(p => p.Detail == CollectionDetail.Near && p.Name == nearName);+ }+ else if (wantsNear && near == null+ && prefabs.TryGetValue((placed.Model, CollectionDetail.Near), out var prefab) && prefab != null)+ {+ var farTransform = transform.Find(placed.Name);+ if (farTransform == null) continue;+ var go = Instantiate(prefab, transform, false); go.name = nearName;+ go.transform.SetPositionAndRotation(farTransform.position, farTransform.rotation);+ go.transform.localScale = farTransform.localScale;+ if (!originals.TryGetValue((placed.Model, CollectionDetail.Near), out var owned))+ originals[(placed.Model, CollectionDetail.Near)] = owned = new List<GameObject>();+ owned.Add(go);+ foreach (var renderer in go.GetComponentsInChildren<Renderer>(true))+ { renderer.shadowCastingMode = ShadowCastingMode.On; renderer.forceRenderingOff = !LastClose; renderers.Add((renderer, CollectionDetail.Near, instanceKey)); }+ foreach (var animator in go.GetComponentsInChildren<Animator>(true))+ { animator.enabled = LastClose; animators.Add((animator, CollectionDetail.Near)); }+ Placed.Add((placed.Key, placed.Model, CollectionDetail.Near, placed.At, nearName, placed.Member));+ }+ }}void Rebuild()@@ -308,29 +378,39 @@ namespace Statecraft.Game.Map.Collection}var used = new Dictionary<string, int>(StringComparer.Ordinal);var holes = new List<(Vector2 centre, float radius)>();- foreach (var want in Admitted())+ var nearKeys = residencyView?.Keys;+ foreach (var want in wants){- bool answered = prefabs.ContainsKey((want.Model, CollectionDetail.Far)) && prefabs.ContainsKey((want.Model, CollectionDetail.Near));- if (!answered) continue;- bool any = prefabs[(want.Model, CollectionDetail.Far)] != null || prefabs[(want.Model, CollectionDetail.Near)] != null;+ bool hasFar = prefabs.TryGetValue((want.Model, CollectionDetail.Far), out var farPrefab) && farPrefab != null;+ bool hasNear = prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var nearPrefab) && nearPrefab != null;+ // A streamed representation is what makes this a real scene. Until then it owns no anchor, clearance,+ // tree hole or Near demand; a failed Far answer therefore cannot leave an empty permanent clearing.+ if (!hasFar && !hasNear) continue;used.TryGetValue(want.Model, out int n);- if (!any || n >= MaxAnchorsPerModel) continue;+ if (n >= MaxAnchorsPerModel) continue;var at = Spot(want, Free);if (at == null) continue;used[want.Model] = n + 1;Scenes.Add(want);taken.Add((at.Value, ClearanceRadiusM));holes.Add((at.Value, SceneRadiusM(want.Model)));+ bool nearAvailable = (nearKeys == null || nearKeys.Contains(want.Key + "|" + want.Model))+ && prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var admittedNear) && admittedNear != null;for (int member = 0; member < MembersOf(want.Model); member++){var flat = MemberAt(want, at.Value, member);var pos = new Vector3(flat.x, ground.Y(flat.x, flat.y), flat.y);foreach (var detail in new[] { CollectionDetail.Far, CollectionDetail.Near }){- var prefab = prefabs[(want.Model, detail)];+ if (detail == CollectionDetail.Near && nearKeys != null && !nearKeys.Contains(want.Key + "|" + want.Model)) continue;+ if (!prefabs.TryGetValue((want.Model, detail), out var prefab)) continue;if (prefab == null) continue;var go = Instantiate(prefab, transform, false);- string instanceName = want.Key + ":" + want.Model + (member == 0 ? "" : "#" + member) + ":" + detail.ToString().ToLowerInvariant();+ if (!originals.TryGetValue((want.Model, detail), out var owned))+ originals[(want.Model, detail)] = owned = new List<GameObject>();+ owned.Add(go);+ string instanceKey = want.Key + ":" + want.Model + (member == 0 ? "" : "#" + member);+ string instanceName = instanceKey + ":" + detail.ToString().ToLowerInvariant();go.name = instanceName;if (detail == CollectionDetail.Far) OriginalModelPose.Sample(go);// Sized at the world scale by its long side seen from above, measured before the map's yaw.@@ -345,8 +425,8 @@ namespace Statecraft.Game.Map.Collectionforeach (var renderer in go.GetComponentsInChildren<Renderer>(true)){renderer.shadowCastingMode = ShadowCastingMode.On;- renderer.forceRenderingOff = detail == CollectionDetail.Near ? !LastClose : LastClose;- renderers.Add((renderer, detail));+ renderer.forceRenderingOff = detail == CollectionDetail.Near ? !LastClose : LastClose && nearAvailable;+ renderers.Add((renderer, detail, instanceKey));}foreach (var animator in go.GetComponentsInChildren<Animator>(true)){@@ -358,9 +438,9 @@ namespace Statecraft.Game.Map.Collection}}Units.UnitShowcase.HideTrees(map, Name, holes);- foreach (var model in Admitted().Select(w => w.Model).Distinct())- if (prefabs.ContainsKey((model, CollectionDetail.Far)) && prefabs.ContainsKey((model, CollectionDetail.Near))- && (!used.TryGetValue(model, out int got) || got < MaxAnchorsPerModel)) Missing.Add(model);+ foreach (var model in wants.Select(w => w.Model).Distinct())+ if (prefabs.TryGetValue((model, CollectionDetail.Far), out var far)+ && (far == null || !used.TryGetValue(model, out int got) || got < MaxAnchorsPerModel)) Missing.Add(model);Debug.Log($"RURAL: {Scenes.Count} rural scenes placed ({Placed.Count} models); {Missing.Count} models short of {MaxAnchorsPerModel} scenes");}@@ -376,7 +456,7 @@ namespace Statecraft.Game.Map.Collectionvoid DestroyNow(GameObject go){destroyedOriginals.Add(go); destroyedOriginals.RemoveAll(o => o == null);- if (Application.isPlaying) { go.transform.SetParent(null); Destroy(go); }+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) go.transform.SetParent(null); Destroy(go); }else DestroyImmediate(go);}@@ -397,13 +477,15 @@ namespace Statecraft.Game.Map.Collectionvar previousDemand = residencyView.Keys;residencyView.Observe(camera, wants.Select(w => (w.Key + "|" + w.Model,new Vector3(w.Anchor.x, 0, w.Anchor.y), w.AnchorRadius)), Time.frameCount);- if (!previousDemand.SetEquals(residencyView.Keys)) RefreshResidency();+ if (!previousDemand.SetEquals(residencyView.Keys)) { RefreshResidencyCore(false); SyncNearVisuals(); }}int id = camera.GetInstanceID();bool close = CloseAt(TownLandmarks.ViewDistance(camera), closeFor.TryGetValue(id, out var was) ? was : (bool?)null);closeFor[id] = close; LastClose = close;- foreach (var (renderer, detail) in renderers)- if (renderer != null) renderer.forceRenderingOff = detail == CollectionDetail.Near ? !close : close;+ var nearInstances = new HashSet<string>(renderers.Where(p => p.Renderer != null && p.Detail == CollectionDetail.Near)+ .Select(p => p.Instance), StringComparer.Ordinal);+ foreach (var (renderer, detail, instance) in renderers)+ if (renderer != null) renderer.forceRenderingOff = detail == CollectionDetail.Near ? !close : close && nearInstances.Contains(instance);foreach (var (animator, detail) in animators)if (animator != null) animator.enabled = detail == CollectionDetail.Near && close;}diff --git a/unity/Assets/Scripts/Map/Collection/SeaAirCollection.cs b/unity/Assets/Scripts/Map/Collection/SeaAirCollection.csindex 694d8dff1..26e56c179 100644--- a/unity/Assets/Scripts/Map/Collection/SeaAirCollection.cs+++ b/unity/Assets/Scripts/Map/Collection/SeaAirCollection.cs@@ -75,7 +75,9 @@ namespace Statecraft.Game.Map.Collection/// prefab's own rotation, whichever lays its longer side along x.</summary>public const float Heading = 0f;- internal static Action<string, CollectionDetail, Action<GameObject?>> Request = CollectionStream.Request;+ static readonly Action<string, CollectionDetail, Action<GameObject?>> DefaultRequest = CollectionStream.Request;+ internal static Action<string, CollectionDetail, Action<GameObject?>> Request = DefaultRequest;+ sealed class TestSeamLease : IDisposable { public void Dispose() { } }/// <summary>One craft to draw: its key, its model, and the place it belongs to (a SeaCraft coast's place, or "lod").</summary>public readonly struct Want : IEquatable<Want>@@ -145,8 +147,13 @@ namespace Statecraft.Game.Map.Collection// Construction configures before first Show; injected acquisition is a test seam.ClearForRetirement();}- IDisposable AcquireOriginal(string id, CollectionDetail detail, Action<GameObject?> answer) =>- ownedAcquire != null ? ownedAcquire(id, detail, answer) : CollectionStream.Acquire(id, detail, answer);+ IDisposable AcquireOriginal(string id, CollectionDetail detail, Action<GameObject?> answer)+ {+ if (ownedAcquire != null) return ownedAcquire(id, detail, answer);+ // The editor/fake-source seam owns its own assets, as before residency (and as CivilianPeople/RuralLife do).+ if (Request != DefaultRequest) { Request(id, detail, answer); return new TestSeamLease(); }+ return CollectionStream.Acquire(id, detail, answer);+ }IEnumerable<Want> Admitted(){var keys = residencyView?.Keys;@@ -161,14 +168,34 @@ namespace Statecraft.Game.Map.Collectionyield return (w.Key, w.Model == C54 ? map.Frame.ToWorld(LodLon, LodLat, 0) : map.Frame.ToWorld(c.lon, c.lat, 0), SizeOf(w.Model));}}- void RefreshResidency()+ void RefreshResidency() => RefreshResidencyCore(true);+ void RefreshResidencyCore(bool redraw){- if (residencyView == null || !isActiveAndEnabled) return;+ if (!isActiveAndEnabled) return;residency ??= new CollectionResidency(AcquireOriginal, ClearForRetirement, (id, detail, prefab) => OnModel(id, prefab),(instances, owners, keys, complete) => CollectionResidencyMetrics.AfterDestroyed("craft", instances, owners, complete,- Application.isPlaying && ownedAcquire == null ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys));- residency.Replace(Admitted().Select(w => (w.Model, CollectionDetail.Far)));- Rebuild();+ Application.isPlaying && ownedAcquire == null && Request == DefaultRequest ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys), true);+ // v0.3.1 Show requested every wanted craft as Far with no camera or 60 km residency gate.+ residency.Replace(wants.Select(w => (w.Model, CollectionDetail.Far)));+ if (redraw) Rebuild();+ }+ IReadOnlyList<UnityEngine.Object> ClearForRetirement(IReadOnlyCollection<(string id, CollectionDetail detail)> keys)+ {+ var removed = new List<UnityEngine.Object>();+ foreach (var key in keys)+ {+ prefabs.Remove(key.id); asked.Remove(key.id);+ if (!originals.TryGetValue(key.id, out var list)) continue;+ foreach (var go in list) if (go != null)+ {+ removed.Add(go);+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) go.transform.SetParent(null); Destroy(go); } else DestroyImmediate(go);+ }+ originals.Remove(key.id); Placed.RemoveAll(p => p.Model == key.id);+ }+ keepAll = originals.Values.SelectMany(list => list).Where(go => go != null)+ .Select(go => new[] { Bounds(go) }).ToList();+ return removed;}IReadOnlyList<UnityEngine.Object> ClearForRetirement(){@@ -181,9 +208,10 @@ namespace Statecraft.Game.Map.Collectionfor (int i = transform.childCount - 1; i >= 0; i--){var old = transform.GetChild(i).gameObject; if (residencyView != null) retired.Add(old);- if (Application.isPlaying) { old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);}Placed.Clear(); Missing.Clear(); keepAll = new List<Bounds[]>();+ originals.Clear();if (map != null) Statecraft.Game.Map.Units.UnitShowcase.HideTrees(map, Name, Array.Empty<(Vector2, float)>());}bool residencyDirty;@@ -192,12 +220,12 @@ namespace Statecraft.Game.Map.Collectionvar before = residencyView!.Keys;residencyView.Observe(camera, Anchors(), Time.frameCount);if (!before.SetEquals(residencyView.Keys))- { if (Application.isPlaying) residencyDirty = true; else RefreshResidency(); }+ { if (Application.isPlaying) residencyDirty = true; else RefreshResidencyCore(false); }}void LateUpdate(){if (residencyView != null && residencyView.Prune(Time.frameCount)) residencyDirty = true;- if (residencyDirty) { residencyDirty = false; RefreshResidency(); }+ if (residencyDirty) { residencyDirty = false; RefreshResidencyCore(false); }}void OnDestroy() { residency?.Dispose(); residency = null; }@@ -205,6 +233,7 @@ namespace Statecraft.Game.Map.CollectionContent? content;readonly Dictionary<string, GameObject?> prefabs = new Dictionary<string, GameObject?>(StringComparer.Ordinal);readonly HashSet<string> asked = new HashSet<string>(StringComparer.Ordinal);+ readonly Dictionary<string, List<GameObject>> originals = new Dictionary<string, List<GameObject>>(StringComparer.Ordinal);List<Want> wants = new List<Want>();List<(int q, int r)> placements = new List<(int, int)>();List<(Vector2 centre, float radius)> taken = new List<(Vector2, float)>();@@ -233,7 +262,6 @@ namespace Statecraft.Game.Map.Collectionvar go = new GameObject(Name); go.transform.SetParent(map.Terrain.transform, false);layer = go.AddComponent<SeaAirCollection>(); layer.map = map;}- // Not under residency (owner ruling, 26 Oct 2026, #1273: "Craft visible at 60 km"): Show asks once in view.layer.content = content;layer.Show(Wants(date, content), placements.Select(p => (p.Q, p.R)).ToList(), date);return layer;@@ -245,14 +273,7 @@ namespace Statecraft.Game.Map.Collectionvar others = next.Any(w => w.Model == C54) ? Taken() : new List<(Vector2, float)>();if (next.SequenceEqual(wants) && placed.SequenceEqual(placements) && others.SequenceEqual(taken)) return;wants = next; placements = placed; taken = others;- if (residencyView != null) { RefreshResidency(); return; }- OriginalModelRequests.WhenVisible(this, () =>- {- if (residencyView != null) { RefreshResidency(); return; }- foreach (var w in wants)- if (asked.Add(w.Model)) { var model = w.Model; Request(model, CollectionDetail.Far, p => OnModel(model, p)); }- });- Rebuild();+ OriginalModelRequests.WhenVisible(this, () => RefreshResidency());}void OnModel(string model, GameObject? prefab)@@ -271,7 +292,7 @@ namespace Statecraft.Game.Map.Collectionvar ground = PlacementLayer.CampGround(map);var works = map.KitStats?.HarbourWorks ?? Array.Empty<SettlementKits.Placed>();var boats = new List<SeaCraft.Craft>(map.KitStats?.Crafts ?? Array.Empty<SeaCraft.Craft>());- foreach (var w in Admitted())+ foreach (var w in wants){if (!prefabs.TryGetValue(w.Model, out var prefab)) continue; // still streamingVector2? at = null;@@ -282,6 +303,8 @@ namespace Statecraft.Game.Map.Collection}if (at == null) { Missing.Add(w.Key); continue; }var go = Instantiate(prefab!, transform, false); go.name = w.Key;+ if (!originals.TryGetValue(w.Model, out var owned)) originals[w.Model] = owned = new List<GameObject>();+ owned.Add(go);// The yaw goes on top of the prefab's own rotation: every Collection Far prefab's root carries the FBX axis// conversion (-90 degrees about X), and setting the yaw alone lays a model on its side (#979).go.transform.localRotation = prefab!.transform.localRotation;diff --git a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.csindex dfd210154..07a4e2e7a 100644--- a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs+++ b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs@@ -140,7 +140,8 @@ namespace Statecraft.Game.Map.Collectionif (map == null) yield break;foreach (var w in wants) yield return (w.Key, map.Frame.ToWorld(w.Lon, w.Lat, 0), ClearanceOf(w.Model));}- void RefreshResidency()+ void RefreshResidency() => RefreshResidencyCore(true);+ void RefreshResidencyCore(bool redraw){if (residencyView == null || !isActiveAndEnabled) return;residency ??= new CollectionResidency(AcquireOriginal, ClearForRetirement, (id, detail, prefab) =>@@ -150,9 +151,29 @@ namespace Statecraft.Game.Map.CollectionRebuild();},(instances, owners, keys, complete) => CollectionResidencyMetrics.AfterDestroyed("special", instances, owners, complete,- Application.isPlaying && ownedAcquire == null ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys));- residency.Replace(Admitted().Select(w => (w.Model, CollectionDetail.Near)));- Rebuild();+ Application.isPlaying && ownedAcquire == null ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys), true);+ // v0.3.1 Show requested every wanted special as Near immediately; only its renderers were close-camera gated.+ residency.Replace(wants.Select(w => (w.Model, CollectionDetail.Near)));+ if (redraw) Rebuild();+ }+ IReadOnlyList<UnityEngine.Object> ClearForRetirement(IReadOnlyCollection<(string id, CollectionDetail detail)> keys)+ {+ var removed = new List<UnityEngine.Object>();+ foreach (var key in keys)+ {+ prefabs.Remove(key.id); asked.Remove(key.id);+ if (!originals.TryGetValue(key.id, out var list)) continue;+ foreach (var go in list) if (go != null)+ {+ var ownedRenderers = new HashSet<Renderer>(go.GetComponentsInChildren<Renderer>(true));+ renderers.RemoveAll(ownedRenderers.Contains);+ removed.Add(go);+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) go.transform.SetParent(null); Destroy(go); } else DestroyImmediate(go);+ }+ originals.Remove(key.id);+ Placed.RemoveAll(p => p.Model == key.id);+ }+ return removed;}IReadOnlyList<UnityEngine.Object> ClearForRetirement(){@@ -165,9 +186,10 @@ namespace Statecraft.Game.Map.Collectionfor (int i = transform.childCount - 1; i >= 0; i--){var old = transform.GetChild(i).gameObject; if (residencyView != null) retired.Add(old);- if (Application.isPlaying) { old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);}renderers.Clear(); Placed.Clear();+ originals.Clear();if (map != null) Statecraft.Game.Map.Units.UnitShowcase.HideTrees(map, Name, Array.Empty<(Vector2, float)>());}bool residencyDirty;@@ -176,12 +198,12 @@ namespace Statecraft.Game.Map.Collectionvar before = residencyView!.Keys;residencyView.Observe(camera, Anchors(), Time.frameCount);if (!before.SetEquals(residencyView.Keys))- { if (Application.isPlaying) residencyDirty = true; else RefreshResidency(); }+ { if (Application.isPlaying) residencyDirty = true; else RefreshResidencyCore(false); }}void LateUpdate(){if (residencyView != null && residencyView.Prune(Time.frameCount)) residencyDirty = true;- if (residencyDirty) { residencyDirty = false; RefreshResidency(); }+ if (residencyDirty) { residencyDirty = false; RefreshResidencyCore(false); }}void OnDestroy() { residency?.Dispose(); residency = null; }@@ -189,6 +211,7 @@ namespace Statecraft.Game.Map.Collectionpublic readonly List<(string Key, string Model, Vector3 At)> Placed = new List<(string, string, Vector3)>();public bool FailedOpen { get; private set; }public bool LastClose { get; private set; }+ readonly Dictionary<string, List<GameObject>> originals = new Dictionary<string, List<GameObject>>(StringComparer.Ordinal);public static SpecialBuildingModels? ShowAt(MapScene map, DateTime date){@@ -233,7 +256,7 @@ namespace Statecraft.Game.Map.Collection&& ground.Inside(p.x - r, p.y - r) && ground.Inside(p.x + r, p.y + r)&& !ground.Water(p.x, p.y) && !ground.OnRoute(p, r) && !ground.OnToken(p, r, date);var holes = new List<(Vector2 centre, float radius)>();- foreach (var w in Admitted())+ foreach (var w in wants){if (!prefabs.TryGetValue(w.Model, out var prefab) || prefab == null) continue;var anchor3 = map.Frame.ToWorld(w.Lon, w.Lat, 0); var anchor = new Vector2(anchor3.x, anchor3.z);@@ -243,6 +266,8 @@ namespace Statecraft.Game.Map.Collectiontaken.Add((at.Value, clearance));holes.Add((at.Value, clearance));var go = Instantiate(prefab, transform, false); go.name = w.Key;+ if (!originals.TryGetValue(w.Model, out var owned)) originals[w.Model] = owned = new List<GameObject>();+ owned.Add(go);go.transform.localRotation = Rotation(prefab.transform.localRotation, 0f);var b = Bounds(go); float edge = Mathf.Max(b.size.x, b.size.z);go.transform.localScale *= edge > 1e-3f ? SizeOf(w.Model) / edge : 1f;diff --git a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs b/unity/Assets/Scripts/Map/Collection/TownLandmarks.csindex 8d7aa5da9..f9b6e54e8 100644--- a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs+++ b/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs@@ -19,12 +19,8 @@ namespace Statecraft.Game.Map.Collection/// far, buildings near". Far off, a mapped town's whole-town model stands ON its town, on its core (<see cref="CoreOf"/>:/// where most of its building models stand, inside its kit footprint, clear of the next town and of the sea), as wide as/// that core, tilted to its ground and seated so it never floats (<see cref="SeatOn"/>).- /// C89/C93 bounds that representation by each camera's admitted focus. Overview cameras acquire whole-town originals;- /// close cameras acquire individual building originals where available, with no duplicate ownership. Only a complete,- /// admitted representation hides that camera's procedural houses. Loading, failure and outside-focus views keep code-built- /// fallback. Within an admitted layer, absence of an individual-building representation leaves the whole town eligible- /// up close; a failed/null streamed Near reply instead keeps the code-built kit, without a second whole-town bundle.- /// Without a layer/configured spatial policy, no whole-town original is admitted.+ /// Whole-town originals and placement landmarks are Far representations requested map-wide. Close cameras show individual+ /// building originals where available; only a complete detailed representation hides that town's whole-town model./// A placement's landmark (ma'abara or shikun) stands beside its camp/housing project on free ground (Spot)./// CollectionDetail.Far now names the same original file, not a generated 4,500-triangle mesh. Requests stream after/// the first frame, are shared by acquired lease and retire when the last camera leaves. A failed model warns once;@@ -293,6 +289,7 @@ namespace Statecraft.Game.Map.Collectionreadonly HashSet<string> asked = new HashSet<string>(StringComparer.Ordinal);readonly Dictionary<string, IDisposable?> leases = new Dictionary<string, IDisposable?>(StringComparer.Ordinal);readonly Dictionary<string, int> versions = new Dictionary<string, int>(StringComparer.Ordinal);+ readonly Dictionary<string, List<GameObject>> originals = new Dictionary<string, List<GameObject>>(StringComparer.Ordinal);readonly List<IDisposable> retiring = new List<IDisposable>();readonly List<UnityEngine.Object> retiredInstances = new List<UnityEngine.Object>();readonly Dictionary<Renderer, string> rendererTowns = new Dictionary<Renderer, string>();@@ -344,11 +341,10 @@ namespace Statecraft.Game.Map.Collectionasked.Select(id => id + "|Far"));row.retiringLeases = retiring.Count; row.pendingDestroy = retiredInstances.Count(o => o != null && o is GameObject); return row;}- bool Allowed(Want want) => map != null- ? map!.Residency.Towns.Enabled && Layer()?.WantsWholeTownAny(want.Key) == true- : !want.OnTown || Layer()?.WantsWholeTownAny(want.Key) == true;+ // Owner ruling, 30 October 2026: whole towns and placement landmarks remain v0.3.1 Far demand, map-wide.+ bool Allowed(Want want) => map != null ? map.Residency.Towns.Enabled : true;bool WholeReady(string id, Camera camera) =>- Layer()?.WantsWholeTown(id, camera) == true && Seats.ContainsKey(id);+ Seats.ContainsKey(id) && Layer()?.ReadyForTown(id, camera) != true;void Show(List<Want> next, DateTime at){@@ -382,15 +378,17 @@ namespace Statecraft.Game.Map.Collectionleases.Remove(model);}bool membershipChanged = !keep.SetEquals(asked);- if (townsChanged || old.Count > 0 || membershipChanged) { dirty = true; CollectionResidencyMetrics.MarkDirty(); }+ if (townsChanged || old.Count > 0 || membershipChanged) CollectionResidencyMetrics.MarkDirty();// Retire the old generation before rebuilding or acquiring the next batch.if (old.Count > 0 && retiring.Count > 0){- ClearInstances(); dirty = true;+ // Retiring one model must not destroy/recreate surviving town instances (the visible panning/date blink).+ ClearInstances(old); dirty |= townsChanged || keep.Except(asked).Any();if (Application.isPlaying && !retirementScheduled) { retirementScheduled = true; StartCoroutine(RetireAfterFrame()); }else if (!Application.isPlaying) RetireLeases();return;}+ if (townsChanged || membershipChanged) dirty = true;if (pendingRetirementLeases > 0) return;Rebuild(); // stop old instances before retiring their asset ownershipif (retiring.Count > 0 && !retirementScheduled && Application.isPlaying)@@ -489,7 +487,7 @@ namespace Statecraft.Game.Map.Collectionvar townCentres = map.KitFootprints.Where(f => gameIds.Contains(f.id)).Select(f => (c: f.centre, id: f.id)).ToList();foreach (var w in wants){- if (!Allowed(w)) continue; // only towns admitted by an active camera acquire a whole original+ if (!Allowed(w)) continue;if (!prefabs.TryGetValue(w.Model, out var prefab)) continue; // still streamingif (prefab == null) { Missing.Add(w.Key); continue; }Vector2 at; float edge, baseY; Vector3 normal = Vector3.up;@@ -512,6 +510,8 @@ namespace Statecraft.Game.Map.Collection}var go = Instantiate(prefab, transform, false);go.name = w.Key;+ if (!originals.TryGetValue(w.Model, out var owned)) originals[w.Model] = owned = new List<GameObject>();+ owned.Add(go);// This owned instance obeys the map's approved town view band and per-camera fallback swap.// The prefab's older strategic cap must not override that policy or hide a ready original early.foreach (var cap in go.GetComponentsInChildren<OriginalModelDistance>(true)) cap.enabled = false;@@ -533,7 +533,7 @@ namespace Statecraft.Game.Map.Collectionforeach (var rr in go.GetComponentsInChildren<Renderer>(true)){rr.shadowCastingMode = ShadowCastingMode.On;- rr.forceRenderingOff = w.OnTown; // a camera enables only its admitted whole-town representation+ rr.forceRenderingOff = false;renderers.Add(rr);if (w.OnTown) rendererTowns[rr] = w.Key;}@@ -574,20 +574,55 @@ namespace Statecraft.Game.Map.CollectionStopAllCoroutines(); retirementScheduled = false;RestoreRenderers(); ReleaseOwned();}- void ClearInstances()+ void ClearInstances(IReadOnlyCollection<string>? models = null){CollectionResidencyMetrics.MarkDirty();RestoreRenderers();- for (int i = transform.childCount - 1; i >= 0; i--)+ if (models != null){- var old = transform.GetChild(i).gameObject; old.SetActive(false);- retiredInstances.RemoveAll(instance => instance == null); retiredInstances.Add(old);- retiredInstances.AddRange(old.GetComponentsInChildren<Renderer>(true));- retiredInstances.AddRange(old.GetComponentsInChildren<MeshFilter>(true));- if (Application.isPlaying) { old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);+ var removed = new HashSet<string>(models, StringComparer.Ordinal);+ var removedTownKeys = new HashSet<string>(Placed.Where(p => removed.Contains(p.Model)).Select(p => p.Key), StringComparer.Ordinal);+ var removedRenderers = new HashSet<Renderer>();+ foreach (string model in removed)+ {+ if (!originals.TryGetValue(model, out var instances)) continue;+ foreach (var old in instances.Where(go => go != null).ToArray())+ {+ removedRenderers.UnionWith(old.GetComponentsInChildren<Renderer>(true));+ RetireInstance(old);+ }+ originals.Remove(model);+ }+ renderers.RemoveAll(renderer => renderer == null || removedRenderers.Contains(renderer));+ foreach (var renderer in rendererTowns.Where(pair => pair.Key == null || removedRenderers.Contains(pair.Key)+ || removedTownKeys.Contains(pair.Value)).Select(pair => pair.Key).ToArray())+ rendererTowns.Remove(renderer);+ Placed.RemoveAll(p => removed.Contains(p.Model));+ Missing.RemoveAll(removedTownKeys.Contains);+ foreach (string key in removedTownKeys) Seats.Remove(key);+ Layer()?.Suppress(Seats.Keys);+ return;}+ for (int i = transform.childCount - 1; i >= 0; i--)+ RetireInstance(transform.GetChild(i).gameObject);+ originals.Clear();renderers.Clear(); rendererTowns.Clear(); Placed.Clear(); Missing.Clear(); Seats.Clear();}+ void RetireInstance(GameObject old)+ {+ old.SetActive(false);+ retiredInstances.RemoveAll(instance => instance == null); retiredInstances.Add(old);+ retiredInstances.AddRange(old.GetComponentsInChildren<Renderer>(true));+ retiredInstances.AddRange(old.GetComponentsInChildren<MeshFilter>(true));+ if (Application.isPlaying)+ {+ // Unity forbids hierarchy changes while this layer is being deactivated (OnDisable -> ReleaseOwned). The+ // inactive instance is then destroyed in place; detach only while the layer is active, as RoadVehicles does.+ if (gameObject.activeInHierarchy) old.transform.SetParent(null);+ Destroy(old);+ }+ else DestroyImmediate(old);+ }void ReleaseOwned(){ClearInstances();@@ -611,8 +646,7 @@ namespace Statecraft.Game.Map.CollectionRefreshWanted();}- /// <summary>Admit whole-town originals only for this camera's overview focus; close cameras use individual- /// buildings. A whole-town asset owned for another camera never hides this camera's fallback.</summary>+ /// <summary>Show each map-wide whole-town original unless this camera has that town's detailed buildings ready.</summary>internal void Choose(ScriptableRenderContext context, Camera cam){if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;@@ -625,8 +659,7 @@ namespace Statecraft.Game.Map.Collectionforeach (var renderer in renderers){if (renderer == null) continue;- bool hide = rendererTowns.TryGetValue(renderer, out var town) && layer != null &&- (!layer.WantsWholeTown(town, cam) || layer.ReadyForTown(town, cam));+ bool hide = rendererTowns.TryGetValue(renderer, out var town) && layer?.ReadyForTown(town, cam) == true;previous.Add((renderer, renderer.forceRenderingOff)); renderer.forceRenderingOff = hide;LastHidden |= hide;}diff --git a/unity/Assets/Scripts/Map/Kits/DiscIndex.cs b/unity/Assets/Scripts/Map/Kits/DiscIndex.csindex 17dd2fe94..587da4671 100644--- a/unity/Assets/Scripts/Map/Kits/DiscIndex.cs+++ b/unity/Assets/Scripts/Map/Kits/DiscIndex.cs@@ -25,6 +25,7 @@ namespace Statecraft.Game.Map.Kitspublic int Count => all.Count;public (Vector2 centre, float radius, string id) this[int i] => all[i];+ internal IReadOnlyList<(Vector2 centre, float radius, string id)> Items => all;/// <summary>The farthest from a disc's edge a query may look (beyond this <see cref="Near"/> may miss the disc).</summary>public float Reach(float radius) => radius * reachScale + reachPad;diff --git a/unity/Assets/Scripts/Map/Kits/KitLayer.cs b/unity/Assets/Scripts/Map/Kits/KitLayer.csindex 1be8cbd9b..e4a423747 100644--- a/unity/Assets/Scripts/Map/Kits/KitLayer.cs+++ b/unity/Assets/Scripts/Map/Kits/KitLayer.cs@@ -74,17 +74,25 @@ namespace Statecraft.Game.Map.Kits// its buildings, with the models' plinths), which TownModelLayer swaps in when the camera is close.var swaps = new List<(Renderer kit, Renderer? close)>();var rendererTownIds = new Dictionary<Renderer, string>();- void AddKit(string name, Mesh mesh, string? townId = null)+ var rendererTileIds = new Dictionary<Renderer, string[]>();+ Renderer AddKit(string name, Mesh mesh, string? townId = null){var kit = Add(name, mesh);Renderer? close = null;if (built.Close.TryGetValue(mesh.name, out var cm)) { close = Add(name + CloseSuffix, cm, count: false); st.CloseVertices += cm.vertexCount; }swaps.Add((kit, close));if (townId != null) rendererTownIds[kit] = townId;+ return kit;}var nearTowns = new List<string>();foreach (var (s, mesh, n) in built.Towns) { AddKit(s.Id, mesh, s.Id); nearTowns.Add(s.Id); stats.Buildings += n; }- foreach (var (name, mesh) in built.Tiles) AddKit(name, mesh);+ // A merged tile is no named town: it carries its villages, and swaps once all of them are ready (owner ruling,+ // 31 Oct 2026, "Load all in view (Recommended)").+ foreach (var (name, mesh) in built.Tiles)+ {+ var kit = AddKit(name, mesh);+ if (built.TileIds.TryGetValue(name, out var ids)) rendererTileIds[kit] = ids.ToArray();+ }// The boats (SeaCraft): off the coast and moored in the harbours the kits recorded.var crafts = SeaCraft.Place(ground, placed);if (crafts.Count > 0)@@ -103,7 +111,10 @@ namespace Statecraft.Game.Map.Kitsvar towns = townGo.AddComponent<TownModelLayer>();if (residency == null) throw new System.ArgumentNullException(nameof(residency));towns.ConfigureProduction(residency.Towns);- towns.Init(built.Models, townModels, swaps, nearTowns, rendererTownIds);+ towns.Init(built.Models, townModels, swaps, nearTowns, rendererTownIds, rendererTileIds);+ var localityIds = new HashSet<string>(System.StringComparer.Ordinal);+ foreach (var locality in localities) localityIds.Add(locality.Id);+ towns.ConfigureTownFootprints(stats.Footprints, localityIds);stats.Models = built.Models.Count;stats.Localities = localities.Count; stats.LocalityBuildings = built.LocalityBuildings; stats.Camps = built.Camps; stats.Tents = built.Tents;stats.Buildings += built.LocalityBuildings + built.Tents;diff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs b/unity/Assets/Scripts/Map/Kits/SettlementKits.csindex c2a16521f..8c7b9bc18 100644--- a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.cs@@ -24,6 +24,8 @@ namespace Statecraft.Game.Map.Kits/// <summary>How far past its footprint radius a town's plots reach (UnitGround.FootprintMargin: the units assume no/// building beyond it; PaintGround tints the same disc).</summary>public const float PlotReach = 1.1f;+ /// <summary>The normalized centre distance at a circular footprint's boundary.</summary>+ internal const float FootprintBoundary = 1f;public static Archetype ArchetypeOf(Settlement s){@@ -49,6 +51,35 @@ namespace Statecraft.Game.Map.Kitsreturn Mathf.Sqrt(hexes * hexArea / Mathf.PI);}+ /// <summary>Distance from a point to a settlement centre as a share of that settlement's footprint radius. The+ /// smallest value owns points where footprints overlap.</summary>+ internal static float NormalizedFootprintDistance(Vector2 point, Vector2 centre, float radius) =>+ (point - centre).magnitude / radius;++ /// <summary>Whether <paramref name="id"/> owns <paramref name="point"/> under the kit generator's normalized-distance+ /// partition. <paramref name="candidates"/> may restrict the scan to a spatial index's nearby entries.</summary>+ internal static bool OwnsFootprint(Vector2 point, string id, Vector2 centre, float radius,+ IReadOnlyList<(Vector2 centre, float radius, string id)> footprints, IReadOnlyList<int>? candidates = null,+ HashSet<string>? ignored = null)+ {+ float mine = NormalizedFootprintDistance(point, centre, radius);+ bool Closer(int i)+ {+ var footprint = footprints[i];+ return footprint.id != id && (ignored == null || !ignored.Contains(footprint.id))+ && NormalizedFootprintDistance(point, footprint.centre, footprint.radius) < mine;+ }+ if (candidates == null)+ {+ for (int i = 0; i < footprints.Count; i++) if (Closer(i)) return false;+ }+ else+ {+ for (int i = 0; i < candidates.Count; i++) if (Closer(candidates[i])) return false;+ }+ return true;+ }+/// <summary>Claims every settlement's footprint on <paramref name="ground"/> (largest first, so a big town's disc is/// whole and its small neighbour fits around it) and returns one mesh per settlement, keyed by id.</summary>public static List<(Settlement s, Mesh mesh, int buildings)> Build(IReadOnlyList<Settlement> list, KitGround ground) =>@@ -117,6 +148,9 @@ namespace Statecraft.Game.Map.Kits/// mesh without the buildings and with the models' plinths (KitMesh.ToCloseMesh), by the kit mesh's name; none/// where nothing would be left.</summary>public Dictionary<string, Mesh> Close = new Dictionary<string, Mesh>();+ /// <summary>The 1948 localities merged into each tile mesh, by the tile's name in <see cref="Tiles"/> (ordinal+ /// order): TownModelLayer swaps a tile only when every one of them has its building models ready.</summary>+ public Dictionary<string, List<string>> TileIds = new Dictionary<string, List<string>>();/// <summary>Issue #1032: every kit landmark as the close mesh draws it, at the models' world scale/// (SettlementKits.AtWorldScale): its kind, its anchor, and its copy's box (width along x, depth along z, height/// over its ground level Y), in placement order.</summary>@@ -258,12 +292,21 @@ namespace Statecraft.Game.Map.Kitsforeach (var (km, from, to) in kv.Value) km.Positions(from, to, pts);if (pts.Count > 0) columns[kv.Key] = KitMesh.Columns(pts);}+ static string TileName((int x, int z) key) => $"Localities {key.x},{key.z}";foreach (var kv in tiles){var mesh = kv.Value.ToMesh($"localities_{kv.Key.Item1}_{kv.Key.Item2}");if (kv.Value.ToCloseMesh(mesh.name + "_close") is Mesh close) result.Close[mesh.name] = close;- result.Tiles.Add(($"Localities {kv.Key.Item1},{kv.Key.Item2}", mesh));+ result.Tiles.Add((TileName(kv.Key), mesh));}+ foreach (var id in spans.Keys)+ {+ var c = centres[id];+ string name = TileName((Mathf.FloorToInt(c.x / TileM), Mathf.FloorToInt(c.y / TileM)));+ if (!result.TileIds.TryGetValue(name, out var ids)) result.TileIds[name] = ids = new List<string>();+ ids.Add(id);+ }+ foreach (var ids in result.TileIds.Values) ids.Sort(string.CompareOrdinal);result.Claimed = lots.List.ConvertAll(l => (centre: l.c, radius: l.r, id: l.id));result.KibbutzHalls = kibbutzHalls; result.FarmSheds = farmSheds;return result;@@ -502,16 +545,8 @@ namespace Statecraft.Game.Map.Kits// not count: a game settlement keeps the ground it had before the villages came (their landmarks' lots still stand).bool Mine(Vector2 p){- float mine = (p - centre).magnitude / R;var fp = ground.Footprints;- var near = fp.Near(p);- for (int k = 0; k < near.Count; k++)- {- int i = near[k];- if (fp[i].id != s.Id && (ignoreCellsOf == null || !ignoreCellsOf.Contains(fp[i].id))- && (p - fp[i].centre).magnitude / fp[i].radius < mine) return false;- }- return true;+ return OwnsFootprint(p, s.Id, centre, R, fp.Items, fp.Near(p), ignoreCellsOf);}// Only a town with water near its footprint tests the beach setback per plot (eight samples each: the boot budget).@@ -1113,16 +1148,8 @@ namespace Statecraft.Game.Map.Kits// radius), so Jaffa and Tel Aviv, or Lod and Ramla, meet along a seam instead of overlapping.bool Mine(Vector2 p){- float mine = (p - centre).magnitude / R;var fp = ground.Footprints;- var near = fp.Near(p);- for (int k = 0; k < near.Count; k++)- {- int i = near[k];- if (fp[i].id != s.Id && (ignoreCellsOf == null || !ignoreCellsOf.Contains(fp[i].id))- && (p - fp[i].centre).magnitude / fp[i].radius < mine) return false;- }- return true;+ return OwnsFootprint(p, s.Id, centre, R, fp.Items, fp.Near(p), ignoreCellsOf);}bool Free(Vector2 p, float r) => FreeAt(lots, p, r);diff --git a/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs b/unity/Assets/Scripts/Map/Kits/TownModelLayer.csindex 04d68bd25..3d22969fd 100644--- a/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs+++ b/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs@@ -5,10 +5,12 @@ using UnityEngine.Rendering;namespace Statecraft.Game.Map.Kits{- /// <summary>Original building meshes for admitted camera-focus towns, instanced per model/tile. At overview zoom- /// TownLandmarks owns the admitted whole-town representation; close cameras own individual buildings. Each camera- /// swaps only complete towns; loading, failed and outside-focus towns retain code-built fallback. Source artwork is- /// unchanged. Edge admission is off until a diagnostic-backed allowance is explicitly supplied.</summary>+ /// <summary>Original building meshes for admitted towns and villages, instanced per model/tile. At overview zoom+ /// TownLandmarks owns the whole-town representation; close cameras own individual buildings. Under the production policy+ /// (owner ruling, 31 Oct 2026, "Load all in view (Recommended)") a close camera admits every town and every merged village+ /// tile in its view (+<see cref="ViewMarginM"/>), nearest first, and they unload above <see cref="CloseExitM"/>. Each camera+ /// swaps only complete towns and complete village tiles; loading and failed places retain code-built fallback. Source+ /// artwork is unchanged. Edge admission is off until a diagnostic-backed allowance is explicitly supplied.</summary>[ExecuteAlways]public sealed class TownModelLayer : MonoBehaviour{@@ -19,6 +21,10 @@ namespace Statecraft.Game.Map.Kits/// 10% of the distance), so a notch out and back never flips the towns twice. diorama02 (250 km) is far beyond it, the/// close checks (hero06, 6 km: CameraController.MinDistance) well inside.</summary>public const float CloseEnterM = 40000f, CloseExitM = 45000f;+ /// <summary>Owner ruling, 31 Oct 2026, "Load all in view (Recommended)": a close camera admits a town or village tile+ /// whose building-model bounds, widened by ViewMarginM on every side, are in its view; an admitted one stays until it+ /// leaves the view widened by ViewKeepM, so a pan does not drop and reload a kind at the margin.</summary>+ public const float ViewMarginM = 3000f, ViewKeepM = 6000f;/// <summary>Compatibility input for LodFor's projection helper; original shipping meshes have no generated LODs.</summary>public const float FullDetailPx = 512f;@@ -28,6 +34,19 @@ namespace Statecraft.Game.Map.Kitsreadonly Dictionary<string, List<SettlementKits.ModelInstance>> perPlace = new Dictionary<string, List<SettlementKits.ModelInstance>>();readonly List<(Renderer kit, Renderer? close)> swaps = new List<(Renderer, Renderer?)>();readonly Dictionary<Renderer, string> swapIds = new Dictionary<Renderer, string>();+ /// <summary>Each merged locality tile renderer's villages with building models: the tile swaps as one, only when every+ /// one of them is ready (<see cref="villageTiles"/>: each village's group).</summary>+ readonly Dictionary<Renderer, string[]> tileIds = new Dictionary<Renderer, string[]>();+ readonly Dictionary<string, string[]> villageTiles = new Dictionary<string, string[]>(System.StringComparer.Ordinal);+ /// <summary>The view-admission units: each detailed town alone, each village tile's villages together.</summary>+ readonly List<(string[] ids, Bounds bounds)> viewPlaces = new List<(string[], Bounds)>();+ readonly Plane[] frustum = new Plane[6];+ readonly List<(int place, float distance)> viewScratch = new List<(int, float)>();+ readonly List<string> viewNext = new List<string>();+ readonly Dictionary<string[], bool> villagesReady = new Dictionary<string[], bool>();+ /// <summary>Set by <see cref="ConfigureProduction"/>. Explicit spatial values (<see cref="ConfigureResidency"/>: tests and+ /// diagnostics) keep the camera-focus admission alone.</summary>+ bool viewAdmission;/// <summary>The towns whose kit buildings never draw (<see cref="Suppress"/>), by settlement id.</summary>readonly HashSet<string> suppressed = new HashSet<string>(System.StringComparer.Ordinal);TownModelSet? set;@@ -44,12 +63,32 @@ namespace Statecraft.Game.Map.Kitsif (!float.IsFinite(enterM) || !float.IsFinite(exitM) || !float.IsFinite(edgeM) || enterM < 0 || exitM < enterM || edgeM < 0 || maxEdges < 0 || string.IsNullOrWhiteSpace(diagnosticEvidence))throw new System.ArgumentException("Residency requires finite accepted spatial values and diagnostic evidence.");admittedEnterM = enterM; admittedExitM = exitM; admittedEdgeM = edgeM; admittedEdges = maxEdges;- SpatialPolicyEvidence = diagnosticEvidence; SpatialPolicyConfigured = true;- foreach (var choice in choices.Values) { choice.hadFocus = false; choice.selected = System.Array.Empty<string>(); choice.towns.Clear(); choice.primary = null; }+ SpatialPolicyEvidence = diagnosticEvidence; SpatialPolicyConfigured = true; viewAdmission = false;+ foreach (var choice in choices.Values)+ {+ choice.hadFocus = false; choice.selected = System.Array.Empty<string>(); choice.towns.Clear(); choice.primary = null;+ choice.inView.Clear(); choice.viewed.Clear(); choice.viewValid = false;+ }ReconcileModels();}internal System.Func<string, Camera, bool>? WholeTownReady;readonly List<(string id, Bounds bounds)> buildingPlaces = new List<(string, Bounds)>();+ // The full kit partition includes settlements without detailed models: those settlements must still be able to own+ // ground against a detailed neighbour.+ readonly List<(Vector2 centre, float radius, string id)> townFootprints = new List<(Vector2, float, string)>();+ readonly List<(Vector2 centre, float radius, string id)> configuredTownFootprints = new List<(Vector2, float, string)>();+ readonly HashSet<string> ignoredTownFootprintIds = new HashSet<string>(System.StringComparer.Ordinal);+ readonly Dictionary<string, (Vector2 centre, float radius, string id)> admissionFootprintsById =+ new Dictionary<string, (Vector2, float, string)>(System.StringComparer.Ordinal);+ readonly HashSet<string> loggedDuplicateTownFootprintIds = new HashSet<string>(System.StringComparer.Ordinal);+ static readonly IReadOnlyDictionary<string, (Vector2 centre, float radius, string id)> NoFootprintsById =+ new Dictionary<string, (Vector2, float, string)>(System.StringComparer.Ordinal);+ sealed class EdgeDistanceComparer : IComparer<(string id, float distance)>+ {+ public static readonly EdgeDistanceComparer Instance = new EdgeDistanceComparer();+ public int Compare((string id, float distance) a, (string id, float distance) b)+ { int c = a.distance.CompareTo(b.distance); return c != 0 ? c : string.CompareOrdinal(a.id, b.id); }+ }internal static System.Func<string, Collection.CollectionDetail, System.Action<GameObject?>, System.IDisposable> ModelAcquire = Collection.CollectionStream.Acquire;sealed class Choice{@@ -61,6 +100,11 @@ namespace Statecraft.Game.Map.Kitspublic bool hadFocus;public string[] selected = System.Array.Empty<string>();public readonly HashSet<string> towns = new HashSet<string>(System.StringComparer.Ordinal);+ /// <summary>The towns and villages admitted by view (nearest first), and the same as a set.</summary>+ public readonly List<string> inView = new List<string>();+ public readonly HashSet<string> viewed = new HashSet<string>(System.StringComparer.Ordinal);+ public Matrix4x4 viewMatrix;+ public bool viewValid;}sealed class Model{@@ -87,19 +131,20 @@ namespace Statecraft.Game.Map.Kits{if (!policy.Enabled){- SpatialPolicyConfigured = false; SpatialPolicyEvidence = "disabled";+ SpatialPolicyConfigured = false; SpatialPolicyEvidence = "disabled"; viewAdmission = false;choices.Clear(); RestoreRenderers(); ReleaseModels(); return;}cameraGraceFrames = policy.Grace;productionViewEnter = policy.ViewEnter; productionViewExit = policy.ViewExit;ConfigureResidency(policy.Enter, policy.Exit, policy.Edge, policy.MaxEdges, policy.Evidence);+ viewAdmission = true;}public bool UsesFocusedOriginals => places.Count > 0;internal Collection.CollectionResidencyMetrics.Category ResidencySnapshot(){var active = new HashSet<string>(System.StringComparer.Ordinal);- foreach (var c in choices.Values) foreach (var town in c.towns) active.Add(town);+ foreach (var c in choices.Values) { foreach (var town in c.towns) active.Add(town); foreach (var id in c.viewed) active.Add(id); }var ids = new List<string>(); int owners = 0, pending = 0, refs = 0, instances = 0, missing = 0;foreach (var pair in models){@@ -122,12 +167,48 @@ namespace Statecraft.Game.Map.Kits/// <summary>C89: one town near camera focus and at most two immediate edge neighbours; no map-wide Near load.</summary>internal static string[] FocusedTowns(IReadOnlyList<(string id, Bounds bounds)> towns, Vector3 focus, string? previous, System.Func<IReadOnlyList<string>, string, bool>? edgeAllowance, float enterM, float exitM, float edgeM, int maxEdges)+ => FocusedTownsWithFootprints(towns, NoFootprintsById, System.Array.Empty<(Vector2, float, string)>(), focus, previous,+ edgeAllowance, enterM, exitM, edgeM, maxEdges);++ /// <summary>As <see cref="FocusedTowns"/>, with detailed towns found in a precomputed id-to-footprint lookup and+ /// ownership decided against the full kit footprint partition, including settlements without detailed models.</summary>+ internal static string[] FocusedTownsWithFootprints(IReadOnlyList<(string id, Bounds bounds)> towns,+ IReadOnlyDictionary<string, (Vector2 centre, float radius, string id)> footprintsByTownId,+ IReadOnlyList<(Vector2 centre, float radius, string id)> allFootprints, Vector3 focus, string? previous,+ System.Func<IReadOnlyList<string>, string, bool>? edgeAllowance, float enterM, float exitM, float edgeM, int maxEdges){+ maxEdges = Mathf.Max(0, maxEdges);int primary = -1; float best = float.PositiveInfinity, bestCentre = float.PositiveInfinity;- for (int i = 0; i < towns.Count; i++)+ var groundFocus = new Vector2(focus.x, focus.z);+ bool insideFootprintPartition = false;+ for (int i = 0; i < allFootprints.Count && !insideFootprintPartition; i++)+ insideFootprintPartition = SettlementKits.NormalizedFootprintDistance(groundFocus,+ allFootprints[i].centre, allFootprints[i].radius) <= SettlementKits.FootprintBoundary;+ // Seam ownership is subordinate to hysteresis only while the previous town still owns the focus under the same+ // normalized-distance partition as admission, or while the focus remains in its instance-bounds exit band.+ if (previous != null) for (int i = 0; i < towns.Count; i++)+ {+ if (towns[i].id != previous) continue;+ bool ownsFootprint = footprintsByTownId.TryGetValue(previous, out var footprint)+ && SettlementKits.NormalizedFootprintDistance(groundFocus, footprint.centre, footprint.radius)+ <= SettlementKits.FootprintBoundary+ && SettlementKits.OwnsFootprint(groundFocus, footprint.id, footprint.centre, footprint.radius, allFootprints);+ if (ownsFootprint || GroundDistance(towns[i].bounds, focus) <= exitM) primary = i;+ break;+ }+ if (primary < 0) for (int i = 0; i < towns.Count; i++)+ {+ if (!footprintsByTownId.TryGetValue(towns[i].id, out var footprint)) continue;+ float normalized = SettlementKits.NormalizedFootprintDistance(groundFocus, footprint.centre, footprint.radius);+ if (normalized <= SettlementKits.FootprintBoundary && SettlementKits.OwnsFootprint(groundFocus, footprint.id, footprint.centre,+ footprint.radius, allFootprints) && (normalized < best || (normalized == best &&+ (primary < 0 || string.CompareOrdinal(towns[i].id, towns[primary].id) < 0))))+ { primary = i; best = normalized; }+ }+ if (primary < 0 && insideFootprintPartition) return System.Array.Empty<string>();+ if (primary < 0) for (int i = 0; i < towns.Count; i++){float distance = GroundDistance(towns[i].bounds, focus);- if (towns[i].id == previous && distance <= exitM) { primary = i; break; }var centreDelta = towns[i].bounds.center - focus; centreDelta.y = 0;float centre = centreDelta.sqrMagnitude;if (distance <= enterM && (distance < best || (distance == best &&@@ -135,19 +216,22 @@ namespace Statecraft.Game.Map.Kits{ primary = i; best = distance; bestCentre = centre; }}if (primary < 0) return System.Array.Empty<string>();- var edge = new List<(string id, float distance)>();+ if (edgeAllowance == null || maxEdges == 0) return new[] { towns[primary].id };+ var edge = new (string id, float distance)[towns.Count - 1]; int edgeCount = 0;var box = towns[primary].bounds; box.Expand(new Vector3(edgeM * 2, 0, edgeM * 2));for (int i = 0; i < towns.Count; i++){if (i == primary) continue;var b = towns[i].bounds; b.center = new Vector3(b.center.x, box.center.y, b.center.z);- if (box.Intersects(b)) edge.Add((towns[i].id, GroundDistance(b, focus)));+ if (box.Intersects(b)) edge[edgeCount++] = (towns[i].id, GroundDistance(b, focus));}- edge.Sort((a, b) => { int c = a.distance.CompareTo(b.distance); return c != 0 ? c : string.CompareOrdinal(a.id, b.id); });- var result = new List<string> { towns[primary].id };- for (int i = 0; i < edge.Count && result.Count <= maxEdges; i++)- if (edgeAllowance != null && edgeAllowance(result, edge[i].id)) result.Add(edge[i].id);- return result.ToArray();+ System.Array.Sort(edge, 0, edgeCount, EdgeDistanceComparer.Instance);+ int capacity = maxEdges >= towns.Count ? towns.Count : maxEdges + 1;+ var result = new string[capacity]; result[0] = towns[primary].id; int resultCount = 1;+ for (int i = 0; i < edgeCount && resultCount <= maxEdges; i++)+ if (edgeAllowance(new System.ArraySegment<string>(result, 0, resultCount), edge[i].id)) result[resultCount++] = edge[i].id;+ if (resultCount != result.Length) System.Array.Resize(ref result, resultCount);+ return result;}public bool Draw { get; set; } = true;/// <summary>Whether the layer has a complete model list (else the towns keep their kits at every zoom).</summary>@@ -170,12 +254,16 @@ namespace Statecraft.Game.Map.Kitspublic long LastTriangles { get; private set; }public int LastDraws { get; private set; }- /// <summary>Explicit town ids and renderer identities distinguish individual towns from mixed locality tiles.- /// A complete editor model set is optional in a player: acquired originals become ready independently per town,- /// while incomplete/missing replies keep fallback. No tile or unrelated town swaps on a partial global set.</summary>- public void Init(IReadOnlyList<SettlementKits.ModelInstance> instances, TownModelSet? models, IReadOnlyList<(Renderer kit, Renderer? close)> swaps, IReadOnlyCollection<string>? townIds = null, IReadOnlyDictionary<Renderer, string>? rendererTownIds = null)+ /// <summary>Explicit town ids and renderer identities distinguish individual towns from mixed locality tiles+ /// (<paramref name="rendererTileIds"/>: each tile renderer's villages). A complete editor model set is optional in a+ /// player: acquired originals become ready independently per town, while incomplete/missing replies keep fallback. A+ /// tile swaps only when every village in it is ready; no tile or unrelated town swaps on a partial global set.</summary>+ public void Init(IReadOnlyList<SettlementKits.ModelInstance> instances, TownModelSet? models, IReadOnlyList<(Renderer kit, Renderer? close)> swaps, IReadOnlyCollection<string>? townIds = null, IReadOnlyDictionary<Renderer, string>? rendererTownIds = null,+ IReadOnlyDictionary<Renderer, string[]>? rendererTileIds = null){- RestoreRenderers(); ReleaseModels(); choices.Clear(); places.Clear(); buildingPlaces.Clear(); required.Clear();+ RestoreRenderers(); ReleaseModels(); choices.Clear(); places.Clear(); buildingPlaces.Clear();+ townFootprints.Clear(); configuredTownFootprints.Clear(); ignoredTownFootprintIds.Clear();+ admissionFootprintsById.Clear(); loggedDuplicateTownFootprintIds.Clear(); required.Clear();string? why = models == null ? "the map scene has no model list" : models.Missing();streaming = models == null && Application.isPlaying;if (why != null && !streaming && !suppressMissingLog) Debug.LogError($"town models: {why}; the towns keep their kits at every zoom (issue #659)");@@ -219,19 +307,39 @@ namespace Statecraft.Game.Map.Kits}var eligible = townIds == null ? new HashSet<string>(System.StringComparer.Ordinal) : new HashSet<string>(townIds, System.StringComparer.Ordinal);if (townIds == null) foreach (var pair in swaps) if (pair.kit != null) eligible.Add(pair.kit.name);- foreach (string id in eligible)+ // A place's building-model bounds, and the model kinds it needs (required); false without building models.+ bool Describe(string id, out Bounds placeBounds){- if (!perPlace.TryGetValue(id, out var list) || list.Count == 0) continue;+ placeBounds = default;+ if (!perPlace.TryGetValue(id, out var list) || list.Count == 0) return false;var corners = new List<Vector3>();foreach (var item in list) item.Corners(corners);- var bounds = new Bounds(corners[0], Vector3.zero);- foreach (var corner in corners) bounds.Encapsulate(corner);- places.Add((id, bounds));+ placeBounds = new Bounds(corners[0], Vector3.zero);+ foreach (var corner in corners) placeBounds.Encapsulate(corner);var kinds = new HashSet<TownModel>();foreach (var item in list) kinds.Add(item.Model);var orderedKinds = new List<TownModel>(kinds); orderedKinds.Sort(); required[id] = orderedKinds.ToArray();+ return true;}+ foreach (string id in eligible) if (Describe(id, out var bounds)) places.Add((id, bounds));places.Sort((a, b) => string.CompareOrdinal(a.id, b.id)); buildingPlaces.AddRange(places);+ tileIds.Clear(); villageTiles.Clear(); viewPlaces.Clear();+ foreach (var place in places) viewPlaces.Add((new[] { place.id }, place.bounds));+ if (rendererTileIds != null) foreach (var pair in this.swaps)+ {+ if (pair.kit == null || !rendererTileIds.TryGetValue(pair.kit, out var ids)) continue;+ var villages = new List<string>(); var tile = new Bounds();+ foreach (string id in ids)+ {+ if (eligible.Contains(id) || !Describe(id, out var bounds)) continue;+ if (villages.Count == 0) tile = bounds; else tile.Encapsulate(bounds);+ villages.Add(id);+ }+ if (villages.Count == 0) continue; // camps' tents and model-less places: the close mesh keeps them+ villages.Sort(string.CompareOrdinal);+ var group = villages.ToArray(); tileIds[pair.kit] = group; viewPlaces.Add((group, tile));+ foreach (string id in group) villageTiles[id] = group;+ }Count = instances.Count;foreach (var (kit, close) in this.swaps){ if (kit != null) kit.forceRenderingOff = false; if (close != null) close.forceRenderingOff = true; }@@ -316,7 +424,8 @@ namespace Statecraft.Game.Map.Kits{if (Collection.CollectionResidencyView.TryGroundFocus(cam, out var focus)){- next = choice.hadFocus && focus == choice.focus && EdgeAllowance == null ? choice.selected : FocusedTowns(places, focus, choice.primary, EdgeAllowance == null ? null : (local, edge) =>+ next = choice.hadFocus && focus == choice.focus && EdgeAllowance == null ? choice.selected : FocusedTownsWithFootprints(+ places, admissionFootprintsById, townFootprints, focus, choice.primary, EdgeAllowance == null ? null : (local, edge) =>{var admitted = new List<string>();foreach (var c in OrderedChoices()) if (c.primary != null && !admitted.Contains(c.primary)) admitted.Add(c.primary);@@ -337,14 +446,66 @@ namespace Statecraft.Game.Map.Kits{choice.towns.Clear(); foreach (var id in next) choice.towns.Add(id); changed = true;}+ changed |= AdmitInView(choice, cam);if (changed) { if (Application.isPlaying) reconcileDirty = true; else ReconcileModels(); }+ villagesReady.Clear();foreach (var (kit, close) in swaps){- bool ready = kit != null && swapIds.TryGetValue(kit, out var town) && (ReadyForTown(town, cam) || WholeTownReady?.Invoke(town, cam) == true);+ bool ready = kit != null && (swapIds.TryGetValue(kit, out var town)+ ? ReadyForTown(town, cam) || WholeTownReady?.Invoke(town, cam) == true+ : tileIds.TryGetValue(kit, out var villages) && VillagesReady(villages, cam));Remember(kit, ready); Remember(close, !ready);}}+ /// <summary>Owner ruling, 31 Oct 2026, "Load all in view (Recommended)": under the production policy a close camera+ /// admits every town and village tile in its view (<see cref="ViewMarginM"/>, kept to <see cref="ViewKeepM"/>), nearest+ /// its ground focus first. Returns whether the admitted set changed.</summary>+ bool AdmitInView(Choice choice, Camera cam)+ {+ if (!viewAdmission || !SpatialPolicyConfigured || !choice.close)+ {+ choice.viewValid = false;+ if (choice.inView.Count == 0) return false;+ choice.inView.Clear(); choice.viewed.Clear(); return true;+ }+ var viewProjection = cam.projectionMatrix * cam.worldToCameraMatrix;+ if (choice.viewValid && viewProjection == choice.viewMatrix) return false;+ choice.viewMatrix = viewProjection; choice.viewValid = true;+ GeometryUtility.CalculateFrustumPlanes(viewProjection, frustum);+ var from = choice.hadFocus ? choice.focus : cam.transform.position;+ viewScratch.Clear();+ for (int i = 0; i < viewPlaces.Count; i++)+ {+ var (ids, bounds) = viewPlaces[i];+ float margin = choice.viewed.Contains(ids[0]) ? ViewKeepM : ViewMarginM;+ var wide = bounds; wide.Expand(new Vector3(2f * margin, 0f, 2f * margin));+ if (GeometryUtility.TestPlanesAABB(frustum, wide)) viewScratch.Add((i, GroundDistance(bounds, from)));+ }+ viewScratch.Sort((a, b) =>+ {+ int c = a.distance.CompareTo(b.distance);+ return c != 0 ? c : string.CompareOrdinal(viewPlaces[a.place].ids[0], viewPlaces[b.place].ids[0]);+ });+ viewNext.Clear();+ foreach (var (i, _) in viewScratch) viewNext.AddRange(viewPlaces[i].ids);+ bool changed = !choice.viewed.SetEquals(viewNext);+ choice.inView.Clear(); choice.inView.AddRange(viewNext); // the order alone loads nothing new+ if (changed) { choice.viewed.Clear(); choice.viewed.UnionWith(viewNext); }+ return changed;+ }++ /// <summary>Whether every village of a merged tile has its building models ready for this camera (cached per+ /// PrepareCamera: the swap and the draw decide alike).</summary>+ bool VillagesReady(string[] villages, Camera cam)+ {+ if (villagesReady.TryGetValue(villages, out bool ready)) return ready;+ ready = villages.Length > 0;+ foreach (string id in villages) if (!ReadyForTown(id, cam)) { ready = false; break; }+ villagesReady[villages] = ready;+ return ready;+ }+void Remember(Renderer? renderer, bool off){if (renderer == null) return;@@ -356,23 +517,107 @@ namespace Statecraft.Game.Map.KitspreviousRenderers.Clear();}+ /// <summary>Whether the camera-focus selection holds this town at close zoom (the focused town and its edges).</summary>internal bool WantsTown(string id, Camera cam) => choices.TryGetValue(cam.GetInstanceID(), out var c) && c.close && c.towns.Contains(id);+ /// <summary>Whether this camera admits the place's building models: the focus selection, or (production) its view.</summary>+ internal bool AdmitsTown(string id, Camera cam) =>+ choices.TryGetValue(cam.GetInstanceID(), out var c) && c.close && (c.towns.Contains(id) || c.viewed.Contains(id));internal bool ReadyForTown(string id, Camera cam){- if (!Draw || !WantsTown(id, cam) || !required.TryGetValue(id, out var kinds) || kinds.Length == 0) return false;+ if (!Draw || !AdmitsTown(id, cam) || !required.TryGetValue(id, out var kinds) || kinds.Length == 0) return false;if (set != null) return true;foreach (var kind in kinds)if (!models.TryGetValue(kind, out var model) || model.mesh == null || model.material == null) return false;return true;}+ static void BuildAdmissionFootprints(IReadOnlyList<(string id, Bounds bounds)> proposedPlaces,+ IReadOnlyList<(Vector2 centre, float radius, string id)> configured,+ HashSet<string> ignored, List<(Vector2 centre, float radius, string id)> partition,+ Dictionary<string, (Vector2 centre, float radius, string id)> byTownId, HashSet<string> loggedDuplicateIds)+ {+ var detailedIds = new HashSet<string>(System.StringComparer.Ordinal);+ foreach (var town in proposedPlaces) detailedIds.Add(town.id);+ var counts = new Dictionary<string, int>(System.StringComparer.Ordinal);+ foreach (var footprint in configured)+ {+ counts.TryGetValue(footprint.id, out int count);+ counts[footprint.id] = count + 1;+ }+ var invalid = new HashSet<string>(System.StringComparer.Ordinal);+ foreach (var town in proposedPlaces)+ if (counts.TryGetValue(town.id, out int count) && count > 1 && invalid.Add(town.id)+ && loggedDuplicateIds.Add(town.id))+ Debug.LogError($"Detailed town footprint id '{town.id}' occurs more than once; dropping its footprint and using instance bounds.");+ foreach (var footprint in configured)+ {+ if (invalid.Contains(footprint.id) || ignored.Contains(footprint.id)) continue;+ partition.Add(footprint);+ if (detailedIds.Contains(footprint.id)) byTownId.Add(footprint.id, footprint);+ }+ }++ void CommitAdmissionFootprints(List<(Vector2 centre, float radius, string id)> partition,+ Dictionary<string, (Vector2 centre, float radius, string id)> byTownId)+ {+ townFootprints.Clear(); townFootprints.AddRange(partition);+ admissionFootprintsById.Clear();+ foreach (var pair in byTownId) admissionFootprintsById.Add(pair.Key, pair.Value);+ }++ void ClearFocusChoices()+ {+ foreach (var choice in choices.Values) { choice.hadFocus = false; choice.primary = null; }+ }++ void ClearMissingFocusChoices()+ {+ var present = new HashSet<string>(System.StringComparer.Ordinal);+ foreach (var place in places) present.Add(place.id);+ foreach (var choice in choices.Values)+ {+ choice.hadFocus = false;+ if (choice.primary != null && !present.Contains(choice.primary)+ && !admissionFootprintsById.ContainsKey(choice.primary)) choice.primary = null;+ }+ }++ /// <summary>Stores the game-settlement footprint partition separately from detailed-instance and whole-town bounds.+ /// Camera focus and town labels use a footprint centre, which need not fall among surviving model placements. The+ /// caller excludes the same 1948 locality ids that game-town generation ignores; non-detailed game settlements and+ /// camps still block detailed neighbours. Repeated non-detailed camp ids remain separate discs. A duplicate detailed+ /// id is logged and dropped so that town safely falls back to its instance bounds.</summary>+ internal void ConfigureTownFootprints(IReadOnlyList<(Vector2 centre, float radius, string id)> footprints,+ IReadOnlyCollection<string>? ignoredForGameSettlements = null)+ {+ var proposedConfigured = new List<(Vector2 centre, float radius, string id)>(footprints);+ var proposedIgnored = ignoredForGameSettlements == null+ ? new HashSet<string>(System.StringComparer.Ordinal)+ : new HashSet<string>(ignoredForGameSettlements, System.StringComparer.Ordinal);+ var partition = new List<(Vector2 centre, float radius, string id)>();+ var byTownId = new Dictionary<string, (Vector2 centre, float radius, string id)>(System.StringComparer.Ordinal);+ var proposedLoggedDuplicates = new HashSet<string>(System.StringComparer.Ordinal);+ BuildAdmissionFootprints(places, proposedConfigured, proposedIgnored, partition, byTownId, proposedLoggedDuplicates);+ configuredTownFootprints.Clear(); configuredTownFootprints.AddRange(proposedConfigured);+ ignoredTownFootprintIds.Clear(); ignoredTownFootprintIds.UnionWith(proposedIgnored);+ loggedDuplicateTownFootprintIds.Clear(); loggedDuplicateTownFootprintIds.UnionWith(proposedLoggedDuplicates);+ CommitAdmissionFootprints(partition, byTownId);+ ClearFocusChoices();+ }internal void ConfigureWholeTowns(IReadOnlyList<(string id, Bounds bounds)> towns){- places.Clear(); places.AddRange(buildingPlaces);+ var proposedPlaces = new List<(string id, Bounds bounds)>(buildingPlaces);var ids = new HashSet<string>(System.StringComparer.Ordinal);- foreach (var town in places) ids.Add(town.id);- foreach (var town in towns) if (ids.Add(town.id)) places.Add(town);- places.Sort((a, b) => string.CompareOrdinal(a.id, b.id));- foreach (var choice in choices.Values) choice.hadFocus = false;+ foreach (var town in proposedPlaces) ids.Add(town.id);+ foreach (var town in towns) if (ids.Add(town.id)) proposedPlaces.Add(town);+ proposedPlaces.Sort((a, b) => string.CompareOrdinal(a.id, b.id));+ var partition = new List<(Vector2 centre, float radius, string id)>();+ var byTownId = new Dictionary<string, (Vector2 centre, float radius, string id)>(System.StringComparer.Ordinal);+ var proposedLoggedDuplicates = new HashSet<string>(loggedDuplicateTownFootprintIds, System.StringComparer.Ordinal);+ BuildAdmissionFootprints(proposedPlaces, configuredTownFootprints, ignoredTownFootprintIds, partition, byTownId, proposedLoggedDuplicates);+ places.Clear(); places.AddRange(proposedPlaces);+ loggedDuplicateTownFootprintIds.Clear(); loggedDuplicateTownFootprintIds.UnionWith(proposedLoggedDuplicates);+ CommitAdmissionFootprints(partition, byTownId);+ ClearMissingFocusChoices();}internal bool WantsWholeTown(string id, Camera camera) =>Draw && choices.TryGetValue(camera.GetInstanceID(), out var c) && c.towns.Contains(id) && (!c.close || !required.ContainsKey(id) || (!streaming && set == null));@@ -413,6 +658,8 @@ namespace Statecraft.Game.Map.Kits// A focused town loads before any edge town, even when its model's enum value is larger.foreach (var c in OrderedChoices()) if (c.close && c.primary != null) AddTown(c.primary);foreach (var c in OrderedChoices()) if (c.close) foreach (string id in c.selected) if (id != c.primary) AddTown(id);+ // Then every town and village in view, nearest first (owner ruling, 31 Oct 2026, "Load all in view").+ foreach (var c in OrderedChoices()) if (c.close) foreach (string id in c.inView) AddTown(id);var obsolete = new List<TownModel>();foreach (var pair in models) if (!needed.Contains(pair.Key)) obsolete.Add(pair.Key);foreach (var id in obsolete)@@ -512,6 +759,8 @@ namespace Statecraft.Game.Map.Kitsforeach (var t in tiles){if (!ReadyForTown(t.town, cam)) continue;+ // A village's buildings draw only with its whole tile swapped (else they would stand on its kit houses).+ if (villageTiles.TryGetValue(t.town, out var villages) && !VillagesReady(villages, cam)) continue;// The shadow pass sees casters outside the view too: cull on a widened box (as the trees).var wide = t.bounds; wide.Expand(new Vector3(3000f, 0f, 3000f));if (!GeometryUtility.TestPlanesAABB(planes, wide)) continue;diff --git a/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs b/unity/Assets/Scripts/Map/Routes/RoadVehicles.csindex 42c3732ef..1c17b3c1f 100644--- a/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs+++ b/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs@@ -15,12 +15,15 @@ namespace Statecraft.Game.Map.Routes/// towns (their labels), the unit tokens and the other vehicles, and stands only on ground Israel held on the game date/// (<see cref="Control1948"/>, the map's own sourced control layer). It is sized against the steam locomotive the map/// runs (<see cref="ServiceTrain"/>): <see cref="LengthShare"/> of the locomotive's car. A model that does not stream- /// removes only its own vehicles.</summary>+ /// removes only its own vehicles. It runs in edit mode as every other Collection consumer does, so a layer destroyed+ /// there still retires the model leases it took (OnDisable/OnDestroy).</summary>+ [ExecuteAlways]public sealed class RoadVehicles : MonoBehaviour{public const string Name = "RoadVehicles";internal Collection.CollectionResidencyMetrics.Category RetainedSnapshot() => Collection.CollectionResidencyMetrics.Row(- "retained_road", prefabs.Count, transform.childCount, prefabs.Keys, 0, 0, prefabs.Count, 0, 0, 0);+ "retained_road", prefabs.Count, transform.childCount, prefabs.Keys, residency?.OwnerCount ?? 0,+ residency?.PendingCount ?? 0, prefabs.Count, 0, 0, 0, prefabs.Keys.Select(id => id + "|Far"));internal Collection.CollectionResidencyMetrics.Category SharedSnapshot() => Collection.CollectionResidencyMetrics.Row("shared_road", 0, 0, System.Array.Empty<string>(), 0, 0, 0, 0, 0, 0);public const string IntercityBus = "figure-vehicle-intercity-bus-1948-v2";@@ -80,8 +83,10 @@ namespace Statecraft.Game.Map.Routes/// <summary>A test seam: how the layer asks for a model. Null (the default): the game's stream in Play mode, and none/// in the editor's edit mode (as UnitFigures), so a map built by an editor tool or another test fetches nothing.</summary>internal static Action<string, CollectionDetail, Action<GameObject?>>? Request;+ internal static Func<IDisposable>? RequestOwner;static Action<string, CollectionDetail, Action<GameObject?>>? Stream =>Request ?? (Application.isPlaying ? CollectionStream.Request : (Action<string, CollectionDetail, Action<GameObject?>>?)null);+ sealed class TestSeamLease : IDisposable { public void Dispose() { } }public readonly struct PlacedVehicle{@@ -102,6 +107,8 @@ namespace Statecraft.Game.Map.RoutesIReadOnlyDictionary<string, IReadOnlyList<bool>>? built;string? drawnKey;bool lastClose;+ CollectionResidency? residency;+ readonly Dictionary<string, List<GameObject>> originals = new Dictionary<string, List<GameObject>>(StringComparer.Ordinal);public readonly List<PlacedVehicle> Placed = new List<PlacedVehicle>();/// <summary>How many times the vehicles were laid out (a test reads it: a date change with nothing new costs nothing).</summary>@@ -125,13 +132,54 @@ namespace Statecraft.Game.Map.Routespublic void ShowAt(DateTime at, IReadOnlyDictionary<string, IReadOnlyList<bool>>? segmentsBuilt = null){date = at; built = segmentsBuilt;- var stream = Stream;- if (stream != null)- foreach (var plan in Plans)- if (InForce(plan) && asked.Add(plan.Model)) { var id = plan.Model; stream(id, CollectionDetail.Near, p => OnModel(id, p)); }+ RefreshResidency();Rebuild();}+ IDisposable AcquireOriginal(string id, CollectionDetail detail, Action<GameObject?> answer)+ {+ if (Request != null) { Request(id, detail, answer); return RequestOwner?.Invoke() ?? new TestSeamLease(); }+ if (!Application.isPlaying) return new TestSeamLease();+ return CollectionStream.Acquire(id, detail, answer);+ }+ void RefreshResidency()+ {+ if (!isActiveAndEnabled) return;+ residency ??= new CollectionResidency(AcquireOriginal, ClearForRetirement,+ (id, detail, prefab) => OnModel(id, prefab),+ (instances, owners, keys, complete) => CollectionResidencyMetrics.AfterDestroyed("retained_road",+ instances, owners, complete, Application.isPlaying && Request == null+ ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys), true);+ // v0.3.1 ShowAt requested CollectionDetail.Near for every in-force road-vehicle plan.+ residency.Replace(Plans.Where(InForce).Select(plan => (plan.Model, CollectionDetail.Near)));+ }+ IReadOnlyList<UnityEngine.Object> ClearForRetirement(IReadOnlyCollection<(string id, CollectionDetail detail)> keys)+ {+ var removed = new List<UnityEngine.Object>();+ foreach (var key in keys)+ {+ prefabs.Remove(key.id); asked.Remove(key.id);+ if (!originals.TryGetValue(key.id, out var list)) continue;+ foreach (var go in list) if (go != null)+ {+ var ownedRenderers = new HashSet<Renderer>(go.GetComponentsInChildren<Renderer>(true));+ renderers.RemoveAll(ownedRenderers.Contains);+ removed.Add(go);+ if (Application.isPlaying)+ {+ // Unity forbids hierarchy changes while a parent is being deactivated. In that path the child can+ // be destroyed in place; detach only while this layer is still active, as CampTentModels does.+ if (gameObject.activeInHierarchy) go.transform.SetParent(null);+ Destroy(go);+ }+ else DestroyImmediate(go);+ }+ originals.Remove(key.id); Placed.RemoveAll(p => p.Model == key.id);+ }+ drawnKey = null;+ return removed;+ }+void OnModel(string model, GameObject? prefab){if (this == null) return; // the map was rebuilt before the model came; the new layer asks again@@ -167,6 +215,7 @@ namespace Statecraft.Game.Map.Routesvar old = transform.GetChild(i).gameObject;if (Application.isPlaying) { old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);}+ originals.Clear();renderers.Clear(); Placed.Clear();var control = map.Control;if (control == null) return; // no control layer: no claim about who held a road, so no vehicle@@ -194,6 +243,8 @@ namespace Statecraft.Game.Map.Routesvoid Place(Plan plan, int n, GameObject prefab, Vector2 at, Vector2 along){var go = Instantiate(prefab, transform, false); go.name = $"{plan.Model}_{n}";+ if (!originals.TryGetValue(plan.Model, out var owned)) originals[plan.Model] = owned = new List<GameObject>();+ owned.Add(go);var own = prefab.transform.localRotation;go.transform.localRotation = own;var b = Bounds(go);@@ -261,8 +312,13 @@ namespace Statecraft.Game.Map.Routes}public static bool CloseAt(float distanceM, bool was) => was ? distanceM <= CloseExitM : distanceM <= CloseEnterM;- void OnEnable() => RenderPipelineManager.beginCameraRendering += Choose;- void OnDisable() => RenderPipelineManager.beginCameraRendering -= Choose;+ void OnEnable() { RenderPipelineManager.beginCameraRendering += Choose; if (map != null) RefreshResidency(); }+ void OnDisable()+ {+ RenderPipelineManager.beginCameraRendering -= Choose;+ residency?.Replace(Array.Empty<(string, CollectionDetail)>());+ }+ void OnDestroy() { residency?.Dispose(); residency = null; }internal void Choose(ScriptableRenderContext context, Camera cam){if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;diff --git a/unity/Assets/Scripts/Map/Units/UnitFigureDetail.cs b/unity/Assets/Scripts/Map/Units/UnitFigureDetail.csindex 53ada3147..532e19484 100644--- a/unity/Assets/Scripts/Map/Units/UnitFigureDetail.cs+++ b/unity/Assets/Scripts/Map/Units/UnitFigureDetail.cs@@ -43,11 +43,18 @@ namespace Statecraft.Game.Map.Units/// <summary>The switch of the unit layer or showcase that <paramref name="piece"/> stands in (the root that owns its/// runtime assets, so it goes with the layer), made on first use.</summary>- internal static UnitFigureDetail Of(Transform piece)+ internal static UnitFigureDetail Of(Transform piece) => Existing(piece) ?? RootOf(piece).AddComponent<UnitFigureDetail>();++ /// <summary>The switch <paramref name="piece"/> stands in, if one exists; never made. Teardown uses this: a token the+ /// unit layer has detached for destruction is its own root, and Unity refuses a component on an object being destroyed.+ /// A figure left registered in its layer's switch is pruned once its holder is destroyed (<see cref="Gone"/>).</summary>+ internal static UnitFigureDetail? Existing(Transform piece) =>+ RootOf(piece).TryGetComponent<UnitFigureDetail>(out var detail) ? detail : null;++ static GameObject RootOf(Transform piece){var assets = piece.GetComponentInParent<MapRuntimeAssets>(true);- var root = assets != null ? assets.gameObject : piece.root.gameObject;- return root.TryGetComponent<UnitFigureDetail>(out var detail) ? detail : root.AddComponent<UnitFigureDetail>();+ return assets != null ? assets.gameObject : piece.root.gameObject;}/// <summary>A figure whose far model <paramref name="holder"/> now holds (its first child), with an idle clip.</summary>@@ -99,6 +106,29 @@ namespace Statecraft.Game.Map.UnitsnearAsked.RemoveWhere(id => !figures.Exists(f => f.Id == id));}+ /// <summary>Stops using and destroys only a holder's camera-gated near clone. The independently owned far model+ /// remains registered and visible while the near source lease completes its deferred retirement.</summary>+ internal static IReadOnlyList<UnityEngine.Object> RetireNear(Transform piece)+ {+ var holder = piece.Find(UnitFigures.ModelName);+ if (holder == null) return Array.Empty<UnityEngine.Object>();+ var figure = Existing(piece)?.figures.Find(f => f.Holder == holder);+ var near = holder.Find(NearName);+ if (figure != null)+ {+ foreach (var renderer in figure.FarRenderers) if (renderer != null) renderer.forceRenderingOff = false;+ foreach (var renderer in figure.NearRenderers) if (renderer != null) renderer.forceRenderingOff = true;+ foreach (var animator in figure.Animators) if (animator != null) animator.enabled = false;+ figure.NearRenderers = Array.Empty<Renderer>();+ figure.Animators = Array.Empty<Animator>();+ }+ if (near == null) return Array.Empty<UnityEngine.Object>();+ var original = near.gameObject;+ if (Application.isPlaying) { near.SetParent(null); Destroy(original); } else DestroyImmediate(original);+ UnitFigures.GeometryChanged();+ return new UnityEngine.Object[] { original };+ }+void Arrived(string id){if (this == null) return; // the layer was rebuilt meanwhilediff --git a/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs b/unity/Assets/Scripts/Map/Units/UnitFigureResidency.csindex 9cf6111ad..1ab34851d 100644--- a/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs+++ b/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs@@ -1,50 +1,97 @@#nullable enableusing System;using System.Collections.Generic;+using System.Linq;using Statecraft.Game.Map.Collection;using UnityEngine;using UnityEngine.Rendering;namespace Statecraft.Game.Map.Units{- /// <summary>Per-consumer ownership: one live token holder, with imported children retired before its original leases.</summary>+ /// <summary>Per-consumer ownership: one live token holder, with imported children retired before its original leases.+ /// A roster holder keeps Far once acquired while its token object lives, including while an ancestor is inactive. Destroying the token+ /// releases Far in <see cref="OnDestroy"/>; disabling this component explicitly releases it in <see cref="OnDisable"/>. Disabling the+ /// component while its GameObject is already inactive does not invoke OnDisable, so that Far lease remains until destruction.</summary>[ExecuteAlways]public sealed class UnitFigureResidency : MonoBehaviour{string id = "";- CollectionResidency? residency;+ CollectionResidency? residency, retainedFarResidency, retainedNearResidency;CollectionResidencyView? view;- bool nearWanted, initialized, draws = true;+ bool nearWanted, initialized, draws = true, retainFar;Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? acquire;internal void Initialize(string model, CollectionResidencyPolicy policy,- Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? source, bool draw = true)+ Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? source, bool draw = true, bool retainFar = false,+ CollectionResidency.Retire? retirement = null){if (initialized) { if (model != id) throw new InvalidOperationException("A live holder cannot change its original id."); return; }- initialized = true; draws = draw; id = model; view = new CollectionResidencyView(policy); acquire = source;- residency = new CollectionResidency(Acquire, Clear, Answer,- (instances, owners, keys, complete) => CollectionResidencyMetrics.AfterDestroyed("units", instances, owners, complete,- Application.isPlaying && acquire == null ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys));- // The already-visible live token is its first demand. Camera observations subsequently bound spatial residency.- if (isActiveAndEnabled && !Application.isPlaying) Refresh(true);+ initialized = true; draws = draw; this.retainFar = retainFar; id = model;+ view = new CollectionResidencyView(policy); acquire = source;+ CollectionResidency Make(Func<IReadOnlyList<UnityEngine.Object>> clear) => new CollectionResidency(Acquire, clear, Answer,+ retirement ?? ((instances, owners, keys, complete) => CollectionResidencyMetrics.AfterDestroyed("units", instances, owners, complete,+ Application.isPlaying && acquire == null ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys)));+ if (retainFar)+ {+ retainedFarResidency = Make(Clear);+ retainedNearResidency = Make(ClearNear);+ }+ else residency = Make(Clear);+ // The already-visible holder is its first demand. Roster holders keep Far for their whole lifetime; camera+ // observations subsequently bound only Near. Other consumers retain the original spatial residency behaviour.+ if (isActiveAndEnabled)+ {+ if (retainFar) Refresh(false);+ else if (!Application.isPlaying) Refresh(true);+ }}IDisposable Acquire(string model, CollectionDetail detail, Action<GameObject?> answer) =>UnitFigures.AcquireOwned(model, detail, answer, acquire);void Answer(string model, CollectionDetail detail, GameObject? prefab){UnitFigures.AnswerOwned(model, detail, prefab);+ // A gate answer can synchronously rebuild the layer and destroy this draw:false prefetch holder.if (!draws) return;if (detail == CollectionDetail.Far && prefab != null) UnitFigures.Swap(transform, model, prefab);if (detail == CollectionDetail.Near) UnitFigureDetail.Of(transform).OwnedArrived(model);+ // A holder dressed below an inactive layer acquires its cached Far only when the layer is reactivated. Mark+ // that handoff for UnitLayer.LateUpdate: never destroy the gate holder inside this answer/lifecycle stack.+ if (detail == CollectionDetail.Far && ActiveAnsweredFar)+ GetComponentInParent<UnitLayer>()?.ScheduleSatisfiedPrefetchRetirement(model);+ }+ IEnumerable<(string id, CollectionDetail detail)> ActiveKeys() =>+ (residency?.ActiveKeys ?? Array.Empty<(string, CollectionDetail)>())+ .Concat(retainedFarResidency?.ActiveKeys ?? Array.Empty<(string, CollectionDetail)>())+ .Concat(retainedNearResidency?.ActiveKeys ?? Array.Empty<(string, CollectionDetail)>());+ /// <summary>The ownership snapshot. Its demanded anchor is any active retained/detail key, including a retained Far+ /// that is not currently camera-demanded; <see cref="CameraResident"/> reports camera demand separately.</summary>+ internal CollectionResidencyMetrics.Category ResidencySnapshot()+ {+ var keys = ActiveKeys().Distinct().ToArray();+ return CollectionResidencyMetrics.Row("units", keys.Length == 0 ? 0 : 1,+ transform.Find(UnitFigures.ModelName)?.childCount ?? 0, keys.Select(key => key.id).Distinct(StringComparer.Ordinal),+ (residency?.OwnerCount ?? 0) + (retainedFarResidency?.OwnerCount ?? 0) + (retainedNearResidency?.OwnerCount ?? 0),+ (residency?.PendingCount ?? 0) + (retainedFarResidency?.PendingCount ?? 0) + (retainedNearResidency?.PendingCount ?? 0),+ 0, 0, 0, 0, keys.Select(key => key.id + "|" + key.detail));}- internal CollectionResidencyMetrics.Category ResidencySnapshot() => CollectionResidencyMetrics.Row("units",- initialized && isActiveAndEnabled && (!observed || view!.Keys.Contains(id)) ? 1 : 0,- transform.Find(UnitFigures.ModelName)?.childCount ?? 0, initialized ? new[] { id } : Array.Empty<string>(),- residency?.OwnerCount ?? 0, residency?.PendingCount ?? 0, 0, 0, 0, 0, nearWanted ? new[] { id + "|Far", id + "|Near" } : new[] { id + "|Far" });- void Refresh(bool admitted)+ internal bool CameraResident => observed && view != null && view.Keys.Contains(id);+ internal string ModelId => id;+ /// <summary>True only after this live holder has acquired and answered its retained Far key. An inactive holder cannot+ /// complete a roster-gate handoff; deactivation also excludes an object during its deferred-destroy frame.</summary>+ internal bool ActiveAnsweredFar => isActiveAndEnabled && UnitFigures.Arrived(id)+ && retainedFarResidency?.ActiveAndAnswered((id, CollectionDetail.Far)) == true;+ void Refresh(bool nearAdmitted, bool releaseFar = false){+ if (retainFar)+ {+ retainedNearResidency?.Replace(isActiveAndEnabled && nearAdmitted && nearWanted+ ? new[] { (id, CollectionDetail.Near) } : Array.Empty<(string, CollectionDetail)>());+ retainedFarResidency?.Replace(releaseFar ? Array.Empty<(string, CollectionDetail)>() : new[] { (id, CollectionDetail.Far) });+ return;+ }if (residency == null) return;var keys = new List<(string, CollectionDetail)>();- if (admitted) { keys.Add((id, CollectionDetail.Far)); if (nearWanted) keys.Add((id, CollectionDetail.Near)); }+ if (isActiveAndEnabled && nearAdmitted) keys.Add((id, CollectionDetail.Far));+ if (isActiveAndEnabled && nearAdmitted && nearWanted) keys.Add((id, CollectionDetail.Near));residency.Replace(keys);}bool refreshPending, pendingAdmitted;@@ -71,7 +118,7 @@ namespace Statecraft.Game.Map.Unitsvar holder = transform.Find(UnitFigures.ModelName);if (holder != null){- UnitFigureDetail.Of(transform).Remove(holder);+ UnitFigureDetail.Existing(transform)?.Remove(holder); // never add a switch to a token being destroyedvar original = holder.gameObject; gone.Add(original);if (Application.isPlaying) { holder.SetParent(null); Destroy(original); } else DestroyImmediate(original);UnitFigures.GeometryChanged();@@ -80,16 +127,28 @@ namespace Statecraft.Game.Map.Unitsif (TryGetComponent<MeshRenderer>(out var code)) code.enabled = true;return gone;}+ IReadOnlyList<UnityEngine.Object> ClearNear() => UnitFigureDetail.RetireNear(transform);void OnEnable(){RenderPipelineManager.beginCameraRendering += Choose;- if (initialized) { observed = false; if (!Application.isPlaying) Refresh(true); }+ if (initialized)+ {+ observed = false;+ if (retainFar) Refresh(false);+ else if (!Application.isPlaying) Refresh(true);+ }}void OnDisable(){RenderPipelineManager.beginCameraRendering -= Choose;- refreshPending = false; view?.Clear(); Refresh(false);+ // GameObject deactivation keeps a roster holder's Far lease until the object is destroyed, so a hidden or+ // deferred-destroy token cannot open a source-ownership gap. Disabling the component is an explicit release.+ refreshPending = false; view?.Clear(); Refresh(false, releaseFar: !enabled);+ }+ void OnDestroy()+ {+ residency?.Dispose(); retainedNearResidency?.Dispose(); retainedFarResidency?.Dispose();+ residency = retainedNearResidency = retainedFarResidency = null;}- void OnDestroy() { residency?.Dispose(); residency = null; }}}diff --git a/unity/Assets/Scripts/Map/Units/UnitFigures.cs b/unity/Assets/Scripts/Map/Units/UnitFigures.csindex ab78e1382..52883ef95 100644--- a/unity/Assets/Scripts/Map/Units/UnitFigures.cs+++ b/unity/Assets/Scripts/Map/Units/UnitFigures.cs@@ -17,8 +17,9 @@ namespace Statecraft.Game.Map.Units/// read, and the badge and flag). It fails open: until a model arrives, and for ever when its bundle is missing or/// damaged, the code-built figure stays. An Arab force's token has no code-built figure at all (owner, 17 October 2026,/// #740: "Nothing is drawn with IDF figures, and there is no placeholder art"): the roster draws it only once its model- /// has arrived (<see cref="Arrived"/>). A vehicle has no code-built model either: it appears when it arrives. A model- /// that has arrived once is put on new tokens at once (a roster change rebuilds them), so a rebuild never shows the+ /// has arrived (<see cref="Arrived"/>), or, when its model failed to load (<see cref="Failed"/>), with the plain built-in+ /// figure (owner, 31 October 2026: "Yes, fallback in v0.3.2"). A vehicle has no code-built model either: it appears+ /// when it arrives. A model that has arrived once is put on new tokens at once (a roster change rebuilds them), so a rebuild never shows the/// code-built figures for a frame. Up close (<see cref="UnitFigureDetail"/>), each figure whose model has an idle clip/// shows its skinned near model playing it instead.</summary>public static class UnitFigures@@ -137,6 +138,9 @@ namespace Statecraft.Game.Map.Units/// <summary>The models that have arrived, by id, and the ids asked for and not yet answered.</summary>static readonly Dictionary<string, GameObject> arrived = new Dictionary<string, GameObject>(StringComparer.Ordinal);static readonly HashSet<string> asked = new HashSet<string>(StringComparer.Ordinal);+ /// <summary>The side figures answered with nothing (<see cref="Failed"/>), and those already logged this session.</summary>+ static readonly HashSet<string> failed = new HashSet<string>(StringComparer.Ordinal);+ static readonly HashSet<string> warnedFailed = new HashSet<string>(StringComparer.Ordinal);/// <summary>The figures and vehicles waiting for each asked-for model.</summary>static readonly Dictionary<string, List<Transform>> waiting = new Dictionary<string, List<Transform>>(StringComparer.Ordinal);/// <summary>The near prefabs answered (null: missing or damaged, so the far model stays), and the callers waiting for@@ -152,6 +156,10 @@ namespace Statecraft.Game.Map.Unitsinternal static int GeometryVersion { get; private set; }internal static void GeometryChanged() => GeometryVersion++;static readonly Dictionary<string, int> owned = new Dictionary<string, int>(StringComparer.Ordinal);+ static readonly Dictionary<(string id, CollectionDetail detail), int> ownedDetails =+ new Dictionary<(string, CollectionDetail), int>();+ internal static int OwnedRefCount => owned.Values.Sum();+ internal static int OwnedDetailRefCount => ownedDetails.Values.Sum();static readonly HashSet<string> legacyPinned = new HashSet<string>(StringComparer.Ordinal);internal static CollectionResidencyMetrics.Category ResidencyCaches() => CollectionResidencyMetrics.Row("units", 0, 0,arrived.Keys.Concat(near.Keys).Concat(asked).Concat(waiting.Keys).Concat(nearWaiting.Keys), 0, asked.Count + nearWaiting.Count,@@ -171,7 +179,7 @@ namespace Statecraft.Game.Map.Unitscallbacks.Add(answer);if (callbacks.Count == 1) Source(id, detail, prefab =>{- if (!externalPending.TryGetValue(key, out var current) || current != callbacks || !owned.ContainsKey(id)) return;+ if (!externalPending.TryGetValue(key, out var current) || current != callbacks || !ownedDetails.ContainsKey(key)) return;externalPending.Remove(key);AnswerOwned(id, detail, prefab);foreach (var done in callbacks.ToArray()) done(prefab);@@ -180,48 +188,92 @@ namespace Statecraft.Game.Map.Units}sealed class Owner : IDisposable{- readonly string id; IDisposable? lease;- internal Owner(string id, IDisposable lease) { this.id = id; this.lease = lease; }+ readonly string id; readonly CollectionDetail detail; IDisposable? lease;+ internal Owner(string id, CollectionDetail detail, IDisposable lease) { this.id = id; this.detail = detail; this.lease = lease; }public void Dispose(){if (lease == null) return;lease.Dispose(); lease = null;- if (--owned[id] != 0) return;- owned.Remove(id); externalPending.Remove((id, CollectionDetail.Far)); externalPending.Remove((id, CollectionDetail.Near));+ var key = (id, detail);+ bool lastDetailOwner = --ownedDetails[key] == 0;+ if (lastDetailOwner) ownedDetails.Remove(key);+ bool lastModelOwner = --owned[id] == 0;+ if (lastModelOwner) owned.Remove(id);+ if (lastDetailOwner) externalPending.Remove(key);+ if (lastModelOwner)+ {+ externalPending.Remove((id, CollectionDetail.Far));+ externalPending.Remove((id, CollectionDetail.Near));+ }// A permanent legacy caller is an explicit retained blocker; never erase its still-live source cache.if (legacyPinned.Contains(id)) return;- if (arrived.Remove(id)) AvailabilityVersion++; asked.Remove(id); waiting.Remove(id); near.Remove(id); nearWaiting.Remove(id);+ if (lastDetailOwner)+ {+ if (detail == CollectionDetail.Near) { near.Remove(id); nearWaiting.Remove(id); }+ else { if (arrived.Remove(id) | failed.Remove(id)) AvailabilityVersion++; asked.Remove(id); waiting.Remove(id); }+ }}}internal static IDisposable AcquireOwned(string id, CollectionDetail detail, Action<GameObject?> answer,Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? acquire){owned.TryGetValue(id, out int count); owned[id] = count + 1;- try { return new Owner(id, (acquire ?? AcquireSource)(id, detail, answer)); }- catch { if (--owned[id] == 0) owned.Remove(id); throw; }+ var key = (id, detail);+ ownedDetails.TryGetValue(key, out int detailCount); ownedDetails[key] = detailCount + 1;+ try { return new Owner(id, detail, (acquire ?? AcquireSource)(id, detail, answer)); }+ catch+ {+ if (--owned[id] == 0) owned.Remove(id);+ if (--ownedDetails[key] == 0) ownedDetails.Remove(key);+ throw;+ }}internal static void AnswerOwned(string id, CollectionDetail detail, GameObject? prefab){if (detail == CollectionDetail.Near) near[id] = prefab;else if (prefab != null){- bool first = !arrived.ContainsKey(id); arrived[id] = prefab;+ bool first = !arrived.ContainsKey(id); arrived[id] = prefab; failed.Remove(id);if (first) { AvailabilityVersion++; ModelArrived?.Invoke(id); }}+ else Fail(id);}/// <summary>Forgets every model and request (tests, and a change of <see cref="Source"/>).</summary>[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]internal static void ResetSession(){- if (owned.Count != 0) throw new InvalidOperationException("Unit original owners must retire before session reset.");+ if (owned.Count != 0 || ownedDetails.Count != 0) throw new InvalidOperationException("Unit original owners must retire before session reset.");Forget(); Source = null; ModelArrived = null;}- public static void Forget() { externalPending.Clear(); arrived.Clear(); asked.Clear(); waiting.Clear(); near.Clear(); nearWaiting.Clear(); legacyPinned.Clear(); }+ public static void Forget()+ {+ if (owned.Count == 0) ownedDetails.Clear();+ externalPending.Clear(); arrived.Clear(); asked.Clear(); waiting.Clear(); near.Clear(); nearWaiting.Clear(); legacyPinned.Clear();+ failed.Clear(); warnedFailed.Clear();+ }/// <summary>True when model <paramref name="id"/> has arrived (and its prefab still exists).</summary>public static bool Arrived(string id) => arrived.TryGetValue(id, out var p) && p != null;+ /// <summary>True when Arab side figure <paramref name="id"/> (<see cref="BySide"/>) was answered with nothing: its+ /// bundle is missing or damaged. The unit layer then draws that side's tokens with the plain built-in figure (owner,+ /// 31 October 2026: "Yes, fallback in v0.3.2", the one exception to #740's "no placeholder art"). A figure still+ /// loading is not failed, so a normal start never flashes the built-in figure. Cleared when the model arrives, when+ /// its last owner lets it go (a later demand asks again), and by <see cref="Forget"/>.</summary>+ public static bool Failed(string id) => failed.Contains(id);++ /// <summary>Marks a side figure's failed load: the layer draws again (<see cref="AvailabilityVersion"/>), and the first+ /// failure of each side's figure in a session is logged once. Other models fail open as before.</summary>+ static void Fail(string id)+ {+ if (!BySide.Values.Contains(id) || !failed.Add(id)) return;+ AvailabilityVersion++;+ if (!warnedFailed.Add(id)) return;+ foreach (var side in BySide.Where(kv => kv.Value == id).Select(kv => kv.Key))+ Debug.LogWarning($"UNITS figures: {side}'s figure {id} did not load; its tokens are drawn with the plain built-in figure.");+ }+/// <summary>Asks for model <paramref name="id"/> once, without a figure to put it on (an Arab force's token waits for it).</summary>public static void Prefetch(string id) => Ask(id);@@ -229,13 +281,13 @@ namespace Statecraft.Game.Map.Units/// scaled by <see cref="UnitShowcase.FigureScale"/>): at once when it has arrived, else when it arrives. Nothing for a/// null id.</summary>internal static void Dress(Transform piece, string? id, CollectionResidencyPolicy policy,- Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? acquire = null)+ Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? acquire = null, bool retainFar = false){if (policy == null) throw new ArgumentNullException(nameof(policy));if (id == null || piece == null) return;// The sandwich original remains explicitly pinned by the road consumer in this first production slice.var owner = piece.GetComponent<UnitFigureResidency>() ?? piece.gameObject.AddComponent<UnitFigureResidency>();- owner.Initialize(id, policy, acquire);+ owner.Initialize(id, policy, acquire, retainFar: retainFar);}public static void Dress(Transform piece, string? id)@@ -281,9 +333,9 @@ namespace Statecraft.Game.Map.Unitsasked.Remove(id);var pieces = waiting.TryGetValue(id, out var l) ? l : null;waiting.Remove(id);- if (prefab == null) return; // fail open: the code-built figure stays (the stream has warned once)+ if (prefab == null) { Fail(id); return; } // fail open: the code-built figure stays (the stream has warned once)if (arrived.Count == 0 && Application.isPlaying) Debug.Log("UNITS figures: the Collection's figures streamed in");- arrived[id] = prefab;+ arrived[id] = prefab; failed.Remove(id);if (pieces != null) foreach (var p in pieces) if (p != null) Swap(p, id, prefab); // a token rebuilt meanwhile is goneModelArrived?.Invoke(id);});diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.csindex 1f4f9371b..dd2609a47 100644--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs@@ -42,7 +42,10 @@ namespace Statecraft.Game.Map.Unitsreadonly List<Mesh> tokenMeshes = new List<Mesh>();List<UnitToken>? roster;readonly Dictionary<string, UnitFigureResidency> figurePrefetch = new Dictionary<string, UnitFigureResidency>();- bool updatingPrefetch;+ readonly HashSet<string> wantedFigurePrefetch = new HashSet<string>(StringComparer.Ordinal);+ internal int FigurePrefetchCount => figurePrefetch.Count;+ bool updatingPrefetch, prefetchRetirementDirty;+ string? prefetchRetirementId;int seenAvailability = -1;int seenGeometry = -1;static readonly Predicate<MeshFilter> MissingMesh = mesh => mesh == null;@@ -51,34 +54,59 @@ namespace Statecraft.Game.Map.UnitsupdatingPrefetch = true;try{- var needed = new HashSet<string>();- foreach (var token in candidates)+ var rosterGateModels = new HashSet<string>(candidates.Where(token => token.Unit.Side != UnitData.Israel)+ .Select(token => UnitFigures.SideFigure(token.Unit.Side)).Where(id => id != null)+ .Select(id => id!), StringComparer.Ordinal);+ wantedFigurePrefetch.Clear(); wantedFigurePrefetch.UnionWith(rosterGateModels);+ foreach (var id in rosterGateModels){- var ids = Enumerable.Range(0, token.Figures).Select(i => UnitFigures.FigureFor(token.Unit, i,- token.Unit.Side == UnitData.Israel ? token.Headgear[i] : null))- .Concat(token.Vehicles).Where(id => id != null).Distinct();- foreach (var id in ids)+ // A foreign token cannot create its own figure holders until this side model passes Show's roster+ // gate. Keep one temporary owner per missing side model, never N+1 permanent owners beside the+ // roster figures; RetireSatisfiedPrefetch transfers ownership after Rebuild has drawn the token.+ if (!UnitFigures.Arrived(id) && !figurePrefetch.TryGetValue(id, out var owner)){- string key = token.Unit.Id + "|" + id; needed.Add(key);- if (!figurePrefetch.TryGetValue(key, out var owner))- {- var holder = new GameObject("Original demand " + key); holder.transform.SetParent(transform, false);- owner = holder.AddComponent<UnitFigureResidency>(); figurePrefetch[key] = owner;- holder.transform.position = map.Frame.ToWorld(token.Anchor.Lon, token.Anchor.Lat, 0);- owner.Initialize(id!, map.Residency.Units, null, draw: false);- }- owner.transform.position = map.Frame.ToWorld(token.Anchor.Lon, token.Anchor.Lat, 0);+ var holder = new GameObject("Roster gate demand " + id); holder.transform.SetParent(transform, false);+ owner = holder.AddComponent<UnitFigureResidency>(); figurePrefetch[id] = owner;+ owner.Initialize(id, map.Residency.Units, null, draw: false, retainFar: true);}}- foreach (string key in figurePrefetch.Keys.ToArray()) if (!needed.Contains(key))- {- var old = figurePrefetch[key]; figurePrefetch.Remove(key);- old.gameObject.SetActive(false);- if (Application.isPlaying) Destroy(old.gameObject); else DestroyImmediate(old.gameObject);- }+ if (figurePrefetch.Keys.Any(key => !rosterGateModels.Contains(key))) ScheduleSatisfiedPrefetchRetirement();}finally { updatingPrefetch = false; }}+ internal void ScheduleSatisfiedPrefetchRetirement(string id)+ {+ if (figurePrefetch.Count == 0 || !figurePrefetch.ContainsKey(id)) return;+ if (!prefetchRetirementDirty) prefetchRetirementId = id;+ else if (prefetchRetirementId != id) prefetchRetirementId = null;+ prefetchRetirementDirty = true;+ }+ void ScheduleSatisfiedPrefetchRetirement()+ {+ if (figurePrefetch.Count == 0) return;+ prefetchRetirementId = null; prefetchRetirementDirty = true;+ }+ void RetireSatisfiedPrefetch(string? onlyId = null)+ {+ if (figurePrefetch.Count == 0) { prefetchRetirementDirty = false; prefetchRetirementId = null; return; }+ if (onlyId != null && !figurePrefetch.ContainsKey(onlyId))+ { prefetchRetirementDirty = false; prefetchRetirementId = null; return; }+ var heldByFigures = new HashSet<string>(tokensRoot.GetComponentsInChildren<UnitFigureResidency>(true)+ .Where(owner => owner.ActiveAnsweredFar).Select(owner => owner.ModelId), StringComparer.Ordinal);+ var candidates = onlyId == null ? figurePrefetch.Keys.ToArray() : new[] { onlyId };+ foreach (string id in candidates.Where(id => !wantedFigurePrefetch.Contains(id) || heldByFigures.Contains(id)))+ {+ var old = figurePrefetch[id]; figurePrefetch.Remove(id);+ old.gameObject.SetActive(false);+ if (Application.isPlaying) Destroy(old.gameObject); else DestroyImmediate(old.gameObject);+ }+ prefetchRetirementDirty = false; prefetchRetirementId = null;+ }+ /// <summary>Runs the deferred roster-gate ownership handoff. Production calls it from <see cref="LateUpdate"/>;+ /// EditMode tests call it explicitly because they do not advance a player frame.</summary>+ internal void FlushPrefetchRetirement()+ { if (prefetchRetirementDirty) RetireSatisfiedPrefetch(prefetchRetirementId); }+ void LateUpdate() => FlushPrefetchRetirement();/// <summary>What <see cref="Show"/> last drew from, so a Collection model's arrival can draw the tokens that waited for/// it (an Arab force's, issue #665).</summary>Content? shownContent;@@ -312,12 +340,15 @@ namespace Statecraft.Game.Map.Units? UnitRoster.FromState(units, content, state, _ => true, (row, start, q, r) => MovedAnchor(content, row, start, q, r)): UnitRoster.Build(units, content, state, _ => true);PrefetchFigures(now);- now = now.Where(t => t.Unit.Side == UnitData.Israel || UnitFigures.Arrived(UnitFigures.SideFigure(t.Unit.Side)!)).ToList();+ // An Arab force's token waits while its figure loads, and is drawn with the plain built-in figure if it failed.+ now = now.Where(t => t.Unit.Side == UnitData.Israel || UnitFigures.Arrived(UnitFigures.SideFigure(t.Unit.Side)!)+ || UnitFigures.Failed(UnitFigures.SideFigure(t.Unit.Side)!)).ToList();if (roster != null && roster.SequenceEqual(now)) { seenAvailability = UnitFigures.AvailabilityVersion; return false; }roster = now;PlaceMoved(now);placed = UnitPlacer.Place(now, drawSpots ?? DisplaySpots);Rebuild();+ ScheduleSatisfiedPrefetchRetirement();if (Selected != null && !placed.Any(p => p.Token.Unit.Id == Selected)) Select(null); else Select(Selected);seenAvailability = UnitFigures.AvailabilityVersion;return true;@@ -561,12 +592,25 @@ namespace Statecraft.Game.Map.Unitsvoid Rebuild(){+ var outgoing = new List<GameObject>();for (int i = tokensRoot.childCount - 1; i >= 0; i--){var old = tokensRoot.GetChild(i).gameObject;+ // Roster holders retain Far through deactivation and release it only on destruction. Deactivate before+ // deferred Destroy so these outgoing holders are never considered a live prefetch handoff target.+ old.SetActive(false);old.transform.SetParent(null);- if (Application.isPlaying) Destroy(old); else DestroyImmediate(old);+ outgoing.Add(old);}+ // The outgoing holders are destroyed only after the new tokens have acquired their models, as the player's+ // deferred Destroy already does: an edit-mode rebuild must not drop a model's last owner in between and ask the+ // source again for a request still in flight (or release an arrived model) only to re-acquire it.+ try { BuildTokens(); }+ finally { foreach (var old in outgoing) if (Application.isPlaying) Destroy(old); else DestroyImmediate(old); }+ }++ void BuildTokens()+ {FreeTokenMeshes();badges.Clear(); badgeHomes.Clear(); facedFor = null;trios.Clear(); turnedFor = null; // the new figures stand as at yaw 0@@ -594,6 +638,9 @@ namespace Statecraft.Game.Map.Unitsvar offsets = UnitShowcase.FigureOffsets(t.Figures);float highest = foot.y; // the badge clears the highest figure (on a slope the uphill one stands higher)bool israel = t.Unit.Side == UnitData.Israel;+ // Owner, 31 October 2026 ("Yes, fallback in v0.3.2"): an Arab force whose figure failed to load stands+ // with the plain built-in rifleman (steel helmet), the Israeli fail-open figure; only for that failure.+ bool builtIn = !israel && !UnitFigures.Arrived(UnitFigures.SideFigure(t.Unit.Side)!);int vehicles = Mathf.Min(t.Vehicles.Count, VehicleSlots.Length);figures = new (Transform, Vector3, float)[offsets.Length + vehicles];for (int i = 0; i < offsets.Length; i++)@@ -611,8 +658,16 @@ namespace Statecraft.Game.Map.Unitsfigure = UnitShowcase.Piece(go.transform, $"Rifleman{i}", type, () => MeshFor($"{type}/{pose}", () => UnitModels.Rifleman(hat, pose, faded, type)),paint, at, Quaternion.Euler(0, heading, 0), UnitShowcase.FigureScale, out _).transform;}+ else if (builtIn)+ {+ var type = UnitRoster.RiflemanType(UnitData.SteelHelmet);+ figure = UnitShowcase.Piece(go.transform, $"Figure{i}", type, () => MeshFor($"{type}/{pose}",+ () => UnitModels.Rifleman(UnitModels.Headgear.SteelHelmet, pose, faded, type)),+ paint, at, Quaternion.Euler(0, heading, 0), UnitShowcase.FigureScale, out _).transform;+ }else figure = EmptyPiece(go.transform, $"Figure{i}", at, heading); // no code-built figure for another side (#740)- UnitFigures.Dress(figure, UnitFigures.FigureFor(t.Unit, i, israel ? t.Headgear[i] : null), map.Residency.Units); // the Collection's figure, once streamed (#665)+ UnitFigures.Dress(figure, UnitFigures.FigureFor(t.Unit, i, israel ? t.Headgear[i] : null),+ map.Residency.Units, retainFar: true); // the Collection's figure, held while its roster token lives (#665)figures[i] = (figure, new Vector3(offsets[i].x, 0, offsets[i].y) * k, heading);}for (int j = 0; j < vehicles; j++)@@ -622,7 +677,8 @@ namespace Statecraft.Game.Map.Unitsvar at = centre + offset;at.y = UnitPlinth.FigureY(map, plinth, at.x, at.z);var vehicle = EmptyPiece(go.transform, $"Vehicle{j}", at, heading);- UnitFigures.Dress(vehicle, t.Vehicles[j], map.Residency.Units); // the gun or the jeep: drawn only once streamed (#665)+ UnitFigures.Dress(vehicle, t.Vehicles[j], map.Residency.Units,+ retainFar: true); // the gun or the jeep: held while its roster token lives (#665)figures[offsets.Length + j] = (vehicle, offset, heading);}foot.y = highest;diff --git a/unity/Assets/Tests/EditMode/CollectionLeaveTests.cs b/unity/Assets/Tests/EditMode/CollectionLeaveTests.csindex 3601bba4a..1768a4838 100644--- a/unity/Assets/Tests/EditMode/CollectionLeaveTests.cs+++ b/unity/Assets/Tests/EditMode/CollectionLeaveTests.cs@@ -1,6 +1,7 @@#nullable enableusing System;using System.Collections.Generic;+using System.Linq;using System.Reflection;using NUnit.Framework;using Statecraft.Game.Map;@@ -17,6 +18,9 @@ public class CollectionLeaveTestsreadonly List<Action<GameObject?>> delayed = new List<Action<GameObject?>>();GameObject prefab = null!;int acquired, released;+ readonly Dictionary<CollectionDetail, int> acquiredBy = new Dictionary<CollectionDetail, int>(), releasedBy = new Dictionary<CollectionDetail, int>();+ int Acquired(CollectionDetail detail) => acquiredBy.TryGetValue(detail, out int n) ? n : 0;+ int Released(CollectionDetail detail) => releasedBy.TryGetValue(detail, out int n) ? n : 0;sealed class Lease : IDisposable{Action? release;@@ -25,7 +29,7 @@ public class CollectionLeaveTests}[SetUp] public void Setup(){- acquired = released = 0; delayed.Clear();+ acquired = released = 0; delayed.Clear(); acquiredBy.Clear(); releasedBy.Clear();people = CivilianPeople.Request; rural = RuralLife.Request;prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);prefab.name = "TEST ONLY original"; prefab.transform.position = Vector3.one * -100000;@@ -46,6 +50,22 @@ public class CollectionLeaveTestsComponent Layer(bool isRural, MapScene map) => isRural ? RuralLife.Show(map)! :CivilianPeople.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), ContentLoader.Load(Statecraft.Game.Paths.Content))!;static int Count(Component layer) => ((System.Collections.ICollection)layer.GetType().GetField("Placed")!.GetValue(layer)!).Count;+ /// <summary>Placed Far originals: every civilian figure (each has its Far), or RuralLife's Far rows.</summary>+ static int FarCount(Component layer)+ {+ int n = 0;+ foreach (var placed in (System.Collections.IEnumerable)layer.GetType().GetField("Placed")!.GetValue(layer)!)+ {+ // RuralLife.Placed is a (Key, Model, Detail, ...) value tuple: its Detail is the runtime field Item3.+ var detail = placed.GetType().GetField("Item3");+ if (detail == null || detail.FieldType != typeof(CollectionDetail)+ || (CollectionDetail)detail.GetValue(placed)! == CollectionDetail.Far) n++;+ }+ return n;+ }+ /// <summary>Live Near original instances: a figure's "Near" child or a rural ":near" instance.</summary>+ static int NearInstances(Component layer) =>+ layer.GetComponentsInChildren<Transform>(true).Count(t => t.name == "Near" || t.name.EndsWith(":near", StringComparison.Ordinal));void Configure(Component layer, bool delay){// The baseline has neither API; still drive its existing visible/leave behaviour and observe the regression.@@ -55,9 +75,9 @@ public class CollectionLeaveTestsvar policy = Activator.CreateInstance(policyType, 1000000f, 1000001f, 100000f, 110000f, 0, "TEST ONLY");Func<string, CollectionDetail, Action<GameObject?>, IDisposable> acquire = (_, __, answer) =>{- acquired++;+ acquired++; acquiredBy[__] = Acquired(__) + 1;if (delay) delayed.Add(answer); else answer(prefab);- return new Lease(() => released++);+ return new Lease(() => { released++; releasedBy[__] = Released(__) + 1; });};configure.Invoke(layer, new object[] { policy!, acquire });}@@ -78,10 +98,23 @@ public class CollectionLeaveTestsCamera(layer, 10000);Assert.AreSame(first, layer.transform.GetChild(0), "an unchanged camera demand must not rebuild every frame");Assert.AreEqual(stableAcquires, acquired);- Camera(layer, 250000); Assert.AreEqual(0, Count(layer), "hiding is not retirement");- Assert.AreEqual(acquired, released, "every old lease retired");- int before = acquired;- Camera(layer, 10000); Assert.Greater(Count(layer), 0); Assert.Greater(acquired, before);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": Far stays map-wide; only Near loads/unloads by camera.+ // Leaving keeps every Far original and its lease, and retires (destroys and releases) every Near one.+ int far = FarCount(layer), nearFirst = Acquired(CollectionDetail.Near);+ Assert.Greater(far, 0, "Far originals are drawn at 10 km");+ Assert.Greater(nearFirst, 0, "the close 10 km camera took Near leases (people and rural)");+ Assert.AreEqual(nearFirst > 0, NearInstances(layer) > 0, "Near leases have Near instances");+ Camera(layer, 250000);+ Assert.AreEqual(far, FarCount(layer), "leaving keeps every map-wide Far original");+ Assert.AreSame(first, layer.transform.GetChild(0), "the Far instances are not rebuilt");+ Assert.AreEqual(0, NearInstances(layer), "hiding is not retirement");+ Assert.AreEqual(Acquired(CollectionDetail.Near), Released(CollectionDetail.Near), "every old Near lease retired");+ Assert.AreEqual(0, Released(CollectionDetail.Far), "no Far lease retires on leave");+ int farBefore = Acquired(CollectionDetail.Far), nearBefore = Acquired(CollectionDetail.Near);+ Camera(layer, 10000); Assert.AreEqual(far, FarCount(layer));+ Assert.AreEqual(farBefore, Acquired(CollectionDetail.Far), "revisit re-acquires no Far");+ Assert.AreEqual(nearFirst, Acquired(CollectionDetail.Near) - nearBefore, "revisit acquires the same Near set again");+ Assert.AreEqual(nearFirst > 0, NearInstances(layer) > 0);Object.DestroyImmediate(layer.gameObject); Assert.AreEqual(acquired, released);}[TestCase(false)] [TestCase(true)]@@ -89,8 +122,13 @@ public class CollectionLeaveTests{var layer = Layer(isRural, Map()); Configure(layer, true);Camera(layer, 10000); Camera(layer, 250000);- foreach (var answer in delayed) answer(prefab);- Assert.AreEqual(0, Count(layer));- Assert.AreEqual(acquired, released);+ foreach (var answer in delayed.ToArray()) answer(prefab);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": Far stays map-wide; only Near loads/unloads by camera.+ // A Far demand never left, so its late answer draws; a late Near answer for the departed view cannot.+ Assert.Greater(Acquired(CollectionDetail.Near), 0, "the close 10 km camera asked for Near (people and rural)");+ Assert.AreEqual(0, NearInstances(layer), "no Near original is resurrected");+ Assert.AreEqual(Acquired(CollectionDetail.Near), Released(CollectionDetail.Near), "every departed Near lease retired");+ Assert.AreEqual(0, Released(CollectionDetail.Far), "the map-wide Far leases are kept");+ Assert.Greater(FarCount(layer), 0, "the Far answers draw map-wide");}}diff --git a/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.cs b/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.csindex cc1317196..545da2ad2 100644--- a/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.cs+++ b/unity/Assets/Tests/EditMode/CollectionOtherLeaveTests.cs@@ -73,17 +73,30 @@ public class CollectionOtherLeaveTests{var layer = MapLayer(special); View(layer, 10000);Assert.Greater(layer.transform.childCount, 0); int before = acquired;- View(layer, 250000); Assert.AreEqual(0, layer.transform.childCount, "forceRenderingOff is not release");- Assert.AreEqual(acquired, released);- if (!special) Assert.AreEqual(0, ((SeaAirCollection)layer).KeepClear.Count, "labels must forget retired hulls");- View(layer, 10000); Assert.Greater(layer.transform.childCount, 0); Assert.Greater(acquired, before);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": craft and special buildings keep their v0.3.1 map-wide originals.+ // Leaving neither destroys nor releases them; only teardown does.+ int children = layer.transform.childCount; var first = layer.transform.GetChild(0);+ View(layer, 250000); Assert.AreEqual(children, layer.transform.childCount, "leaving keeps every map-wide original");+ Assert.AreSame(first, layer.transform.GetChild(0), "the originals are not rebuilt");+ Assert.AreEqual(0, released, "no lease retires on leave");+ if (!special) Assert.AreEqual(((SeaAirCollection)layer).Placed.Count, ((SeaAirCollection)layer).KeepClear.Count, "labels keep clear of every drawn hull");+ View(layer, 10000); Assert.AreEqual(children, layer.transform.childCount); Assert.AreEqual(before, acquired, "revisit re-acquires nothing");Object.DestroyImmediate(layer.gameObject); Assert.AreEqual(acquired, released);}[TestCase(false)] [TestCase(true)] public void LateAnswerDoesNotRebuildDepartedCraftOrBuilding(bool special){delayed = true; var layer = MapLayer(special); View(layer, 10000); View(layer, 250000);foreach (var done in pending.ToArray()) done(prefab);- Assert.AreEqual(0, layer.transform.childCount); Assert.AreEqual(acquired, released);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": craft and special buildings keep their v0.3.1 map-wide originals.+ // The camera leaving departs nothing, so the late answers draw; teardown is the departure that releases them.+ Assert.Greater(acquired, 0); Assert.AreEqual(0, released, "no lease retires on leave");+ Assert.Greater(layer.transform.childCount, 0, "the late answers of a map-wide demand draw");+ Object.DestroyImmediate(layer.gameObject);+ int objects = Object.FindObjectsByType<Transform>(FindObjectsInactive.Include, FindObjectsSortMode.None).Length;+ foreach (var done in pending.ToArray()) done(prefab); // answers after teardown rebuild nothing and throw nothing+ Assert.AreEqual(objects, Object.FindObjectsByType<Transform>(FindObjectsInactive.Include, FindObjectsSortMode.None).Length,+ "a late answer after teardown creates no instance");+ Assert.AreEqual(acquired, released);}GameObject Piece(string name){diff --git a/unity/Assets/Tests/EditMode/CollectionResidencyCoordinatorTests.cs b/unity/Assets/Tests/EditMode/CollectionResidencyCoordinatorTests.csindex ccaa87ebc..88328bd7e 100644--- a/unity/Assets/Tests/EditMode/CollectionResidencyCoordinatorTests.cs+++ b/unity/Assets/Tests/EditMode/CollectionResidencyCoordinatorTests.cs@@ -53,6 +53,23 @@ public class CollectionResidencyCoordinatorTestsr.Replace(new[] { ("a", CollectionDetail.Far) }); r.Replace(new[] { ("b", CollectionDetail.Far) });r.Dispose(); r.Dispose(); retire!(); Assert.AreEqual(1, acquired);}+ /// <summary>Regression guard: disposal permanently invalidates a source callback that arrives late.</summary>+ [Test]+ public void LateAnswerAfterDisposeIsANoOp()+ {+ Action<GameObject?>? lateAnswer = null; int answers = 0;+ var r = new CollectionResidency((_, __, answer) => { lateAnswer = answer; return new Lease(); },+ () => Array.Empty<Object>(), (_, __, ___) => answers++,+ (_, owners, __, done) => { foreach (var owner in owners) owner.Dispose(); done(); });+ r.Replace(new[] { ("a", CollectionDetail.Far) });++ r.Dispose();+ lateAnswer!(null);++ Assert.AreEqual(0, answers, "a disposed residency ignores its source's late callback");+ Assert.AreEqual(0, r.OwnerCount, "the late callback cannot recreate ownership");+ Assert.AreEqual(0, r.PendingCount, "the late callback cannot restore disposed demand");+ }[Test]public void TwoCamerasKeepAUnionUntilTheirOwnDemandExpires(){diff --git a/unity/Assets/Tests/EditMode/FarMapWideResidencyTests.cs b/unity/Assets/Tests/EditMode/FarMapWideResidencyTests.csnew file mode 100644index 000000000..fa91eca5e--- /dev/null+++ b/unity/Assets/Tests/EditMode/FarMapWideResidencyTests.cs@@ -0,0 +1,362 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using System.Reflection;+using NUnit.Framework;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Collection;+using Statecraft.Game.Map.Kits;+using Statecraft.Game.Map.Routes;+using Statecraft.Sim;+using UnityEditor.SceneManagement;+using UnityEngine;+using Object = UnityEngine.Object;++/// <summary>Owner decision, 30 October 2026: far originals are consumer-lifetime demand; only Near is spatial.</summary>+public sealed class FarMapWideResidencyTests+{+ sealed class Lease : IDisposable+ {+ readonly Action release;+ bool disposed;+ public Lease(Action release) { this.release = release; }+ public void Dispose() { if (disposed) return; disposed = true; release(); }+ }++ [TearDown]+ public void TearDown()+ {+ RoadVehicles.Request = null;+ RoadVehicles.RequestOwner = null;+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ }++ [Test]+ public void RemovingOneKeyRetiresOnlyItsInstancesAndKeepsEverySurvivorAlive()+ {+ int acquired = 0, released = 0;+ var a = new GameObject("a instance");+ var b = new GameObject("b instance");+ var instances = new Dictionary<(string id, CollectionDetail detail), GameObject>+ {+ [("a", CollectionDetail.Near)] = a,+ [("b", CollectionDetail.Far)] = b,+ };+ var residency = new CollectionResidency((_, __, answer) =>+ { acquired++; return new Lease(() => released++); }, keys =>+ {+ var removed = new List<Object>();+ foreach (var key in keys)+ if (instances.Remove(key, out var instance)) { removed.Add(instance); Object.DestroyImmediate(instance); }+ return removed;+ }, (_, __, ___) => { }, (_, owners, __, done) =>+ { foreach (var owner in owners) owner.Dispose(); done(); }, true);++ residency.Replace(instances.Keys);+ residency.Replace(new[] { ("b", CollectionDetail.Far) });++ Assert.AreSame(b, instances[("b", CollectionDetail.Far)], "a pan cannot replace or blink a still-demanded instance");+ Assert.AreEqual(2, acquired);+ Assert.AreEqual(1, released, "only the departed Near key retires");+ Assert.AreEqual(1, residency.OwnerCount);+ residency.Dispose();+ Assert.AreEqual(acquired, released, "all refcounts return to zero on teardown");+ Assert.IsTrue(b == null, "the final bundle lease is released only after its instance is destroyed");+ }++ [Test]+ public void RemovingOneKeyAndAddingAnotherAcquiresTheAdditionBeforeRetirementCompletes()+ {+ var sourceAnswers = new Dictionary<string, Action<GameObject?>>(StringComparer.Ordinal);+ var instances = new Dictionary<string, GameObject>(StringComparer.Ordinal);+ var retirements = new List<Action>(); int references = 0;+ var residency = new CollectionResidency((id, _, answer) =>+ {+ references++; sourceAnswers[id] = answer; return new Lease(() => references--);+ }, keys =>+ {+ var removed = new List<Object>();+ foreach (var key in keys)+ if (instances.Remove(key.id, out var instance)) { removed.Add(instance); Object.DestroyImmediate(instance); }+ return removed;+ }, (id, _, prefab) => instances[id] = Object.Instantiate(prefab!),+ (_, owners, __, complete) => retirements.Add(() => { foreach (var owner in owners) owner.Dispose(); complete(); }), true);+ var prefab = new GameObject("fake acquired original");+ try+ {+ residency.Replace(new[] { ("a", CollectionDetail.Far), ("b", CollectionDetail.Far) });+ sourceAnswers["a"](prefab); sourceAnswers["b"](prefab);+ var survivor = instances["b"];++ residency.Replace(new[] { ("b", CollectionDetail.Far), ("c", CollectionDetail.Far) });++ Assert.IsTrue(sourceAnswers.ContainsKey("c"), "an unrelated addition is acquired in the removal call");+ sourceAnswers["c"](prefab);+ Assert.AreSame(survivor, instances["b"], "the consumer instance for a kept key cannot blink");+ Assert.AreEqual(3, references, "the retiring lease is still held until its consumer is destroyed");+ retirements.Single().Invoke(); retirements.Clear();+ Assert.AreEqual(2, references);+ residency.Dispose(); retirements.Single().Invoke();+ Assert.AreEqual(0, references);+ }+ finally { Object.DestroyImmediate(prefab); }+ }++ [Test]+ public void RedemandDuringRetirementReusesAnsweredLeaseWithoutZeroRefcount()+ {+ Action<GameObject?>? sourceAnswer = null; Action? finishRetirement = null;+ GameObject? instance = null; int acquisitions = 0, references = 0, releases = 0;+ var residency = new CollectionResidency((_, __, answer) =>+ {+ acquisitions++; references++; sourceAnswer = answer;+ return new Lease(() => { references--; releases++; });+ }, _ =>+ {+ if (instance == null) return Array.Empty<Object>();+ var removed = new Object[] { instance }; Object.DestroyImmediate(instance); instance = null; return removed;+ }, (_, __, prefab) => instance = Object.Instantiate(prefab!),+ (_, owners, __, complete) => finishRetirement = () => { foreach (var owner in owners) owner.Dispose(); complete(); }, true);+ var prefab = new GameObject("fake redemand original");+ try+ {+ residency.Replace(new[] { ("a", CollectionDetail.Near) }); sourceAnswer!(prefab);+ residency.Replace(Array.Empty<(string, CollectionDetail)>());+ Assert.IsTrue(instance == null);+ residency.Replace(new[] { ("a", CollectionDetail.Near) });+ Assert.AreEqual(1, acquisitions, "only the key still retiring is deferred");+ Assert.AreEqual(1, references, "its original lease stays live during retirement");++ finishRetirement!();++ Assert.AreEqual(1, acquisitions, "the answered lease and prefab are reused");+ Assert.AreEqual(0, releases); Assert.AreEqual(1, references);+ Assert.IsTrue(instance != null, "the fake acquisition callback recreates the consumer after retirement");+ residency.Dispose(); finishRetirement!();+ Assert.AreEqual(1, releases); Assert.AreEqual(0, references);+ }+ finally { Object.DestroyImmediate(prefab); }+ }++ [Test]+ public void PeopleFarDemandSurvivesA90KmCameraOutsideTheNearDisc() =>+ AssertFarDemand<CivilianPeople>(new List<CivilianPeople.Want>+ { new CivilianPeople.Want("far/0", CivilianPeople.Townsman, Vector3.right, 0) }, "wanted", ProductionResidency.Approved().People);++ [Test]+ public void RuralFarDemandSurvivesA90KmCameraOutsideTheNearDisc() =>+ AssertFarDemand<RuralLife>(new List<RuralLife.Want>+ { new RuralLife.Want("far", RuralLife.Tractor, Vector2.right, 0) }, "wants", ProductionResidency.Approved().Rural);++ void AssertFarDemand<T>(object wants, string field, CollectionResidencyPolicy policy) where T : MonoBehaviour+ {+ int acquired = 0, released = 0;+ var go = new GameObject(typeof(T).Name); var layer = go.AddComponent<T>();+ var prefab = new GameObject("fake " + typeof(T).Name + " original");+ try+ {+ typeof(T).GetMethod("ConfigureResidency", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(layer,+ new object[] { policy,+ (Func<string, CollectionDetail, Action<GameObject?>, IDisposable>)((_, detail, answer) =>+ { Assert.AreEqual(CollectionDetail.Far, detail); acquired++; answer(prefab); return new Lease(() => released++); }) });+ typeof(T).GetField(field, BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(layer, wants);+ typeof(T).GetMethod("RefreshResidency", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(layer, null);+ var cameraGo = new GameObject("start-view camera", typeof(Camera), typeof(CameraRig));+ var camera = cameraGo.GetComponent<Camera>(); float startView = cameraGo.GetComponent<CameraRig>().Distance;+ camera.transform.SetPositionAndRotation(new Vector3(0, startView, 0), Quaternion.Euler(90, 0, 0));+ typeof(T).GetMethod("Choose", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(layer,+ new object[] { default(UnityEngine.Rendering.ScriptableRenderContext), camera });+ Object.DestroyImmediate(camera.gameObject);+ Assert.AreEqual(1, acquired, "the Far model is consumer demand, not camera-focus demand");+ }+ finally { Object.DestroyImmediate(go); Object.DestroyImmediate(prefab); }+ Assert.AreEqual(acquired, released);+ }++ [Test]+ public void SpecialFarRepresentationIsDemandedWithoutCameraAdmission()+ {+ AssertUnfocusedDemand<SpecialBuildingModels, SpecialBuildingModels.Want>(+ new SpecialBuildingModels.Want("fort", SpecialBuildingModels.Tegart, DateTime.MinValue, 0, 0, "TEST"),+ "wants", CollectionDetail.Near);+ }++ [Test]+ public void CraftFarRepresentationIsDemandedWithoutCameraAdmission()+ {+ AssertUnfocusedDemand<SeaAirCollection, SeaAirCollection.Want>(+ new SeaAirCollection.Want("boat", SeaAirCollection.FishingBoat, "jaffa"),+ "wants", CollectionDetail.Far);+ }++ void AssertUnfocusedDemand<TLayer, TWant>(TWant want, string field, CollectionDetail expected) where TLayer : MonoBehaviour+ {+ int acquired = 0, released = 0;+ var go = new GameObject(typeof(TLayer).Name); var layer = go.AddComponent<TLayer>();+ try+ {+ typeof(TLayer).GetMethod("ConfigureResidency", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(layer,+ new object[] { ProductionResidency.Approved().Special,+ (Func<string, CollectionDetail, Action<GameObject?>, IDisposable>)((_, detail, __) =>+ { Assert.AreEqual(expected, detail); acquired++; return new Lease(() => released++); }) });+ typeof(TLayer).GetField(field, BindingFlags.Instance | BindingFlags.NonPublic)!+ .SetValue(layer, new List<TWant> { want });+ typeof(TLayer).GetMethod("RefreshResidency", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(layer, null);+ Assert.AreEqual(1, acquired);+ }+ finally { Object.DestroyImmediate(go); }+ Assert.AreEqual(acquired, released);+ }++ [Test]+ public void SharedRoadVehiclesOwnV031NearLeasesUntilLayerTeardown()+ {+ int acquired = 0, released = 0;+ RoadVehicles.Request = (_, detail, __) => { Assert.AreEqual(CollectionDetail.Near, detail); acquired++; };+ RoadVehicles.RequestOwner = () => new Lease(() => released++);+ var go = new GameObject("roads"); var roads = go.AddComponent<RoadVehicles>();+ roads.ShowAt(new DateTime(1948, 5, 15));+ Assert.AreEqual(2, acquired, "the two start-date road models are retained before any camera chooses Near visibility");+ Object.DestroyImmediate(go);+ Assert.AreEqual(acquired, released, "road layer teardown releases every acquired model lease");+ }++ /// <summary>The documented edit-mode default is inert: building the layer without a request seam must not touch the+ /// shared collection stream.</summary>+ [Test]+ public void EditModeRoadBuildWithNullRequestAcquiresNothing()+ {+ RoadVehicles.Request = null;+ int before = CollectionStream.SharedDiagnostics().Sum(row => row.Owners);+ MapScene? map = null;+ try+ {+ map = RouteTests.BuildMap();+ Assert.AreEqual(before, CollectionStream.SharedDiagnostics().Sum(row => row.Owners),+ "an editor map build does not acquire road-vehicle bundles");+ }+ finally { if (map != null) Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>A retiring model and a surviving model's town-set change can share one Show call; completion must redraw+ /// the survivor at its new town without leaving either departed town behind.</summary>+ [Test]+ public void TownRetirementPreservesThePendingSurvivorTownChange()+ {+ const BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic;+ var savedRequest = TownLandmarks.Request;+ var savedAcquire = TownLandmarks.Acquire;+ var defaultRequest = (Action<string, CollectionDetail, Action<GameObject?>>)typeof(TownLandmarks)+ .GetField("DefaultRequest", flags)!.GetValue(null)!;+ GameObject? prefab = null;+ MapScene? map = null;+ try+ {+ TownLandmarks.Request = defaultRequest;+ TownLandmarks.Acquire = (_, detail, answer) =>+ {+ Assert.AreEqual(CollectionDetail.Far, detail);+ answer(prefab);+ return new Lease(() => { });+ };+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ // Made after OpenScene(Single), which destroys every object of the scene it replaces.+ prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);+ map = Object.FindFirstObjectByType<MapScene>(); map.Build();+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);+ var all = TownLandmarks.Wants(map, DateTime.MinValue, Array.Empty<Placement>(), content)+ .Where(w => w.OnTown).ToList();+ var survivorTowns = all.GroupBy(w => w.Model).First(group => group.Count() >= 2).Take(2).ToArray();+ var retiredTown = all.First(w => w.Model != survivorTowns[0].Model);+ var root = new GameObject(TownLandmarks.Name); root.transform.SetParent(map.Terrain.transform, false);+ var towns = root.AddComponent<TownLandmarks>();+ typeof(TownLandmarks).GetField("map", flags)!.SetValue(towns, map);+ var show = typeof(TownLandmarks).GetMethod("Show", flags)!;++ show.Invoke(towns, new object[] { new List<TownLandmarks.Want> { retiredTown, survivorTowns[0] }, DateTime.MinValue });+ Assert.IsNotNull(towns.transform.Find(retiredTown.Key));+ Assert.IsNotNull(towns.transform.Find(survivorTowns[0].Key));++ show.Invoke(towns, new object[] { new List<TownLandmarks.Want> { survivorTowns[1] }, DateTime.MinValue });++ Assert.IsNull(towns.transform.Find(retiredTown.Key), "the retired model's town instance is gone");+ Assert.IsNull(towns.transform.Find(survivorTowns[0].Key), "the surviving model's departed town is gone");+ Assert.IsNotNull(towns.transform.Find(survivorTowns[1].Key), "the surviving model draws at its new town");+ }+ finally+ {+ TownLandmarks.Request = savedRequest;+ TownLandmarks.Acquire = savedAcquire;+ if (map != null) Object.DestroyImmediate(map.gameObject);+ if (prefab != null) Object.DestroyImmediate(prefab);+ }+ }++ [Test]+ public void WholeTownsAreRequestedAndDrawnMapWideThenOnlyTheDetailedTownHides()+ {+ var old = TownLandmarks.Request;+ GameObject? prefab = null;+ try+ {+ var requested = new List<string>();+ TownLandmarks.Request = (id, detail, answer) =>+ {+ Assert.AreEqual(CollectionDetail.Far, detail); requested.Add(id); answer(prefab);+ };+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ // Made after OpenScene(Single), which destroys every object of the scene it replaces.+ prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);+ var towns = TownLandmarks.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), content)!;+ var mapped = towns.Wanted.Where(w => w.OnTown).ToList();+ CollectionAssert.AreEquivalent(mapped.Select(w => w.Model).Distinct().ToList(), requested,+ "the 90 km start view requests every wanted whole-town Far model map-wide");+ CollectionAssert.AreEquivalent(mapped.Select(w => w.Key).ToList(), towns.Seats.Keys.ToList(),+ "every mapped town draws even when towns share one requested model");++ var buildings = map.GetComponentInChildren<TownModelLayer>(true);+ var focus = mapped.First(w => buildings.CountFor(w.Key) > 0);+ var camera = new GameObject("90 km then close camera").AddComponent<Camera>();+ camera.transform.SetPositionAndRotation(new Vector3(focus.At.x, 90000f, focus.At.y),+ Quaternion.LookRotation(Vector3.down, Vector3.forward));+ towns.Choose(default, camera);+ foreach (var want in mapped)+ Assert.IsFalse(towns.transform.Find(want.Key).GetComponentsInChildren<Renderer>(true).All(r => r.forceRenderingOff),+ want.Key + " draws at the 90 km start view");++ camera.transform.position = new Vector3(focus.At.x, 10000f, focus.At.y);+ towns.Choose(default, camera);+ Assert.IsTrue(buildings.ReadyForTown(focus.Key, camera), focus.Key + " has its detailed models ready up close");+ foreach (var want in mapped)+ {+ bool hidden = towns.transform.Find(want.Key).GetComponentsInChildren<Renderer>(true).All(r => r.forceRenderingOff);+ Assert.AreEqual(want.Key == focus.Key, hidden,+ want.Key + ": only the close camera's detailed town hides its whole-town model");+ }+ Object.DestroyImmediate(camera.gameObject);+ }+ finally { TownLandmarks.Request = old; if (prefab != null) Object.DestroyImmediate(prefab); }+ }++ [Test]+ public void DisabledTownKillSwitchRequestsNoWholeTownOrPlacementLandmarks()+ {+ var old = TownLandmarks.Request;+ try+ {+ int requested = 0; TownLandmarks.Request = (_, __, ___) => requested++;+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();+ typeof(ProductionResidency.TownPolicy).GetField("Enabled", BindingFlags.Instance | BindingFlags.NonPublic)!+ .SetValue(map.Residency.Towns, false);+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);+ TownLandmarks.ShowAt(map, new DateTime(1951, 1, 1),+ new[] { new Placement(MapActions.TransitCamp, 0, 0, new DateTime(1951, 1, 1)) }, content);+ Assert.AreEqual(0, requested, "Towns.Enabled=false is the map-wide Far demand kill switch");+ }+ finally { TownLandmarks.Request = old; }+ }+}diff --git a/unity/Assets/Tests/EditMode/FarMapWideResidencyTests.cs.meta b/unity/Assets/Tests/EditMode/FarMapWideResidencyTests.cs.metanew file mode 100644index 000000000..6cee7f431--- /dev/null+++ b/unity/Assets/Tests/EditMode/FarMapWideResidencyTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 3a4ef0826e584b31a81816f7c954392adiff --git a/unity/Assets/Tests/EditMode/OriginalResidencyPlayerTests.cs b/unity/Assets/Tests/EditMode/OriginalResidencyPlayerTests.csindex 2cf91efab..29f91c404 100644--- a/unity/Assets/Tests/EditMode/OriginalResidencyPlayerTests.cs+++ b/unity/Assets/Tests/EditMode/OriginalResidencyPlayerTests.cs@@ -135,7 +135,9 @@ public sealed class OriginalResidencyPlayerTestsChoose(towns, camera, focus.At, true);yield return Until(() => asks.Any(a => a.detail == CollectionDetail.Near), "near requested");Assert.IsTrue(asks.Any(a => a.detail == CollectionDetail.Near), "Map.Build player path must acquire Near originals");- Assert.IsFalse(asks.Any(a => a.id == focus.Model), "no duplicate whole-town acquisition while Near loads");+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns are requested map-wide; only near detail is camera-gated.+ Assert.AreEqual(1, asks.Count(a => a.id == focus.Model && a.detail == CollectionDetail.Far), "the one map-wide whole-town request");+ Assert.AreEqual(1, asks.Count(a => a.id == focus.Model), "no duplicate whole-town acquisition while Near loads");Assert.IsFalse((bool)Call(layer, typeof(TownModelLayer), "ReadyForTown", focus.Key, camera)!);yield return Until(() => { towns.Choose(default, camera); return (bool)Call(layer, typeof(TownModelLayer), "ReadyForTown", focus.Key, camera)!; }, "near ready: " + focus.Key);var near = asks.Where(a => a.detail == CollectionDetail.Near).Select(a => CollectionCatalog.BundleOf(a.id)!).ToHashSet();@@ -172,12 +174,21 @@ public sealed class OriginalResidencyPlayerTestsAssert.IsNotEmpty(nearIds, "failure proof requires actual Near requests");foreach (var _ in nearIds)LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("Collection: bundle .* has no .*"));- yield return Until(() => nearIds.All(id => source.CompletedLoads.Contains(CollectionCatalog.BundleOf(id)!)));+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns are requested map-wide; only near detail is camera-gated.+ // The map-wide whole-town loads now queue ahead of the Near load: keep the close camera rendering while waiting, as a+ // player's camera does every frame, or its admission expires (grace frames) and the Near request is withdrawn.+ yield return Until(() => { towns.Choose(default, camera); return nearIds.All(id => source.CompletedLoads.Contains(CollectionCatalog.BundleOf(id)!)); });Assert.IsFalse((bool)Call(layer, typeof(TownModelLayer), "ReadyForTown", focus.Key, camera)!);Assert.IsFalse((bool)Call(layer, typeof(TownModelLayer), "WantsWholeTown", focus.Key, camera)!);- Assert.IsFalse(asks.Any(a => a.id == focus.Model));+ // The failed Near acquires no replacement: the focus town's whole-town Far stays its one map-wide request.+ Assert.AreEqual(1, asks.Count(a => a.id == focus.Model), "exactly one whole-town request, the map-wide Far");+ Assert.IsTrue(asks.Where(a => a.id == focus.Model).All(a => a.detail == CollectionDetail.Far));+ yield return Until(() => { towns.Choose(default, camera); return towns.Seats.ContainsKey(focus.Key); }, "whole town drawn: " + focus.Key);+ towns.Choose(default, camera); // this camera's choice, read before any render callback restores it+ Assert.IsFalse(towns.transform.Find(focus.Key).GetComponentsInChildren<Renderer>(true).All(r => r.forceRenderingOff),+ "with no detailed buildings the whole town stays drawn for the close camera");var ids = (IDictionary<Renderer, string>)typeof(TownModelLayer).GetField("swapIds", Flags)!.GetValue(layer)!;- foreach (var pair in ids) if (pair.Value == focus.Key) Assert.IsFalse(pair.Key.forceRenderingOff);+ foreach (var pair in ids) if (pair.Value == focus.Key) Assert.IsTrue(pair.Key.forceRenderingOff, "the whole-town original replaces the kit houses");}[UnityTest]public IEnumerator HexPlayerTeardownWaitsForGeneratedObjectsAndTheirRendererReferences()diff --git a/unity/Assets/Tests/EditMode/RuralLifeTests.cs b/unity/Assets/Tests/EditMode/RuralLifeTests.csindex e3cb5c8ec..3535c03ad 100644--- a/unity/Assets/Tests/EditMode/RuralLifeTests.cs+++ b/unity/Assets/Tests/EditMode/RuralLifeTests.cs@@ -53,6 +53,13 @@ public class RuralLifeTestsvar pending = asked.ToList();asked.Clear();foreach (var (id, detail, done) in pending) done(found ? Prefab(id, detail) : null);+ // A successful Far answer creates the real scenes whose Near demand is then admitted.+ while (asked.Count > 0)+ {+ pending = asked.ToList();+ asked.Clear();+ foreach (var (id, detail, done) in pending) done(found ? Prefab(id, detail) : null);+ }}[Test]@@ -62,6 +69,9 @@ public class RuralLifeTestsvar layer = CollectionGeometryFixture.Rural(map)!;CollectionAssert.AreEquivalent(RuralLife.Models, layer.Wanted.Select(w => w.Model).Distinct());Assert.AreEqual(layer.Wanted.Count, layer.Wanted.Select(w => (w.Key, w.Model)).Distinct().Count(), "each anchor once per model");+ // Far makes a scene real; only those real scenes create the v0.3.1 Near demand.+ foreach (var request in asked.Where(a => a.detail == CollectionDetail.Far).ToArray())+ request.done(Prefab(request.id, request.detail));foreach (var id in RuralLife.Models){Assert.Greater(layer.Wanted.Count(w => w.Model == id), RuralLife.MaxAnchorsPerModel, id + " has spare anchors");@@ -88,6 +98,31 @@ public class RuralLifeTestsAssert.AreEqual(RuralLife.MaxAnchorsPerModel * RuralLife.FlockSize * 2, layer.Placed.Count(p => p.Model == RuralLife.Sheep), "the sheep stand in flocks");}+ /// <summary>A request is not a scene: no spot, capacity, tree hole or Near request exists until a detail is drawable,+ /// and a null Far answer remains visible in the layer's missing-model report.</summary>+ [Test]+ public void UnansweredOrFailedFarModelsReserveNoRuralSceneOrTreeHole()+ {+ var map = OpenMap();+ var vegetation = map.GetComponentInChildren<Statecraft.Game.Map.Kits.VegetationLayer>(true);+ int hiddenBefore = vegetation.Hidden;+ var layer = CollectionGeometryFixture.Rural(map)!;++ CollectionAssert.IsEmpty(layer.Scenes, "unanswered requests own no rural anchors");+ Assert.AreEqual(hiddenBefore, vegetation.Hidden, "unanswered requests cut no tree holes");+ Assert.IsTrue(asked.All(a => a.detail == CollectionDetail.Far), "Near demand comes only from placed scenes");++ var failed = asked.First();+ LogAssert.Expect(LogType.Warning, $"RURAL: {failed.id} far did not stream; that rural detail stays off the map.");+ failed.done(null);++ Assert.IsFalse(layer.Scenes.Any(w => w.Model == failed.id), "a failed Far model still owns no anchor");+ Assert.AreEqual(hiddenBefore, vegetation.Hidden, "a failed Far model cuts no tree hole");+ CollectionAssert.Contains(layer.Missing, failed.id, "a failed Far model is reported missing");+ Assert.IsFalse(asked.Any(a => a.id == failed.id && a.detail == CollectionDetail.Near),+ "a failed Far model creates no phantom Near demand");+ }+[Test]public void SeededSpotsAreDeterministicClearAndUpright(){diff --git a/unity/Assets/Tests/EditMode/TownLandmarksTests.cs b/unity/Assets/Tests/EditMode/TownLandmarksTests.csindex ab34da902..4e0573d93 100644--- a/unity/Assets/Tests/EditMode/TownLandmarksTests.cs+++ b/unity/Assets/Tests/EditMode/TownLandmarksTests.cs@@ -661,11 +661,13 @@ public class TownLandmarksTests// original: an original stands in (kit houses hidden); buildings: it is the building models (else the whole town).var steps = new (float d, bool original, bool buildings, string why)[]{- (125000f, false, false, "in: outside the 120 km view band, fallback"), (119000f, true, false, "in: inside the view band"),+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ // The whole-town original therefore stands in beyond the 120/160 km view band too.+ (125000f, true, false, "in: outside the 120 km view band, map-wide whole town"), (119000f, true, false, "in: inside the view band"),(60000f, true, false, "in: the gameplay view"), (44000f, true, false, "in: above the 40 km close threshold, whole town"),(39000f, true, true, "in: below 40 km, building models"), (CameraController.MinDistance, true, true, "in: the closest zoom"),(44000f, true, true, "out: below the 45 km close exit, still buildings"), (46000f, true, false, "out: above 45 km, whole town again"),- (150000f, true, false, "out: inside the 160 km view exit"), (165000f, false, false, "out: beyond 160 km, fallback restored"),+ (150000f, true, false, "out: inside the 160 km view exit"), (165000f, true, false, "out: beyond 160 km, map-wide whole town"),};foreach (var (d, original, buildings, why) in steps){@@ -676,7 +678,11 @@ public class TownLandmarksTestsif (f.acquired.Count > arrived) { f.Arrive(); arrived = f.acquired.Count; f.towns.Choose(default, f.camera); }string at = FormattableString.Invariant($"{f.focus.Key} at {d / 1000f} km ({why})");Assert.AreEqual(buildings, f.buildings.ReadyForTown(f.focus.Key, f.camera), "building models: " + at);- Assert.AreEqual(original && !buildings, f.buildings.WantsWholeTown(f.focus.Key, f.camera), "whole-town original: " + at);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ // The drawn whole-town instance (not the camera admission) is what stands in above the close band.+ var whole = f.towns.transform.Find(f.focus.Key);+ Assert.IsNotNull(whole, "whole-town instance: " + at);+ Assert.AreEqual(original && !buildings, !whole.GetComponentsInChildren<Renderer>(true).All(r => r.forceRenderingOff), "whole-town original: " + at);foreach (var r in kit) Assert.AreEqual(original, r.forceRenderingOff, "kit houses: " + at);Assert.AreEqual(!original, closeR!.forceRenderingOff, "close mesh: " + at);}@@ -689,12 +695,14 @@ public class TownLandmarksTests{using (var f = new ResidencyFixture(saved)){- CollectionAssert.IsEmpty(f.acquired, "no camera has admitted a town yet");- f.Choose(); CollectionAssert.AreEqual(new[] { f.focus.Model }, f.acquired);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ var mapWide = f.towns.Wanted.Select(w => w.Model).Distinct().ToList();+ CollectionAssert.AreEquivalent(mapWide, f.acquired, "every wanted whole-town model is acquired before any camera");+ f.Choose(); CollectionAssert.AreEquivalent(mapWide, f.acquired, "a camera adds no second whole-town request");Assert.IsFalse(f.buildings.Suppressed(f.focus.Key), "pending original cannot hide fallback");f.Arrive(); Assert.IsTrue(f.towns.Seats.ContainsKey(f.focus.Key));Assert.AreEqual(1, f.towns.Placed.Count(p => p.Key == f.focus.Key));- Assert.AreEqual(1, f.source.Opens);+ Assert.AreEqual(mapWide.Count, f.source.Opens, "one bundle open per map-wide model, none twice");f.Choose();var identity = (IDictionary<Renderer, string>)typeof(TownModelLayer).GetField("swapIds", ResidencyFlags)!.GetValue(f.buildings)!;foreach (var pair in identity) if (pair.Value == f.focus.Key) Assert.IsTrue(pair.Key.forceRenderingOff);@@ -705,12 +713,19 @@ public class TownLandmarksTests{using (var f = new ResidencyFixture(saved)){+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ // The whole-town lease is held map-wide; up close only the individual Near buildings may draw.+ var mapWide = f.towns.Wanted.Select(w => w.Model).Distinct().ToList();f.Choose(close: true);- CollectionAssert.IsEmpty(f.acquired, "individual Near buildings are the only admitted representation");+ CollectionAssert.AreEquivalent(mapWide, f.acquired, "a close camera adds no whole-town request");Assert.IsTrue((bool)ResidencyCall(f.buildings, typeof(TownModelLayer), "ReadyForTown", f.focus.Key, f.camera)!);f.Choose(); f.Arrive(); Assert.IsTrue(f.towns.Seats.ContainsKey(f.focus.Key));- f.Choose(close: true); Assert.IsFalse(f.towns.Seats.ContainsKey(f.focus.Key));- Assert.AreEqual(1, f.source.Unloads, "whole lease retires when near representation takes over");+ var whole = f.towns.transform.Find(f.focus.Key).GetComponentsInChildren<Renderer>(true);+ Assert.IsFalse(whole.All(r => r.forceRenderingOff), "the overview draws the whole town");+ f.Choose(close: true);+ Assert.IsTrue((bool)ResidencyCall(f.buildings, typeof(TownModelLayer), "ReadyForTown", f.focus.Key, f.camera)!);+ Assert.IsTrue(whole.All(r => r != null && r.forceRenderingOff), "individual Near buildings are the only drawn representation");+ Assert.AreEqual(0, f.source.Unloads, "the map-wide whole-town lease stays while its town shows Near buildings");}}[Test]@@ -719,11 +734,17 @@ public class TownLandmarksTestsusing (var f = new ResidencyFixture(saved)){f.Choose(); f.Arrive();+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ // Leaving focus no longer unloads; layer teardown (LayerDisable...) keeps the clear-before-unload order.+ var instance = f.towns.transform.Find(f.focus.Key);f.source.BeforeUnload = f.AssertConsumerCleared;f.Choose(outside: true);- Assert.AreEqual(1, f.source.Unloads); f.AssertConsumerCleared();+ Assert.AreEqual(0, f.source.Unloads, "leaving focus keeps the map-wide whole town");+ Assert.AreSame(instance, f.towns.transform.Find(f.focus.Key), "the drawn whole town is not rebuilt");+ Assert.IsTrue(f.towns.Seats.ContainsKey(f.focus.Key));var identity = (IDictionary<Renderer, string>)typeof(TownModelLayer).GetField("swapIds", ResidencyFlags)!.GetValue(f.buildings)!;- foreach (var pair in identity) Assert.IsFalse(pair.Key.forceRenderingOff, "outside focus is code-built fallback");+ foreach (var pair in identity) if (pair.Value == f.focus.Key)+ Assert.IsTrue(pair.Key.forceRenderingOff, "outside focus the whole-town original still replaces the kit houses");}}[Test]@@ -731,11 +752,16 @@ public class TownLandmarksTests{using (var f = new ResidencyFixture(saved)){- f.Choose(); var late = f.callbacks.Single(); f.Choose(outside: true);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ // A camera leaving no longer evicts a town; disabling the layer is the remaining eviction.+ var late = f.callbacks[f.acquired.IndexOf(f.focus.Model)];+ f.towns.enabled = false; f.towns.enabled = true; // evict, then the re-enabled layer asks again+ Assert.Greater(f.acquired.LastIndexOf(f.focus.Model), f.acquired.IndexOf(f.focus.Model), "the re-enabled layer asks again");late(null); // stale reply must not create a warning, asset reference or instanceAssert.IsFalse(f.towns.Seats.ContainsKey(f.focus.Key));- f.Choose(); LogAssert.Expect(LogType.Warning, new Regex("LANDMARKS: the town model .* did not stream"));- f.callbacks.Last()(null);+ Assert.IsFalse(f.buildings.Suppressed(f.focus.Key), "a stale reply cannot hide the fallback");+ LogAssert.Expect(LogType.Warning, new Regex("LANDMARKS: the town model .* did not stream"));+ f.callbacks[f.acquired.LastIndexOf(f.focus.Model)](null);Assert.IsFalse(f.buildings.Suppressed(f.focus.Key)); Assert.IsFalse(f.towns.Seats.ContainsKey(f.focus.Key));}}@@ -746,13 +772,18 @@ public class TownLandmarksTests{f.Choose(); f.Arrive(); f.source.BeforeUnload = f.AssertConsumerCleared;f.towns.enabled = false;- Assert.AreEqual(1, f.source.Unloads); f.AssertConsumerCleared();+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ Assert.AreEqual(f.towns.Wanted.Select(w => w.Model).Distinct().Count(), f.source.Unloads,+ "disable retires every map-wide whole-town lease, each after its consumers"); f.AssertConsumerCleared();}}+ /// <summary>A merged locality tile is one renderer for many villages, never one named town. Owner ruling, 31 Oct 2026,+ /// "Load all in view (Recommended)": it swaps as one, once every village in it with building models has them ready,+ /// and keeps its fallback otherwise.</summary>[Test]public void ProductionKitWiringNeverTreatsAMixedRendererAsOneNamedTown(){- using (var f = new ResidencyFixture(saved))+ using (var f = new ResidencyFixture(saved, approved: true)){var identity = (IDictionary<Renderer, string>)typeof(TownModelLayer).GetField("swapIds", ResidencyFlags)!.GetValue(f.buildings)!;var settlementIds = f.map.Settlements.Select(s => s.Id).ToHashSet(StringComparer.Ordinal);@@ -761,8 +792,47 @@ public class TownLandmarksTestsvar swaps = (IEnumerable<(Renderer kit, Renderer? close)>)typeof(TownModelLayer).GetField("swaps", ResidencyFlags)!.GetValue(f.buildings)!;var mixed = swaps.Where(pair => !identity.ContainsKey(pair.kit)).ToList();Assert.IsNotEmpty(mixed, "Map.Build must include grouped localities/camps for this fixture");+ var villages = (IDictionary<Renderer, string[]>)typeof(TownModelLayer).GetField("tileIds", ResidencyFlags)!.GetValue(f.buildings)!;+ f.camera.nearClipPlane = 50f; f.camera.farClipPlane = 1_000_000f; // CameraRig.Init's planes: the view reaches the groundf.Choose(close: true);- foreach (var pair in mixed) Assert.IsFalse(pair.kit.forceRenderingOff, "an atomic mixed tile keeps its fallback");+ int swapped = 0;+ foreach (var pair in mixed)+ {+ var ids = villages.TryGetValue(pair.kit, out var v) ? v : Array.Empty<string>();+ foreach (var id in ids) Assert.IsFalse(settlementIds.Contains(id), pair.kit.name + ": " + id + " is a locality, not a game town");+ bool ready = ids.Length > 0 && ids.All(id => f.buildings.ReadyForTown(id, f.camera));+ Assert.AreEqual(ready, pair.kit.forceRenderingOff, pair.kit.name + ": the tile swaps only as one, once every village in it is ready");+ if (ready) swapped++;+ }+ Assert.Greater(swapped, 0, "a mixed tile in view swaps once its villages are ready");+ }+ }++ /// <summary>Nazareth's whole-town model (stone-village-v1, the town's Far model) stands in for the town only above the+ /// close band. At 12 km with Nazareth in view but not under the screen centre (the minimap jump lands beside it), the+ /// town's building models are admitted and its whole-town model hides, as in v0.3.1.</summary>+ [Test]+ public void NazarethWholeTownModelHidesAtTwelveKmWhenInViewBesideTheFocus()+ {+ using (var f = new ResidencyFixture(saved, approved: true))+ {+ f.Choose(); f.Arrive();+ var nazareth = f.map.KitFootprints.Single(p => p.id == "nazareth");+ Assert.Greater(f.buildings.CountFor("nazareth"), 0, "Nazareth has building models");+ var whole = f.towns.transform.Find("nazareth");+ Assert.IsNotNull(whole, "Nazareth's whole-town model stands map-wide (ruling 29)");+ var lookAt = new Vector3(nazareth.centre.x, 0f, nazareth.centre.y - (nazareth.radius + 1000f));+ f.camera.transform.rotation = Quaternion.Euler(CameraRig.Pitch, 0f, 0f);+ f.camera.transform.position = lookAt - f.camera.transform.forward * 11_775f;+ f.camera.fieldOfView = CameraRig.Fov; f.camera.aspect = 16f / 9f;+ f.camera.nearClipPlane = 50f; f.camera.farClipPlane = 1_000_000f; // CameraRig.Init's planes+ Assert.IsTrue(CollectionResidencyView.TryGroundFocus(f.camera, out var focus));+ Assert.Greater(Vector2.Distance(new Vector2(focus.x, focus.z), nazareth.centre), nazareth.radius,+ "precondition: the screen centre is outside Nazareth's footprint");+ f.towns.Choose(default, f.camera);+ Assert.IsTrue(f.buildings.ReadyForTown("nazareth", f.camera), "Nazareth in view at 12 km: building models");+ Assert.IsTrue(whole!.GetComponentsInChildren<Renderer>(true).All(r => r.forceRenderingOff),+ "Nazareth's whole-town model hides while its building models stand");}}@@ -775,22 +845,42 @@ public class TownLandmarksTestsf.Choose(); f.Arrive(); f.source.BeforeUnload = f.AssertConsumerCleared;ResidencyCall(f.buildings, typeof(TownModelLayer), "AdvanceCameraFrame", Time.frameCount + 3);ResidencyCall(f.towns, typeof(TownLandmarks), "RefreshWanted");- Assert.AreEqual(1, f.source.Unloads); f.AssertConsumerCleared();+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ Assert.AreEqual(0, f.source.Unloads, "a quiet camera expiring keeps the map-wide whole town");+ Assert.IsTrue(f.towns.Seats.ContainsKey(f.focus.Key));+ Assert.IsNotNull(f.towns.transform.Find(f.focus.Key));}}+ /// <summary>Was NoAdmissionLayerCannotFallBackToUnboundedWholeTownRequests: under ruling 29 no camera admission bounds a+ /// whole town any more; the only bound is the map's Towns.Enabled kill switch.</summary>[Test]- public void NoAdmissionLayerCannotFallBackToUnboundedWholeTownRequests()+ public void WholeTownsAndPlacementsAreBoundOnlyByTheTownsKillSwitch(){+ var whole = new TownLandmarks.Want("town", TownLandmarks.TelAviv, Vector2.zero, 100, true);+ var placement = new TownLandmarks.Want("placement", TownLandmarks.Kibbutz, Vector2.zero, 100, false);var root = new GameObject("no town policy");try{var towns = root.AddComponent<TownLandmarks>();- var whole = new TownLandmarks.Want("town", TownLandmarks.TelAviv, Vector2.zero, 100, true);- var placement = new TownLandmarks.Want("placement", TownLandmarks.Kibbutz, Vector2.zero, 100, false);- Assert.IsFalse((bool)ResidencyCall(towns, typeof(TownLandmarks), "Allowed", whole)!);+ // Owner ruling 29 (30 Oct 2026): "Far models map-wide (Recommended)": whole towns stay map-wide; only near detail is camera-gated.+ // Without a map there is no Towns.Enabled kill switch to consult: whole towns are allowed as placements are.+ Assert.IsTrue((bool)ResidencyCall(towns, typeof(TownLandmarks), "Allowed", whole)!);Assert.IsTrue((bool)ResidencyCall(towns, typeof(TownLandmarks), "Allowed", placement)!);}finally { Object.DestroyImmediate(root); }+ using (var f = new ResidencyFixture(saved))+ {+ Assert.IsTrue((bool)ResidencyCall(f.towns, typeof(TownLandmarks), "Allowed", whole)!, "a map with towns enabled allows a whole town");+ Assert.IsTrue((bool)ResidencyCall(f.towns, typeof(TownLandmarks), "Allowed", placement)!);+ var enabled = typeof(ProductionResidency.TownPolicy).GetField("Enabled", ResidencyFlags)!;+ enabled.SetValue(f.map.Residency.Towns, false);+ try+ {+ Assert.IsFalse((bool)ResidencyCall(f.towns, typeof(TownLandmarks), "Allowed", whole)!, "the kill switch bounds whole towns");+ Assert.IsFalse((bool)ResidencyCall(f.towns, typeof(TownLandmarks), "Allowed", placement)!, "and placement landmarks");+ }+ finally { enabled.SetValue(f.map.Residency.Towns, true); }+ }}}diff --git a/unity/Assets/Tests/EditMode/TownModelResidencyTests.cs b/unity/Assets/Tests/EditMode/TownModelResidencyTests.csindex a62b55aef..377e8cd81 100644--- a/unity/Assets/Tests/EditMode/TownModelResidencyTests.cs+++ b/unity/Assets/Tests/EditMode/TownModelResidencyTests.cs@@ -1,14 +1,21 @@#nullable enableusing System;using System.Collections.Generic;+using System.Linq;using System.Reflection;using NUnit.Framework;+using UnityEditor.SceneManagement;using UnityEngine;+using UnityEngine.TestTools;+using Statecraft.Game.Map;using Statecraft.Game.Map.Kits;using Statecraft.Game.Map.Collection;+using Statecraft.Game.UI;/// <summary>C89/C91: original artwork near the camera focus, with fallback elsewhere. Reflection keeps the test-only/// revision compilable on the pre-change tree so the requested deferred red run can fail on behavior/API assertions.</summary>+/// <remarks>That compatibility claim covers the original reflection-based residency tests only. The later footprint+/// admission tests intentionally call their new internal production APIs directly and are compile-time reds pre-change.</remarks>public class TownModelResidencyTests{const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;@@ -22,6 +29,324 @@ public class TownModelResidencyTests(id, new Bounds(new Vector3(x, 0, z), new Vector3(100, 100, 100)));static string[] Focus(IReadOnlyList<(string id, Bounds bounds)> places, Vector3 point, string? previous = null, Func<IReadOnlyList<string>, string, bool>? allowance = null) =>(string[])Call(null, "FocusedTowns", places, point, previous, allowance, 1000f, 2000f, 1000f, 2)!;+ static Dictionary<string, (Vector2 centre, float radius, string id)> FootprintLookup(+ IEnumerable<(Vector2 centre, float radius, string id)> footprints) =>+ footprints.ToDictionary(f => f.id, f => f, StringComparer.Ordinal);++ static Bounds InstanceBounds(TownModelLayer layer, string id)+ {+ var corners = new List<Vector3>();+ foreach (var instance in layer.InstancesOf(id)) instance.Corners(corners);+ Assert.IsNotEmpty(corners, id + ": detailed-model instances");+ var bounds = new Bounds(corners[0], Vector3.zero);+ foreach (var corner in corners) bounds.Encapsulate(corner);+ return bounds;+ }++ static Bounds PlaceBounds(TownModelLayer layer, string id)+ {+ var places = (IReadOnlyList<(string id, Bounds bounds)>)typeof(TownModelLayer).GetField("places", Flags)!.GetValue(layer)!;+ return places.Single(place => place.id == id).bounds;+ }++ static Camera CopyCamera(Camera source, string name)+ {+ var camera = new GameObject(name).AddComponent<Camera>();+ camera.CopyFrom(source);+ camera.transform.SetPositionAndRotation(source.transform.position, source.transform.rotation);+ return camera;+ }++ static Camera GroundCamera(Vector2 focus, float distanceM, string name)+ {+ var camera = new GameObject(name).AddComponent<Camera>();+ camera.transform.position = new Vector3(focus.x, distanceM, focus.y);+ camera.transform.rotation = Quaternion.LookRotation(Vector3.down, Vector3.forward);+ return camera;+ }++ /// <summary>R2: the production camera centres a town on its sourced label point, also the kit-footprint centre. Some+ /// detailed instances do not cover that point; admission must therefore use the authoritative footprint union rather+ /// than treating the detailed-instance rectangle as the town itself.</summary>+ [Test]+ public void EveryDetailedTownIsAdmittedAtItsLabelAndKitFootprintCentre()+ {+ const float ReportedCameraDistanceM = 11_800f;+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ try+ {+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>(); map.Build();+ var layer = map.GetComponentInChildren<TownModelLayer>(true);+ layer.EdgeAllowance = null;+ var rig = UnityEngine.Object.FindFirstObjectByType<CameraRig>();+ var rigCamera = rig.GetComponent<Camera>();+ var detailed = map.Settlements.Where(s => layer.CountFor(s.Id) > 0).OrderBy(s => s.Id, StringComparer.Ordinal).ToList();+ CollectionAssert.IsSubsetOf(new[] { "jaffa", "jerusalem", "nazareth" }, detailed.Select(s => s.Id).ToArray(),+ "the three reported towns must remain in the mapped detailed-model census");++ var outsideInstances = new List<string>();+ var notAdmitted = new List<string>();+ var notReady = new List<string>();+ foreach (var town in detailed)+ {+ var footprint = map.KitFootprints.Single(f => f.id == town.Id);+ var label = MapLabelsPresenter.MarkerTop(map, town);+ Assert.AreEqual(footprint.centre.x, label.x, 0.01f, town.Id + ": label and kit centre x");+ Assert.AreEqual(footprint.centre.y, label.z, 0.01f, town.Id + ": label and kit centre z");++ rig.LookAt = new Vector3(label.x, 0f, label.z); rig.Distance = ReportedCameraDistanceM;+ rig.Yaw = 0f; rig.TopInset = 0f; rig.Apply();+ var camera = CopyCamera(rigCamera, town.Id + " fresh residency camera");+ try+ {+ Assert.IsTrue(CollectionResidencyView.TryGroundFocus(camera, out var focus), town.Id + ": production ground focus");+ var instances = InstanceBounds(layer, town.Id);+ var instancePoint = focus; instancePoint.y = instances.center.y;+ float instanceDistance = Mathf.Sqrt(instances.SqrDistance(instancePoint));+ if (instanceDistance > 0f) outsideInstances.Add(town.Id);+ float kitDistance = Mathf.Max(0f, Vector2.Distance(new Vector2(focus.x, focus.z), footprint.centre) - footprint.radius);+ TestContext.WriteLine($"R2 {town.Id}: focus={focus}; instance_bounds={instances}; " ++ $"instance_distance={instanceDistance:0.###}m; " ++ $"kit_centre={footprint.centre}; kit_radius={footprint.radius:0.###}m; kit_distance={kitDistance:0.###}m");++ layer.PrepareCamera(camera);+ if (!layer.WantsTown(town.Id, camera)) notAdmitted.Add(town.Id);+ if (!layer.ReadyForTown(town.Id, camera)) notReady.Add(town.Id);+ }+ finally { UnityEngine.Object.DestroyImmediate(camera.gameObject); }+ }+ // QA reported Jaffa, Jerusalem and Nazareth; the measured label foci outside their instance rectangles are Acre,+ // Jaffa and Tel Aviv (Jerusalem and Nazareth lie inside theirs, instance_distance=0). The three reported towns are+ // still checked below with every other detailed town.+ CollectionAssert.IsSubsetOf(new[] { "acre", "jaffa", "tel_aviv" }, outsideInstances,+ "the regression evidence must keep covering the measured focus points outside their instance rectangles");+ CollectionAssert.IsEmpty(notAdmitted,+ "a camera focused on each authoritative town footprint must admit that town's detailed models");+ CollectionAssert.IsEmpty(notReady,+ "every admitted production town must have every required detailed-model kind");+ }+ finally+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ VisualToggles.Clear();+ }+ }++ [Test]+ public void PanningFromEveryNestedDetailedTownToItsNeighboursLabelAdmitsTheNeighbour()+ {+ const float ReportedCameraDistanceM = 11_800f;+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ try+ {+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>(); map.Build();+ var layer = map.GetComponentInChildren<TownModelLayer>(true);+ layer.EdgeAllowance = null;+ // Pan targets are the game's towns (map.Settlements, from content): the focus partition is theirs. 1948 localities+ // also have model instances (CountFor > 0) but stand in merged locality tiles, which load with every place in view+ // and swap as one tile (owner ruling, 31 Oct 2026, "Load all in view"; see+ // TownLandmarksTests.ProductionKitWiringNeverTreatsAMixedRendererAsOneNamedTown), so they are not pan targets.+ var gameTowns = map.Settlements.Select(s => s.Id).ToHashSet(StringComparer.Ordinal);+ var detailed = map.KitFootprints.Where(f => layer.CountFor(f.id) > 0 && gameTowns.Contains(f.id))+ .OrderBy(f => f.id, StringComparer.Ordinal).ToList();+ var nestedPairs = new List<((Vector2 centre, float radius, string id) from,+ (Vector2 centre, float radius, string id) to)>();+ for (int i = 0; i < detailed.Count; i++) for (int j = i + 1; j < detailed.Count; j++)+ {+ var first = detailed[i]; var second = detailed[j];+ if (Vector2.Distance(first.centre, second.centre) >= Mathf.Max(first.radius, second.radius)) continue;+ if (second.radius > first.radius) (first, second) = (second, first);+ nestedPairs.Add((first, second));+ }+ Assert.IsNotEmpty(nestedPairs, "the real-map census must retain a nested detailed-town pair for this regression");++ foreach (var pair in nestedPairs)+ {+ var camera = GroundCamera(pair.from.centre, ReportedCameraDistanceM,+ pair.from.id + " to " + pair.to.id + " sequential pan camera");+ try+ {+ layer.PrepareCamera(camera);+ Assert.IsTrue(layer.WantsTown(pair.from.id, camera), pair.from.id + ": admitted at its own label before the pan");+ camera.transform.position = new Vector3(pair.to.centre.x, ReportedCameraDistanceM, pair.to.centre.y);+ layer.PrepareCamera(camera);+ Assert.IsTrue(layer.WantsTown(pair.to.id, camera),+ pair.from.id + " -> " + pair.to.id + ": the normalized-distance owner is admitted at its label");+ Assert.IsFalse(layer.WantsTown(pair.from.id, camera),+ pair.from.id + " -> " + pair.to.id + ": the previous town cannot retain on its whole disc");+ }+ finally { UnityEngine.Object.DestroyImmediate(camera.gameObject); }+ }+ }+ finally+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ VisualToggles.Clear();+ }+ }++ [Test]+ public void FocusOutsideEveryFootprintAndInstanceBoundsAdmitsNothing()+ {+ const float FootprintRadiusM = 500f;+ const float TownSeparationM = 4000f;+ const float CircleAabbCornerShare = 0.8f;+ const float OutsideFocusXM = FootprintRadiusM * CircleAabbCornerShare;+ const float OutsideFocusZM = FootprintRadiusM * CircleAabbCornerShare;+ var places = new[] { Place("jaffa", 0f), Place("tel_aviv", TownSeparationM) };+ var footprints = new[] {+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "jaffa"),+ (centre: new Vector2(TownSeparationM, 0f), radius: FootprintRadiusM, id: "tel_aviv") };+ var selected = TownModelLayer.FocusedTownsWithFootprints(places, FootprintLookup(footprints), footprints,+ new Vector3(OutsideFocusXM, 0f, OutsideFocusZM), null, null, 0f, 0f, 0f, 0);+ CollectionAssert.IsEmpty(selected);+ }++ [Test]+ public void InstanceBoundsStillAdmitOutsideTheKitFootprint()+ {+ const float InstanceCentreXM = 2000f;+ const float FootprintRadiusM = 500f;+ var places = new[] { Place("town", InstanceCentreXM) };+ var footprints = new[] { (centre: Vector2.zero, radius: FootprintRadiusM, id: "town") };+ var selected = TownModelLayer.FocusedTownsWithFootprints(places, FootprintLookup(footprints), footprints,+ new Vector3(InstanceCentreXM, 0f, 0f), null, null, 0f, 0f, 0f, 0);+ CollectionAssert.AreEqual(new[] { "town" }, selected);+ }++ [Test]+ public void NonDetailedFootprintOwnerExcludesADetailedNeighbour()+ {+ const float FootprintRadiusM = 1000f;+ const float DetailedCentreXM = 0f;+ const float NonDetailedCentreXM = 500f;+ const float FocusXM = 400f;+ var places = new[] { Place("detailed", DetailedCentreXM) };+ var footprints = new[] {+ (centre: new Vector2(DetailedCentreXM, 0f), radius: FootprintRadiusM, id: "detailed"),+ (centre: new Vector2(NonDetailedCentreXM, 0f), radius: FootprintRadiusM, id: "non_detailed") };+ var selected = TownModelLayer.FocusedTownsWithFootprints(places,+ new Dictionary<string, (Vector2, float, string)> { ["detailed"] = footprints[0] }, footprints,+ new Vector3(FocusXM, 0f, 0f), null, null, 0f, 0f, 0f, 0);+ CollectionAssert.IsEmpty(selected,+ "the detailed town cannot claim a point which the full kit partition assigns to a non-detailed settlement");+ }++ [Test]+ public void A1948LocalityDiscDoesNotTakeGroundFromAGameSettlement()+ {+ const float FootprintRadiusM = 1000f;+ const float LocalityCentreXM = 500f;+ const float FocusXM = 400f;+ using var fixture = new Fixture();+ var footprints = new[] {+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "a"),+ (centre: new Vector2(LocalityCentreXM, 0f), radius: FootprintRadiusM, id: "1948_locality") };+ fixture.layer.ConfigureTownFootprints(footprints, new[] { "1948_locality" });+ var camera = fixture.Camera(FocusXM); fixture.Prepare(camera);+ Assert.IsTrue(fixture.layer.WantsTown("a", camera),+ "camera ownership must ignore the same locality disc that game-town generation ignores");+ }++ [Test]+ public void AnIgnored1948LocalityDiscDoesNotSuppressInstanceBoundsFallback()+ {+ const float FootprintRadiusM = 500f;+ using var fixture = new Fixture();+ var footprints = new[] {+ (centre: new Vector2(-2000f, 0f), radius: FootprintRadiusM, id: "a"),+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "1948_locality") };+ fixture.layer.ConfigureTownFootprints(footprints, new[] { "1948_locality" });+ var camera = fixture.Camera(); fixture.Prepare(camera);+ Assert.IsTrue(fixture.layer.WantsTown("a", camera),+ "an ignored locality is not a game-settlement partition disc, so instance bounds remain the fallback");+ }++ [Test]+ public void PreviousTownInsideItsInstanceBoundsBeatsAnotherTownsFootprint()+ {+ const float FootprintRadiusM = 500f;+ const float PreviousFootprintXM = -1000f;+ var places = new[] { Place("p", 0f), Place("q", 1000f) };+ var footprints = new[] {+ (centre: new Vector2(PreviousFootprintXM, 0f), radius: FootprintRadiusM, id: "p"),+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "q") };+ var selected = TownModelLayer.FocusedTownsWithFootprints(places, FootprintLookup(footprints), footprints,+ Vector3.zero, "p", null, 0f, 0f, 0f, 0);+ CollectionAssert.AreEqual(new[] { "p" }, selected);+ }++ [Test]+ public void OneCameraTraversesTheJaffaTelAvivSeamInBothDirectionsDeterministically()+ {+ const float ReportedCameraDistanceM = 11_800f;+ const float SeamSampleShareOfCentreDistance = 0.02f;+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ try+ {+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>(); map.Build();+ var layer = map.GetComponentInChildren<TownModelLayer>(true);+ layer.EdgeAllowance = null;+ Assert.Greater(layer.CountFor("jaffa"), 0, "Jaffa remains a detailed town");+ Assert.Greater(layer.CountFor("tel_aviv"), 0, "Tel Aviv remains a detailed town");+ var footprints = map.KitFootprints;+ var ignoredLocalities = new HashSet<string>(map.Localities.Select(place => place.Settlement.Id), StringComparer.Ordinal);+ float focusExitM = ProductionResidency.Approved().Towns.Exit;+ var jaffa = footprints.Single(f => f.id == "jaffa");+ var telAviv = footprints.Single(f => f.id == "tel_aviv");+ var between = telAviv.centre - jaffa.centre;+ var seam = jaffa.centre + between * (jaffa.radius / (jaffa.radius + telAviv.radius));+ var offset = between * SeamSampleShareOfCentreDistance;+ var jaffaSide = seam - offset;+ var telAvivSide = seam + offset;+ float BoundsDistance(Bounds bounds, Vector2 point)+ {+ var point3 = new Vector3(point.x, bounds.center.y, point.y);+ return Mathf.Sqrt(bounds.SqrDistance(point3));+ }+ bool Owns((Vector2 centre, float radius, string id) footprint, Vector2 point) =>+ SettlementKits.NormalizedFootprintDistance(point, footprint.centre, footprint.radius)+ <= SettlementKits.FootprintBoundary+ && SettlementKits.OwnsFootprint(point, footprint.id, footprint.centre, footprint.radius, footprints,+ ignored: ignoredLocalities);+ void AssertOwnershipMechanism((Vector2 centre, float radius, string id) owner,+ (Vector2 centre, float radius, string id) previous, Bounds previousBounds, Vector2 point)+ {+ Assert.IsTrue(Owns(owner, point), owner.id + ": normalized-distance ownership admits this seam sample");+ Assert.IsFalse(Owns(previous, point), previous.id + ": normalized-distance ownership does not retain this sample");+ Assert.LessOrEqual(SettlementKits.NormalizedFootprintDistance(point, previous.centre, previous.radius),+ SettlementKits.FootprintBoundary, previous.id + ": sample remains inside the previous whole disc");+ Assert.Greater(BoundsDistance(previousBounds, point), focusExitM,+ previous.id + ": previous instance-bounds exit band does not retain this sample");+ }+ var jaffaBounds = PlaceBounds(layer, "jaffa");+ var telAvivBounds = PlaceBounds(layer, "tel_aviv");+ AssertOwnershipMechanism(jaffa, telAviv, telAvivBounds, jaffaSide);+ AssertOwnershipMechanism(telAviv, jaffa, jaffaBounds, telAvivSide);++ var camera = GroundCamera(jaffaSide, ReportedCameraDistanceM, "Jaffa Tel Aviv seam camera");+ void Move(Vector2 point)+ {+ camera.transform.position = new Vector3(point.x, ReportedCameraDistanceM, point.y);+ layer.PrepareCamera(camera);+ }+ try+ {+ Move(jaffaSide);+ Assert.IsTrue(layer.WantsTown("jaffa", camera)); Assert.IsFalse(layer.WantsTown("tel_aviv", camera));+ Move(telAvivSide);+ Assert.IsFalse(layer.WantsTown("jaffa", camera)); Assert.IsTrue(layer.WantsTown("tel_aviv", camera));+ Move(jaffaSide);+ Assert.IsFalse(layer.WantsTown("tel_aviv", camera)); Assert.IsTrue(layer.WantsTown("jaffa", camera));+ }+ finally { UnityEngine.Object.DestroyImmediate(camera.gameObject); }+ }+ finally+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ VisualToggles.Clear();+ }+ }[TestCase("FocusEnterM", 0f)][TestCase("FocusExitM", 0f)]@@ -48,6 +373,14 @@ public class TownModelResidencyTestsvar places = new[] { Place("far", 6000), Place("edge-c", 800), Place("focus", 0), Place("edge-b", 500), Place("edge-a", 300) };CollectionAssert.AreEqual(new[] { "focus", "edge-a", "edge-b" }, Focus(places, Vector3.zero, allowance: (_, __) => true));}+ /// <summary>Regression guard: a malformed negative edge allowance is clamped to the primary town only.</summary>+ [Test]+ public void NegativeMaximumEdgesSafelyKeepsOnlyThePrimary()+ {+ var places = new[] { Place("focus", 0), Place("edge", 300) };+ CollectionAssert.AreEqual(new[] { "focus" }, TownModelLayer.FocusedTowns(places, Vector3.zero, null,+ (_, __) => true, 1000f, 2000f, 1000f, -1));+ }[Test]public void EqualDistancesUseOrdinalTownIdRegardlessOfInputOrder(){@@ -172,6 +505,7 @@ public class TownModelResidencyTeststypeof(TownModelLayer).GetField("cameraGraceFrames", Flags)!.SetValue(layer, 2);}Call(layer, "InitStreaming", items, new List<(Renderer kit, Renderer? close)> { (a, null), (b, null) });+ layer.EdgeAllowance = null;}public GameObject Original => prefab;public Camera Camera(float x = 0, bool far = false)@@ -192,6 +526,113 @@ public class TownModelResidencyTests}}+ [Test]+ public void ConfigureWholeTownsBeforeOrAfterFootprintsProducesTheSameAdmissionOutcomes()+ {+ const float FootprintRadiusM = 500f;+ const float WholeTownXM = 12_000f;+ const float FocusOffsetM = 200f;+ const float FocusXM = WholeTownXM + FocusOffsetM;+ var footprints = new[] {+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "a"),+ (centre: new Vector2(WholeTownXM, 0f), radius: FootprintRadiusM, id: "whole") };+ var whole = new[] { (id: "whole", bounds: new Bounds(new Vector3(WholeTownXM, 0f, 0f), Vector3.one)) };+ using var footprintsFirst = new Fixture();+ using var wholeTownsFirst = new Fixture();++ footprintsFirst.layer.ConfigureTownFootprints(footprints);+ footprintsFirst.layer.ConfigureWholeTowns(whole);++ wholeTownsFirst.layer.ConfigureWholeTowns(whole);+ wholeTownsFirst.layer.ConfigureTownFootprints(footprints);++ var firstCamera = footprintsFirst.Camera(FocusXM);+ var secondCamera = wholeTownsFirst.Camera(FocusXM);+ footprintsFirst.Prepare(firstCamera); wholeTownsFirst.Prepare(secondCamera);+ Assert.IsTrue(footprintsFirst.layer.WantsTown("whole", firstCamera));+ Assert.IsTrue(wholeTownsFirst.layer.WantsTown("whole", secondCamera));+ Assert.IsFalse(footprintsFirst.layer.WantsTown("a", firstCamera));+ Assert.IsFalse(wholeTownsFirst.layer.WantsTown("a", secondCamera));+ }++ [Test]+ public void ConfigureTownFootprintsLogsAndDropsDuplicateDetailedTownIds()+ {+ const float FootprintRadiusM = 500f;+ using var fixture = new Fixture();+ var duplicate = new[] {+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "a"),+ (centre: Vector2.right, radius: FootprintRadiusM, id: "a") };+ LogAssert.Expect(LogType.Error,+ "Detailed town footprint id 'a' occurs more than once; dropping its footprint and using instance bounds.");+ Assert.DoesNotThrow(() => fixture.layer.ConfigureTownFootprints(duplicate));+ Assert.DoesNotThrow(() => fixture.layer.ConfigureWholeTowns(Array.Empty<(string id, Bounds bounds)>()));+ Assert.DoesNotThrow(() => fixture.layer.ConfigureWholeTowns(Array.Empty<(string id, Bounds bounds)>()));+ LogAssert.NoUnexpectedReceived();+ var camera = fixture.Camera(); fixture.Prepare(camera);+ Assert.IsTrue(fixture.layer.WantsTown("a", camera), "the dropped footprint falls back to the detailed instance bounds");+ }++ [Test]+ public void ConfigureWholeTownsPreservesAPrimaryThatRemainsConfigured()+ {+ const float FootprintRadiusM = 1000f;+ const float OtherTownXM = 800f;+ const float OtherOwnedFocusXM = 600f;+ using var fixture = new Fixture(otherX: OtherTownXM);+ fixture.layer.ConfigureTownFootprints(new[] {+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "a"),+ (centre: new Vector2(OtherTownXM, 0f), radius: FootprintRadiusM, id: "b") });+ var camera = fixture.Camera(); fixture.Prepare(camera);+ Assert.IsTrue(fixture.layer.WantsTown("a", camera));++ camera.transform.position = new Vector3(OtherOwnedFocusXM, camera.transform.position.y, camera.transform.position.z);+ camera.transform.LookAt(new Vector3(OtherOwnedFocusXM, 0f, 0f));+ fixture.layer.ConfigureWholeTowns(Array.Empty<(string id, Bounds bounds)>());+ fixture.Prepare(camera);+ Assert.IsTrue(fixture.layer.WantsTown("a", camera),+ "whole-town streaming must preserve valid instance-bounds hysteresis");+ Assert.IsFalse(fixture.layer.WantsTown("b", camera));+ }++ [Test]+ public void ConfigureTownFootprintsKeepsEveryDiscForARepeatedNonDetailedCampId()+ {+ const float FootprintRadiusM = 1000f;+ const float FirstCampXM = 5000f;+ const float SecondCampXM = 200f;+ using var fixture = new Fixture();+ var footprints = new[] {+ (centre: Vector2.zero, radius: FootprintRadiusM, id: "a"),+ (centre: new Vector2(FirstCampXM, 0f), radius: FootprintRadiusM, id: "camp:subdistrict"),+ (centre: new Vector2(SecondCampXM, 0f), radius: FootprintRadiusM, id: "camp:subdistrict") };+ Assert.DoesNotThrow(() => fixture.layer.ConfigureTownFootprints(footprints));+ var camera = fixture.Camera(SecondCampXM); fixture.Prepare(camera);+ Assert.IsFalse(fixture.layer.WantsTown("a", camera)); Assert.IsFalse(fixture.layer.WantsTown("b", camera));+ }++ [Test]+ public void ReconfiguringFootprintsClearsThePreviousPrimarySelection()+ {+ const float FootprintRadiusM = 500f;+ const float FocusXM = 1000f;+ using var fixture = new Fixture();+ var first = new[] {+ (centre: new Vector2(FocusXM, 0f), radius: FootprintRadiusM, id: "a"),+ (centre: new Vector2(8000f, 0f), radius: FootprintRadiusM, id: "b") };+ fixture.layer.ConfigureTownFootprints(first);+ var camera = fixture.Camera(FocusXM); fixture.Prepare(camera);+ Assert.IsTrue(fixture.layer.WantsTown("a", camera));++ var second = new[] {+ (centre: new Vector2(-8000f, 0f), radius: FootprintRadiusM, id: "a"),+ (centre: new Vector2(FocusXM, 0f), radius: FootprintRadiusM, id: "b") };+ fixture.layer.ConfigureTownFootprints(second);+ fixture.Prepare(camera);+ Assert.IsFalse(fixture.layer.WantsTown("a", camera));+ Assert.IsTrue(fixture.layer.WantsTown("b", camera));+ }+[Test]public void AnotherCameraKeepsItsTownWhenTheFirstCameraDisappears(){@@ -360,4 +801,173 @@ public class TownModelResidencyTestsAssert.IsInstanceOf<ArgumentException>(error!.InnerException);Assert.IsFalse((bool)typeof(TownModelLayer).GetProperty("SpatialPolicyConfigured", Flags)!.GetValue(f.layer)!);}++ /// <summary>Owner ruling, 31 Oct 2026, "Load all in view (Recommended)": below 40 km the building models of every town+ /// AND village in the camera's view (+3 km) load, nearest first, and unload on zoom-out. The real map in the player's+ /// streaming path: no editor model list, every original kind acquired through the ModelAcquire seam.</summary>+ sealed class StreamedMap : IDisposable+ {+ readonly FieldInfo acquire;+ readonly object? previousAcquire;+ readonly GameObject prefab;+ readonly Material material;+ readonly List<Camera> cameras = new List<Camera>();+ public readonly MapScene map;+ public readonly TownModelLayer layer;+ public readonly Transform kits;+ readonly CameraRig rig;+ public readonly List<string> RequestOrder = new List<string>();+ readonly Dictionary<string, Action<GameObject?>> answers = new Dictionary<string, Action<GameObject?>>();+ public int Released;+ public StreamedMap()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ map = UnityEngine.Object.FindFirstObjectByType<MapScene>(); map.Build();+ layer = map.GetComponentInChildren<TownModelLayer>(true);+ layer.EdgeAllowance = null;+ kits = map.transform.Find(KitLayer.RootName);+ rig = UnityEngine.Object.FindFirstObjectByType<CameraRig>();+ prefab = GameObject.CreatePrimitive(PrimitiveType.Cube); prefab.name = "stub original";+ // Submit draws with Graphics.RenderMeshInstanced, which needs an instancing material (as the originals' are).+ var renderer = prefab.GetComponent<MeshRenderer>();+ material = new Material(renderer.sharedMaterial) { enableInstancing = true }; renderer.sharedMaterial = material;+ acquire = typeof(TownModelLayer).GetField("ModelAcquire", Flags)!;+ previousAcquire = acquire.GetValue(null);+ acquire.SetValue(null, new Func<string, CollectionDetail, Action<GameObject?>, IDisposable>((id, _, done) =>+ {+ RequestOrder.Add(id); answers[id] = done;+ return new Release(() => Released++);+ }));+ // The player's path: no editor model list; each original kind streams on demand.+ typeof(TownModelLayer).GetField("set", Flags)!.SetValue(layer, null);+ typeof(TownModelLayer).GetField("streaming", Flags)!.SetValue(layer, true);+ }+ public (Vector2 centre, float radius, string id) Footprint(string id) => map.KitFootprints.Single(f => f.id == id);+ /// <summary>The production rig's pose (50 degree pitch, 35 degree FOV, 16:9) looking at <paramref name="at"/>.</summary>+ public Camera Camera(Vector2 at, float distanceM)+ {+ var camera = new GameObject("in-view residency camera").AddComponent<Camera>(); cameras.Add(camera);+ Pose(camera, at, distanceM);+ return camera;+ }+ public void Pose(Camera camera, Vector2 at, float distanceM)+ {+ rig.LookAt = new Vector3(at.x, 0f, at.y); rig.Distance = distanceM; rig.Yaw = 0f; rig.TopInset = 0f; rig.Apply();+ var source = rig.GetComponent<Camera>();+ camera.CopyFrom(source); camera.ResetProjectionMatrix();+ camera.fieldOfView = CameraRig.Fov; camera.aspect = 16f / 9f;+ camera.nearClipPlane = 50f; camera.farClipPlane = 1_000_000f; // CameraRig.Init's planes+ camera.transform.SetPositionAndRotation(source.transform.position, source.transform.rotation);+ }+ /// <summary>Prepares the camera, answers every request with a stub original, and prepares it again.</summary>+ public void Settle(Camera camera)+ {+ layer.PrepareCamera(camera);+ foreach (var answer in answers.Values.ToList()) answer(prefab);+ layer.PrepareCamera(camera);+ }+ public void Submit(Camera camera) =>+ typeof(TownModelLayer).GetMethod("Submit", Flags)!.Invoke(layer, new object[] { default(UnityEngine.Rendering.ScriptableRenderContext), camera });+ /// <summary>The merged locality tile renderer (and its close mesh) that holds a place's ground point.</summary>+ public (MeshRenderer kit, MeshRenderer close) Tile(Vector2 at)+ {+ string name = $"Localities {Mathf.FloorToInt(at.x / SettlementKits.TileM)},{Mathf.FloorToInt(at.y / SettlementKits.TileM)}";+ var kit = kits.Find(name)?.GetComponent<MeshRenderer>();+ var close = kits.Find(name + KitLayer.CloseSuffix)?.GetComponent<MeshRenderer>();+ Assert.IsNotNull(kit, name + ": the merged locality tile"); Assert.IsNotNull(close, name + ": its close mesh");+ return (kit!, close!);+ }+ public void Dispose()+ {+ acquire.SetValue(null, previousAcquire);+ foreach (var camera in cameras) if (camera != null) UnityEngine.Object.DestroyImmediate(camera.gameObject);+ UnityEngine.Object.DestroyImmediate(prefab); UnityEngine.Object.DestroyImmediate(material);+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ VisualToggles.Clear();+ }+ }++ const float TwelveKmM = 11_775f, ThirtyKmM = 30_394f, GameplayM = 60_000f;++ /// <summary>The v0.3.2 blocker (white 100x kit houses where v0.3.1 drew Tal Heuberger's building models): Imwas's merged+ /// locality tile swaps to its building models at 12 km and at 30 km, and the models draw.</summary>+ [Test]+ public void ImwasVillageTileSwapsToBuildingModelsAtTwelveAndThirtyKm()+ {+ using var s = new StreamedMap();+ var imwas = s.Footprint("imwas");+ Assert.Greater(s.layer.CountFor("imwas"), 0, "Imwas has building models");+ var (kit, close) = s.Tile(imwas.centre);+ foreach (float d in new[] { TwelveKmM, ThirtyKmM })+ {+ var camera = s.Camera(imwas.centre, d);+ string at = FormattableString.Invariant($"Imwas at {d / 1000f} km");+ s.Settle(camera);+ Assert.IsTrue(s.layer.ReadyForTown("imwas", camera), at + ": building models admitted and ready");+ Assert.IsTrue(kit.forceRenderingOff, at + ": the 100x kit tile gives way");+ Assert.IsFalse(close.forceRenderingOff, at + ": the tile's close mesh (ground, plinths) draws");+ s.Submit(camera);+ Assert.Greater(s.layer.LastDrawn, 0, at + ": the building models draw");+ }+ }++ /// <summary>The Latrun front, where no game town is under the screen centre: every village there (Imwas, Yalu, Beit Nuba)+ /// is admitted at 12 km and at 30 km.</summary>+ [Test]+ public void EveryLatrunVillageInViewIsAdmitted()+ {+ using var s = new StreamedMap();+ var imwas = s.Footprint("imwas");+ foreach (float d in new[] { TwelveKmM, ThirtyKmM })+ {+ var camera = s.Camera(imwas.centre, d);+ s.Settle(camera);+ foreach (var id in new[] { "imwas", "yalo", "bayt_nuba" })+ {+ Assert.Greater(s.layer.CountFor(id), 0, id + " has building models");+ Assert.IsTrue(s.layer.ReadyForTown(id, camera), FormattableString.Invariant($"{id} at {d / 1000f} km: admitted and ready"));+ }+ }+ }++ /// <summary>A town's neighbours in view load too, not only the town under the screen centre; the focused town's kinds+ /// are asked first (nearest first).</summary>+ [Test]+ public void NeighbouringTownsOfTheFocusLoadToo()+ {+ using var s = new StreamedMap();+ var telAviv = s.Footprint("tel_aviv");+ var camera = s.Camera(telAviv.centre, ThirtyKmM);+ s.Settle(camera);+ foreach (var id in new[] { "tel_aviv", "jaffa", "petah_tikva" })+ {+ Assert.Greater(s.layer.CountFor(id), 0, id + " has building models");+ Assert.IsTrue(s.layer.ReadyForTown(id, camera), id + " at 30 km over Tel Aviv: admitted and ready");+ }+ var telAvivKinds = s.layer.InstancesOf("tel_aviv").Select(m => TownModels.Ids[(int)m.Model]).ToHashSet(StringComparer.Ordinal);+ CollectionAssert.Contains(telAvivKinds, s.RequestOrder[0], "the focused town's kinds are asked first");+ var jaffa = s.Footprint("jaffa");+ s.Pose(camera, jaffa.centre, TwelveKmM); s.Settle(camera);+ Assert.IsTrue(s.layer.ReadyForTown("jaffa", camera), "Jaffa at 12 km");+ Assert.IsTrue(s.layer.ReadyForTown("tel_aviv", camera), "Tel Aviv beside Jaffa at 12 km");+ }++ /// <summary>The 1.5 GB guard: zooming out to the 60 km gameplay view releases every building-model lease and the kits+ /// draw again.</summary>+ [Test]+ public void BuildingModelsUnloadAtSixtyKm()+ {+ using var s = new StreamedMap();+ var imwas = s.Footprint("imwas");+ var (kit, _) = s.Tile(imwas.centre);+ var camera = s.Camera(imwas.centre, ThirtyKmM);+ s.Settle(camera);+ Assert.IsTrue(s.layer.ReadyForTown("imwas", camera), "precondition: Imwas ready at 30 km");+ Assert.IsNotEmpty(s.RequestOrder);+ s.Pose(camera, imwas.centre, GameplayM);+ s.layer.PrepareCamera(camera); s.layer.RetireReleasedModels();+ Assert.AreEqual(s.RequestOrder.Count, s.Released, "every building-model lease is released at 60 km");+ Assert.IsFalse(s.layer.ReadyForTown("imwas", camera), "no building models at 60 km");+ Assert.IsFalse(kit.forceRenderingOff, "the kit tile draws again at 60 km");+ }}diff --git a/unity/Assets/Tests/EditMode/UnitFiguresTests.cs b/unity/Assets/Tests/EditMode/UnitFiguresTests.csindex eec4bd01f..f603bf113 100644--- a/unity/Assets/Tests/EditMode/UnitFiguresTests.cs+++ b/unity/Assets/Tests/EditMode/UnitFiguresTests.cs@@ -493,7 +493,8 @@ public class UnitFiguresTests/// <summary>The Arab forces are drawn only once their own figure has arrived, three of it on/// a base under the neutral pennant, never an IDF figure, and on ground no Israeli force held on the window's first day- /// (#226, ruling 9). A figure that never comes (null: a missing or damaged bundle) draws nothing, and warns nothing more.</summary>+ /// (#226, ruling 9). A figure that fails (null: a missing or damaged bundle) draws its force with the plain built-in+ /// figure and warns once (owner, 31 October 2026: "Yes, fallback in v0.3.2").</summary>[Test]public void TheArabForcesAreDrawnOnlyWithTheirOwnFiguresOnceTheyArrive(){@@ -510,10 +511,15 @@ public class UnitFiguresTestsAssert.IsFalse(asked.ContainsKey(UnitFigures.SyrianInfantry), "no inactive global prefetch pin");Assert.IsFalse(asked.ContainsKey(UnitFigures.IraqiInfantry), "no inactive global prefetch pin");Assert.IsFalse(layer.Tokens.Any(t => t.Token.Unit.Side != UnitData.Israel), "no Arab force before its figure arrives");- asked[UnitFigures.Irregular](null); // the ALA's figure never comes- Assert.IsFalse(layer.Tokens.Any(t => t.Token.Unit.Side != UnitData.Israel), "a figure that never comes draws nothing");+ LogAssert.Expect(LogType.Warning, new Regex("^UNITS figures: ala's figure " + UnitFigures.Irregular + " did not load"));+ asked[UnitFigures.Irregular](null); // the ALA's figure fails+ layer.Show(C, StateAt(May20, 0.8));+ CollectionAssert.AreEqual(new[] { "arab_liberation_army" }, layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel).Select(t => t.Token.Unit.Id),+ "a failed figure draws its force with the built-in fallback");+ foreach (var f in Tokens(map).Find("arab_liberation_army").Cast<Transform>().Where(c => c.name.StartsWith("Figure")))+ Assert.IsTrue(f.TryGetComponent<MeshRenderer>(out var mr) && mr.enabled && !UnitFigures.Dressed(f), $"ALA {f.name}: the built-in figure");asked[UnitFigures.ArabLegion](Prefab(UnitFigures.ArabLegion));- var legion = layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel).ToList();+ var legion = layer.Tokens.Where(t => t.Token.Unit.Side == UnitFlags.Jordan).ToList();CollectionAssert.AreEqual(new[] { "arab_legion" }, legion.Select(t => t.Token.Unit.Id), "the Legion, drawn when its figure arrives");var go = Tokens(map).Find("arab_legion");Assert.AreEqual(0, go.Cast<Transform>().Count(c => c.name.StartsWith("Rifleman")), "no IDF figure");@@ -615,7 +621,8 @@ public class UnitFiguresTests}/// <summary>Fail open: with the people and vehicles bundles missing, or damaged, the real stream answers null with one- /// warning per bundle; every Israeli figure keeps its code-built mesh, drawn, no vehicle is drawn, and no Arab force.</summary>+ /// warning per bundle; every Israeli figure keeps its code-built mesh, drawn, no vehicle is drawn, and each Arab force+ /// stands with the plain built-in figure, its side's failure logged once (owner, 31 October 2026: "Yes, fallback in v0.3.2").</summary>[Test]public void TheCodeBuiltFiguresStayWhenTheBundleIsMissingOrDamaged(){@@ -633,14 +640,14 @@ public class UnitFiguresTestsvar stream = new CollectionStream(new CollectionStream.BundleSource(folder));var requested = new List<string>();UnitFigures.Source = (id, d, done) => { requested.Add(id); stream.Enqueue(id, d, done); };+ var warnings = new List<string>();+ void Capture(string message, string _, LogType type) { if (type == LogType.Warning) warnings.Add(message); }+ Application.logMessageReceived += Capture;var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);layer.Show(C, StateAt(May20, 0.8));layer.Show(C, StateAt(July12, 0.8));// A generated figure's bundle waits while a people's request is queued (#1763, CollectionCatalog.After), even when// its own request was queued first; otherwise the stream serves requests in order.- var expectedBundles = ServedOrder(requested).Select(CollectionCatalog.BundleOf).Distinct();- foreach (var b in expectedBundles)- LogAssert.Expect(LogType.Warning, new Regex("^Collection: bundle " + b + " did not load \\(" + (damaged ? "not an AssetBundle" : "no file")));Step(stream.Run(), 80);var figures = Pieces(map, "Rifleman");Assert.Greater(figures.Count, 10, "the riflemen of 12 July 1948 (not a vacuous pass)");@@ -651,7 +658,31 @@ public class UnitFiguresTests}Assert.IsTrue(Pieces(map, "Vehicle").All(v => v.GetComponentsInChildren<Renderer>().Length == 0), "no vehicle is drawn");layer.Show(C, StateAt(May20, 0.8));- Assert.IsFalse(layer.Tokens.Any(t => t.Token.Unit.Side != UnitData.Israel), "no Arab force, and no placeholder");+ Step(stream.Run(), 80); // the forces of 20 May ask again; their failed bundles answer null at once+ // Every bundle served so far, the fallback tokens' third figures' included (the ALA infantry's bundle).+ var expectedBundles = ServedOrder(requested).Select(CollectionCatalog.BundleOf).Distinct().ToList();+ layer.Show(C, StateAt(May20, 0.8));+ Application.logMessageReceived -= Capture;+ var arab = layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel).ToList();+ Assert.IsNotEmpty(arab, "each Arab force of 20 May is drawn with the built-in fallback");+ foreach (var t in arab)+ {+ var pieces = Tokens(map).Find(t.Token.Unit.Id).Cast<Transform>().Where(c => c.name.StartsWith("Figure")).ToList();+ Assert.AreEqual(t.Token.Figures, pieces.Count, $"{t.Token.Unit.Id}: its figure count");+ foreach (var f in pieces)+ Assert.IsTrue(f.TryGetComponent<MeshRenderer>(out var mr) && mr.enabled && !UnitFigures.Dressed(f), $"{t.Token.Unit.Id} {f.name}: the built-in figure");+ }+ // The stream's warnings (one per bundle, in serving order) and the sides' (one per failed side) interleave;+ // LogAssert matches in order, so each is expected by one pattern and checked exactly here.+ foreach (var b in expectedBundles)+ Assert.AreEqual(1, warnings.Count(w => Regex.IsMatch(w, "^Collection: bundle " + b + " did not load \\(" + (damaged ? "not an AssetBundle" : "no file"))), $"{b}: one stream warning");+ var sideWarnings = warnings.Where(w => w.StartsWith("UNITS figures: ", StringComparison.Ordinal)).ToList();+ var warnedSides = sideWarnings.Select(w => w.Substring("UNITS figures: ".Length).Split('\'')[0]).ToList();+ CollectionAssert.AllItemsAreUnique(warnedSides, "one warning per failed side");+ CollectionAssert.IsSubsetOf(arab.Select(t => t.Token.Unit.Side).Distinct(), warnedSides, "every drawn fallback side was logged");+ Assert.AreEqual(expectedBundles.Count + sideWarnings.Count, warnings.Count, "no other warning:\n" + string.Join("\n", warnings));+ foreach (var _ in warnings)+ LogAssert.Expect(LogType.Warning, new Regex("^(Collection: bundle \\S+ did not load|UNITS figures: \\w+'s figure \\S+ did not load)"));LogAssert.NoUnexpectedReceived();}finally { UnityEngine.Object.DestroyImmediate(map.gameObject); Directory.Delete(folder, true); }diff --git a/unity/Assets/Tests/EditMode/UnitRosterFallbackTests.cs b/unity/Assets/Tests/EditMode/UnitRosterFallbackTests.csnew file mode 100644index 000000000..385d11c16--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitRosterFallbackTests.cs@@ -0,0 +1,336 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using System.Text.RegularExpressions;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Collection;+using Statecraft.Game.Map.Kits;+using Statecraft.Game.Map.Units;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using Object = UnityEngine.Object;++/// <summary>v0.3.2 (owner, 31 October 2026: "Yes, fallback in v0.3.2"): an enemy token whose side figure FAILED to load is+/// drawn anyway, on its plinth under its side's flag, with the plain built-in figure (the Israeli fail-open figure), and the+/// failure is logged once per side. While the figure is only loading, the token still waits; an arrived figure is drawn as+/// before.</summary>+public class UnitRosterFallbackTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static List<UnitEntry> Rows => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));+ static readonly HashSet<string> SideFigures = new HashSet<string>(UnitFigures.BySide.Values, StringComparer.Ordinal);++ [SetUp]+ public void Fresh()+ {+ EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);+ UnitFigures.Source = null;+ UnitFigures.Forget();+ }++ [TearDown]+ public void Restore()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ UnitFigures.Source = null;+ UnitFigures.Forget();+ }++ static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");++ static MapScene BuildMap()+ {+ var map = new GameObject("MapScene").AddComponent<MapScene>();+ map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));+ KitPopulation.Use(KitPopulation.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", KitPopulation.FileName))));+ map.Build();+ return map;+ }++ static GameState JuneState()+ {+ var state = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();+ state.Date = new DateTime(1948, 6, 15);+ return state;+ }++ static Camera TopDownCamera()+ {+ var camera = new GameObject("TEST ONLY fallback camera").AddComponent<Camera>();+ camera.transform.SetPositionAndRotation(new Vector3(0f, 90000f, 0f), Quaternion.Euler(90f, 0f, 0f));+ return camera;+ }++ static GameObject Prefab(string id) => AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, CollectionDetail.Far));++ static Dictionary<string, Action<GameObject?>> PendingSource()+ {+ var pending = new Dictionary<string, Action<GameObject?>>(StringComparer.Ordinal);+ UnitFigures.Source = (id, detail, done) =>+ {+ Assert.AreEqual(CollectionDetail.Far, detail, "no Near request at the start view");+ pending[id] = done;+ };+ return pending;+ }++ /// <summary>Answers every request (and the requests the answers cause): <paramref name="answer"/> null leaves a request+ /// pending (still loading); otherwise it gives the prefab or null (a failed load).</summary>+ static void Answer(Dictionary<string, Action<GameObject?>> pending, Func<string, (bool answer, GameObject? prefab)> answer)+ {+ for (int round = 0; round < 10; round++)+ {+ var batch = pending.Where(kv => answer(kv.Key).answer).ToArray();+ if (batch.Length == 0) return;+ foreach (var (id, _) in batch) pending.Remove(id);+ foreach (var (id, done) in batch) done(answer(id).prefab);+ }+ Assert.Fail("the source kept asking");+ }++ /// <summary>Every on-map enemy token the roster gives for the fixture's date, by row id.</summary>+ static Dictionary<string, UnitToken> EnemyCandidates(List<UnitEntry> rows, GameState state) =>+ UnitRoster.FromState(rows, C, state, _ => true, (_, start, _, _) => start)+ .Where(t => t.Unit.Side != UnitData.Israel).ToDictionary(t => t.Unit.Id, StringComparer.Ordinal);++ /// <summary>Exactly one "did not load" warning per side in <paramref name="sides"/> and no other warning. LogAssert+ /// matches in order and the sides fail in answer order, so the warnings are captured and expected by one pattern.</summary>+ static void ExpectOneWarningPerSide(List<string> warned, IEnumerable<string> sides)+ {+ var pattern = new Regex(@"^UNITS figures: (\w+)'s figure \S+ did not load; its tokens are drawn with the plain built-in figure\.$");+ var got = warned.Select(w => pattern.Match(w)).Select(m => m.Success ? m.Groups[1].Value : "<other> ").ToList();+ CollectionAssert.AreEquivalent(sides, got, "one warning per failed side, and no other warning");+ foreach (var _ in got) LogAssert.Expect(LogType.Warning, pattern);+ }++ [Test]+ public void FixtureDateHoldsATokenForEverySideInBySide()+ {+ var sides = EnemyCandidates(Rows, JuneState()).Values.Select(t => t.Unit.Side).Distinct().OrderBy(s => s, StringComparer.Ordinal);+ CollectionAssert.AreEqual(UnitFigures.BySide.Keys.OrderBy(s => s, StringComparer.Ordinal), sides,+ "15 June 1948 draws every side with a figure, Egypt and Lebanon included");+ }++ [Test]+ public void FailedSideFigureDrawsEveryEnemyTokenWithTheBuiltInFigureAndWarnsOncePerSide()+ {+ var map = BuildMap();+ var pending = PendingSource();+ var camera = TopDownCamera();+ try+ {+ var state = JuneState();+ var rows = Rows;+ var expected = EnemyCandidates(rows, state);+ var layer = UnitLayer.Create(map, rows, C.Hexes, still: true);+ layer.Show(C, state);+ Assert.IsEmpty(layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel), "no enemy token before any answer");++ var warned = new List<string>();+ void Capture(string message, string _, LogType type) { if (type == LogType.Warning) warned.Add(message); }+ Application.logMessageReceived += Capture;+ Func<string, (bool, GameObject?)> failSides = id => (true, SideFigures.Contains(id) ? null : Prefab(id));+ Answer(pending, failSides); // every side figure fails+ layer.FaceCamera(camera); // the next render draws again+ Answer(pending, failSides); // the drawn tokens' own holders ask again and fail again: no second warning+ Application.logMessageReceived -= Capture;+ ExpectOneWarningPerSide(warned, UnitFigures.BySide.Keys);+ layer.FlushPrefetchRetirement();+ Assert.IsFalse(layer.Show(C, state), "the failed roster is stable");+ LogAssert.NoUnexpectedReceived();++ var drawn = layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel).ToDictionary(t => t.Token.Unit.Id, StringComparer.Ordinal);+ CollectionAssert.AreEquivalent(expected.Keys, drawn.Keys, "every enemy token is drawn despite its failed figure");+ var root = layer.transform.Find("Tokens");+ foreach (var (id, want) in expected)+ {+ var got = drawn[id].Token;+ Assert.AreSame(want.Anchor, got.Anchor, $"{id}: same anchor");+ Assert.AreEqual(want.Figures, got.Figures, $"{id}: same figure count");+ Assert.AreEqual(want.ArtType, got.ArtType, $"{id}: same side figure id");+ var token = root.Find(id);+ Assert.IsNotNull(token, $"{id}: token object");+ Assert.IsNotNull(token.Find(UnitPlinth.PlinthName), $"{id}: plinth");+ var flag = token.Find(UnitPlinth.FlagName);+ Assert.IsNotNull(flag, $"{id}: flag");+ if (!UnitFlags.HasPennant(got.Unit.Side))+ Assert.IsTrue(flag.GetComponent<MeshRenderer>().sharedMaterials.Any(m => m != null && m.name.StartsWith($"UnitFlag ({got.Unit.Side} ", StringComparison.Ordinal)),+ $"{id}: the {got.Unit.Side} flag");+ for (int i = 0; i < got.Figures; i++)+ {+ var figure = token.Find($"Figure{i}");+ Assert.IsNotNull(figure, $"{id}: figure {i}");+ if (i == 2 && UnitFigures.ThirdBySide.ContainsKey(got.Unit.Side))+ {+ Assert.IsTrue(UnitFigures.Dressed(figure), $"{id}: its loaded third figure is still dressed");+ continue;+ }+ Assert.IsTrue(figure.TryGetComponent<MeshRenderer>(out var mr) && mr.enabled, $"{id}: figure {i} is the built-in figure");+ Assert.IsNotNull(figure.GetComponent<MeshFilter>().sharedMesh, $"{id}: figure {i} has its mesh");+ }+ Assert.IsNull(token.Find($"Figure{got.Figures}"), $"{id}: no extra figure");+ }+ }+ finally+ {+ Object.DestroyImmediate(camera.gameObject);+ Object.DestroyImmediate(map.gameObject);+ }+ }++ [Test]+ public void LoadingSideFigureStillDrawsNoEnemyToken()+ {+ var map = BuildMap();+ var pending = PendingSource();+ var camera = TopDownCamera();+ try+ {+ var state = JuneState();+ var layer = UnitLayer.Create(map, Rows, C.Hexes, still: true);+ layer.Show(C, state);+ Answer(pending, id => (!SideFigures.Contains(id), SideFigures.Contains(id) ? null : Prefab(id))); // side figures stay loading+ layer.FaceCamera(camera);+ layer.Show(C, state);+ Assert.IsNotEmpty(layer.Tokens.Where(t => t.Token.Unit.Side == UnitData.Israel), "fixture draws Israel");+ Assert.IsEmpty(layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel), "a loading figure draws no placeholder");+ Assert.IsTrue(SideFigures.All(pending.ContainsKey), "every side figure is still asked for");+ foreach (var id in SideFigures) Assert.IsFalse(UnitFigures.Failed(id), $"{id}: loading is not failed");+ LogAssert.NoUnexpectedReceived();+ }+ finally+ {+ Object.DestroyImmediate(camera.gameObject);+ Object.DestroyImmediate(map.gameObject);+ }+ }++ [Test]+ public void ArrivedSideFigureDrawsTheRealFigure()+ {+ var map = BuildMap();+ var pending = PendingSource();+ var camera = TopDownCamera();+ try+ {+ var state = JuneState();+ var rows = Rows;+ var expected = EnemyCandidates(rows, state);+ var layer = UnitLayer.Create(map, rows, C.Hexes, still: true);+ layer.Show(C, state);+ Answer(pending, id => (true, Prefab(id)));+ layer.FaceCamera(camera);+ var root = layer.transform.Find("Tokens");+ CollectionAssert.AreEquivalent(expected.Keys,+ layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel).Select(t => t.Token.Unit.Id), "every enemy token is drawn");+ foreach (var (id, want) in expected)+ for (int i = 0; i < want.Figures; i++)+ {+ var figure = root.Find(id).Find($"Figure{i}");+ Assert.IsFalse(figure.TryGetComponent<MeshRenderer>(out _), $"{id}: figure {i} has no built-in mesh");+ Assert.IsTrue(UnitFigures.Dressed(figure), $"{id}: figure {i} shows its Collection figure");+ }+ LogAssert.NoUnexpectedReceived();+ }+ finally+ {+ Object.DestroyImmediate(camera.gameObject);+ Object.DestroyImmediate(map.gameObject);+ }+ }++ /// <summary>The bug players hit (v0.3.1 on CrazyGames: no enemy unit at all): a new game at the opening state, 15 May+ /// 1948 with the real content, draws exactly one token per enemy starting force, per side, whether the side figures+ /// arrived (the real figure) or failed to load (the built-in fallback).</summary>+ static readonly IReadOnlyDictionary<string, int> OpeningEnemyTokens = new Dictionary<string, int>(StringComparer.Ordinal)+ {+ ["egypt"] = 1, ["jordan"] = 1, ["syria"] = 1, ["iraq"] = 1, ["ala"] = 1,+ };++ static void NewGameDrawsEveryEnemyStartingForce(bool figuresLoad)+ {+ var map = BuildMap();+ var pending = PendingSource();+ var camera = TopDownCamera();+ try+ {+ var state = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);+ Assert.AreEqual(new DateTime(1948, 5, 15), state.Date, "the opening state");+ var fromSim = C.StartingForces.Where(f => f.Arrives == null && f.Side != UnitData.Israel)+ .GroupBy(f => f.Side).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ CollectionAssert.AreEquivalent(OpeningEnemyTokens, fromSim, "the sim's enemy starting forces (StartingForcesTests)");+ Assert.IsFalse(fromSim.ContainsKey("lebanon"), "Lebanon's map-only token starts on 6 June");++ var layer = UnitLayer.Create(map, Rows, C.Hexes, still: true);+ layer.Show(C, state);+ var warned = new List<string>();+ void Capture(string message, string _, LogType type) { if (type == LogType.Warning) warned.Add(message); }+ Application.logMessageReceived += Capture;+ Func<string, (bool, GameObject?)> answer = id => (true, !figuresLoad && SideFigures.Contains(id) ? null : Prefab(id));+ Answer(pending, answer);+ layer.FaceCamera(camera);+ Answer(pending, answer);+ Application.logMessageReceived -= Capture;+ ExpectOneWarningPerSide(warned, figuresLoad ? Array.Empty<string>() : OpeningEnemyTokens.Keys);+ layer.FlushPrefetchRetirement();++ var enemy = layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel).Select(t => t.Token).ToList();+ var perSide = enemy.GroupBy(t => t.Unit.Side).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ CollectionAssert.AreEquivalent(OpeningEnemyTokens, perSide, $"one token per enemy starting force ({(figuresLoad ? "arrived" : "failed")} figures)");+ var root = layer.transform.Find("Tokens");+ foreach (var t in enemy)+ {+ Assert.AreEqual(3, t.Figures, $"{t.Unit.Id}: full strength");+ for (int i = 0; i < t.Figures; i++)+ {+ var figure = root.Find(t.Unit.Id).Find($"Figure{i}");+ Assert.IsNotNull(figure, $"{t.Unit.Id}: figure {i}");+ bool builtIn = figure.TryGetComponent<MeshRenderer>(out var mr) && mr.enabled;+ bool third = i == 2 && UnitFigures.ThirdBySide.ContainsKey(t.Unit.Side);+ if (figuresLoad || third) Assert.IsTrue(UnitFigures.Dressed(figure), $"{t.Unit.Id}: figure {i} is its Collection figure");+ else Assert.IsTrue(builtIn, $"{t.Unit.Id}: figure {i} is the built-in fallback");+ }+ }+ LogAssert.NoUnexpectedReceived();+ }+ finally+ {+ Object.DestroyImmediate(camera.gameObject);+ Object.DestroyImmediate(map.gameObject);+ }+ }++ [Test]+ public void ANewGameDrawsEveryEnemyStartingForceWithItsArrivedFigure() => NewGameDrawsEveryEnemyStartingForce(true);++ [Test]+ public void ANewGameDrawsEveryEnemyStartingForceWithTheFallbackWhenFiguresFail() => NewGameDrawsEveryEnemyStartingForce(false);++ [Test]+ public void FailedIsSetByANullFarAnswerAndClearedByArrivalOrForget()+ {+ string id = UnitFigures.EgyptianInfantry;+ LogAssert.Expect(LogType.Warning, new Regex("^UNITS figures: egypt's figure .* did not load"));+ LogAssert.Expect(LogType.Warning, new Regex("^UNITS figures: lebanon's figure")); // in this order+ UnitFigures.AnswerOwned(id, CollectionDetail.Far, null);+ Assert.IsTrue(UnitFigures.Failed(id), "a null Far answer marks the figure failed");+ UnitFigures.AnswerOwned(id, CollectionDetail.Far, null); // no second warning+ UnitFigures.AnswerOwned(id, CollectionDetail.Near, null);+ Assert.IsTrue(UnitFigures.Failed(id), "a Near answer leaves it");+ UnitFigures.AnswerOwned(id, CollectionDetail.Far, Prefab(id));+ Assert.IsFalse(UnitFigures.Failed(id), "a later arrival clears the failure");+ Assert.IsTrue(UnitFigures.Arrived(id));+ UnitFigures.Forget();+ UnitFigures.AnswerOwned(UnitFigures.LebaneseRegular, CollectionDetail.Far, null);+ UnitFigures.Forget();+ Assert.IsFalse(UnitFigures.Failed(UnitFigures.LebaneseRegular), "Forget clears failures");+ LogAssert.NoUnexpectedReceived();+ }+}diff --git a/unity/Assets/Tests/EditMode/UnitRosterFallbackTests.cs.meta b/unity/Assets/Tests/EditMode/UnitRosterFallbackTests.cs.metanew file mode 100644index 000000000..72cd55679--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitRosterFallbackTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 753ab5e9835f04bf79928a92df7e7eca\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs b/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.csnew file mode 100644index 000000000..17c5e5494--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs@@ -0,0 +1,529 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Collection;+using Statecraft.Game.Map.Kits;+using Statecraft.Game.Map.Units;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using Object = UnityEngine.Object;++/// <summary>Regression R1: a roster token owns the strategic Far originals for its full lifetime. Camera residency still+/// controls Near only, so leaving the approved unit band retires close detail without leaving a drawn bare plinth.</summary>+public class UnitRosterResidencyTests+{+ const float StartViewM = 90000f;+ const float DisplacedViewM = 11800f;+ const int DeferredRetirementSteps = 3;+ const int NoOwners = 0;+ const int OneOwnerPerFarKey = 1;+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static List<UnitEntry> Rows => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));++ sealed class Lease : IDisposable+ {+ Action? release;+ internal Lease(Action release) { this.release = release; }+ public void Dispose() { var done = release; release = null; done?.Invoke(); }+ }++ sealed class DeferredRetirement+ {+ sealed class Batch+ {+ internal readonly IDisposable[] Owners;+ internal readonly Action Complete;+ internal int Steps = DeferredRetirementSteps;+ internal Batch(IReadOnlyList<IDisposable> owners, Action complete)+ { Owners = owners.ToArray(); Complete = complete; }+ }+ readonly Queue<Batch> batches = new Queue<Batch>();+ internal bool Pending => batches.Count != 0;+ internal void Retire(IReadOnlyList<Object> _, IReadOnlyList<IDisposable> owners,+ IReadOnlyList<(string id, CollectionDetail detail)> __, Action complete)+ {+ if (owners.Count == 0) { complete(); return; }+ batches.Enqueue(new Batch(owners, complete));+ }+ internal void Step()+ {+ Assert.IsNotEmpty(batches, "a retirement batch is waiting");+ var batch = batches.Peek();+ if (--batch.Steps != 0) return;+ batches.Dequeue();+ foreach (var owner in batch.Owners) owner.Dispose();+ batch.Complete();+ }+ }++ [SetUp]+ public void Fresh()+ {+ EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);+ UnitFigures.Source = null;+ UnitFigures.Forget();+ }++ [TearDown]+ public void Restore()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ UnitFigures.Source = null;+ UnitFigures.Forget();+ }++ static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");++ static MapScene BuildMap()+ {+ var map = new GameObject("MapScene").AddComponent<MapScene>();+ map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));+ KitPopulation.Use(KitPopulation.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", KitPopulation.FileName))));+ map.Build();+ return map;+ }++ static GameState JuneState()+ {+ var state = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();+ state.Date = new DateTime(1948, 6, 15);+ return state;+ }++ static Camera TopDownCamera(float height, Vector3 focus)+ {+ var camera = new GameObject("TEST ONLY residency camera").AddComponent<Camera>();+ camera.transform.SetPositionAndRotation(new Vector3(focus.x, height, focus.z), Quaternion.Euler(90f, 0f, 0f));+ return camera;+ }++ static GameObject Prefab(string id, CollectionDetail detail) =>+ AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, detail));++ static Dictionary<string, Action<GameObject?>> PendingSource()+ {+ var pending = new Dictionary<string, Action<GameObject?>>(StringComparer.Ordinal);+ UnitFigures.Source = (id, detail, done) =>+ {+ Assert.AreEqual(CollectionDetail.Far, detail, "no Near request before a close-detail switch");+ pending[id] = done;+ };+ return pending;+ }++ static void AnswerAll(Dictionary<string, Action<GameObject?>> pending)+ {+ while (pending.Count != 0)+ {+ var batch = pending.ToArray();+ pending.Clear();+ foreach (var (id, done) in batch) done(Prefab(id, CollectionDetail.Far));+ }+ }++ static Transform Tokens(UnitLayer layer) => layer.transform.Find("Tokens");++ static void AssertNoOwnedOriginals(string because)+ {+ Assert.AreEqual(NoOwners, UnitFigures.OwnedRefCount, because + ": model refcount");+ Assert.AreEqual(NoOwners, UnitFigures.OwnedDetailRefCount, because + ": detail refcount");+ }++ [Test]+ public void AnsweredDrawnHoldersReplaceEveryRosterGatePrefetchOwner()+ {+ var map = BuildMap();+ var pending = PendingSource();+ try+ {+ var layer = UnitLayer.Create(map, Rows, C.Hexes, still: true);+ layer.Show(C, JuneState());+ Assert.Greater(layer.FigurePrefetchCount, NoOwners, "foreign roster gates start with temporary owners");++ AnswerAll(pending);++ Assert.Greater(layer.FigurePrefetchCount, NoOwners,+ "answers defer roster-gate destruction until the layer's frame-boundary flush");+ layer.FlushPrefetchRetirement();+ Assert.AreEqual(NoOwners, layer.FigurePrefetchCount, "every answered model transfers from prefetch to its drawn holders");+ var holders = Tokens(layer).GetComponentsInChildren<UnitFigureResidency>(true);+ Assert.IsNotEmpty(holders, "fixture has drawn figure holders");+ foreach (var holder in holders)+ Assert.AreEqual(OneOwnerPerFarKey, holder.ResidencySnapshot().ownedLeases,+ $"{holder.transform.parent.name}/{holder.name}: one owner for its one retained (model, Far) key");+ // These holder-count equalities assume the fixture's 90 km start view, where no Near lease is requested.+ Assert.AreEqual(holders.Length, UnitFigures.OwnedRefCount, "no extra model owner remains beside the drawn holders");+ Assert.AreEqual(holders.Length, UnitFigures.OwnedDetailRefCount, "no extra detail owner remains beside the drawn holders");++ Object.DestroyImmediate(map.gameObject);+ AssertNoOwnedOriginals("layer teardown releases all transferred owners");+ }+ finally+ {+ if (map != null) Object.DestroyImmediate(map.gameObject);+ }+ }++ [Test]+ public void InactiveDrawnHolderCannotRetireItsGateOrLoseTheRosteredToken()+ {+ var map = BuildMap();+ var pending = PendingSource();+ try+ {+ var layer = UnitLayer.Create(map, Rows, C.Hexes, still: true);+ var state = JuneState();+ layer.Show(C, state);+ string model = UnitFigures.LebaneseRegular;+ Assert.IsTrue(pending.TryGetValue(model, out var answer), "fixture has an unanswered foreign roster gate");+ pending.Remove(model);+ layer.gameObject.SetActive(false);++ answer!(Prefab(model, CollectionDetail.Far));++ Assert.IsTrue(UnitFigures.Arrived(model), "the roster-gate model remains available during inactive dressing");+ Assert.Greater(layer.FigurePrefetchCount, NoOwners, "an inactive holder cannot retire the live gate owner early");+ Assert.IsNotNull(Tokens(layer).Find("lebanese_army"), "the rostered token is built under the inactive parent");+ Assert.IsFalse(layer.Show(C, state), "the unchanged roster does not rebuild");+ Assert.IsNotNull(Tokens(layer).Find("lebanese_army"), "the roster gate cannot flicker the shown token away");+ Assert.IsTrue(UnitFigures.Arrived(model), "a shown roster token never loses its side model during handoff");++ AnswerAll(pending);+ layer.gameObject.SetActive(true);+ var holders = Tokens(layer).GetComponentsInChildren<UnitFigureResidency>(true);+ Assert.Greater(layer.FigurePrefetchCount, NoOwners,+ "reactivation marks the handoff without destroying a child inside the activation callback");+ LogAssert.NoUnexpectedReceived();+ layer.FlushPrefetchRetirement();+ Assert.AreEqual(NoOwners, layer.FigurePrefetchCount,+ "reactivated holders retire the temporary gate owner after acquiring answered Far");+ Assert.AreEqual(holders.Length, UnitFigures.OwnedRefCount,+ "reactivation leaves exactly the drawn holders owning their Far models");++ Object.DestroyImmediate(map.gameObject);+ AssertNoOwnedOriginals("inactive layer teardown releases retained gate and holder owners");+ }+ finally+ {+ if (map != null) Object.DestroyImmediate(map.gameObject);+ }+ }++ [Test]+ public void StartViewRetainsEveryOnMapNonIsraeliTokenAfterItsFakeSourceAnswers()+ {+ var map = BuildMap();+ var pending = PendingSource();+ var camera = TopDownCamera(StartViewM, Vector3.zero);+ try+ {+ var rows = Rows;+ var state = JuneState();+ var expectedSides = rows.Where(UnitRoster.OnMap).Where(u => u.Side != UnitData.Israel)+ .Select(u => u.Side).Distinct().OrderBy(s => s, StringComparer.Ordinal).ToArray();+ var candidates = UnitRoster.FromState(rows, C, state, _ => true, (_, start, _, _) => start)+ .Where(t => t.Unit.Side != UnitData.Israel).ToArray();+ CollectionAssert.AreEqual(expectedSides, candidates.Select(t => t.Unit.Side).Distinct()+ .OrderBy(s => s, StringComparer.Ordinal).ToArray(), "fixture date contains every on-map non-Israeli side");+ var expectedTokens = candidates.Select(t => t.Unit.Id).OrderBy(id => id, StringComparer.Ordinal).ToArray();++ var layer = UnitLayer.Create(map, rows, C.Hexes, still: true);+ layer.Show(C, state);+ foreach (var holder in layer.GetComponentsInChildren<UnitFigureResidency>(true)) holder.Choose(default, camera);+ Assert.AreEqual(StartViewM, TownModelLayer.ViewDistance(camera), 1f, "the verified 90 km start view");++ AnswerAll(pending);++ foreach (var holder in layer.GetComponentsInChildren<UnitFigureResidency>(true)) holder.Choose(default, camera);++ var actual = layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel).Select(t => t.Token.Unit.Id)+ .OrderBy(id => id, StringComparer.Ordinal).ToArray();+ CollectionAssert.AreEqual(expectedTokens, actual, "source answers restore every side's tokens even outside camera residency");+ var tokenRoot = layer.transform.Find("Tokens");+ foreach (var token in layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel))+ {+ var drawn = tokenRoot.Find(token.Token.Unit.Id);+ Assert.IsNotNull(drawn, $"{token.Token.Unit.Id}: roster token is drawn");+ var holders = drawn.GetComponentsInChildren<UnitFigureResidency>(true);+ Assert.IsNotEmpty(holders, $"{token.Token.Unit.Id}: drawn token has figure holders");+ foreach (var holder in holders)+ {+ Assert.IsFalse(holder.CameraResident, $"{token.Token.Unit.Id}/{holder.name}: 90 km is outside camera residency");+ Assert.IsNotNull(holder.transform.Find(UnitFigures.ModelName),+ $"{token.Token.Unit.Id}/{holder.name}: retained Far model dresses the out-of-residency holder");+ }+ }+ }+ finally+ {+ Object.DestroyImmediate(camera.gameObject);+ Object.DestroyImmediate(map.gameObject);+ }+ }++ [Test]+ public void DisplacedFocusNeverLeavesAFigureHolderOnABarePlinth()+ {+ var map = BuildMap();+ var pending = PendingSource();+ Camera? camera = null;+ try+ {+ var layer = UnitLayer.Create(map, Rows, C.Hexes, still: true);+ layer.Show(C, JuneState());+ AnswerAll(pending);+ Assert.IsNotEmpty(layer.Tokens.Where(t => t.Token.Unit.Side != UnitData.Israel), "fixture draws the foreign tokens");++ var subject = layer.Tokens.First(t => t.Token.Unit.Side != UnitData.Israel);+ var policy = ProductionResidency.Approved().Units;+ var focus = new Vector3((float)subject.Spot.X + policy.ExitM + policy.EnterM, 0f, (float)subject.Spot.Z);+ camera = TopDownCamera(DisplacedViewM, focus);+ Assert.AreEqual(DisplacedViewM, TownModelLayer.ViewDistance(camera), 1f, "the verified 11.8 km view");+ Assert.Greater(Vector2.Distance(new Vector2(focus.x, focus.z), new Vector2((float)subject.Spot.X, (float)subject.Spot.Z)),+ policy.ExitM, "focus is beyond the approved leave radius from the token's displaced placement spot");+ foreach (var holder in layer.GetComponentsInChildren<UnitFigureResidency>(true)) holder.Choose(default, camera);++ var tokenRoot = layer.transform.Find("Tokens");+ var holders = tokenRoot.GetComponentsInChildren<UnitFigureResidency>(true);+ Assert.IsNotEmpty(holders, "drawn army tokens have figure or vehicle holders");+ foreach (var holder in holders)+ Assert.IsNotNull(holder.transform.Find(UnitFigures.ModelName), $"{holder.transform.parent.name}/{holder.name}: no bare plinth");+ }+ finally+ {+ if (camera != null) Object.DestroyImmediate(camera.gameObject);+ Object.DestroyImmediate(map.gameObject);+ }+ }++ [Test]+ public void NearLeaseStillRetiresWhenCameraLeavesWhileRosterFarRemains()+ {+ var piece = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var live = new List<CollectionDetail>();+ IDisposable Acquire(string _, CollectionDetail detail, Action<GameObject?> answer)+ {+ live.Add(detail);+ answer(prefab);+ return new Lease(() => live.Remove(detail));+ }+ var policy = ProductionResidency.Approved().Units;+ var camera = TopDownCamera(DisplacedViewM, new Vector3(policy.ExitM + policy.EnterM, 0f, 0f));+ try+ {+ var owner = piece.AddComponent<UnitFigureResidency>();+ owner.Initialize(UnitFigures.YoungRecruit, policy, Acquire, retainFar: true);+ owner.RequestNear();+ CollectionAssert.AreEquivalent(new[] { CollectionDetail.Far, CollectionDetail.Near }, live,+ "fixture starts with both roster Far and admitted Near leases");++ owner.Choose(default, camera);++ CollectionAssert.AreEqual(new[] { CollectionDetail.Far }, live, "leaving retires Near but keeps roster Far");+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName), "the retained Far model still dresses the holder");+ Object.DestroyImmediate(piece);+ Assert.IsEmpty(live, "the roster Far lease retires when its holder is destroyed");+ }+ finally+ {+ Object.DestroyImmediate(camera.gameObject);+ if (piece != null) Object.DestroyImmediate(piece);+ Object.DestroyImmediate(prefab);+ }+ }++ [Test]+ public void NearCloneReturnsAfterEnterLeaveRetireAndEnterAgain()+ {+ var piece = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var retirement = new DeferredRetirement();+ IDisposable Acquire(string _, CollectionDetail detail, Action<GameObject?> answer)+ {+ answer(prefab);+ return new Lease(() => { });+ }+ var camera = TopDownCamera(DisplacedViewM, Vector3.zero);+ try+ {+ var owner = piece.AddComponent<UnitFigureResidency>();+ owner.Initialize(UnitFigures.YoungRecruit, ProductionResidency.Approved().Units, Acquire,+ retainFar: true, retirement: retirement.Retire);+ Assert.IsTrue(piece.TryGetComponent<UnitFigureDetail>(out var detail), "the Far answer registers close detail");+ owner.Choose(default, camera);+ detail.Choose(default, camera);+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName + "/" + UnitFigureDetail.NearName),+ "enter creates the Near clone");++ camera.transform.position = new Vector3(0f, StartViewM, 0f);+ owner.Choose(default, camera);+ detail.Choose(default, camera);+ Assert.IsNull(piece.transform.Find(UnitFigures.ModelName + "/" + UnitFigureDetail.NearName),+ "leave removes the Near clone before its lease retires");+ while (retirement.Pending) retirement.Step();++ camera.transform.position = new Vector3(0f, DisplacedViewM, 0f);+ owner.Choose(default, camera);+ detail.Choose(default, camera);+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName + "/" + UnitFigureDetail.NearName),+ "a fresh Near answer recreates the clone after retirement");+ }+ finally+ {+ Object.DestroyImmediate(camera.gameObject);+ if (piece != null) Object.DestroyImmediate(piece);+ while (retirement.Pending) retirement.Step();+ Object.DestroyImmediate(prefab);+ }+ }++ [Test]+ public void DeferredNearRetirementNeverRemovesTheIndependentRosterFarModel()+ {+ var piece = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var live = new List<CollectionDetail>();+ var retirement = new DeferredRetirement();+ IDisposable Acquire(string _, CollectionDetail detail, Action<GameObject?> answer)+ {+ live.Add(detail);+ answer(prefab);+ return new Lease(() => live.Remove(detail));+ }+ var policy = ProductionResidency.Approved().Units;+ var close = TopDownCamera(DisplacedViewM, Vector3.zero);+ var strategic = TopDownCamera(StartViewM, Vector3.zero);+ try+ {+ var owner = piece.AddComponent<UnitFigureResidency>();+ owner.Initialize(UnitFigures.YoungRecruit, policy, Acquire, retainFar: true, retirement: retirement.Retire);+ owner.Choose(default, close);+ owner.RequestNear();+ CollectionAssert.AreEquivalent(new[] { CollectionDetail.Far, CollectionDetail.Near }, live,+ "close view owns independent Far and Near leases");+ var closeSnapshot = owner.ResidencySnapshot();+ CollectionAssert.AreEqual(new[] { UnitFigures.YoungRecruit }, closeSnapshot.originalIds,+ "one original id is reported once while both Far and Near keys are held");+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName));+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName + "/" + UnitFigureDetail.NearName));++ // Admission is per camera, and an edit-mode frame never advances to expire the close camera's grace: the close+ // camera stops rendering (as when the player's view zooms out), so the strategic view is the only demand left.+ close.enabled = false;+ owner.Choose(default, strategic);++ Assert.IsTrue(retirement.Pending, "Near uses the deferred multi-step retirement seam");+ Assert.IsNull(piece.transform.Find(UnitFigures.ModelName + "/" + UnitFigureDetail.NearName),+ "strategic view immediately reverts the camera-gated detail");+ while (retirement.Pending)+ {+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName), "Far exists before every deferred step");+ retirement.Step();+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName), "Far exists after every deferred step");+ }+ CollectionAssert.AreEqual(new[] { CollectionDetail.Far }, live, "deferred completion releases Near only");+ Assert.IsNull(UnitFigures.Near(UnitFigures.YoungRecruit), "the last Near owner releases the Near cache while Far remains");+ var strategicSnapshot = owner.ResidencySnapshot();+ Assert.AreEqual(1, strategicSnapshot.demandedAnchors);+ CollectionAssert.AreEqual(new[] { UnitFigures.YoungRecruit + "|Far" }, strategicSnapshot.detailIds,+ "snapshot reports the one detail key the strategic holder actually owns");++ owner.enabled = false;+ var disabled = owner.ResidencySnapshot();+ Assert.AreEqual(0, disabled.demandedAnchors, "disabled holder reports no active demand");+ Assert.AreEqual(0, disabled.originalIds.Length, "disabled holder reports no actively held ids");+ Assert.AreEqual(0, disabled.detailIds.Length, "disabled holder reports no actively held detail keys");+ while (retirement.Pending) retirement.Step();+ Assert.IsEmpty(live, "disabling releases the lifetime Far lease after retirement");+ }+ finally+ {+ Object.DestroyImmediate(close.gameObject);+ Object.DestroyImmediate(strategic.gameObject);+ if (piece != null) Object.DestroyImmediate(piece);+ Object.DestroyImmediate(prefab);+ }+ }++ [Test]+ public void DeactivatedRosterHolderKeepsFarUntilDestroyButComponentDisableReleasesIt()+ {+ var inactivePiece = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var disabledPiece = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var live = new List<string>();+ IDisposable Acquire(string model, CollectionDetail detail, Action<GameObject?> answer)+ {+ Assert.AreEqual(CollectionDetail.Far, detail);+ live.Add(model);+ answer(prefab);+ return new Lease(() => live.Remove(model));+ }+ try+ {+ var inactive = inactivePiece.AddComponent<UnitFigureResidency>();+ inactive.Initialize(UnitFigures.YoungRecruit, ProductionResidency.Approved().Units, Acquire, retainFar: true);+ inactivePiece.SetActive(false);+ CollectionAssert.Contains(live, UnitFigures.YoungRecruit,+ "ancestor or object deactivation retains Far for the token object's lifetime");+ Assert.IsNotNull(inactivePiece.transform.Find(UnitFigures.ModelName), "deactivation keeps the dressed Far model");+ Object.DestroyImmediate(inactivePiece);+ CollectionAssert.DoesNotContain(live, UnitFigures.YoungRecruit, "destroy releases the deactivated holder's Far lease");++ var disabled = disabledPiece.AddComponent<UnitFigureResidency>();+ disabled.Initialize(UnitFigures.VeteranFighter, ProductionResidency.Approved().Units, Acquire, retainFar: true);+ disabled.enabled = false;+ CollectionAssert.DoesNotContain(live, UnitFigures.VeteranFighter,+ "explicit component disable releases Far even while its token object lives");+ }+ finally+ {+ if (inactivePiece != null) Object.DestroyImmediate(inactivePiece);+ if (disabledPiece != null) Object.DestroyImmediate(disabledPiece);+ Object.DestroyImmediate(prefab);+ }+ }++ [Test]+ public void ComponentReenableReacquiresAndRedressesAnsweredFar()+ {+ var piece = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var prefab = GameObject.CreatePrimitive(PrimitiveType.Cube);+ var live = new List<string>();+ IDisposable Acquire(string model, CollectionDetail detail, Action<GameObject?> answer)+ {+ Assert.AreEqual(CollectionDetail.Far, detail);+ live.Add(model);+ answer(prefab);+ return new Lease(() => live.Remove(model));+ }+ try+ {+ var owner = piece.AddComponent<UnitFigureResidency>();+ owner.Initialize(UnitFigures.VeteranFighter, ProductionResidency.Approved().Units, Acquire, retainFar: true);+ owner.enabled = false;+ CollectionAssert.DoesNotContain(live, UnitFigures.VeteranFighter, "component disable releases Far");+ Assert.IsNull(piece.transform.Find(UnitFigures.ModelName), "component disable removes the released Far model");++ owner.enabled = true;++ CollectionAssert.Contains(live, UnitFigures.VeteranFighter, "component re-enable reacquires Far");+ Assert.IsNotNull(piece.transform.Find(UnitFigures.ModelName), "the reacquired Far answer re-dresses CollectionModel");+ Assert.IsTrue(owner.ActiveAnsweredFar, "the re-enabled, re-dressed holder counts as ActiveAnsweredFar");+ }+ finally+ {+ if (piece != null) Object.DestroyImmediate(piece);+ Object.DestroyImmediate(prefab);+ }+ }+}diff --git a/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs.meta b/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs.metanew file mode 100644index 000000000..93583c6e8--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: d3b066aa6f65436396381f4982b9fa0ediff --git a/unity/ProjectSettings/ProjectSettings.asset b/unity/ProjectSettings/ProjectSettings.assetindex e77d6b0d9..12bf3b3c6 100644--- a/unity/ProjectSettings/ProjectSettings.asset+++ b/unity/ProjectSettings/ProjectSettings.asset@@ -147,7 +147,7 @@ PlayerSettings:loadStoreDebugModeEnabled: 0visionOSBundleVersion: 1.0tvOSBundleVersion: 1.0- bundleVersion: 0.3.1+ bundleVersion: 0.3.2preloadedAssets: []metroInputSource: 0wsaTransparentSwapchain: 0