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.

Map: MATKOT's civilian figures at the towns, kibbutzim and transit camps (refs #666) (#1023)

Eyal Goland64c6f7482a3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 670465b11..abf4c3050 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,6 +41,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
the ibex on level ledges of the Judean Desert west of the Dead Sea, the hyenas in the hills of Mount Carmel and the
central hill country, the ranges their sources give. Seeded, so the same spots every game; streamed after the first
frame (refs #670, #663).
+- Map: MATKOT's five civilian figures from The 1948 Collection stand in small seeded groups beside the cities, towns,
+ kibbutzim and the moshav (a townsman, a smith and a nurse), and an arriving man and woman beside each transit camp from
+ the day it is placed. They are scenery, never units; the static figures stream after the first frame and the animated
+ ones only at close zoom (refs #666, #663).
### Changed
- The population-tier badge on the twelve city and town pills keeps the values it shipped with, now owner-approved: tiers 1
diff --git a/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs b/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs
new file mode 100644
index 000000000..9fc4a3937
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs
@@ -0,0 +1,300 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Game.Map.Kits;
+using Statecraft.Game.Map.Units;
+using Statecraft.Sim;
+using UnityEngine;
+using UnityEngine.Rendering;
+
+namespace Statecraft.Game.Map.Collection
+{
+ /// <summary>Small groups of MATKOT's civilian figures at the Israeli towns, kibbutzim, moshavim and the player's transit
+ /// camps (issue #666 and #663's owner ruling that every delivered model is used). They are period-generic ambience,
+ /// never units and never simulation state. C02, C03 and C13 stand at the settled places; C01 and C10 stand at a transit
+ /// camp from the day it is placed. The Arab towns get none of this set: #666 maps it to the towns, kibbutzim, moshavim and
+ /// camps, and the Collection's Arab villager figure (#708, waiting on its licence line) is the one made for them. Which
+ /// figures stand at the Arab towns until then is an owner question on the pull request.
+ ///
+ /// Far static meshes stream after the first frame through <see cref="CollectionStream"/>. Near skinned meshes and their
+ /// idle clips are not even requested until a camera enters close zoom. A missing bundle or prefab fails open: the affected
+ /// figures stay off the map, the far mesh remains when a near mesh fails, and play continues. Repeated figures share the
+ /// collection prefabs' GPU-instanced materials.</summary>
+ public sealed class CivilianPeople : MonoBehaviour
+ {
+ public const string Name = "CivilianPeople";
+
+ public const string ArrivingMan = "figure-c01-arriving-man-v2", Townsman = "figure-c02-townsman-v2",
+ Craftsman = "figure-c03-smith-carpenter-v2", Woman = "figure-c10-woman-blue-dress-v2", Nurse = "figure-c13-nurse-v2";
+
+ public static readonly string[] SettledModels = { Townsman, Craftsman, Nurse };
+ public static readonly string[] CampModels = { ArrivingMan, Woman };
+ public static readonly string[] SettledTypes = { "city", "town", "kibbutz", "moshav" };
+
+ public const int SettledGroupSize = 3; // design value: one small, legible group at a permanent settlement
+ public const int CampGroupSize = 2; // design value: one arriving pair at a transit camp
+ public const float FigureScale = UnitShowcase.FigureScale; // design value: reuse the established symbolic figure scale
+ public const float FigureHeightM = UnitBadge.FigureHeightM * FigureScale;
+ public const float FigureSpacingM = 1200f; // design value: separates silhouettes without reading as a crowd
+ public const float FigureClearanceM = 500f; // design value: conservative half-width/clearance for one symbolic figure
+ public const float LabelClearanceM = 400f; // design value: extra ground outside the labelled settlement footprint
+ public const float SearchStepM = 1400f; // design value: outward step when the nearest ring is occupied
+ public const int SearchRings = 8, SearchBearings = 16; // design values: bounded cosmetic placement search
+ // The near (animated) figures from 40 km in, the far ones again beyond 45 km: the close-zoom band of the town models
+ // (TownModelLayer), so the people change detail with the buildings they stand by.
+ public const float CloseEnterM = TownModelLayer.CloseEnterM, CloseExitM = TownModelLayer.CloseExitM;
+
+ internal static Action<string, CollectionDetail, Action<GameObject?>> Request = CollectionStream.Request;
+
+ public readonly struct Want : IEquatable<Want>
+ {
+ public readonly string Key, Model; public readonly Vector3 At; public readonly float Yaw;
+ public Want(string key, string model, Vector3 at, float yaw) { Key = key; Model = model; At = at; Yaw = yaw; }
+ public bool Equals(Want other) => Key == other.Key && Model == other.Model && At == other.At && Yaw == other.Yaw;
+ public override bool Equals(object? obj) => obj is Want other && Equals(other);
+ public override int GetHashCode() => (Key, Model, At, Yaw).GetHashCode();
+ }
+
+ /// <summary>One successfully placed figure (test and diagnostics aid).</summary>
+ public readonly struct PlacedFigure
+ {
+ public readonly string Key, Model; public readonly Vector3 At; public readonly float Yaw;
+ public PlacedFigure(Want want) { Key = want.Key; Model = want.Model; At = want.At; Yaw = want.Yaw; }
+ }
+
+ /// <summary>Builds the deterministic presentation plan. Every group is outside its settlement or camp footprint,
+ /// which also keeps it clear of the name pill anchored there, and clear of route corridors, water, unit tokens and
+ /// all earlier groups. Settlement and placement order are their stable source-file/state order.</summary>
+ public static List<Want> Wants(MapScene map, DateTime date, IEnumerable<Placement> placements, Content content)
+ {
+ var wants = new List<Want>();
+ if (map == null || map.Terrain == null || map.Hexes == null) return wants;
+ var ground = PlacementLayer.CampGround(map);
+ var radii = new Dictionary<string, float>(StringComparer.Ordinal);
+ foreach (var (_, radius, id) in map.KitFootprints) if (!radii.ContainsKey(id)) radii[id] = radius;
+ var reserved = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();
+ var taken = new List<(Vector2 centre, float radius)>();
+
+ foreach (var settlement in map.Settlements)
+ {
+ if (!SettledTypes.Contains(settlement.Type)) continue;
+ var world = map.Frame.ToWorld(settlement.Lon, settlement.Lat, 0f);
+ float radius = radii.TryGetValue(settlement.Id, out var kitRadius)
+ ? kitRadius : 0.5f * SettlementPlacer.MarkerHeightM(settlement.Type);
+ AddGroup(settlement.Id, new Vector2(world.x, world.z), radius, SettledModels, date, ground, reserved, taken, wants);
+ }
+
+ foreach (var placement in placements)
+ {
+ if (placement.Action != MapActions.TransitCamp || date < placement.Date) continue;
+ var hex = content.HexAt(placement.Q, placement.R);
+ if (hex == null) continue;
+ var world = map.Frame.ToWorld(hex.Lon, hex.Lat, 0f);
+ string key = $"{placement.Action}_{placement.Q}_{placement.R}";
+ // Reserve the whole hex around the later-built ma'abara. Its seeded kit may move inside the hex while it
+ // searches for room; the people therefore stand just outside it rather than assuming an unsourced camp plan.
+ AddGroup(key, new Vector2(world.x, world.z), map.Hexes.hex_size_km * 1000f, CampModels, placement.Date,
+ ground, reserved, taken, wants);
+ }
+ return wants;
+ }
+
+ static void AddGroup(string key, Vector2 anchor, float anchorRadius, IReadOnlyList<string> models, DateTime from,
+ KitGround ground, List<(Vector2 centre, float radius)> reserved, List<(Vector2 centre, float radius)> taken, List<Want> wants)
+ {
+ var random = new KitRandom(key, 666UL);
+ float turn = random.Range(0f, 360f);
+ var offsets = Offsets(models.Count, turn);
+ float groupRadius = offsets.Max(o => o.magnitude) + FigureClearanceM;
+
+ bool Free(Vector2 centre, float radius)
+ {
+ if (!TownLandmarks.Clear(centre, radius, reserved) || !TownLandmarks.Clear(centre, radius, taken)) return false;
+ if (!ground.Inside(centre.x - radius, centre.y - radius) || !ground.Inside(centre.x + radius, centre.y + radius)) return false;
+ if (ground.OnRoute(centre, radius) || ground.OnToken(centre, radius) || ground.OnToken(centre, radius, from)) return false;
+ foreach (var offset in offsets)
+ {
+ var p = centre + offset;
+ if (ground.Water(p.x, p.y)) return false;
+ }
+ return true;
+ }
+
+ Vector2? spot = null;
+ int firstBearing = random.Range(0, SearchBearings);
+ for (int ring = 0; ring < SearchRings && spot == null; ring++)
+ {
+ float distance = anchorRadius + LabelClearanceM + groupRadius + ring * SearchStepM;
+ for (int step = 0; step < SearchBearings; step++)
+ {
+ float angle = (firstBearing + step) * (360f / SearchBearings) * Mathf.Deg2Rad;
+ var candidate = anchor + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * distance;
+ if (Free(candidate, groupRadius)) { spot = candidate; break; }
+ }
+ }
+ if (spot == null) return;
+ taken.Add((spot.Value, groupRadius));
+ for (int i = 0; i < models.Count; i++)
+ {
+ var p = spot.Value + offsets[i];
+ wants.Add(new Want($"{key}/{i}", models[i], new Vector3(p.x, ground.Y(p.x, p.y), p.y), random.Range(0f, 360f)));
+ }
+ }
+
+ static Vector2[] Offsets(int count, float turn)
+ {
+ var offsets = new Vector2[count];
+ float radius = count == 2 ? FigureSpacingM * 0.5f : FigureSpacingM / Mathf.Sqrt(3f);
+ float phase = turn * Mathf.Deg2Rad;
+ for (int i = 0; i < count; i++)
+ {
+ float angle = phase + i * 2f * Mathf.PI / count;
+ offsets[i] = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius;
+ }
+ return offsets;
+ }
+
+ MapScene? map;
+ List<Want> wanted = new List<Want>();
+ readonly Dictionary<(string Model, CollectionDetail Detail), GameObject?> prefabs =
+ new Dictionary<(string, CollectionDetail), GameObject?>();
+ readonly HashSet<(string Model, CollectionDetail Detail)> asked = new HashSet<(string, CollectionDetail)>();
+ readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();
+ readonly List<(Renderer[] Far, Renderer[] Near)> pairs = new List<(Renderer[], Renderer[])>();
+ bool lastClose;
+
+ public readonly List<PlacedFigure> Placed = new List<PlacedFigure>();
+ public readonly List<string> Missing = new List<string>();
+ public IReadOnlyList<Want> Wanted => wanted;
+
+ public static CivilianPeople? ShowAt(MapScene map, DateTime date, IEnumerable<Placement> placements, Content content)
+ {
+ if (map == null || map.Terrain == null || map.Hexes == null) return null;
+ var layer = map.Terrain.transform.Find(Name)?.GetComponent<CivilianPeople>();
+ if (layer == null)
+ {
+ var go = new GameObject(Name);
+ go.transform.SetParent(map.Terrain.transform, false);
+ layer = go.AddComponent<CivilianPeople>();
+ layer.map = map;
+ }
+ layer.Show(date, placements, content);
+ return layer;
+ }
+
+ void Show(DateTime at, IEnumerable<Placement> nextPlacements, Content nextContent)
+ {
+ var next = Wants(map!, at, nextPlacements, nextContent);
+ if (next.SequenceEqual(wanted)) return;
+ wanted = next;
+ Ask(CollectionDetail.Far);
+ Rebuild();
+ }
+
+ void Ask(CollectionDetail detail)
+ {
+ foreach (var model in wanted.Select(w => w.Model).Distinct())
+ {
+ var key = (model, detail);
+ if (!asked.Add(key)) continue;
+ Request(model, detail, prefab => OnModel(model, detail, prefab));
+ }
+ }
+
+ void OnModel(string model, CollectionDetail detail, GameObject? prefab)
+ {
+ if (this == null) return;
+ prefabs[(model, detail)] = prefab;
+ if (prefab == null)
+ Debug.LogWarning($"PEOPLE: {model} {detail.ToString().ToLowerInvariant()} did not stream; "
+ + (detail == CollectionDetail.Far ? "its civilians are not drawn" : "its far civilians remain") + ", and the map plays on.");
+ Rebuild();
+ }
+
+ void Rebuild()
+ {
+ for (int i = transform.childCount - 1; i >= 0; i--)
+ {
+ var old = transform.GetChild(i).gameObject;
+ if (Application.isPlaying) { old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);
+ }
+ pairs.Clear(); Placed.Clear(); Missing.Clear();
+ var parents = new Dictionary<string, Transform>(StringComparer.Ordinal);
+ foreach (var want in wanted)
+ {
+ bool farKnown = prefabs.TryGetValue((want.Model, CollectionDetail.Far), out var farPrefab);
+ if (!farKnown) continue;
+ if (farPrefab == null) { Missing.Add(want.Key); continue; }
+ int slash = want.Key.LastIndexOf('/');
+ string groupKey = slash < 0 ? want.Key : want.Key.Substring(0, slash);
+ string personKey = slash < 0 ? "0" : want.Key.Substring(slash + 1);
+ if (!parents.TryGetValue(groupKey, out var parent))
+ {
+ parent = new GameObject(groupKey).transform;
+ parent.SetParent(transform, false);
+ parents[groupKey] = parent;
+ }
+ var person = new GameObject(personKey).transform;
+ person.SetParent(parent, false);
+ var far = Make(person, "Far", farPrefab, want);
+ Renderer[] near = Array.Empty<Renderer>();
+ if (prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var nearPrefab) && nearPrefab != null)
+ near = Make(person, "Near", nearPrefab, want);
+ pairs.Add((far, near));
+ Placed.Add(new PlacedFigure(want));
+ }
+ Apply(lastClose);
+ Debug.Log($"PEOPLE: {Placed.Count} civilian figures placed, {Missing.Count} not drawn");
+ }
+
+ static Renderer[] Make(Transform parent, string name, GameObject prefab, Want want)
+ {
+ var go = Instantiate(prefab, parent, false);
+ go.name = name;
+ // Compose the seeded yaw on top of the prefab root's FBX -90-degree X conversion (#979).
+ go.transform.localRotation = Quaternion.Euler(0f, want.Yaw, 0f) * prefab.transform.localRotation;
+ var before = Bounds(go);
+ go.transform.localScale *= before.size.y > 1e-3f ? FigureHeightM / before.size.y : FigureScale;
+ go.transform.position = want.At;
+ var after = Bounds(go);
+ go.transform.position += new Vector3(want.At.x - after.center.x, want.At.y - after.min.y, want.At.z - after.center.z);
+ return go.GetComponentsInChildren<Renderer>(true);
+ }
+
+ static Bounds Bounds(GameObject go)
+ {
+ var renderers = go.GetComponentsInChildren<Renderer>(true);
+ if (renderers.Length == 0) return new Bounds(go.transform.position, Vector3.zero);
+ var bounds = renderers[0].bounds;
+ foreach (var renderer in renderers) bounds.Encapsulate(renderer.bounds);
+ return bounds;
+ }
+
+ public static bool CloseAt(float distanceM, bool? was) =>
+ was == true ? distanceM <= CloseExitM : distanceM <= CloseEnterM;
+
+ void OnEnable() => RenderPipelineManager.beginCameraRendering += Choose;
+ void OnDisable() => RenderPipelineManager.beginCameraRendering -= Choose;
+
+ internal void Choose(ScriptableRenderContext context, Camera camera)
+ {
+ if (camera.cameraType == CameraType.Preview || camera.cameraType == CameraType.Reflection) return;
+ int id = camera.GetInstanceID();
+ bool close = CloseAt(TownLandmarks.ViewDistance(camera), closeFor.TryGetValue(id, out var previous) ? previous : (bool?)null);
+ closeFor[id] = close; lastClose = close;
+ if (close) Ask(CollectionDetail.Near);
+ Apply(close);
+ }
+
+ void Apply(bool close)
+ {
+ foreach (var pair in pairs)
+ {
+ bool near = close && pair.Near.Length > 0;
+ foreach (var renderer in pair.Far) renderer.forceRenderingOff = near;
+ foreach (var renderer in pair.Near) renderer.forceRenderingOff = !near;
+ }
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs.meta b/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs.meta
new file mode 100644
index 000000000..74497838a
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Collection/CivilianPeople.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 182f3a10bfc94181af82cc619f5988ac
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index a7899ca84..592724d98 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -447,6 +447,8 @@ namespace Statecraft.Game.UI
Statecraft.Game.Map.Collection.TownLandmarks.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content);
// MATKOT's ibex and striped hyena, sparse in their sourced terrain zones and visible only at close zoom (#670).
Statecraft.Game.Map.Collection.WildlifeLayer.Show(map);
+ // MATKOT's civilian figures at towns and transit camps, ambience only and streamed after the first frame (#666).
+ Statecraft.Game.Map.Collection.CivilianPeople.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content);
RenderSitesIfChanged();
var now = Bridge.State.Placements.Select(p => (p.Action, p.Q, p.R, p.Date)).ToList();
if (drawn != null && drawn.SequenceEqual(now)) return;
diff --git a/unity/Assets/Tests/EditMode/CivilianPeopleTests.cs b/unity/Assets/Tests/EditMode/CivilianPeopleTests.cs
new file mode 100644
index 000000000..a2bd651e4
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CivilianPeopleTests.cs
@@ -0,0 +1,216 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using Statecraft.Game.Map.Collection;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.TestTools;
+using Object = UnityEngine.Object;
+
+/// <summary>Issue #666: MATKOT's civilian figures stand in small deterministic groups at the Israeli towns,
+/// kibbutzim, moshavim and placed transit camps. They are ambience, never combat units, and stream after the first frame.</summary>
+public sealed class CivilianPeopleTests
+{
+ Action<string, CollectionDetail, Action<GameObject?>> saved = null!;
+ readonly List<(string id, CollectionDetail detail, Action<GameObject?> done)> asked = new List<(string, CollectionDetail, Action<GameObject?>)>();
+
+ [SetUp]
+ public void Seam()
+ {
+ saved = CivilianPeople.Request;
+ asked.Clear();
+ CivilianPeople.Request = (id, detail, done) => asked.Add((id, detail, done));
+ }
+
+ [TearDown]
+ public void Reset()
+ {
+ CivilianPeople.Request = saved;
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ }
+
+ static MapScene OpenMap()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build();
+ return map;
+ }
+
+ static GameObject Prefab(string id, CollectionDetail detail) =>
+ AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, detail));
+
+ void Answer(CollectionDetail detail)
+ {
+ foreach (var request in asked.Where(a => a.detail == detail).ToList())
+ {
+ asked.Remove(request);
+ request.done(Prefab(request.id, detail));
+ }
+ }
+
+ [Test]
+ public void EveryCivilianModelIsUsedAtTheRequestedPlacesAndStreamsFromThePeopleBundle()
+ {
+ Assert.AreEqual(typeof(CollectionStream), saved.Method.DeclaringType, "the game's seam is CollectionStream.Request");
+ Assert.AreEqual(nameof(CollectionStream.Request), saved.Method.Name);
+ CollectionAssert.AreEqual(new[]
+ {
+ "figure-c02-townsman-v2", "figure-c03-smith-carpenter-v2", "figure-c13-nurse-v2",
+ }, CivilianPeople.SettledModels);
+ CollectionAssert.AreEqual(new[]
+ {
+ "figure-c01-arriving-man-v2", "figure-c10-woman-blue-dress-v2",
+ }, CivilianPeople.CampModels);
+ foreach (var id in CivilianPeople.SettledModels.Concat(CivilianPeople.CampModels))
+ {
+ Assert.AreEqual(CollectionCatalog.People, CollectionCatalog.BundleOf(id), id);
+ foreach (var detail in new[] { CollectionDetail.Far, CollectionDetail.Near })
+ {
+ var path = CollectionCatalog.PrefabPath(id, detail);
+ Assert.IsNotNull(AssetDatabase.LoadAssetAtPath<GameObject>(path), path);
+ StringAssert.DoesNotContain("/Resources/", path);
+ }
+ Assert.IsNull(Resources.Load<GameObject>(id), id + " is never in the first-frame Resources load");
+ }
+ CollectionAssert.AreEquivalent(new[] { "city", "town", "kibbutz", "moshav" }, CivilianPeople.SettledTypes);
+ CollectionAssert.DoesNotContain(CivilianPeople.SettledTypes, "arab_town", "the Arab towns wait for the Arab villager figure (#708)");
+ }
+
+ [Test]
+ public void EveryEligibleSettlementGetsOneSmallGroupAndEveryPlacedCampGetsItsTwoPeopleFromItsDate()
+ {
+ var map = OpenMap();
+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);
+ var hex = content.SettlementHexes.Single(s => s.Id == "revivim");
+ var camp = new[] { new Placement(MapActions.TransitCamp, hex.Q, hex.R, new DateTime(1950, 8, 1)) };
+
+ var before = CivilianPeople.Wants(map, new DateTime(1950, 7, 31), camp, content);
+ int settlements = map.Settlements.Count(s => CivilianPeople.SettledTypes.Contains(s.Type));
+ Assert.AreEqual(settlements * CivilianPeople.SettledGroupSize, before.Count);
+ CollectionAssert.DoesNotContain(before.Select(w => w.Model), CivilianPeople.ArrivingMan);
+
+ var from = CivilianPeople.Wants(map, new DateTime(1950, 8, 1), camp, content);
+ Assert.AreEqual(settlements * CivilianPeople.SettledGroupSize + CivilianPeople.CampGroupSize, from.Count);
+ CollectionAssert.AreEqual(CivilianPeople.CampModels,
+ from.Where(w => w.Key.StartsWith("transit_camp_", StringComparison.Ordinal)).Select(w => w.Model));
+ Assert.AreEqual(3, CivilianPeople.SettledGroupSize, "design value: a small settled group");
+ Assert.AreEqual(2, CivilianPeople.CampGroupSize, "design value: a small camp group");
+ }
+
+ [Test]
+ public void SeededSpotsAreStableAndFiguresStandClearOfTownsTokensRoutesAndEachOther()
+ {
+ var map = OpenMap();
+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);
+ var first = CivilianPeople.Wants(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), content);
+ var second = CivilianPeople.Wants(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), content);
+ CollectionAssert.AreEqual(first, second, "same ids and seed give bit-for-bit equal plans");
+
+ var layer = CivilianPeople.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), content)!;
+ Assert.AreEqual(3, asked.Count, "only the three far settled models, once each");
+ Assert.IsTrue(asked.All(a => a.detail == CollectionDetail.Far));
+ CollectionAssert.IsEmpty(layer.Placed, "the stream never answers in the requesting frame");
+ Answer(CollectionDetail.Far);
+
+ Assert.AreEqual(first.Count, layer.Placed.Count, "placement count");
+ CollectionAssert.IsEmpty(layer.Missing);
+ var ground = PlacementLayer.CampGround(map);
+ foreach (var p in layer.Placed)
+ {
+ var at = new Vector2(p.At.x, p.At.z);
+ foreach (var f in map.KitFootprints)
+ Assert.GreaterOrEqual((at - f.centre).magnitude, f.radius + CivilianPeople.FigureClearanceM - 1f, $"{p.Key} clear of {f.id}");
+ Assert.IsFalse(ground.OnRoute(at, CivilianPeople.FigureClearanceM), p.Key + " clear of routes");
+ Assert.IsFalse(ground.OnToken(at, CivilianPeople.FigureClearanceM), p.Key + " clear of unit tokens");
+ }
+ for (int i = 0; i < layer.Placed.Count; i++)
+ for (int j = i + 1; j < layer.Placed.Count; j++)
+ Assert.GreaterOrEqual(Vector3.Distance(layer.Placed[i].At, layer.Placed[j].At), CivilianPeople.FigureSpacingM - 1f,
+ $"{layer.Placed[i].Key} clear of {layer.Placed[j].Key}");
+ }
+
+ [Test]
+ public void EveryFigureKeepsThePrefabAxisConversionUnderItsSeededYaw()
+ {
+ var map = OpenMap();
+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);
+ var layer = CivilianPeople.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), content)!;
+ Answer(CollectionDetail.Far);
+ Assert.Greater(layer.Placed.Count, 0);
+ foreach (var p in layer.Placed)
+ {
+ var child = layer.transform.Find(p.Key + "/Far");
+ Assert.IsNotNull(child, p.Key);
+ var prefab = Prefab(p.Model, CollectionDetail.Far);
+ var expected = layer.transform.rotation * Quaternion.Euler(0f, p.Yaw, 0f) * prefab.transform.localRotation;
+ Assert.Less(Quaternion.Angle(expected, child!.rotation), 0.01f, p.Key + " upright");
+ Assert.AreEqual(CivilianPeople.FigureHeightM, WorldBounds(child.gameObject).size.y, CivilianPeople.FigureHeightM * 0.02f, p.Key + " symbolic height");
+ Assert.IsTrue(child.GetComponentsInChildren<Renderer>(true).All(r => r.sharedMaterial.enableInstancing), p.Key + " is GPU-instanced");
+ }
+ }
+
+ [Test]
+ public void CloseZoomStreamsTheNearIdleFiguresAndKeepsFarFiguresUntilTheyArrive()
+ {
+ Assert.IsTrue(CivilianPeople.CloseAt(40000f, false), "near enters at the 40 km design value");
+ Assert.IsTrue(CivilianPeople.CloseAt(45000f, true), "near stays through the 45 km hysteresis band");
+ Assert.IsFalse(CivilianPeople.CloseAt(45001f, true));
+ Assert.IsFalse(CivilianPeople.CloseAt(40001f, false));
+ var map = OpenMap();
+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);
+ var layer = CivilianPeople.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), content)!;
+ Answer(CollectionDetail.Far);
+ var camera = CameraAt(30000f);
+ try
+ {
+ layer.Choose(default, camera);
+ Assert.AreEqual(3, asked.Count, "near models asked once on entering close zoom");
+ Assert.IsTrue(asked.All(a => a.detail == CollectionDetail.Near));
+ Assert.IsTrue(layer.GetComponentsInChildren<Renderer>(true).Any(r => !r.forceRenderingOff), "far figures remain while near streams");
+ Answer(CollectionDetail.Near);
+ Assert.AreEqual(layer.Placed.Count, layer.GetComponentsInChildren<Animator>(true).Length, "the near idle prefab for every figure");
+ Assert.IsTrue(layer.Placed.All(p => layer.transform.Find(p.Key + "/Far").GetComponentInChildren<Renderer>().forceRenderingOff));
+ Assert.IsTrue(layer.Placed.All(p => !layer.transform.Find(p.Key + "/Near").GetComponentInChildren<Renderer>().forceRenderingOff));
+ }
+ finally { Object.DestroyImmediate(camera.gameObject); }
+ }
+
+ [Test]
+ public void AModelThatDoesNotStreamFailsOpenWithoutDroppingTheOtherPeople()
+ {
+ var map = OpenMap();
+ var content = ContentLoader.Load(Statecraft.Game.Paths.Content);
+ var layer = CivilianPeople.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), content)!;
+ var failed = asked.Single(a => a.id == CivilianPeople.Townsman);
+ asked.Remove(failed);
+ LogAssert.Expect(LogType.Warning, new Regex("^PEOPLE: figure-c02-townsman-v2 far did not stream"));
+ failed.done(null);
+ Answer(CollectionDetail.Far);
+ Assert.Greater(layer.Placed.Count, 0, "the other models are drawn");
+ CollectionAssert.DoesNotContain(layer.Placed.Select(p => p.Model), CivilianPeople.Townsman);
+ Assert.AreEqual(layer.Wanted.Count(w => w.Model == CivilianPeople.Townsman), layer.Missing.Count(k => k.EndsWith("/0", StringComparison.Ordinal)));
+ }
+
+ static Camera CameraAt(float distanceM)
+ {
+ var camera = new GameObject("People camera").AddComponent<Camera>();
+ camera.transform.rotation = Quaternion.Euler(CameraRig.Pitch, 0f, 0f);
+ camera.transform.position = new Vector3(50000f, 0f, 50000f) - camera.transform.forward * distanceM;
+ return camera;
+ }
+
+ static Bounds WorldBounds(GameObject go)
+ {
+ var renderers = go.GetComponentsInChildren<Renderer>(true);
+ var bounds = renderers[0].bounds;
+ foreach (var renderer in renderers) bounds.Encapsulate(renderer.bounds);
+ return bounds;
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/CivilianPeopleTests.cs.meta b/unity/Assets/Tests/EditMode/CivilianPeopleTests.cs.meta
new file mode 100644
index 000000000..bfaf90bc4
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CivilianPeopleTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2dcd4a0cf16e43d8ba040b892c93dd4c