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.

96.8 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.TestTools.Constraints;
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;
    static object? Call(object? target, string name, params object?[] args)
    {
        var method = typeof(TownModelLayer).GetMethod(name, Flags);
        Assert.IsNotNull(method, "option A must implement " + name);
        return method!.Invoke(target, args);
    }
    static (string id, Bounds bounds) Place(string id, float x, float z = 0) =>
        (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;
    }

    /// <summary>Whether this camera's focus selection holds the town (its primary or an edge), whether or not its zoom
    /// admits the town's building models: the selection mechanism alone (the major cities, TownModels.IsMajorCity, are
    /// admitted only below the close switch: owner, 7 November 2026, "Tal's models close (Recommended)").</summary>
    static bool Selects(TownModelLayer layer, string id, Camera camera)
    {
        var choices = (System.Collections.IDictionary)typeof(TownModelLayer).GetField("choices", Flags)!.GetValue(layer)!;
        var choice = choices[camera.GetInstanceID()];
        Assert.IsNotNull(choice, camera.name + ": a prepared camera");
        return ((HashSet<string>)choice!.GetType().GetField("towns", Flags)!.GetValue(choice)!).Contains(id);
    }

    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. The focus selects every detailed town there and,
    /// at 11.8 km (below the close switch), admits its models, the major cities' included (TownModels.IsMajorCity; owner,
    /// 7 November 2026, "Tal's models close (Recommended)", which supersedes "Big blocks, every zoom" (6 November 2026)
    /// from 40 km out only).</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 notSelected = 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 (!Selects(layer, town.Id, camera)) notSelected.Add(town.Id);
                    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(notSelected,
                "a camera focused on each authoritative town footprint must select that town");
            CollectionAssert.IsEmpty(notAdmitted,
                "a camera focused on each authoritative town footprint must admit that town's detailed models, a major city's too below the close switch");
            CollectionAssert.IsEmpty(notReady,
                "every admitted production town must have every required detailed-model kind, a major city's too");
        }
        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
                {
                    // The selection moves with the pan, and so does the admission: at 11.8 km, below the close switch, a major
                    // city's building models are admitted too (owner, 7 November 2026, "Tal's models close (Recommended)").
                    layer.PrepareCamera(camera);
                    Assert.IsTrue(Selects(layer, pair.from.id, camera), pair.from.id + ": selected at its own label before the pan");
                    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(Selects(layer, pair.to.id, camera),
                        pair.from.id + " -> " + pair.to.id + ": the normalized-distance owner is selected at its label");
                    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(Selects(layer, pair.from.id, camera),
                        pair.from.id + " -> " + pair.to.id + ": the previous town cannot retain on its whole disc");
                    Assert.IsFalse(layer.WantsTown(pair.from.id, camera),
                        pair.from.id + " -> " + pair.to.id + ": nor its admission");
                }
                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
            {
                // Both are major cities, admitted below the close switch (owner, 7 November 2026, "Tal's models close
                // (Recommended)"): the selection and the admission cross the seam together.
                void Expect(string selected, string other)
                {
                    Assert.IsTrue(Selects(layer, selected, camera), selected + " selected");
                    Assert.IsFalse(Selects(layer, other, camera), other + " not selected");
                    Assert.IsTrue(layer.WantsTown(selected, camera), selected + "'s building models admitted");
                    Assert.IsFalse(layer.WantsTown(other, camera), other + "'s building models not admitted");
                }
                Move(jaffaSide); Expect("jaffa", "tel_aviv");
                Move(telAvivSide); Expect("tel_aviv", "jaffa");
                Move(jaffaSide); Expect("jaffa", "tel_aviv");
            }
            finally { UnityEngine.Object.DestroyImmediate(camera.gameObject); }
        }
        finally
        {
            EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
            VisualToggles.Clear();
        }
    }

    [TestCase("FocusEnterM", 0f)]
    [TestCase("FocusExitM", 0f)]
    [TestCase("EdgeM", 0f)]
    [TestCase("MaxEdgeTowns", 0f)]
    [TestCase("CameraGraceFrames", 1f)]
    public void SpatialNumbersAreNamedAndTunable(string name, float expected)
    {
        Assert.IsNull(typeof(TownModelLayer).GetField(name, Flags), name + ": no provisional alternative to the approved policy");
        var policy = ProductionResidency.Approved().Towns;
        float actual = name switch {
            "FocusEnterM" => policy.Enter, "FocusExitM" => policy.Exit, "EdgeM" => policy.Edge,
            "MaxEdgeTowns" => policy.MaxEdges, "CameraGraceFrames" => policy.Grace,
            _ => throw new ArgumentException(name)
        };
        Assert.AreEqual(expected, actual);
        Assert.AreEqual(120000f, policy.ViewEnter);
        Assert.AreEqual(160000f, policy.ViewExit);
    }

    [Test]
    public void FocusKeepsOnlyThePrimaryAndTwoNearestEdgeTowns()
    {
        var 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()
    {
        var places = new[] { Place("z", 200), Place("a", -200) };
        Assert.AreEqual("a", Focus(places, Vector3.zero)[0]);
        Array.Reverse(places);
        Assert.AreEqual("a", Focus(places, Vector3.zero)[0]);
    }
    [Test]
    public void WaterOrAnEmptyMapRequestsNoNearTown()
    {
        CollectionAssert.IsEmpty(Focus(new[] { Place("town", 0) }, new Vector3(5000, 0, 0)));
        CollectionAssert.IsEmpty(Focus(Array.Empty<(string, Bounds)>(), Vector3.zero));
    }
    [Test]
    public void FocusRetentionHasASeparateExitBand()
    {
        var places = new[] { Place("old", 0), Place("new", 1800) };
        Assert.AreEqual("old", Focus(places, new Vector3(1500, 0, 0), "old")[0]);
        Assert.AreEqual("new", Focus(places, new Vector3(2200, 0, 0), "old")[0]);
    }
    [Test]
    public void AltitudeDoesNotChangeGroundMembership()
    {
        var places = new[] { Place("focus", 0), Place("edge", 500) };
        CollectionAssert.AreEqual(Focus(places, Vector3.zero), Focus(places, new Vector3(0, 100000, 0)));
    }

    sealed class Release : IDisposable
    {
        Action? action;
        public Release(Action action) { this.action = action; }
        public void Dispose() { var a = action; action = null; a?.Invoke(); }
    }

    [Test]
    public void LoadingKeepsFallbackAndReadinessSwapsOnlyTheFocusedTown()
    {
        var field = typeof(TownModelLayer).GetField("ModelAcquire", Flags);
        Assert.IsNotNull(field, "stream injection for delayed arrival");
        var before = field!.GetValue(null);
        var root = new GameObject("option A test"); var cameraObject = new GameObject("camera");
        var prefab = new GameObject("original"); var mesh = new Mesh();
        var material = new Material(Shader.Find("Hidden/InternalErrorShader"));
        Action<GameObject?>? answer = null; int released = 0;
        var requested = new List<string>();
        try
        {
            field.SetValue(null, new Func<string, Statecraft.Game.Map.Collection.CollectionDetail, Action<GameObject?>, IDisposable>((id, _, done) =>
            { requested.Add(id); answer = done; return new Release(() => released++); }));
            var layer = root.AddComponent<TownModelLayer>();
            Call(layer, "ConfigureResidency", 1000f, 2000f, 1000f, 2, "test fixture only; not measured");
            var kit = new GameObject("focus").AddComponent<MeshRenderer>(); kit.transform.SetParent(root.transform);
            var other = new GameObject("other").AddComponent<MeshRenderer>(); other.transform.SetParent(root.transform);
            var items = new[] {
                new SettlementKits.ModelInstance("focus", TownModel.B01WhiteCity, Matrix4x4.identity, Vector2.zero, 0, 100, 100, 0, 100),
                new SettlementKits.ModelInstance("other", TownModel.B03aArches, Matrix4x4.identity, new Vector2(6000, 0), 0, 100, 100, 0, 100) };
            Call(layer, "InitStreaming", items, new List<(Renderer kit, Renderer? close)> { (kit, null), (other, null) });
            var camera = cameraObject.AddComponent<Camera>();
            camera.transform.position = new Vector3(0, 10000, -10000); camera.transform.LookAt(Vector3.zero);
            Call(layer, "PrepareCamera", camera);
            CollectionAssert.AreEqual(new[] { "b01-white-city-v2" }, requested);
            Assert.IsFalse(kit.forceRenderingOff, "fallback while loading");
            Assert.IsFalse(other.forceRenderingOff);
            Assert.IsFalse((bool)Call(layer, "ReadyForTown", "focus", camera)!);
            prefab.AddComponent<MeshFilter>().sharedMesh = mesh; prefab.AddComponent<MeshRenderer>().sharedMaterial = material;
            answer!(prefab);
            Call(layer, "RestoreRenderers"); Call(layer, "PrepareCamera", camera);
            Assert.IsTrue((bool)Call(layer, "ReadyForTown", "focus", camera)!);
            Assert.IsTrue(kit.forceRenderingOff);
            Assert.IsFalse(other.forceRenderingOff, "not all towns hide behind global HasModels");
            Call(layer, "RestoreRenderers");
            camera.transform.position = new Vector3(0, 100000, -100000); camera.transform.LookAt(Vector3.zero);
            Call(layer, "PrepareCamera", camera);
            Assert.IsFalse(kit.forceRenderingOff, "fallback before original release");
            Call(layer, "RetireReleasedModels");
            Assert.AreEqual(1, released);
        }
        finally
        {
            field.SetValue(null, before);
            UnityEngine.Object.DestroyImmediate(root); UnityEngine.Object.DestroyImmediate(cameraObject);
            UnityEngine.Object.DestroyImmediate(prefab); UnityEngine.Object.DestroyImmediate(mesh); UnityEngine.Object.DestroyImmediate(material);
        }
    }
    sealed class Fixture : IDisposable
    {
        readonly FieldInfo field;
        readonly object? previous;
        readonly GameObject root;
        readonly GameObject prefab;
        readonly Mesh mesh;
        readonly Material material;
        readonly List<GameObject> cameras = new List<GameObject>();
        public readonly TownModelLayer layer;
        public readonly MeshRenderer a, b;
        public readonly List<string> RequestOrder = new List<string>();
        public readonly Dictionary<string, Action<GameObject?>> Answers = new Dictionary<string, Action<GameObject?>>();
        public readonly Dictionary<string, int> Requests = new Dictionary<string, int>(), Releases = new Dictionary<string, int>();
        public Fixture(bool mixedTile = false, float otherX = 8000, bool configurePolicy = true)
        {
            field = typeof(TownModelLayer).GetField("ModelAcquire", Flags)!;
            Assert.IsNotNull(field); previous = field.GetValue(null);
            root = new GameObject("town residency fixture"); prefab = new GameObject("original"); mesh = new Mesh();
            material = new Material(Shader.Find("Hidden/InternalErrorShader"));
            field.SetValue(null, new Func<string, Statecraft.Game.Map.Collection.CollectionDetail, Action<GameObject?>, IDisposable>((id, _, done) =>
            {
                Requests.TryGetValue(id, out int n); Requests[id] = n + 1; Answers[id] = done; RequestOrder.Add(id);
                return new Release(() => { Releases.TryGetValue(id, out int count); Releases[id] = count + 1; });
            }));
            prefab.AddComponent<MeshFilter>().sharedMesh = mesh; prefab.AddComponent<MeshRenderer>().sharedMaterial = material;
            layer = root.AddComponent<TownModelLayer>();
            a = new GameObject(mixedTile ? "Localities 0,0" : "a").AddComponent<MeshRenderer>(); a.transform.SetParent(root.transform);
            b = new GameObject("b").AddComponent<MeshRenderer>(); b.transform.SetParent(root.transform);
            var items = new[] {
                new SettlementKits.ModelInstance("a", TownModel.B01WhiteCity, Matrix4x4.identity, Vector2.zero, 0, 100, 100, 0, 100),
                new SettlementKits.ModelInstance("b", TownModel.B03aArches, Matrix4x4.identity, new Vector2(otherX, 0), 0, 100, 100, 0, 100) };
            if (configurePolicy)
            {
                Call(layer, "ConfigureResidency", 1000f, 2000f, 1000f, 2, "test fixture only; not measured");
                // Private-field reflection makes ONLY this fixture's historical grace2 explicit; leave its view path unchanged.
                typeof(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)
        {
            var go = new GameObject("camera"); cameras.Add(go); var c = go.AddComponent<Camera>();
            c.transform.position = new Vector3(x, far ? 100000 : 10000, far ? -100000 : -10000); c.transform.LookAt(new Vector3(x, 0, 0)); return c;
        }
        public void Prepare(Camera camera) => Call(layer, "PrepareCamera", camera);
        public bool Ready(string id, Camera camera) => (bool)Call(layer, "ReadyForTown", id, camera)!;
        public void Arrive(string model) => Answers[model](prefab);
        public void Retire() => Call(layer, "RetireReleasedModels");
        public void Dispose()
        {
            UnityEngine.Object.DestroyImmediate(root);
            foreach (var c in cameras) UnityEngine.Object.DestroyImmediate(c);
            field.SetValue(null, previous);
            UnityEngine.Object.DestroyImmediate(prefab); UnityEngine.Object.DestroyImmediate(mesh); UnityEngine.Object.DestroyImmediate(material);
        }
    }

    [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()
    {
        using var f = new Fixture(); var a = f.Camera(); var b = f.Camera(8000);
        f.Prepare(a); f.Arrive("b01-white-city-v2"); f.Prepare(a);
        f.Prepare(b); f.Arrive("b03a-jerusalem-arches-v2"); f.Prepare(b);
        Assert.IsTrue(f.Ready("a", a)); Assert.IsTrue(f.Ready("b", b));
        a.enabled = false; f.Prepare(b); f.Retire();
        Assert.AreEqual(1, f.Releases["b01-white-city-v2"]);
        Assert.IsFalse(f.Releases.ContainsKey("b03a-jerusalem-arches-v2")); Assert.IsTrue(f.Ready("b", b));
        Assert.IsFalse(f.a.forceRenderingOff, "inactive camera cannot leave its fallback hidden");
    }
    [Test]
    public void AnEvictedGenerationCannotAnswerANewRequestForTheSameModel()
    {
        using var f = new Fixture(); var near = f.Camera(); f.Prepare(near);
        var stale = f.Answers["b01-white-city-v2"];
        near.transform.position = new Vector3(0, 100000, -100000); near.transform.LookAt(Vector3.zero);
        f.Prepare(near); f.Retire();
        near.transform.position = new Vector3(0, 10000, -10000); near.transform.LookAt(Vector3.zero); f.Prepare(near);
        Assert.AreEqual(2, f.Requests["b01-white-city-v2"]);
        stale(f.Original); Assert.IsFalse(f.Ready("a", near));
        f.Arrive("b01-white-city-v2"); f.Prepare(near); Assert.IsTrue(f.Ready("a", near));
    }
    [Test]
    public void AMixedLocalityTileStaysWholeAsFallback()
    {
        using var f = new Fixture(mixedTile: true); var camera = f.Camera(); f.Prepare(camera);
        Assert.IsFalse(f.Requests.ContainsKey("b01-white-city-v2"));
        Assert.IsFalse(f.a.forceRenderingOff); Assert.IsFalse(f.Ready("a", camera));
    }
    [Test]
    public void AFailedOriginalKeepsFallbackWithoutRepeatedRequestsEveryCameraFrame()
    {
        using var f = new Fixture(); var camera = f.Camera(); f.Prepare(camera);
        f.Answers["b01-white-city-v2"](null); f.Prepare(camera); f.Prepare(camera);
        Assert.IsFalse(f.Ready("a", camera)); Assert.IsFalse(f.a.forceRenderingOff);
        Assert.AreEqual(1, f.Requests["b01-white-city-v2"]);
    }
    [Test]
    public void DisablingTheLayerReleasesItsOwnershipAndRestoresFallback()
    {
        using var f = new Fixture(); var camera = f.Camera(); f.Prepare(camera); f.Arrive("b01-white-city-v2"); f.Prepare(camera);
        Assert.IsTrue(f.a.forceRenderingOff);
        f.layer.enabled = false;
        Assert.IsFalse(f.a.forceRenderingOff); Assert.AreEqual(1, f.Releases["b01-white-city-v2"]);
    }

    [Test]
    public void TheFocusLoadsBeforeEdgeModelsRatherThanEnumOrder()
    {
        using var f = new Fixture(otherX: 600);
        typeof(TownModelLayer).GetField("EdgeAllowance", Flags)!.SetValue(f.layer,
            new Func<IReadOnlyList<string>, string, bool>((_, __) => true));
        var camera = f.Camera(600); f.Prepare(camera);
        CollectionAssert.AreEqual(new[] { "b03a-jerusalem-arches-v2", "b01-white-city-v2" }, f.RequestOrder);
    }


    [Test]
    public void EdgesWaitForADiagnosticAllowanceAndRejectUnaffordableNeighbours()
    {
        var towns = new[] { Place("focus", 0), Place("costly", 200), Place("cheap", 300) };
        CollectionAssert.AreEqual(new[] { "focus" }, Focus(towns, Vector3.zero));
        CollectionAssert.AreEqual(new[] { "focus", "cheap" }, Focus(towns, Vector3.zero,
            allowance: (resident, candidate) => resident.Count == 1 && candidate == "cheap"));
    }
    [Test]
    public void OneReadyTownDoesNotClaimTheEntireOriginalCatalogIsComplete()
    {
        using (var f = new Fixture())
        {
            var camera = f.Camera(); f.Prepare(camera); f.Arrive("b01-white-city-v2");
            Assert.IsTrue(f.Ready("a", camera)); Assert.IsFalse(f.layer.HasModels);
        }
    }
    [Test]
    public void ACameraThatStopsRenderingExpiresAfterTheNamedFrameGrace()
    {
        using (var f = new Fixture())
        {
            var camera = f.Camera(); f.Prepare(camera); f.Arrive("b01-white-city-v2");
            int start = Time.frameCount;
            Call(f.layer, "AdvanceCameraFrame", start + 2); f.Retire();
            Assert.IsFalse(f.Releases.ContainsKey("b01-white-city-v2"));
            Call(f.layer, "AdvanceCameraFrame", start + 3); f.Retire();
            Assert.AreEqual(1, f.Releases["b01-white-city-v2"]);
            Assert.IsFalse(f.Ready("a", camera));
        }
    }

    [Test]
    public void ProductionInstalledTownReleasesAtStartPlusTwo()
    {
        using (var f = new Fixture(configurePolicy: false))
        {
            Call(f.layer, "ConfigureProduction", ProductionResidency.Approved().Towns);
            var camera = f.Camera(); f.Prepare(camera); f.Arrive("b01-white-city-v2");
            Assert.IsTrue(f.Ready("a", camera));
            int start = Time.frameCount;
            Call(f.layer, "AdvanceCameraFrame", start + 1); f.Retire();
            Assert.IsFalse(f.Releases.ContainsKey("b01-white-city-v2"));
            Call(f.layer, "AdvanceCameraFrame", start + 2); f.Retire();
            Assert.AreEqual(1, f.Releases["b01-white-city-v2"]);
            Assert.IsFalse(f.Ready("a", camera));
        }
    }

    [Test]
    public void CameraPriorityUsesSortedOwnerIdsRatherThanInsertionOrder()
    {
        using (var f = new Fixture())
        {
            var a = f.Camera(); var b = f.Camera(8000);
            f.Prepare(b); f.Prepare(a);
            var ordered = (System.Collections.IEnumerable)Call(f.layer, "OrderedChoices")!;
            var ids = new List<int>();
            foreach (object choice in ordered)
                ids.Add(((Camera)choice.GetType().GetField("camera")!.GetValue(choice)!).GetInstanceID());
            var expected = new[] { a.GetInstanceID(), b.GetInstanceID() }; Array.Sort(expected);
            CollectionAssert.AreEqual(expected, ids);
        }
    }

    [Test]
    public void OverlappingFootprintsChooseTheNearestCentreBeforeTheOrdinalTieBreak()
    {
        var wide = new Bounds(new Vector3(500, 0, 0), new Vector3(2000, 100, 2000));
        var own = new Bounds(Vector3.zero, new Vector3(100, 100, 100));
        Assert.AreEqual("z-own", Focus(new[] { ("a-neighbour", wide), ("z-own", own) }, Vector3.zero)[0]);
    }

    [Test]
    public void ProvisionalConstantsDoNotAdmitAPrimaryBeforeExplicitConfiguration()
    {
        using var f = new Fixture(configurePolicy: false); var camera = f.Camera(); f.Prepare(camera);
        CollectionAssert.IsEmpty(f.Requests); Assert.IsFalse(f.a.forceRenderingOff);
        Assert.IsFalse((bool)typeof(TownModelLayer).GetProperty("SpatialPolicyConfigured", Flags)!.GetValue(f.layer)!);
        Call(f.layer, "ConfigureResidency", 10f, 20f, 0f, 0, "test only; no shipping acceptance");
        f.Prepare(camera); Assert.IsTrue(f.Requests.ContainsKey("b01-white-city-v2"));
    }
    [Test]
    public void SelectionUsesExplicitValuesRatherThanTheProvisionalEntryDistance()
    {
        var towns = new[] { Place("town", 1000) };
        var small = (string[])Call(null, "FocusedTowns", towns, Vector3.zero, null, null, 10f, 20f, 0f, 0)!;
        var large = (string[])Call(null, "FocusedTowns", towns, Vector3.zero, null, null, 1000f, 2000f, 0f, 0)!;
        CollectionAssert.IsEmpty(small); CollectionAssert.AreEqual(new[] { "town" }, large);
    }
    [Test]
    public void FailedNearOriginalKeepsTheKitWithoutAcquiringAWholeTownReplacement()
    {
        using var f = new Fixture(); var camera = f.Camera(); f.Prepare(camera);
        f.Answers["b01-white-city-v2"](null); f.Prepare(camera);
        Assert.IsFalse(f.a.forceRenderingOff); Assert.IsFalse(f.Ready("a", camera));
        Assert.IsFalse((bool)Call(f.layer, "WantsWholeTown", "a", camera)!,
            "null Near means code-built fallback, not a second costly representation");
    }

    [Test]
    public void ConfigurationWithoutDiagnosticEvidenceCannotEnableAdmission()
    {
        using var f = new Fixture(configurePolicy: false);
        var error = Assert.Throws<TargetInvocationException>(() =>
            Call(f.layer, "ConfigureResidency", 1000f, 2000f, 1000f, 0, ""));
        Assert.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>As <see cref="Settle"/>, but the request for <paramref name="failed"/> is answered with nothing (its bundle
        /// did not load).</summary>
        public void SettleFailing(Camera camera, string failed)
        {
            layer.PrepareCamera(camera);
            foreach (var pair in answers.ToList()) pair.Value(pair.Key == failed ? null : prefab);
            answers.Clear();
            layer.PrepareCamera(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. At 90 km it keeps its kit tile
    /// (#2378, owner, 3 November 2026, "Cities/towns only (Recommended)": the 1948 localities take no far-off copies).</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");
        }
        // Within the far band a village keeps its kit tile: no far-off copy (Q15 option a).
        var far = s.Camera(imwas.centre, 90_000f);
        s.Settle(far);
        Assert.IsFalse(s.layer.ReadyForTown("imwas", far), "Imwas at 90 km: no far-off copies for a village");
        Assert.IsFalse(kit.forceRenderingOff, "Imwas at 90 km: the 100x kit tile draws");
        Assert.IsTrue(close.forceRenderingOff, "Imwas at 90 km: the tile's close mesh gives way to the kit");
    }

    /// <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). Over Petah Tikva its kinds come first; over Tel Aviv at 30 km, below the close
    /// switch, Tel Aviv, Jaffa and Petah Tikva all load, the two major cities' models in place of their kits (owner,
    /// 7 November 2026, "Tal's models close (Recommended)").</summary>
    [Test]
    public void NeighbouringTownsOfTheFocusLoadToo()
    {
        using var s = new StreamedMap();
        var petah = s.Footprint("petah_tikva");
        var first = s.Camera(petah.centre, ThirtyKmM);
        s.Settle(first);
        Assert.IsTrue(s.layer.ReadyForTown("petah_tikva", first), "Petah Tikva at 30 km over it: admitted and ready");
        var petahKinds = s.layer.InstancesOf("petah_tikva").Select(m => TownModels.Ids[(int)m.Model]).ToHashSet(StringComparer.Ordinal);
        CollectionAssert.Contains(petahKinds, s.RequestOrder[0], "the focused town's kinds are asked first");
        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("petah_tikva", camera), "petah_tikva at 30 km over Tel Aviv: admitted and ready");
        foreach (var id in new[] { "tel_aviv", "jaffa" })
        {
            Assert.IsTrue(s.layer.ReadyForTown(id, camera), id + " at 30 km over Tel Aviv: a major city below the close switch, admitted and ready");
            Assert.IsTrue(s.kits.Find(id).GetComponent<MeshRenderer>().forceRenderingOff, id + " at 30 km over Tel Aviv: its kit gives way");
        }
        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: its building models");
        Assert.IsTrue(s.layer.ReadyForTown("tel_aviv", camera), "Tel Aviv beside Jaffa at 12 km: its building models");
    }

    /// <summary>Owner ruling, 7 November 2026, "Tal's models close (Recommended)" (it supersedes "Big blocks, every zoom",
    /// 6 November 2026, below the 40 km close switch; from 40 km out that ruling stands). In the player's streaming path and
    /// the production policy, each of the four cities in view keeps its kit at the widest zoom (250 km), the opening zoom
    /// (90 km) and the gameplay view (60 km): its building models are not admitted there and the kit never gives way. At
    /// 30 km and the closest zoom, below the close switch, Tal Heuberger's building models are admitted, the kit gives way
    /// and the models draw. A town with a whole-town model in view at 90 km (Petah Tikva) draws its far-off copies (owner,
    /// 3 November 2026, "Cities/towns only (Recommended)").</summary>
    [Test]
    public void TheFourCitiesKeepTheirKitsFarAndDrawTalsModelsClose()
    {
        using var s = new StreamedMap();
        var majors = s.map.Settlements.Where(x => TownModels.IsMajorCity(x.Id)).Select(x => x.Id).ToList();
        Assert.AreEqual(4, majors.Count, "the four major cities");
        // First, a fresh camera over Petah Tikva (beside Tel Aviv and Jaffa) at the opening zoom: it draws its far-off copies
        // (Q15 option a: the towns), and only far-off copies are asked for.
        var petah = s.Footprint("petah_tikva");
        var far = s.Camera(petah.centre, 90_000f);
        s.Settle(far);
        Assert.IsTrue(s.layer.ReadyForTown("petah_tikva", far), "Petah Tikva at 90 km: its far-off copies");
        Assert.IsTrue(s.kits.Find("petah_tikva").GetComponent<MeshRenderer>().forceRenderingOff, "Petah Tikva's kit gives way at 90 km");
        CollectionAssert.IsSubsetOf(s.layer.InstancesOf("petah_tikva").Select(m => CollectionCatalog.FarCopy(TownModels.Ids[(int)m.Model])).Distinct().ToList(),
            s.RequestOrder.Distinct().ToList(), "Petah Tikva's far-off copies are asked for");
        Assert.IsFalse(s.layer.ReadyForTown("tel_aviv", far), "Tel Aviv in the same view: its kit, no building models");
        CollectionAssert.IsNotEmpty(s.RequestOrder);
        // #2378: far off only far-off copies are asked for, never an original. (That no far-off copy of a kind only the major
        // cities place is asked for: TheMajorCitiesDrawTheirKitsFarAndTalsModelsBelowTheCloseSwitch.)
        foreach (var id in s.RequestOrder) Assert.IsTrue(CollectionCatalog.IsFarCopy(id), "far off, asked for an original: " + id);
        // A merged village tile never holds one of the four cities (AdmitInView decides a place by its first id).
        var viewPlaces = (System.Collections.IEnumerable)typeof(TownModelLayer).GetField("viewPlaces", Flags)!.GetValue(s.layer)!;
        foreach (var (ids, _) in viewPlaces.Cast<(string[] ids, Bounds bounds)>())
            if (ids.Length > 1) CollectionAssert.IsEmpty(ids.Intersect(majors).ToList(), string.Join(",", ids));
        foreach (var id in majors)
        {
            var at = s.Footprint(id).centre;
            Assert.Greater(s.layer.CountFor(id), 0, id + " has building models placed");
            var kit = s.kits.Find(id).GetComponent<MeshRenderer>();
            foreach (float d in new[] { CameraController.MaxDistance, 90_000f, GameplayM, ThirtyKmM, CameraController.MinDistance })
            {
                bool close = d <= TownModelLayer.CloseEnterM;
                var camera = s.Camera(at, d);
                string where = FormattableString.Invariant($"{id} at {d / 1000f} km");
                s.Settle(camera);
                Assert.AreEqual(close, s.layer.ReadyForTown(id, camera), where + (close ? ": building models admitted and ready" : ": building models not admitted"));
                Assert.AreEqual(close, kit.forceRenderingOff, where + (close ? ": the kit gives way" : ": the kit draws"));
                s.Submit(camera);
                if (close) Assert.Greater(s.layer.LastDrawn, 0, where + ": the building models draw");
                TestContext.WriteLine($"{where}: {s.layer.LastDrawn} instances in {s.layer.LastDraws} draws");
            }
        }
    }

    /// <summary>Owner ruling on #2267, 2 November 2026: "Shadows off far, then measure (Recommended)" ("Turn off these
    /// buildings' shadows beyond 40 km now"). Beyond the close switch the buildings (the far-off copies) draw without casting
    /// shadows (90 km and the 60 km gameplay view); below it every building casts as before (30 km and the closest zoom).
    /// Over Petah Tikva, a town with far-off copies: the four cities, whose building models this tested before, keep their
    /// kits from 40 km out (owner, 6 November 2026, "Big blocks, every zoom"; below 40 km they draw Tal's models: owner,
    /// 7 November 2026, "Tal's models close (Recommended)"), so take no far-off copies, and nothing draws far-off copies
    /// beyond the far band (250 km).</summary>
    [Test]
    public void TheBuildingsCastNoShadowsFarOff()
    {
        using var s = new StreamedMap();
        foreach (var id in new[] { "petah_tikva" })
        {
            var at = s.Footprint(id).centre;
            foreach (var (d, cast) in new[] { (90_000f, false), (GameplayM, false), (ThirtyKmM, true), (CameraController.MinDistance, true) })
            {
                var camera = s.Camera(at, d);
                string where = FormattableString.Invariant($"{id} at {d / 1000f} km");
                s.Settle(camera);
                s.Submit(camera);
                Assert.Greater(s.layer.LastDrawn, 0, where + ": the building models draw");
                Assert.AreEqual(cast ? s.layer.LastDrawn : 0, s.layer.LastShadowCasters, where + (cast ? ": every building casts" : ": no building casts"));
            }
        }
    }

    /// <summary>The v0.3.7 web perf fix: the web tier's last quality fallback step (QualityFallback.Steps, TownModelsFar)
    /// sets TownModelLayer.LowTier. Over Petah Tikva at the 30 km opening (CameraRig.StartDistance, below the close switch)
    /// the buildings then draw their far-off copies with no shadow casters instead of the originals with every building
    /// casting; clearing it puts the originals and their shadows back, both with the camera unmoved. (Over Petah Tikva, not
    /// Tel Aviv: Tel Aviv takes no far-off copies; it keeps its kit from 40 km out, owner, 6 November 2026, "Big blocks,
    /// every zoom", and the low tier counts as past the close switch.)</summary>
    [Test]
    public void TheLowTierDrawsTheFarCopiesWithoutShadowsAtTheOpeningAndClearingItPutsTheOriginalsBack()
    {
        using var s = new StreamedMap();
        var at = s.Footprint("petah_tikva").centre;
        var camera = s.Camera(at, CameraRig.StartDistance);
        try
        {
            s.Settle(camera); s.Submit(camera);
            Assert.IsTrue(s.layer.LastClose, "control: the opening is close, the originals draw");
            Assert.Greater(s.layer.LastDrawn, 0);
            Assert.AreEqual(s.layer.LastDrawn, s.layer.LastShadowCasters, "control: every building casts");

            TownModelLayer.LowTier = true;
            s.Settle(camera); s.Submit(camera);
            Assert.IsFalse(s.layer.LastClose, "the low tier is past the close switch at the opening");
            Assert.Greater(s.layer.LastDrawn, 0, "Petah Tikva's buildings still draw (the far copies)");
            Assert.AreEqual(0, s.layer.LastShadowCasters, "and cast no shadows");

            TownModelLayer.LowTier = false;
            s.Settle(camera); s.Submit(camera);
            Assert.IsTrue(s.layer.LastClose, "clearing it puts the originals back, the camera unmoved");
            Assert.AreEqual(s.layer.LastDrawn, s.layer.LastShadowCasters, "with their shadows");
        }
        finally { TownModelLayer.LowTier = false; }
    }

    /// <summary>The shadows follow the close switch with its hysteresis (TownModelLayer.CloseAt: in below CloseEnterM, 40 km,
    /// out above CloseExitM, 45 km). Over Petah Tikva, coming in: none at 90 km and at 42 km (inside the band, still far),
    /// all at 39 km; going out: all at 43 km (inside the band, still close), none at 46 km. (Over Petah Tikva, not Tel Aviv:
    /// Tel Aviv draws no building model from 40 km out, owner, 6 November 2026, "Big blocks, every zoom"; its own switch:
    /// TheMajorCitiesDrawTheirKitsFarAndTalsModelsBelowTheCloseSwitch.)</summary>
    [Test]
    public void TheBuildingsShadowsFollowTheCloseSwitchBothWays()
    {
        using var s = new StreamedMap();
        var at = s.Footprint("petah_tikva").centre;
        var camera = s.Camera(at, 90_000f);
        foreach (var (d, cast) in new[] { (90_000f, false), (42_000f, false), (39_000f, true), (43_000f, true), (46_000f, false) })
        {
            s.Pose(camera, at, d); s.Settle(camera); s.Submit(camera);
            string where = FormattableString.Invariant($"Petah Tikva at {d / 1000f} km");
            Assert.Greater(s.layer.LastDrawn, 0, where + ": the building models draw");
            Assert.AreEqual(cast ? s.layer.LastDrawn : 0, s.layer.LastShadowCasters, where + (cast ? ": every building casts" : ": no building casts"));
        }
    }

    /// <summary>The far view (the far band, where the far-off copies draw) is a common one: once settled, a far camera's draw
    /// submission allocates nothing (no frustum array per camera per frame). Over Petah Tikva at 90 km: the four cities keep
    /// their kits from 40 km out (owner, 6 November 2026, "Big blocks, every zoom"), and at 250 km no building model
    /// draws.</summary>
    [Test]
    public void AFarViewSubmitsWithoutAllocating()
    {
        using var s = new StreamedMap();
        var camera = s.Camera(s.Footprint("petah_tikva").centre, 90_000f);
        s.Settle(camera);
        var submit = (Action<UnityEngine.Rendering.ScriptableRenderContext, Camera>)Delegate.CreateDelegate(
            typeof(Action<UnityEngine.Rendering.ScriptableRenderContext, Camera>), s.layer, typeof(TownModelLayer).GetMethod("Submit", Flags)!);
        for (int i = 0; i < 3; i++) submit(default, camera);   // warm: list capacities, the instancing path
        Assert.IsFalse(s.layer.LastClose, "a far view");
        Assert.Greater(s.layer.LastDrawn, 0, "the far-off copies draw at 90 km");
        // The recorder must see an allocation of the size in question, so a pass is not vacuous.
        Assert.That(() => { var planes = new Plane[6]; GC.KeepAlive(planes); }, new UnityEngine.TestTools.Constraints.AllocatingGCMemoryConstraint());
        Assert.That(() => submit(default, camera), UnityEngine.TestTools.Constraints.Is.Not.AllocatingGCMemory(), "one far submission");
    }

    /// <summary>A failed building bundle in a town that draws far-off copies (Petah Tikva's first kind: its far-off copy at
    /// 90 km, the original at 2 km): the town keeps its code-built kit there (in this fixture no whole-town model stands in),
    /// the map draws on, the original is asked for once, the far-off copy once per visit of the far band (its lease retires
    /// at 2 km), and the layer warns once for each failed id. (Petah Tikva, not Tel Aviv's b01: Tel Aviv takes no far-off
    /// copies, keeping its kit from 40 km out, owner, 6 November 2026, "Big blocks, every zoom".)</summary>
    [Test]
    public void ACityWhoseBuildingBundleFailsKeepsItsKit()
    {
        using var s = new StreamedMap();
        string original = TownModels.Ids[(int)s.layer.InstancesOf("petah_tikva")[0].Model]; string far = CollectionCatalog.FarCopy(original);
        int warnings = 0;
        void Count(string message, string _, LogType type) { if (type == LogType.Warning && message.Contains(original)) warnings++; }
        Application.logMessageReceived += Count;
        try
        {
            var at = s.Footprint("petah_tikva").centre;
            var kit = s.kits.Find("petah_tikva").GetComponent<MeshRenderer>();
            var camera = s.Camera(at, 90_000f);
            foreach (var (d, failed) in new[] { (90_000f, far), (2_000f, original), (90_000f, far) })
            {
                s.Pose(camera, at, d); s.SettleFailing(camera, failed);
                string where = FormattableString.Invariant($"Petah Tikva at {d / 1000f} km");
                Assert.IsFalse(s.layer.ReadyForTown("petah_tikva", camera), where + ": not ready without " + failed);
                Assert.IsFalse(kit.forceRenderingOff, where + ": the kit draws");
                Assert.DoesNotThrow(() => s.Submit(camera), where);
            }
            Assert.AreEqual(2, s.RequestOrder.Count(id => id == far), "the far-off copy of " + original + " is asked for once per far visit");
            Assert.AreEqual(1, s.RequestOrder.Count(id => id == original), original + " is asked for once");
            Assert.AreEqual(2, warnings, "one warning for each failed id");
        }
        finally { Application.logMessageReceived -= Count; }
    }

    /// <summary>The 1.5 GB guard: zooming out to the 60 km gameplay view releases every original's lease and asks for
    /// far-off copies instead (#2378); until those arrive the kits draw again. The four cities in view are not admitted
    /// from 40 km out (owner, 6 November 2026, "Big blocks, every zoom"; below it they are: owner, 7 November 2026, "Tal's
    /// models close (Recommended)").</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);
        foreach (var id in s.RequestOrder) Assert.IsFalse(CollectionCatalog.IsFarCopy(id), "at 30 km the originals are asked for, not " + id);
        int originals = s.RequestOrder.Count;
        s.Pose(camera, imwas.centre, GameplayM);
        s.layer.PrepareCamera(camera); s.layer.RetireReleasedModels();
        // From 60 km over Imwas the view holds Jerusalem, Tel Aviv and Jaffa, not Haifa; none of them is admitted from 40 km
        // out (owner, 6 November 2026, "Big blocks, every zoom"; "Tal's models close (Recommended)", 7 November 2026, admits
        // them only below the close switch).
        var majors = s.map.Settlements.Where(x => TownModels.IsMajorCity(x.Id)).Select(x => x.Id).ToList();
        Assert.AreEqual(4, majors.Count, "the four major cities");
        CollectionAssert.IsEmpty(majors.Where(id => s.layer.AdmitsTown(id, camera)).ToList(), "no major city admitted at 60 km over Imwas");
        Assert.AreEqual(originals, s.Released, "every original's lease is released at 60 km");
        var residency = s.layer.ResidencySnapshot();
        Assert.AreEqual(0, residency.strongCacheRefs, "no original mesh or material is strongly referenced after unload");
        CollectionAssert.IsEmpty(residency.detailIds.Where(id => id.EndsWith("|Near", StringComparison.Ordinal)).ToList(),
            "no unloaded original remains in the Near residency snapshot");
        var asked = s.RequestOrder.Skip(originals).ToList();
        CollectionAssert.IsNotEmpty(asked, "the far-off copies are asked for at 60 km");
        foreach (var id in asked) Assert.IsTrue(CollectionCatalog.IsFarCopy(id), "at 60 km only far-off copies are asked for, not " + id);
        Assert.IsFalse(s.layer.ReadyForTown("imwas", camera), "no building models for a village at 60 km");
        Assert.IsFalse(kit.forceRenderingOff, "the kit tile draws again at 60 km");
    }

    /// <summary>#2378 (owner, 3 November 2026: "Ask Tal; allow them far off only"): over Petah Tikva a camera at 39 km
    /// asks for the originals and draws them; at 41 km and at 90 km it asks for the far-off copies ("&lt;id&gt;-far",
    /// CollectionCatalog.FarCopy) and never an original, and draws at least the town's instances (the copy stands in the
    /// original's matrix); every kind the town places is asked for at its tier. (Over Petah Tikva, not Tel Aviv: Tel Aviv
    /// takes no far-off copies, keeping its kit from 40 km out, owner, 6 November 2026, "Big blocks, every zoom".)</summary>
    [Test]
    public void BelowTheCloseSwitchTheOriginalsStreamAndBeyondItTheFarCopies()
    {
        using var s = new StreamedMap();
        var at = s.Footprint("petah_tikva").centre;
        var kinds = s.layer.InstancesOf("petah_tikva").Select(m => TownModels.Ids[(int)m.Model]).Distinct().ToList();
        var camera = s.Camera(at, CameraController.MaxDistance);
        foreach (var (d, far) in new[] { (39_000f, false), (41_000f, true), (90_000f, true) })
        {
            // Each pose starts from the widest zoom, where no building model is admitted (EditMode retires at once), so
            // every pose asks for its own kinds afresh: the new requests of each pose are checked for their tier, and Petah
            // Tikva's kinds against every request so far.
            s.Pose(camera, at, CameraController.MaxDistance); s.layer.PrepareCamera(camera); s.layer.RetireReleasedModels();
            Assert.AreEqual(0, s.layer.ResidencySnapshot().strongCacheRefs, "nothing held at the widest zoom");
            int before = s.RequestOrder.Count;
            s.Pose(camera, at, d);
            string where = FormattableString.Invariant($"Petah Tikva at {d / 1000f} km");
            s.Settle(camera);
            Assert.IsTrue(s.layer.ReadyForTown("petah_tikva", camera), where + ": ready");
            var asked = s.RequestOrder.Skip(before).Distinct().ToList();
            CollectionAssert.IsNotEmpty(asked, where);
            foreach (var id in asked) Assert.AreEqual(far, CollectionCatalog.IsFarCopy(id), where + ": asked for " + id);
            foreach (var kind in kinds) CollectionAssert.Contains(s.RequestOrder, far ? CollectionCatalog.FarCopy(kind) : kind, where);
            s.Submit(camera);
            Assert.GreaterOrEqual(s.layer.LastDrawn, s.layer.CountFor("petah_tikva"), where + ": Petah Tikva's instances drawn");
            Assert.AreEqual(!far, s.layer.LastClose, where + ": the close switch");
        }
    }

    /// <summary>The owner's bug of 6 November 2026 ("the look of the buildings in tel aviv changes when you change the zoom in
    /// a way that you first see the big buildings and them the small ones"), ruled "Big blocks, every zoom" and "Just the
    /// four (Recommended)" on 6 November 2026, then "Tal's models close (Recommended)" on 7 November 2026, which supersedes
    /// "Big blocks, every zoom" below the close switch: from 40 km out (TownModelLayer.CloseEnterM, out again above
    /// CloseExitM, 45 km, the hysteresis the other layers use) the major cities draw their code-built kit, its landmarks
    /// with it; below it Tal Heuberger's building models, as on main. One camera over each city's footprint centre walks
    /// from the widest zoom in through the far band and the close switch's band (42 km coming in: still far) to the closest
    /// zoom and out again (43 km going out: still close). Far, before the stream answers and once it has, the kit draws, the
    /// city's close mesh does not swap in and its building models are not ready; close, once settled, the models are ready,
    /// the kit gives way and the close mesh swaps in. The low tier at the 31 km opening counts as past the switch: the kit.
    /// Every kind only these cities place is asked for as an original, below the switch, and never as a far-off copy.</summary>
    [Test]
    public void TheMajorCitiesDrawTheirKitsFarAndTalsModelsBelowTheCloseSwitch()
    {
        using var s = new StreamedMap();
        var majors = s.map.Settlements.Where(x => TownModels.IsMajorCity(x.Id)).Select(x => x.Id).ToArray();
        Assert.AreEqual(4, majors.Length, "the four major cities (TheMajorCitiesAreThePlacesOfSixtyThousandOrMoreIn1945)");
        Assert.AreEqual(40_000f, TownModelLayer.CloseEnterM, "the close switch"); Assert.AreEqual(45_000f, TownModelLayer.CloseExitM, "its exit");
        (float d, bool close)[] walk = { (250_000f, false), (112_500f, false), (90_000f, false), (60_000f, false), (42_000f, false), (39_000f, true),
            (CameraRig.StartDistance, true), (6_000f, true), (43_000f, true), (46_000f, false), (101_000f, false), (250_000f, false) };
        foreach (var id in majors)
        {
            var at = s.Footprint(id).centre;
            var kit = s.kits.Find(id)?.GetComponent<MeshRenderer>();
            var close = s.kits.Find(id + KitLayer.CloseSuffix)?.GetComponent<MeshRenderer>();
            Assert.IsNotNull(kit, id + ": its kit"); Assert.IsNotNull(close, id + ": its close mesh");
            var camera = s.Camera(at, walk[0].d);
            void Far(string where)
            {
                Assert.IsFalse(s.layer.AdmitsTown(id, camera), where + ": building models not admitted");
                Assert.IsFalse(kit!.forceRenderingOff, where + ": the kit draws");
                Assert.IsTrue(close!.forceRenderingOff, where + ": the close mesh does not swap in");
                Assert.IsFalse(s.layer.ReadyForTown(id, camera), where + ": no building models");
            }
            void Close(string where)
            {
                Assert.IsTrue(s.layer.AdmitsTown(id, camera), where + ": building models admitted");
                Assert.IsTrue(s.layer.ReadyForTown(id, camera), where + ": building models ready");
                Assert.IsTrue(kit!.forceRenderingOff, where + ": the kit gives way");
                Assert.IsFalse(close!.forceRenderingOff, where + ": the close mesh swaps in");
                s.Submit(camera);
                Assert.IsTrue(s.layer.LastClose, where + ": the close switch");
                Assert.Greater(s.layer.LastDrawn, 0, where + ": the building models draw");
            }
            foreach (var (d, near) in walk)
            {
                string where = FormattableString.Invariant($"{id} at {d / 1000f} km");
                s.Pose(camera, at, d); s.layer.PrepareCamera(camera);
                if (near) Assert.IsTrue(s.layer.AdmitsTown(id, camera), where + ", before the stream answers: admitted");
                else Far(where + ", before the stream answers");
                s.Settle(camera);
                if (near) Close(where + ", settled"); else Far(where + ", settled");
            }
            try
            {
                TownModelLayer.LowTier = true;
                string where = FormattableString.Invariant($"{id} at {CameraRig.StartDistance / 1000f} km on the low tier");
                s.Pose(camera, at, CameraRig.StartDistance); s.layer.PrepareCamera(camera);
                Far(where + ", before the stream answers");
                s.Settle(camera);
                Far(where + ", settled");
            }
            finally { TownModelLayer.LowTier = false; }
        }
        // The kinds only the major cities place, from the data: every other place's instances (the other game settlements and
        // the 1948 localities) leave them out.
        var perPlace = (System.Collections.IDictionary)typeof(TownModelLayer).GetField("perPlace", Flags)!.GetValue(s.layer)!;
        var elsewhere = new HashSet<TownModel>();
        foreach (string place in perPlace.Keys)
            if (!majors.Contains(place)) foreach (var m in s.layer.InstancesOf(place)) elsewhere.Add(m.Model);
        var cityOnly = majors.SelectMany(id => s.layer.InstancesOf(id)).Select(m => m.Model).Where(k => !elsewhere.Contains(k))
            .Distinct().OrderBy(k => k).ToList();
        TestContext.WriteLine("kinds only the major cities place: " + string.Join(", ", cityOnly.Select(k => TownModels.Ids[(int)k])));
        CollectionAssert.IsNotEmpty(cityOnly, "the major cities place kinds of their own (else the check below is vacuous)");
        foreach (var kind in cityOnly)
        {
            string original = TownModels.Ids[(int)kind];
            CollectionAssert.Contains(s.RequestOrder, original, original + " is asked for below the close switch");
            CollectionAssert.DoesNotContain(s.RequestOrder, CollectionCatalog.FarCopy(original), original + "'s far-off copy is never asked for");
        }
    }

    /// <summary>The major cities are a data predicate (owner, 6 November 2026, "Just the four (Recommended)"): a place is one
    /// when its 1945 population (content/map/settlement_population_1945.yaml, the table MapScene.Build hands the kits) is at
    /// least TownModels.MajorCityPopulation, 60,000. Over every game settlement and 1948 locality on the map that is exactly
    /// Haifa, Jaffa, Jerusalem and Tel Aviv; the next place below it, Gaza (34,250), is not one.</summary>
    [Test]
    public void TheMajorCitiesAreThePlacesOfSixtyThousandOrMoreIn1945()
    {
        Assert.AreEqual(60_000, TownModels.MajorCityPopulation, "the threshold");
        bool Major(string id) => TownModels.IsMajorCity(id);
        EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
        try
        {
            var map = UnityEngine.Object.FindFirstObjectByType<MapScene>(); map.Build();
            var places = map.Settlements.Select(x => x.Id).Concat(map.Localities.Select(p => p.Settlement.Id)).Distinct().ToList();
            CollectionAssert.AreEquivalent(new[] { "haifa", "jaffa", "jerusalem", "tel_aviv" }, places.Where(Major).ToList(), "the major cities");
            CollectionAssert.AreEquivalent(TownLandmarksTests.BigCities, places.Where(Major).ToList(), "the tests' own list agrees");
            var next = places.Where(id => !Major(id)).OrderByDescending(id => KitPopulation.Of(id)).ThenBy(id => id, StringComparer.Ordinal).First();
            Assert.AreEqual("gaza", next, "the next place below the threshold");
            Assert.AreEqual(34_250, KitPopulation.Of("gaza"), "Gaza's 1945 population");
            Assert.IsFalse(Major("gaza"), "Gaza is not a major city");
        }
        finally
        {
            EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
            VisualToggles.Clear();
        }
    }

    /// <summary>The production view admission (ConfigureProduction) on a synthetic layer: towns and merged village tiles wired
    /// as KitLayer wires them (explicit town ids, renderer identities and tile ids), in the player's streaming path. Each
    /// model kind is answered only when the test says so.</summary>
    sealed class ViewFixture : IDisposable
    {
        readonly FieldInfo acquire;
        readonly object? previousAcquire;
        readonly GameObject root, prefab;
        readonly Material material;
        readonly List<GameObject> cameras = new List<GameObject>();
        public readonly TownModelLayer layer;
        public readonly List<string> RequestOrder = new List<string>();
        public readonly Dictionary<string, Action<GameObject?>> Answers = new Dictionary<string, Action<GameObject?>>();
        public readonly Dictionary<string, int> Requests = new Dictionary<string, int>(), Releases = new Dictionary<string, int>();
        public readonly Dictionary<string, MeshRenderer> Kits = new Dictionary<string, MeshRenderer>(), Closes = new Dictionary<string, MeshRenderer>();
        /// <param name="towns">Game towns: one kit renderer each, named and identified by the town id.</param>
        /// <param name="tiles">Merged locality tiles: a kit renderer and its close mesh, carrying these villages.</param>
        public ViewFixture(IReadOnlyList<SettlementKits.ModelInstance> items, IReadOnlyList<string> towns,
            IReadOnlyList<(string name, string[] villages)> tiles)
        {
            acquire = typeof(TownModelLayer).GetField("ModelAcquire", Flags)!;
            previousAcquire = acquire.GetValue(null);
            acquire.SetValue(null, new Func<string, CollectionDetail, Action<GameObject?>, IDisposable>((id, _, done) =>
            {
                Requests.TryGetValue(id, out int n); Requests[id] = n + 1; Answers[id] = done; RequestOrder.Add(id);
                return new Release(() => { Releases.TryGetValue(id, out int count); Releases[id] = count + 1; });
            }));
            root = new GameObject("view admission fixture");
            // Submit draws with Graphics.RenderMeshInstanced, which needs an instancing material (as the originals' are).
            prefab = GameObject.CreatePrimitive(PrimitiveType.Cube); prefab.name = "stub original";
            var renderer = prefab.GetComponent<MeshRenderer>();
            material = new Material(renderer.sharedMaterial) { enableInstancing = true }; renderer.sharedMaterial = material;
            layer = root.AddComponent<TownModelLayer>();
            var swaps = new List<(Renderer kit, Renderer? close)>();
            var townIds = new Dictionary<Renderer, string>();
            var tileIds = new Dictionary<Renderer, string[]>();
            MeshRenderer Child(string name) { var r = new GameObject(name).AddComponent<MeshRenderer>(); r.transform.SetParent(root.transform); return r; }
            foreach (string town in towns) { var kit = Child(town); Kits[town] = kit; swaps.Add((kit, null)); townIds[kit] = town; }
            foreach (var (name, villages) in tiles)
            {
                var kit = Child(name); var close = Child(name + KitLayer.CloseSuffix);
                Kits[name] = kit; Closes[name] = close; swaps.Add((kit, close)); tileIds[kit] = villages;
            }
            // KitLayer's order: the shipping policy, then Init. The player streams every kind (no editor model list); private-field
            // reflection only stands in for Application.isPlaying, as StreamedMap does.
            layer.ConfigureProduction(ProductionResidency.Approved().Towns);
            typeof(TownModelLayer).GetField("suppressMissingLog", Flags)!.SetValue(layer, true);
            layer.Init(items, null, swaps, towns, townIds, tileIds);
            typeof(TownModelLayer).GetField("streaming", Flags)!.SetValue(layer, true);
            layer.EdgeAllowance = null;
        }
        /// <summary>One 100 m building of <paramref name="model"/> for place <paramref name="id"/> at ground (x, z).</summary>
        public static SettlementKits.ModelInstance Item(string id, TownModel model, float x, float z) =>
            new SettlementKits.ModelInstance(id, model, Matrix4x4.identity, new Vector2(x, z), 0, 100, 100, 0, 100);
        /// <summary>A close camera whose view reaches the ground (CameraRig.Init's clip planes), square, 60 degree FOV.</summary>
        public Camera Camera(Vector3 position, Quaternion rotation)
        {
            var go = new GameObject("view admission camera"); cameras.Add(go); var camera = go.AddComponent<Camera>();
            camera.fieldOfView = 60f; camera.aspect = 1f; camera.nearClipPlane = 50f; camera.farClipPlane = 1_000_000f;
            camera.transform.SetPositionAndRotation(position, rotation);
            return camera;
        }
        /// <summary>The 10 km view used below: from (0, 8 km, -6 km) at the origin, so its ground focus is the origin.</summary>
        public Camera TenKmAtOrigin()
        {
            var position = new Vector3(0f, 8000f, -6000f);
            return Camera(position, Quaternion.LookRotation(-position));
        }
        public void Arrive(TownModel model) => Answers[TownModels.Ids[(int)model]](prefab);
        public void Submit(Camera camera) =>
            typeof(TownModelLayer).GetMethod("Submit", Flags)!.Invoke(layer, new object[] { default(UnityEngine.Rendering.ScriptableRenderContext), camera });
        public void Dispose()
        {
            UnityEngine.Object.DestroyImmediate(root);
            foreach (var c in cameras) UnityEngine.Object.DestroyImmediate(c);
            acquire.SetValue(null, previousAcquire);
            UnityEngine.Object.DestroyImmediate(prefab); UnityEngine.Object.DestroyImmediate(material);
        }
    }

    /// <summary>A merged village tile swaps as one (owner ruling, 31 Oct 2026, "Load all in view (Recommended)"): with two
    /// villages of different model kinds and only one kind delivered, the tile keeps its kit, its close mesh stays off and none
    /// of its buildings draw (else they would stand on the kit houses); once the second kind arrives, the tile swaps and
    /// both draw.</summary>
    [Test]
    public void APartlyReadyVillageTileKeepsItsKitAndDrawsNoneOfItsBuildings()
    {
        using var f = new ViewFixture(new[] {
            ViewFixture.Item("village_a", TownModel.B16Farmhouse, 200f, 0f),
            ViewFixture.Item("village_b", TownModel.B17CourtyardHouse, -200f, 0f) },
            Array.Empty<string>(), new[] { ("Localities 0,0", new[] { "village_a", "village_b" }) });
        var kit = f.Kits["Localities 0,0"]; var close = f.Closes["Localities 0,0"];
        var camera = f.TenKmAtOrigin();
        f.layer.PrepareCamera(camera);
        CollectionAssert.AreEquivalent(new[] { TownModels.Ids[(int)TownModel.B16Farmhouse], TownModels.Ids[(int)TownModel.B17CourtyardHouse] },
            f.RequestOrder, "both villages' kinds are asked for");

        f.Arrive(TownModel.B16Farmhouse); f.layer.PrepareCamera(camera);
        Assert.IsTrue(f.layer.ReadyForTown("village_a", camera), "precondition: village_a's kind arrived and it is admitted");
        Assert.IsFalse(f.layer.ReadyForTown("village_b", camera), "precondition: village_b's kind has not arrived");
        Assert.IsFalse(kit.forceRenderingOff, "a partly ready tile keeps its kit houses");
        Assert.IsTrue(close.forceRenderingOff, "a partly ready tile's close mesh stays off");
        f.Submit(camera);
        Assert.AreEqual(0, f.layer.LastDrawn, "no building of a partly ready tile draws, not even the ready village's");

        f.Arrive(TownModel.B17CourtyardHouse); f.layer.PrepareCamera(camera);
        Assert.IsTrue(kit.forceRenderingOff, "control: the complete tile swaps");
        Assert.IsFalse(close.forceRenderingOff, "control: the complete tile's close mesh draws");
        f.Submit(camera);
        Assert.AreEqual(2, f.layer.LastDrawn, "control: both villages' buildings draw");
    }

    /// <summary>Nearest first, with no focused town: the screen centre is on open ground between three places. The requests
    /// follow ground distance from the screen centre, which differs here from the id order, the model-enum order, the
    /// admission (list) order and the order by distance from the camera's own position.</summary>
    [Test]
    public void WithNoFocusedTownTheViewLoadsNearestToTheScreenCentreFirst()
    {
        // Ground distance from the focus (0, 0): c_near 2.0 km, b_mid 3.5 km, a_far 5.0 km. From the camera's ground point
        // (0, -6 km): b_mid 2.5 km, a_far 7.8 km, c_near 8.0 km.
        using var f = new ViewFixture(new[] {
            ViewFixture.Item("a_far", TownModel.B01WhiteCity, 5000f, 0f),
            ViewFixture.Item("b_mid", TownModel.B16Farmhouse, 0f, -3500f),
            ViewFixture.Item("c_near", TownModel.B32CargoShed, 0f, 2000f) },
            new[] { "a_far", "c_near" }, new[] { ("Localities 0,-1", new[] { "b_mid" }) });
        var camera = f.TenKmAtOrigin();
        Assert.IsTrue(CollectionResidencyView.TryGroundFocus(camera, out var focus), "precondition: the view has a ground focus");
        Assert.Less(new Vector2(focus.x, focus.z).magnitude, 1f, "precondition: the screen centre is the origin");
        f.layer.PrepareCamera(camera);
        foreach (var id in new[] { "a_far", "c_near" })
            Assert.IsFalse(f.layer.WantsTown(id, camera), id + ": no town is focused, so the primary-first order has nothing to add");
        CollectionAssert.AreEqual(new[] {
            TownModels.Ids[(int)TownModel.B32CargoShed], TownModels.Ids[(int)TownModel.B16Farmhouse], TownModels.Ids[(int)TownModel.B01WhiteCity] },
            f.RequestOrder, "c_near, then b_mid's tile, then a_far: nearest the screen centre first");
    }

    /// <summary>ViewKeepM hysteresis: a place admitted inside the 3 km margin stays admitted while it is 3 to 6 km outside the
    /// view (a pan does not drop and reload its kind), is released beyond 6 km, and is not re-admitted at 3 to 6 km.</summary>
    [Test]
    public void AViewAdmittedPlaceStaysToSixKmOutsideTheViewAndNotBeyond()
    {
        const float HeightM = 10_000f, HalfM = 50f;   // a straight-down 10 km view; the place is a 100 m box at the origin
        using var f = new ViewFixture(new[] { ViewFixture.Item("p", TownModel.B01WhiteCity, 0f, 0f) }, new[] { "p" },
            Array.Empty<(string, string[])>());
        string kind = TownModels.Ids[(int)TownModel.B01WhiteCity];
        var camera = f.Camera(new Vector3(0f, HeightM, 0f), Quaternion.LookRotation(Vector3.down, Vector3.forward));
        // The view's right edge on the ground (y = 0, the box's widest-reaching face) is HeightM tan(30 degrees) right of
        // the camera; place the camera so the box's near side is gapM beyond it.
        float halfWidthM = HeightM * Mathf.Tan(30f * Mathf.Deg2Rad);
        void Outside(float gapM)
        {
            camera.transform.position = new Vector3(-HalfM - halfWidthM - gapM, HeightM, 0f);
            f.layer.PrepareCamera(camera); f.layer.RetireReleasedModels();
        }
        Outside(1500f);
        Assert.IsTrue(f.layer.AdmitsTown("p", camera), "1.5 km outside the view: inside the 3 km admission margin");
        Assert.IsFalse(f.layer.WantsTown("p", camera), "precondition: admitted by view, not by focus");
        Assert.AreEqual(1, f.Requests[kind]);
        Outside(4500f);
        Assert.IsTrue(f.layer.AdmitsTown("p", camera), "4.5 km outside: kept to 6 km");
        Assert.IsFalse(f.Releases.ContainsKey(kind), "kept: the kind is not released");
        Outside(7500f);
        Assert.IsFalse(f.layer.AdmitsTown("p", camera), "7.5 km outside: beyond the 6 km keep");
        Assert.AreEqual(1, f.Releases[kind], "dropped: the kind is released");
        Outside(4500f);
        Assert.IsFalse(f.layer.AdmitsTown("p", camera), "4.5 km outside, not admitted before: beyond the 3 km admission margin");
        Assert.AreEqual(1, f.Requests[kind], "no new request outside the admission margin");
    }

    /// <summary>#2099, as #2046 for the camp tents: the edit-mode render callback (Submit, the beginCameraRendering handler
    /// itself) never acquires or retires building models mid-render. A change of demand only marks the layer, and LateUpdate
    /// reconciles it, as in play mode; once settled, the next render marks nothing. A direct PrepareCamera (no render) still
    /// reconciles at once.</summary>
    [Test]
    public void AnEditModeRenderCallbackDefersTheTownModelsToLateUpdate()
    {
        Assert.IsFalse(Application.isPlaying, "the edit-mode render path");
        const float HeightM = 10_000f, HalfM = 50f;   // a straight-down 10 km view; the place is a 100 m box at the origin
        using var f = new ViewFixture(new[] { ViewFixture.Item("p", TownModel.B01WhiteCity, 0f, 0f) }, new[] { "p" },
            Array.Empty<(string, string[])>());
        string kind = TownModels.Ids[(int)TownModel.B01WhiteCity];
        var lateUpdate = typeof(TownModelLayer).GetMethod("LateUpdate", Flags)!;
        var dirty = typeof(TownModelLayer).GetField("reconcileDirty", Flags)!;
        var camera = f.Camera(new Vector3(0f, HeightM, 0f), Quaternion.LookRotation(Vector3.down, Vector3.forward));

        f.Submit(camera);
        Assert.IsTrue(f.layer.AdmitsTown("p", camera), "the close camera admits the place");
        Assert.IsFalse(f.Requests.ContainsKey(kind), "but nothing is acquired inside the render callback");
        Assert.IsTrue((bool)dirty.GetValue(f.layer)!, "the render marks the change for LateUpdate");
        lateUpdate.Invoke(f.layer, null);
        Assert.AreEqual(1, f.Requests[kind], "LateUpdate acquires the kind");
        f.Submit(camera);
        Assert.IsFalse((bool)dirty.GetValue(f.layer)!, "settled: the next render marks nothing (no update request every render)");

        // 7.5 km beyond the view's right edge: past the 6 km keep (AViewAdmittedPlaceStaysToSixKmOutsideTheViewAndNotBeyond).
        camera.transform.position = new Vector3(-HalfM - HeightM * Mathf.Tan(30f * Mathf.Deg2Rad) - 7500f, HeightM, 0f);
        f.Submit(camera); f.layer.RetireReleasedModels();
        Assert.IsFalse(f.layer.AdmitsTown("p", camera), "the camera no longer admits the place");
        Assert.IsFalse(f.Releases.ContainsKey(kind), "but nothing is released inside the render callback");
        lateUpdate.Invoke(f.layer, null); f.layer.RetireReleasedModels();
        Assert.AreEqual(1, f.Releases[kind], "LateUpdate releases the kind");

        camera.transform.position = new Vector3(0f, HeightM, 0f);
        f.layer.PrepareCamera(camera);
        Assert.AreEqual(2, f.Requests[kind], "a direct call (no render) acquires at once");
    }

    /// <summary>#2099: the deferred change is applied in LateUpdate, which edit mode runs only for an [ExecuteAlways] layer.</summary>
    [Test]
    public void TheDeferringLayersRunInEditMode()
    {
        foreach (var type in new[] { typeof(TownModelLayer), typeof(TownLandmarks), typeof(SpecialBuildingModels) })
            Assert.IsTrue(type.IsDefined(typeof(ExecuteAlways), false), type.Name + " is [ExecuteAlways]");
    }
}