Skip to content

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

35.7 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;

namespace Statecraft.Game.Map.Collection
{
    /// <summary>Period-generic farm and village life from Tal Heuberger's 1948 Collection (issue #667, whose sourced setting is:
    /// tractors and horse-drawn work at kibbutz, moshav and moshava fields; sheep and donkeys at villages; camels at
    /// Bedouin areas). This is presentation only: the figures are scenery, never civilian or combat units.
    ///
    /// A fixed hash orders the eligible anchors, the first <see cref="MaxAnchorsPerModel"/> with clear ground are used, and
    /// another hash chooses each anchor's first bearing. Models stand outside the anchor footprint, clear of every kit,
    /// route, unit token, water and other rural model, at the buildings' one world scale (<see cref="WorldScale"/>: a
    /// tractor is about a third of the steam train's locomotive, a sheep about a seventh). Sheep stand as a small flock.
    /// Both shared prefab details stream through <see cref="CollectionStream"/> after the first frame. Far static meshes draw above 45 km; near meshes
    /// draw at 40 km and closer, with hysteresis, and only their existing idle Animators run there. A missing streamed
    /// prefab leaves that detail out and the map continues.</summary>
    [ExecuteAlways]
    public sealed class RuralLife : MonoBehaviour
    {
        public const string Name = "RuralLife";
        public const string Tractor = "figure-vehicle-farm-tractor-1948-v2";
        public const string Wagon = "figure-vehicle-horse-wagon-1948-v2";
        public const string Horse = "figure-draught-horse-idle-1948-v2";
        public const string Sheep = "figure-sheep-idle-1948-v1";
        public const string Donkey = "figure-donkey-1948-v1";
        public const string Camel = "figure-dromedary-camel-1948-v1";
        /// <summary>Tal Heuberger's enclosed striped Bedouin tent, at the same Bedouin camp areas as the camel (owner, 27 October 2026,
        /// #756: "Sign off all 19"; the prepared role in docs/generated-buildings-props-mapping.json, "Existing Bedouin encampment
        /// tent plots"). It stands on clear ground outside the code-built camps' footprints; their tents stay as they are.</summary>
        public const string BedouinTent = CollectionCatalog.BedouinTent;
        public static readonly string[] Models = { Tractor, Wagon, Horse, Sheep, Donkey, Camel, BedouinTent };

        // Design values (#667): sparse scenery, not a population statement or simulation rule.
        public const int MaxAnchorsPerModel = 3;
        /// <summary>The one world scale of the map's Tal Heuberger models up close: <see cref="Kits.SettlementKits.ModelScale"/>
        /// (issue #1032), so a tractor stands beside a kibbutz house at their real proportion. (Tripo's meshes are all about
        /// one unit across, so one shared scale would make a sheep as long as a tractor.)</summary>
        public const float WorldScale = Kits.SettlementKits.ModelScale;   // #1032: one shared constant
        /// <summary>Design values (#667), typical of each kind, not sourced measurements: the real long side (m), seen from
        /// above, each model stands for.</summary>
        public static float RealLengthM(string model) => model switch
        {
            Tractor => 3f, Wagon => 5f, Horse => 2.5f, Sheep => 1.3f, Donkey => 1.8f, Camel => 3f,
            // Design value, not a sourced measurement: the middle of the camp kit's 7 to 12 m goat-hair tents (SettlementKits.Encampments).
            BedouinTent => 10f,
            _ => throw new ArgumentException($"'{model}' is not one of #667's models", nameof(model)),
        };
        /// <summary>The model's long side on the map (m).</summary>
        public static float SizeOf(string model) => RealLengthM(model) * WorldScale;
        // Design values (#667): a flock is a few sheep, spaced a couple of sheep apart around the scene's spot.
        public const int FlockSize = 5;
        public const float FlockSpacingLengths = 2.5f;
        public static int MembersOf(string model) => model == Sheep ? FlockSize : 1;
        /// <summary>The ground a scene takes (m, radius about its spot): its model, or the flock around the spot, with one
        /// model's length to spare. The kit trees whose crowns reach into it are left out at draw time
        /// (Kits.VegetationLayer.Hide, as under the unit figures), so no orchard tree stands over a tractor.</summary>
        public static float SceneRadiusM(string model) => (MembersOf(model) > 1 ? FlockSpacingLengths + 1.5f : 1.5f) * SizeOf(model);
        // Design value (#667): clearance for the scaled model and its readable space at gameplay zoom.
        public const float ClearanceRadiusM = 700f;
        // #700's town-detail close/far band (40/45 km), reused.
        public const float CloseEnterM = Kits.TownModelLayer.CloseEnterM, CloseExitM = Kits.TownModelLayer.CloseExitM;
        // Design value (#667): eight bearings on three rings gives a bounded search without dense scattering.
        public const int Bearings = 8, Rings = 3;
        // Design values (#667): start beyond the clearance disc, then step outward by one clearance radius per ring.
        public const float FirstRingClearances = 1.25f, RingStepClearances = 1f;
        // Design value (#667): neutral headings diversified by the deterministic seed.
        public const float DefaultYaw = 0f;

        static readonly Action<string, CollectionDetail, Action<GameObject?>> DefaultRequest = CollectionStream.Request;
        internal static Action<string, CollectionDetail, Action<GameObject?>> Request = DefaultRequest;

        public readonly struct Want : IEquatable<Want>
        {
            public readonly string Key, Model, ResidencyKey; public readonly Vector2 Anchor; public readonly float AnchorRadius;
            public Want(string key, string model, Vector2 anchor, float anchorRadius)
            { Key = key; Model = model; ResidencyKey = key + "|" + model; Anchor = anchor; AnchorRadius = anchorRadius; }
            public bool Equals(Want other) => Key == other.Key && Model == other.Model && Anchor == other.Anchor && AnchorRadius == other.AnchorRadius;
            public override bool Equals(object? obj) => obj is Want other && Equals(other);
            public override int GetHashCode() => (Key, Model, Anchor, AnchorRadius).GetHashCode();
        }

        readonly struct Anchor
        {
            public readonly string Key, Type; public readonly Vector2 At; public readonly float Radius;
            public Anchor(string key, string type, Vector2 at, float radius) { Key = key; Type = type; At = at; Radius = radius; }
        }

        /// <summary>Every eligible anchor for every model, each model's in its fixed hash order; the layer uses the first
        /// <see cref="MaxAnchorsPerModel"/> of each that have clear ground.</summary>
        public static List<Want> Wants(MapScene map)
        {
            var footprints = new Dictionary<string, (Vector2 At, float Radius)>(StringComparer.Ordinal);
            foreach (var f in map.KitFootprints) if (!footprints.ContainsKey(f.id)) footprints[f.id] = (f.centre, f.radius);
            var anchors = new List<Anchor>();
            void Add(Statecraft.Game.Map.Settlement s)
            {
                if (!footprints.TryGetValue(s.Id, out var f)) return;
                if (!anchors.Any(a => a.Key == s.Id)) anchors.Add(new Anchor(s.Id, s.Type, f.At, f.Radius));
            }
            foreach (var s in map.Settlements) Add(s);
            foreach (var p in map.Localities) Add(p.Settlement);
            foreach (var f in map.KitFootprints.Where(f => f.id.StartsWith("camp:", StringComparison.Ordinal)))
                if (!anchors.Any(a => a.Key == f.id)) anchors.Add(new Anchor(f.id, "bedouin_area", f.centre, f.radius));

            var result = new List<Want>();
            AddModel(Tractor, anchors.Where(a => a.Type == "kibbutz"));
            var horseFields = anchors.Where(a => a.Type == "moshav" ||
                (TownLandmarks.ById.TryGetValue(a.Key, out var model) && model == TownLandmarks.Moshava)).ToList();
            AddModel(Wagon, horseFields); AddModel(Horse, horseFields);
            var villages = anchors.Where(a => a.Type == "village").ToList();   // #667: "at the villages", not the towns
            AddModel(Sheep, villages); AddModel(Donkey, villages);
            AddModel(Camel, anchors.Where(a => a.Type == "bedouin_area"));
            AddModel(BedouinTent, anchors.Where(a => a.Type == "bedouin_area"));
            return result;

            void AddModel(string model, IEnumerable<Anchor> eligible)
            {
                foreach (var a in eligible.OrderBy(x => StableHash(model + ":" + x.Key)).ThenBy(x => x.Key, StringComparer.Ordinal))
                    result.Add(new Want(a.Key, model, a.At, a.Radius));
            }
        }

        /// <summary>FNV-1a over UTF-16 code units: stable across Unity runtimes (unlike string.GetHashCode).</summary>
        public static uint StableHash(string value)
        {
            uint h = 2166136261u;
            foreach (char c in value) { h ^= c; h = unchecked(h * 16777619u); }
            return h;
        }

        public static Vector2? Spot(Want want, Func<Vector2, float, bool> free)
        {
            uint seed = StableHash(want.Model + ":" + want.Key);
            int first = (int)(seed % Bearings);
            for (int ring = 0; ring < Rings; ring++)
            {
                float distance = want.AnchorRadius + ClearanceRadiusM * (FirstRingClearances + ring * RingStepClearances);
                for (int k = 0; k < Bearings; k++)
                {
                    float angle = (first + k) * (360f / Bearings) * Mathf.Deg2Rad;
                    var p = want.Anchor + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * distance;
                    if (free(p, ClearanceRadiusM)) return p;
                }
            }
            return null;
        }

        public static float YawOf(Want want, int member = 0) => DefaultYaw + StableHash(want.Key + ":" + want.Model + (member == 0 ? "" : "#" + member)) % 360u;

        /// <summary>Where member <paramref name="member"/> of a scene at <paramref name="spot"/> stands: the spot itself, or
        /// around it for a flock's other sheep.</summary>
        public static Vector2 MemberAt(Want want, Vector2 spot, int member)
        {
            if (member == 0) return spot;
            float a = (StableHash(want.Key + ":" + want.Model) % 360u + member * 360f / (MembersOf(want.Model) - 1)) * Mathf.Deg2Rad;
            return spot + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * FlockSpacingLengths * SizeOf(want.Model);
        }
        public static bool CloseAt(float distanceM, bool? was) => was == true ? distanceM <= CloseExitM : distanceM <= CloseEnterM;

        CollectionResidency? residency;
        CollectionResidencyView? residencyView;
        Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? ownedAcquire;
        readonly HashSet<CollectionDetail> desiredDetails = new HashSet<CollectionDetail>();
        readonly List<UnityEngine.Object> destroyedOriginals = new List<UnityEngine.Object>();
        sealed class TestSeamLease : IDisposable { public void Dispose() { } }
        internal CollectionResidencyMetrics.Category ResidencySnapshot() => CollectionResidencyMetrics.Row("rural",
            isActiveAndEnabled ? Admitted().Count() : 0, transform.childCount,
            prefabs.Keys.Select(k => k.Model).Concat((isActiveAndEnabled ? Admitted().Select(w => w.Model) : Enumerable.Empty<string>())), residency?.OwnerCount ?? 0, residency?.PendingCount ?? 0,
            prefabs.Values.Count(p => p != null), GetComponentsInChildren<Renderer>(true).Length, 0, prefabs.Values.Count(p => p == null), prefabs.Keys.Select(k => k.Model + "|" + k.Detail));

        internal void ConfigureResidency(CollectionResidencyPolicy policy,
            Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? acquire)
        {
            ownedAcquire = acquire; residencyView = new CollectionResidencyView(policy);
            residency?.Replace(Array.Empty<(string id, CollectionDetail detail)>());
            desiredDetails.Add(CollectionDetail.Far);
            desiredDetails.Add(CollectionDetail.Near);
        }
        IDisposable AcquireOriginal(string id, CollectionDetail detail, Action<GameObject?> done)
        {
            if (ownedAcquire != null) return ownedAcquire(id, detail, done);
            if (Request != DefaultRequest) { Request(id, detail, done); return new TestSeamLease(); }
            return CollectionStream.Acquire(id, detail, done);
        }
        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.ResidencyKey))
                .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), 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()
        {
            ClearVisuals(); prefabs.Clear(); asked.Clear(); closeFor.Clear();
            var pending = destroyedOriginals.ToArray(); destroyedOriginals.Clear(); return pending;
        }
        void ReleaseResidency()
        {
            residencyView?.Clear();
            residency?.Replace(Array.Empty<(string id, CollectionDetail detail)>());
        }
        void LateUpdate()
        {
            if (residencyView != null && residencyView.Prune(Time.frameCount)) { RefreshResidencyCore(false); SyncNearVisuals(); }
        }
        IEnumerable<Want> Admitted()
        {
            var keys = residencyView?.Keys;
            return keys == null ? wants : wants.Where(w => keys.Contains(w.ResidencyKey));
        }
        void 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)>());
        }

        MapScene? map;
        readonly 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, string Instance)> renderers = new List<(Renderer, CollectionDetail, string)>();
        readonly List<(Animator Animator, CollectionDetail Detail)> animators = new List<(Animator, CollectionDetail)>();
        Action<List<(string key, Vector3 at, float radius)>>? fillResidencyAnchors;
        readonly HashSet<string> nearInstances = new HashSet<string>(StringComparer.Ordinal);
        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 =
            new List<(string, string, CollectionDetail, Vector3, string, int)>();
        /// <summary>The scenes drawn (one per anchor used), and the models with fewer than MaxAnchorsPerModel of them.</summary>
        public readonly List<Want> Scenes = new List<Want>();
        public readonly List<string> Missing = new List<string>();
        public IReadOnlyList<Want> Wanted => wants;
        /// <summary>The other layers' ground this layer keeps clear of (its Plan's input), as last shown.</summary>
        internal List<(Vector2 centre, float radius)> OthersShown => others;
        public bool LastClose { get; private set; }

        /// <summary>The ground the other Collection layers hold (centre, radius m): the civilian figures CivilianPeople wants
        /// now (its FigureClearanceM) and the wildlife (half WildlifeLayer.SizeM), so no rural scene stands under them (#667:
        /// kept clear of the other props). GameRoot shows those layers first.</summary>
        public static List<(Vector2 centre, float radius)> OtherProps(MapScene map)
        {
            var discs = new List<(Vector2, float)>();
            var people = map.Terrain != null ? map.Terrain.transform.Find(CivilianPeople.Name)?.GetComponent<CivilianPeople>() : null;
            if (people != null) foreach (var w in people.Wanted) discs.Add((new Vector2(w.At.x, w.At.z), CivilianPeople.FigureClearanceM));
            foreach (var w in WildlifeLayer.Wants(map)) discs.Add((w.At, 0.5f * WildlifeLayer.SizeM));
            return discs;
        }

        public static RuralLife? Show(MapScene map)
        {
            if (map == null || map.Terrain == null || map.Hexes == null) return null;
            var layer = map.Terrain.transform.Find(Name)?.GetComponent<RuralLife>();
            if (layer == null)
            {
                var go = new GameObject(Name);
                go.transform.SetParent(map.Terrain.transform, false);
                layer = go.AddComponent<RuralLife>();
                layer.map = map;
                layer.ConfigureResidency(map.Residency.Rural, null);
            }
            layer.Show(Wants(map), OtherProps(map));
            return layer;
        }

        List<(Vector2 centre, float radius)> others = new List<(Vector2, float)>();
        System.Collections.ObjectModel.ReadOnlyCollection<(Want want, Vector2 spot)>? fullPlan;
        bool everShown;
        int planVersion;

        /// <summary>#1701 slice F with #2266: the scenes' full plan (every model available) for what this layer was last shown,
        /// computed once per change of its wants or the ground it keeps clear of, read-only. It plans against exactly the
        /// layer's own inputs (<see cref="OthersShown"/>, never the map's current ground), the ones its own Rebuild plans
        /// against, so the scenes drawn and the ground the others keep clear of are one plan. Plan reads nothing else that
        /// changes on a map (its ground, routes and tokens are the map's build; no date). The other layers that keep clear of
        /// the scenes read it through <see cref="PlanOf"/> and rebuild when <see cref="VersionOf"/> moves.</summary>
        internal IReadOnlyList<(Want want, Vector2 spot)> FullPlan => fullPlan ??= Plan(map!, wants, others, _ => true).AsReadOnly();

        /// <summary>The rural plan the other layers keep clear of: the shown layer's <see cref="FullPlan"/>. Before a rural layer
        /// is shown (tests and editor tools; GameRoot shows it first), it is computed from the map's own wants and the other
        /// layers' current ground on each call: deterministic, not cached, and its version is 0.</summary>
        internal static IReadOnlyList<(Want want, Vector2 spot)> PlanOf(MapScene map)
        {
            var layer = Shown(map);
            return layer != null ? layer.FullPlan : Plan(map, Wants(map), OtherProps(map), _ => true);
        }

        /// <summary>A stamp of the plan <see cref="PlanOf"/> returns: it moves each time the shown layer's inputs change, so the
        /// layers built on the plan (SpecialBuildingModels' workshops, HexPropModels) rebuild together onto the new one.</summary>
        internal static int VersionOf(MapScene map) => Shown(map)?.planVersion ?? 0;

        static RuralLife? Shown(MapScene map)
        {
            var layer = map.Terrain != null ? map.Terrain.transform.Find(Name)?.GetComponent<RuralLife>() : null;
            return layer != null && layer.map != null && layer.everShown ? layer : null;
        }

        /// <summary>Shows exactly these wants and other layers' ground (a test seam, as Show(map) does with the map's own).</summary>
        internal void ShowForTest(List<Want> next, List<(Vector2 centre, float radius)> nextOthers) => Show(next, nextOthers);

        void Show(List<Want> next, List<(Vector2 centre, float radius)> nextOthers)
        {
            if (everShown && next.SequenceEqual(wants) && nextOthers.SequenceEqual(others)) return;
            wants = next; others = nextOthers; fullPlan = null; everShown = true; planVersion++;
            OriginalModelRequests.WhenVisible(this, () =>
            {
                desiredDetails.Add(CollectionDetail.Far); desiredDetails.Add(CollectionDetail.Near);
                RefreshResidency();
            });
            Rebuild();
        }

        void OnModel(string model, CollectionDetail detail, GameObject? prefab)
        {
            if (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.");
            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));
                }
            }
        }

        /// <summary>Where the scenes stand: each want in order, the first MaxAnchorsPerModel of each model with clear ground (Spot),
        /// clear of <paramref name="others"/> and of each other, every one taking its ground; those whose model
        /// <paramref name="available"/> holds are listed. It reads only
        /// the map, the wants and the other layers' ground, never what has streamed, so with every model available it is the
        /// plan the layer draws once everything has arrived (HexPropModels keeps clear of it, #2266).</summary>
        internal static List<(Want want, Vector2 spot)> Plan(MapScene map, IReadOnlyList<Want> wants, List<(Vector2 centre, float radius)> others,
            Func<string, bool> available)
        {
            var ground = PlacementLayer.CampGround(map);
            var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();
            var taken = new List<(Vector2 centre, float radius)>();
            bool Free(Vector2 p, float radius)
            {
                if (!TownLandmarks.Clear(p, radius, footprints) || !TownLandmarks.Clear(p, radius, taken) || !TownLandmarks.Clear(p, radius, others)) return false;
                if (!ground.Inside(p.x - radius, p.y - radius) || !ground.Inside(p.x + radius, p.y + radius)) return false;
                for (int k = 0; k < 9; k++)
                {
                    var q = k == 0 ? p : p + new Vector2(Mathf.Cos(k * Mathf.PI / 4f), Mathf.Sin(k * Mathf.PI / 4f)) * radius * 0.8f;
                    if (ground.Water(q.x, q.y)) return false;
                }
                return !ground.OnRoute(p, radius) && !ground.OnToken(p, radius);
            }
            var used = new Dictionary<string, int>(StringComparer.Ordinal);
            var plan = new List<(Want, Vector2)>();
            foreach (var want in wants)
            {
                // Every want takes its ground whether or not its model has streamed (only the plan's output is filtered), so a
                // later scene's spot never depends on what streamed first (#2266 review; the same shape as #2281's).
                used.TryGetValue(want.Model, out int n);
                if (n >= MaxAnchorsPerModel) continue;
                var at = Spot(want, Free);
                if (at == null) continue;
                used[want.Model] = n + 1;
                taken.Add((at.Value, ClearanceRadiusM));
                if (available(want.Model)) plan.Add((want, at.Value));
            }
            return plan;
        }

        void Rebuild()
        {
            CollectionResidencyMetrics.MarkDirty();
            if (map == null || map.Terrain == null) return;
            ClearVisuals();
            var ground = PlacementLayer.CampGround(map);
            // A streamed representation is what makes this a real scene. Until then it draws nothing, owns no tree hole and
            // asks for no Near; but every scene stands at its spot in the plan with every model available, so a scene that
            // streams in later lands where the plan put it, which the hex props keep clear of (HexPropModels, #2266 review).
            bool Streamed(string model) => (prefabs.TryGetValue((model, CollectionDetail.Far), out var f) && f != null)
                || (prefabs.TryGetValue((model, CollectionDetail.Near), out var nr) && nr != null);
            var used = new Dictionary<string, int>(StringComparer.Ordinal);
            var holes = new List<(Vector2 centre, float radius)>();
            var nearKeys = residencyView?.Keys;
            foreach (var (want, spot) in Plan(map, wants, others, Streamed))
            {
                used.TryGetValue(want.Model, out int n); used[want.Model] = n + 1;
                Vector2? at = spot;
                Scenes.Add(want);
                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 })
                    {
                        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);
                        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.
                        go.transform.localRotation = prefab.transform.localRotation;
                        var own = Bounds(go);
                        float edge = Mathf.Max(own.size.x, own.size.z);
                        go.transform.localScale = prefab.transform.localScale * (edge > 1e-4f ? SizeOf(want.Model) / edge : 1f);
                        go.transform.localRotation = Quaternion.Euler(0f, YawOf(want, member), 0f) * prefab.transform.localRotation;
                        go.transform.position = pos;
                        var bounds = Bounds(go);
                        go.transform.position += new Vector3(pos.x - bounds.center.x, pos.y - bounds.min.y, pos.z - bounds.center.z);
                        foreach (var renderer in go.GetComponentsInChildren<Renderer>(true))
                        {
                            renderer.shadowCastingMode = ShadowCastingMode.On;
                            renderer.forceRenderingOff = detail == CollectionDetail.Near ? !LastClose : LastClose && nearAvailable;
                            renderers.Add((renderer, detail, instanceKey));
                        }
                        foreach (var animator in go.GetComponentsInChildren<Animator>(true))
                        {
                            animator.enabled = detail == CollectionDetail.Near && LastClose;
                            animators.Add((animator, detail));
                        }
                        Placed.Add((want.Key, want.Model, detail, pos, instanceName, member));
                    }
                }
            }
            Units.UnitShowcase.HideTrees(map, Name, holes);
            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");
        }

        static Bounds Bounds(GameObject go)
        {
            var rs = go.GetComponentsInChildren<Renderer>(true);
            if (rs.Length == 0) return new Bounds(go.transform.position, Vector3.zero);
            var bounds = rs[0].bounds;
            foreach (var r in rs) bounds.Encapsulate(r.bounds);
            return bounds;
        }

        void DestroyNow(GameObject go)
        {
            destroyedOriginals.Add(go); destroyedOriginals.RemoveAll(o => o == null);
            if (Application.isPlaying) { if (gameObject.activeInHierarchy) go.transform.SetParent(null); Destroy(go); }
            else DestroyImmediate(go);
        }

        void OnEnable()
        {
            RenderPipelineManager.beginCameraRendering += Choose;
            if (map != null) OriginalModelRequests.WhenVisible(this, () =>
            { desiredDetails.Add(CollectionDetail.Far); desiredDetails.Add(CollectionDetail.Near); RefreshResidency(); });
        }
        void OnDisable() { RenderPipelineManager.beginCameraRendering -= Choose; ReleaseResidency(); }
        void OnDestroy() { residency?.Dispose(); residency = null; }

        void FillResidencyAnchors(List<(string key, Vector3 at, float radius)> anchors)
        {
            for (int i = 0; i < wants.Count; i++)
            {
                var w = wants[i];
                anchors.Add((w.ResidencyKey, new Vector3(w.Anchor.x, 0, w.Anchor.y), w.AnchorRadius));
            }
        }
        internal void Choose(ScriptableRenderContext context, Camera camera)
        {
            if (camera.cameraType == CameraType.Preview || camera.cameraType == CameraType.Reflection) return;
            if (residencyView != null)
            {
                var previousDemand = residencyView.Keys;
                residencyView.Observe(camera, fillResidencyAnchors ??= FillResidencyAnchors, Time.frameCount);
                bool same = previousDemand.Count == residencyView.Keys.Count;
                foreach (string key in previousDemand) if (!residencyView.Keys.Contains(key)) { same = false; break; }
                if (!same) { 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;
            nearInstances.Clear();
            for (int i = 0; i < renderers.Count; i++)
                if (renderers[i].Renderer != null && renderers[i].Detail == CollectionDetail.Near) nearInstances.Add(renderers[i].Instance);
            for (int i = 0; i < renderers.Count; i++)
            {
                var (renderer, detail, instance) = renderers[i];
                if (renderer != null) renderer.forceRenderingOff = detail == CollectionDetail.Near ? !close : close && nearInstances.Contains(instance);
            }
            for (int i = 0; i < animators.Count; i++)
            {
                var (animator, detail) = animators[i];
                if (animator != null) animator.enabled = detail == CollectionDetail.Near && close;
            }
        }
    }
}