A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map hover and labels: cache picks and label geometry instead of per-frame scans (Refs #2622) (#2640)
Eyal Golanfdad7d547747
diff --git a/changelog.d/2622.md b/changelog.d/2622.mdnew file mode 100644index 000000000..09be5f741--- /dev/null+++ b/changelog.d/2622.md@@ -0,0 +1,3 @@+### Fixed++- Avoid repeated map-picking, label, city-hover and whole-town scans while the pointer and map view are unchanged.diff --git a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs b/unity/Assets/Scripts/Map/Collection/TownLandmarks.csindex 2873da7f7..aed211a40 100644--- a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs+++ b/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs@@ -333,6 +333,8 @@ namespace Statecraft.Game.Map.CollectionList<Want> wants = new List<Want>();DateTime date;bool dirty;+ bool refreshDirty;+ bool? refreshedAllowed;/// <summary>The landmarks drawn (key, model, the spot its footprint is centred on, at ground height): a test aid.</summary>public readonly List<(string Key, string Model, Vector3 At)> Placed = new List<(string, string, Vector3)>();@@ -416,18 +418,19 @@ namespace Statecraft.Game.Map.Collection(w.Key, new Bounds(new Vector3(w.At.x, 0, w.At.y), new Vector3(w.Radius * 2, 0, w.Radius * 2)))).ToList());layer.WholeTownReady = WholeReady;}- dirty = true; RefreshWanted();+ dirty = true; refreshDirty = true; RefreshWanted();}/// <summary>Whether <see cref="RefreshWanted"/> has work: a redraw, a lease to retire, or a change of the admitted towns/// or of the models asked for. RefreshWanted returns at once without it, and the edit-mode render callback asks for a/// player-loop update only with it, so a settled layer never keeps the editor updating (#2099).</summary>- internal bool RefreshPending => dirty || retiring.Count != 0- || !admittedKeys.SetEquals(wants.Where(Allowed).Select(w => w.Key)) || !asked.SetEquals(wants.Where(Allowed).Select(w => w.Model));+ internal bool RefreshPending => dirty || refreshDirty || retiring.Count != 0 || pendingRetirementLeases != 0+ || refreshedAllowed != (map?.Residency.Towns.Enabled ?? true);void RefreshWanted(){if (!RefreshPending) return;+ if (pendingRetirementLeases != 0) return;var keep = new HashSet<string>(StringComparer.Ordinal);var keys = new HashSet<string>(StringComparer.Ordinal);foreach (var want in wants) if (Allowed(want)) { keep.Add(want.Model); keys.Add(want.Key); }@@ -463,6 +466,11 @@ namespace Statecraft.Game.Map.Collection// Admission already validated this camera's production policy. The stream itself waits for GameReady.RequestWanted();}+ if (retiring.Count == 0 && pendingRetirementLeases == 0)+ {+ refreshedAllowed = map?.Residency.Towns.Enabled ?? true;+ refreshDirty = false;+ }}void RequestWanted()@@ -500,7 +508,7 @@ namespace Statecraft.Game.Map.CollectionCollectionResidencyMetrics.AfterDestroyed("whole_towns", instances, batch, () =>{pendingRetirementLeases -= batch.Length;- if (this != null && isActiveAndEnabled) RefreshWanted();+ if (this != null && isActiveAndEnabled) { refreshDirty = true; RefreshWanted(); }CollectionResidencyMetrics.MarkDirty();}, Application.isPlaying && Acquire == CollectionStream.Acquire ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys);}@@ -699,11 +707,9 @@ namespace Statecraft.Game.Map.Collection}void EndCamera(ScriptableRenderContext _, Camera camera) => RestoreRenderers();- void LateUpdate()- {- // The layer prunes quiet cameras too; releases must not depend on another camera starting a render.- RefreshWanted();- }+ /// <summary>One production frame's reconciliation; exposed internally so allocation tests measure no reflection.</summary>+ internal void Tick() => RefreshWanted();+ void LateUpdate() => Tick();/// <summary>The render callback. Nothing is acquired, instantiated or destroyed while a camera renders, in edit mode/// either (a Scene or Game view camera): the change waits for LateUpdate, as in play mode.</summary>diff --git a/unity/Assets/Scripts/Map/MapPointer.cs b/unity/Assets/Scripts/Map/MapPointer.csindex 228e119ba..0b533d48e 100644--- a/unity/Assets/Scripts/Map/MapPointer.cs+++ b/unity/Assets/Scripts/Map/MapPointer.cs@@ -71,6 +71,8 @@ namespace Statecraft.Game.Mappublic sealed class MapPointer : MonoBehaviour{public MapScene? Map;+ /// <summary>The game camera supplied by GameRoot; tests and tools without one fall back to Camera.main.</summary>+ public Camera? View;public Func<Vector2, bool>? IsOverUi;/// <summary>A picked hex and whether its pointer hit was a city's name pill. Keyboard picks always pass false.</summary>public event Action<int, int, bool>? HexClicked;@@ -80,6 +82,33 @@ namespace Statecraft.Game.Map/// city's hex (#1063), wherever the land under the pill is.</summary>public Func<Vector2, (int q, int r)?>? PillHex;+ Camera? cachedMain;+ Terrain? cachedTerrainRoot;+ int cachedHierarchyCount = -1;+ (Terrain terrain, TerrainCollider? collider)[] grounds = Array.Empty<(Terrain, TerrainCollider?)>();+ GroundSignature[] pickedGrounds = Array.Empty<GroundSignature>();+ Units.UnitLayer? cachedUnits;+ bool pickCached;+ Vector2 pickedAt;+ Camera? pickedCamera;+ Matrix4x4 pickedView, pickedProjection;+ Rect pickedPixelRect;+ Units.UnitLayer? pickedUnits;+ long pickedUnitsVersion;+ bool pickedUnitsActive;+ (int q, int r)? pickedHex;++ struct GroundSignature+ {+ public bool TerrainActive, DrawHeightmap, ColliderActive;+ public int TerrainData;+ public Matrix4x4 LocalToWorld;+ }+#if UNITY_EDITOR+ internal long UncachedPicksForTests { get; private set; }+ internal long TerrainCacheBuildsForTests { get; private set; }+#endif+// Every press, at the position of its own input event (InputConfig keeps a release from merging into the next move),// queued and evaluated in order in Update: several presses in one slow frame are each checked where they happened,// never all at the frame's last pointer position (playtest 2, P2-4).@@ -288,27 +317,104 @@ namespace Statecraft.Game.Mapif (overUi) return null; // the UI is asked first, whatever else is missingif (Map == null || Map.Terrain == null) return null;if (pills && PillHex?.Invoke(pos) is (int, int) pill) { cityPill = true; return pill; }- var cam = Camera.main;+ var cam = View != null ? View : cachedMain != null ? cachedMain : cachedMain = Camera.main;+ RefreshSceneCache(Map);// A unit's badge and figures stand above the ground: a click on them is a click on the unit's hex, not on the// terrain behind them (owner's report on v0.2.0). Not for the keyboard's look-at point (pills false).- var units = pills && cam != null ? Map.Terrain.transform.Find(Units.UnitLayer.RootName) : null;- if (units != null && units.TryGetComponent<Units.UnitLayer>(out var layer) && layer.TokenAtScreen(cam!, pos) is Units.PlacedToken token)- return (token.Q, token.R);- if (cam == null || !TryGroundHit(Map, cam.ScreenPointToRay(pos), out var hit)) return null;- return Pick(Map, hit.point);+ return CachedSceneHex(pos, cam, pills ? cachedUnits : null);+ }++ void RefreshSceneCache(MapScene map)+ {+ int hierarchy = map.transform.hierarchyCount;+ // A board replaced by one of the same shape (HexTilesLook.Apply) keeps the count but destroys the cached+ // terrains: a destroyed one (Unity's null) rebuilds the cache too (Codex review of 981951be0).+ if (cachedTerrainRoot == map.Terrain && cachedHierarchyCount == hierarchy && GroundsAlive()) return;+ cachedTerrainRoot = map.Terrain;+ cachedHierarchyCount = hierarchy;+ var found = map.GetComponentsInChildren<Terrain>(true);+ grounds = new (Terrain, TerrainCollider?)[found.Length];+ for (int i = 0; i < found.Length; i++) grounds[i] = (found[i], found[i].GetComponent<TerrainCollider>());+ pickedGrounds = new GroundSignature[found.Length];+ cachedUnits = map.Terrain.transform.Find(Units.UnitLayer.RootName)?.GetComponent<Units.UnitLayer>();+ pickCached = false;+#if UNITY_EDITOR+ TerrainCacheBuildsForTests++;+#endif+ }++ bool GroundsAlive()+ {+ foreach (var (terrain, collider) in grounds)+ // A terrain with no collider is cached as a real null; one destroyed since is Unity's null.+ if (terrain == null || (!ReferenceEquals(collider, null) && collider == null)) return false;+ return true;+ }++ /// <summary>For a rebuilt scene whose replacement children happen to have the same hierarchy count.</summary>+ internal void InvalidateSceneCache()+ {+ cachedTerrainRoot = null; cachedHierarchyCount = -1; cachedUnits = null; pickCached = false;+ }++ (int q, int r)? CachedSceneHex(Vector2 pos, Camera? cam, Units.UnitLayer? layer)+ {+ if (cam == null) return null;+ var view = cam.worldToCameraMatrix;+ var projection = cam.projectionMatrix;+ var pixelRect = cam.pixelRect;+ long version = layer?.PickVersion ?? 0;+ bool active = layer != null && layer.gameObject.activeInHierarchy;+ bool groundsUnchanged = UpdateGroundSignatures();+ if (pickCached && pickedAt == pos && pickedCamera == cam && pickedView == view && pickedProjection == projection+ && pickedPixelRect == pixelRect && pickedUnits == layer && pickedUnitsVersion == version && pickedUnitsActive == active+ && groundsUnchanged)+ return pickedHex;+#if UNITY_EDITOR+ UncachedPicksForTests++;+#endif+ pickedAt = pos; pickedCamera = cam; pickedView = view; pickedProjection = projection; pickedPixelRect = pixelRect;+ pickedUnits = layer; pickedUnitsActive = active;+ if (layer != null && layer.TokenAtScreen(cam, pos) is Units.PlacedToken token) pickedHex = (token.Q, token.R);+ else pickedHex = TryGroundHit(cam.ScreenPointToRay(pos), out var hit) ? Pick(Map!, hit.point) : ((int, int)?)null;+ // TokenAtScreen calls FaceCamera, which may observe newly supplied figure geometry.+ pickedUnitsVersion = layer?.PickVersion ?? 0;+ pickCached = true;+ return pickedHex;+ }++ bool UpdateGroundSignatures()+ {+ bool unchanged = pickCached && pickedGrounds.Length == grounds.Length;+ for (int i = 0; i < grounds.Length; i++)+ {+ var (terrain, collider) = grounds[i];+ var next = new GroundSignature+ {+ TerrainActive = terrain.isActiveAndEnabled,+ DrawHeightmap = terrain.drawHeightmap,+ ColliderActive = collider != null && collider.enabled, // a Collider is not a Behaviour; the terrain's own check covers the object being active+ TerrainData = terrain.terrainData != null ? terrain.terrainData.GetInstanceID() : 0,+ LocalToWorld = terrain.transform.localToWorldMatrix,+ };+ var previous = pickedGrounds[i];+ if (previous.TerrainActive != next.TerrainActive || previous.DrawHeightmap != next.DrawHeightmap+ || previous.ColliderActive != next.ColliderActive || previous.TerrainData != next.TerrainData+ || !previous.LocalToWorld.Equals(next.LocalToWorld)) unchanged = false;+ pickedGrounds[i] = next;+ }+ return unchanged;}// The opt-in board draws its own terrain above the lowered real map. Use the nearest displayed ground,// falling through its sea/outside holes to the real map. Props and markers never decide the clicked hex.- static bool TryGroundHit(MapScene map, Ray ray, out RaycastHit hit)+ bool TryGroundHit(Ray ray, out RaycastHit hit){hit = default;bool found = false;- foreach (var terrain in map.GetComponentsInChildren<Terrain>())+ foreach (var (terrain, collider) in grounds){- if (!terrain.enabled || !terrain.drawHeightmap) continue;- var collider = terrain.GetComponent<TerrainCollider>();- if (collider == null || !collider.enabled ||+ if (!terrain.isActiveAndEnabled || !terrain.drawHeightmap || collider == null || !collider.enabled ||!collider.Raycast(ray, out var candidate, found ? hit.distance : 1_000_000f)) continue;hit = candidate;found = true;diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.csindex d1bf9f30b..3bd46d972 100644--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs@@ -139,6 +139,12 @@ namespace Statecraft.Game.Map.Units/// out this second list with the same boxes, the two taking turns (no allocation per frame). A new pair per rebuild.</summary>List<Bounds[]> keepClearSpare = new List<Bounds[]>();bool slid; // a token's slide moved since FaceCamera last turned the boxes+ int pickVersion;+ /// <summary>Changes whenever TokenAtScreen's projected source geometry can change.</summary>+ internal long PickVersion => ((long)pickVersion << 32) | (uint)UnitFigures.GeometryVersion;+#if UNITY_EDITOR+ internal long TokenHitQueriesForTests { get; private set; }+#endifGameObject? ring;bool still;/// <summary>The camera pose and projection (vertical scale, orthographic) <see cref="FaceCamera"/> last turned the badges and flags to; a call from the same pose and projection@@ -570,6 +576,9 @@ namespace Statecraft.Game.Map.Units/// a click on a unit's badge showed the hex behind it, with no Move). No allocation.</summary>public PlacedToken? TokenAtScreen(Camera cam, Vector2 screen){+#if UNITY_EDITOR+ TokenHitQueriesForTests++;+#endifif (cam == null || !gameObject.activeInHierarchy) return null;FaceCamera(cam); // the boxes as this camera draws them (a no-op from the pose it last turned them to)PlacedToken? best = null; float nearest = float.MaxValue;@@ -688,6 +697,7 @@ namespace Statecraft.Game.Map.Unitsvoid BuildTokens(IReadOnlyDictionary<(int sim, string row), Vector3> drawnAt,IReadOnlyDictionary<(int sim, string row), float> firing){+ pickVersion++;FreeTokenMeshes();motions.Clear();badges.Clear(); badgeHomes.Clear(); facedFor = null;@@ -812,7 +822,7 @@ namespace Statecraft.Game.Map.Unitsvar motion = token.gameObject.AddComponent<UnitTokenMotion>();motion.enabled = false; // runs only while it moves or attacksmotion.SimId = placed[i].Token.StateUnit?.Id ?? -1;- motion.Changed = () => { facedFor = null; slid = true; }; // FaceCamera sets the badge and the boxes where the token is drawn+ motion.Changed = () => { pickVersion++; facedFor = null; slid = true; }; // FaceCamera sets the badge and the boxes where the token is drawnmotions.Add(motion);// With the units hidden the token cannot be seen, and it would slide only once they are shown again.if (tokensRoot.gameObject.activeInHierarchy && drawnAt.TryGetValue(Key(motion.SimId, token.name), out var was))diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex ea0811b75..040d5c1ed 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -86,6 +86,7 @@ namespace Statecraft.Game.UI/// <summary>Tests: the minimap of the last Begin.</summary>internal MinimapPresenter? Minimap => minimap;string? hoveredCity; // the city HoverCity lit (#1063)+ readonly Dictionary<(int q, int r), List<string>> citiesByHex = new Dictionary<(int, int), List<string>>();OutcomePresenter? outcomes;TurnReportPresenter? report;EndScreenPresenter? end;@@ -530,6 +531,14 @@ namespace Statecraft.Game.UIcameraController.Ground = CameraController.GroundOf(terrain);cameraController.GroundTop = CameraController.GroundTopOf(terrain);pointer.Map = map;+ pointer.InvalidateSceneCache();+ pointer.View = cameraController.GetComponent<Camera>();+ citiesByHex.Clear();+ foreach (var h in bridge.Content.SettlementHexes)+ {+ if (!citiesByHex.TryGetValue((h.Q, h.R), out var ids)) citiesByHex[(h.Q, h.R)] = ids = new List<string>();+ ids.Add(h.Id); // preserve content order where settlement rows share a hex+ }// #1617: the lit hexes of a Move or Attack pick show through the unit card, so the map pointer also takes a click// on the card's text over one of them (InfoPanelPresenter.TakesClickThrough). The camera does not: no drag or wheel// through the card.@@ -612,7 +621,7 @@ namespace Statecraft.Game.UIif (cameraController.HoldsMouseDrag == holdsMouseDrag) cameraController.HoldsMouseDrag = null;if (cameraController.HoldsTouchDrag == holdsTouchDrag) cameraController.HoldsTouchDrag = null;if (cameraController.ScreenTakesUpDown == screenTakesUpDown) cameraController.ScreenTakesUpDown = null;- if (pointer.Map == map) pointer.Map = null;+ if (pointer.Map == map) { pointer.Map = null; pointer.View = null; }cameraController.Bounds = oldBounds;cameraController.Ground = oldGround; cameraController.GroundTop = oldTop;}));@@ -944,7 +953,15 @@ namespace Statecraft.Game.UI/// pointer (a touchscreen). Returns that city's id; called each frame (LateUpdate), it changes the UI only when the city does.</summary>internal string? HoverCity(Vector2? screenYUp){- var city = screenYUp is Vector2 p && Bridge != null && pointer.HexAt(p) is (int q, int r) ? CityAt(Bridge.Content, Bridge.State, q, r) : null;+ var under = screenYUp is Vector2 p ? pointer.HexAt(p) : null;+ return HoverCity(screenYUp, under);+ }++ internal string? HoverCity(Vector2? screenYUp, (int q, int r)? under)+ {+ string? city = null;+ if (screenYUp.HasValue && under is (int q, int r) && Bridge != null && citiesByHex.TryGetValue((q, r), out var ids))+ foreach (var id in ids) if (Bridge.State.Cities.ContainsKey(id)) { city = id; break; }if (city == hoveredCity) return city;hoveredCity = city;labels?.Highlight(city);@@ -952,6 +969,16 @@ namespace Statecraft.Game.UIreturn city;}+ internal void UpdateMapHover(Vector2? hover)+ {+ labels?.Hover(hover);+ var under = hover is Vector2 at ? pointer.HexAt(at) : null;+ HoverCity(hover, under);+ if (under is (int q, int r)) info?.ShowRouteTo(q, r);+ else if (UnityEngine.InputSystem.Pointer.current is UnityEngine.InputSystem.Mouse) info?.HideRoute();+ MarkHover(map, info, under, rig != null ? rig.Distance : float.PositiveInfinity);+ }+/// <summary>The city with a settlement hex at (q, r): one in State.Cities, whose hex opens the city panel (GddHexPanel); or null.</summary>internal static string? CityAt(Content c, GameState s, int q, int r){@@ -1157,12 +1184,7 @@ namespace Statecraft.Game.UI// Today's name under a 1948 locality's pill: while a mouse (or pen) is over it (owner ruling 2026-10-11), or after a// tap on it (#245). A touchscreen has no hover: its last touch position stays after the finger lifts.var hover = MapLabelsPresenter.HoverPosition(UnityEngine.InputSystem.Pointer.current);- labels.Hover(hover);- HoverCity(hover);- var under = hover is Vector2 at ? pointer.HexAt(at) : null;- if (under is (int q, int r)) info?.ShowRouteTo(q, r);- else if (UnityEngine.InputSystem.Pointer.current is UnityEngine.InputSystem.Mouse) info?.HideRoute();- MarkHover(map, info, under, rig != null ? rig.Distance : float.PositiveInfinity);+ UpdateMapHover(hover);var touch = UnityEngine.InputSystem.Touchscreen.current;if (touch != null && touch.primaryTouch.press.wasPressedThisFrame) labels.Tap(touch.primaryTouch.position.ReadValue());}diff --git a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs b/unity/Assets/Scripts/UI/MapLabelsPresenter.csindex 457ddc34c..069139174 100644--- a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs+++ b/unity/Assets/Scripts/UI/MapLabelsPresenter.cs@@ -136,14 +136,23 @@ namespace Statecraft.Game.UIreadonly List<Rect> keepClearRects = new List<Rect>(); // their screen rectangles, in the layer's coordinatesIReadOnlyList<Bounds[]>? lastKeepClear;Rect layerRect; // the panel in the layer's coordinates: a pill stays inside it- readonly EventCallback<GeometryChangedEvent> onOccluderGeometry, onContainerGeometry;+ readonly EventCallback<GeometryChangedEvent> onOccluderGeometry, onContainerGeometry, onLabelGeometry;Matrix4x4 lastViewProjection; Rect lastCameraRect; Vector2 lastPanelSize, lastOrigin; float lastZoom = float.NaN;bool lastKitsShown;- int lastOccluderMask = -1; float lastLabelSizes = float.NaN; bool sizesKnown, geometryDirty = true;+ int lastOccluderMask = -1;+ bool sizesKnown, geometryDirty = true;+ long placementGeneration;+ long pillGeneration = -1, hoverGeneration = -1;+ Vector2 pillPoint, hoverPoint;+ string? pillResult;+ Item? hoverResult;#if UNITY_EDITOR// #1680: observe real projection work without a clock. No callbacks, allocations or player-build instrumentation.internal long ProjectedMarkersForTests { get; private set; }internal long PlacementVisitsForTests { get; private set; }+ internal long LabelSizeReadsForTests { get; private set; }+ internal long PillVisitsForTests { get; private set; }+ internal long HoverVisitsForTests { get; private set; }// ProjectBoxes is static. Tests sample this only around a synchronous main-thread Refresh, with no yield.internal static long ProjectedCornersForTests { get; private set; }#endif@@ -203,6 +212,7 @@ namespace Statecraft.Game.UIFunc<int, decimal, string>? tierTip = null, bool hebrew = false, IReadOnlyList<Statecraft.Sim.MapLocation>? locations = null){var tip = tipText ?? DefaultTip;+ onLabelGeometry = _ => geometryDirty = true;this.keepClear = keepClear;container = root.Q<VisualElement>(ContainerName) ?? throw new InvalidOperationException($"Game.uxml has no '{ContainerName}' element");this.camera = camera;@@ -225,6 +235,7 @@ namespace Statecraft.Game.UIlabel.AddToClassList(LabelClass);label.AddToClassList("map-label-" + s.Type);label.AddToClassList(anchorClass);+ label.RegisterCallback(onLabelGeometry);slot.Add(label);// Issue #710: a pill with a 1948 figure (cities.yaml's people) starts with its tier; the rest have no badge.// The badge is the pill's sibling, drawn over its start padding (left, or right in Hebrew): a child would stop the Label sizing to its text.@@ -273,6 +284,7 @@ namespace Statecraft.Game.UIslot.AddToClassList(SlotClass);var label = new Label(LocationName(loc, hebrew)) { name = "label-" + s.Id, pickingMode = PickingMode.Ignore };label.AddToClassList(LabelClass); label.AddToClassList("map-label-" + s.Type); label.AddToClassList(LocationClass); label.AddToClassList(Centre);+ label.RegisterCallback(onLabelGeometry);slot.Add(label);container.Add(slot);locationLabels.Add(label); locationSlots.Add(slot);@@ -290,6 +302,7 @@ namespace Statecraft.Game.UIslot.AddToClassList(SlotClass);var label = new Label(hebrew && !string.IsNullOrWhiteSpace(place.NameHe) ? place.NameHe : s.Name) { name = "label-" + s.Id, pickingMode = PickingMode.Ignore };label.AddToClassList(LabelClass); label.AddToClassList(LocalityClass); label.AddToClassList(Centre);+ label.RegisterCallback(onLabelGeometry);slot.Add(label);container.Add(slot);localityLabels.Add(label); localitySlots.Add(slot);@@ -354,7 +367,7 @@ namespace Statecraft.Game.UI/// (SiteLayer.Columns) or, with none, its marker box, under the same declutter and clearance rules as every pill.</summary>public void SetSites(IReadOnlyList<(Settlement place, Bounds[]? columns)> sites){- foreach (var it in siteItems) { it.Slot.RemoveFromHierarchy(); items.Remove(it); settlementOrder.Remove(it); }+ foreach (var it in siteItems) { it.Label.UnregisterCallback(onLabelGeometry); it.Slot.RemoveFromHierarchy(); items.Remove(it); settlementOrder.Remove(it); }siteItems.Clear();var at = items.FindIndex(x => x.IsLocality); // the sites go before the localitiesif (at < 0) at = items.Count;@@ -365,6 +378,7 @@ namespace Statecraft.Game.UI// #1219: the Hebrew UI shows the site's name_he, as the settlements' pills do.var label = new Label(hebrew && !string.IsNullOrWhiteSpace(s.NameHe) ? s.NameHe : s.Name) { name = "label-" + s.Id, pickingMode = PickingMode.Ignore };label.AddToClassList(LabelClass); label.AddToClassList("map-label-" + s.Type); label.AddToClassList(Centre);+ label.RegisterCallback(onLabelGeometry);slot.Add(label);container.Insert(System.Math.Max(0, container.IndexOf(Tooltip)), slot); // under the tooltip, as the othersvar top = MarkerTop(map, s);@@ -382,7 +396,7 @@ namespace Statecraft.Game.UI{var route = map.ShownRoute;if (route.Count == labelledRoute.Count && route.SequenceEqual(labelledRoute)) return;- foreach (var x in routeLabels) x.slot.RemoveFromHierarchy();+ foreach (var x in routeLabels) { x.label.UnregisterCallback(onLabelGeometry); x.slot.RemoveFromHierarchy(); }routeLabels.Clear();for (int i = 0; i < route.Count; i++){@@ -393,6 +407,7 @@ namespace Statecraft.Game.UIvar label = new Label(h.turn.ToString(CultureInfo.InvariantCulture)){ name = "route-turn-" + h.turn, pickingMode = PickingMode.Ignore };label.AddToClassList(LabelClass); label.AddToClassList(RouteTurnClass);+ label.RegisterCallback(onLabelGeometry);slot.Add(label); container.Insert(System.Math.Max(0, container.IndexOf(Tooltip)), slot);routeLabels.Add((slot, label, h.q, h.r));}@@ -472,20 +487,14 @@ namespace Statecraft.Game.UIfloat distance = Zoom();bool kitsShown = map.KitsShown; // with the "kits" toggle off the marker boxes are drawn insteadint mask = OccluderMask();- float labelSizes = 0f; // a pill that grows or shrinks (a late font, a new text) is re-placed (re-review N2)bool localities = distance <= LocalityDistanceM; // farther out the localities are skipped outright (cost)var tokens = keepClear?.Invoke();- for (int i = 0; i < items.Count; i++)- {- if (items[i].IsLocality && !localities) continue;- var st = items[i].Label.resolvedStyle; if (!float.IsNaN(st.width) && !float.IsNaN(st.height)) labelSizes += st.width + st.height;- }- if (!force && sizesKnown && !geometryDirty && labelSizes == lastLabelSizes && viewProjection == lastViewProjection && cameraRect == lastCameraRect+ if (!force && sizesKnown && !geometryDirty && viewProjection == lastViewProjection && cameraRect == lastCameraRect&& screen == lastPanelSize && origin == lastOrigin && distance == lastZoom && mask == lastOccluderMask && kitsShown == lastKitsShown&& tokens == lastKeepClear) return;lastKeepClear = tokens;lastViewProjection = viewProjection; lastCameraRect = cameraRect; lastPanelSize = screen; lastOrigin = origin;- lastZoom = distance; lastOccluderMask = mask; lastKitsShown = kitsShown; lastLabelSizes = labelSizes; geometryDirty = false;+ lastZoom = distance; lastOccluderMask = mask; lastKitsShown = kitsShown; geometryDirty = false;sizesKnown = true;bool laidOut = !(float.IsNaN(screen.x) || screen.x <= 0f || float.IsNaN(origin.x) || float.IsNaN(origin.y));if (!laidOut) { sizesKnown = false; origin = Vector2.zero; } // before the first layout: cull by view only, place later@@ -541,6 +550,9 @@ namespace Statecraft.Game.UIvar shift = Vector2.zero;if (shown){+#if UNITY_EDITOR+ LabelSizeReadsForTests++;+#endifvar size = new Vector2(it.Label.resolvedStyle.width, it.Label.resolvedStyle.height);if (!laidOut || float.IsNaN(size.x) || size.x <= 0f) sizesKnown = false; // not laid out yet: show it, place on a later refreshelse@@ -582,6 +594,7 @@ namespace Statecraft.Game.UIx.slot.style.visibility = shown ? Visibility.Visible : Visibility.Hidden;if (shown) x.slot.style.translate = new Translate(at.x, at.y);}+ placementGeneration++;}/// <summary>Whether the pill fits at <paramref name="spot"/>; if so records it as placed and sets the shift from@@ -636,12 +649,17 @@ namespace Statecraft.Game.UI/// order, so a city before a smaller place) that contains it, never a 1948 locality's; null when none does.</summary>public string? PillAtLayer(Vector2 layerPoint){+ if (pillGeneration == placementGeneration && pillPoint == layerPoint) return pillResult;+ pillGeneration = placementGeneration; pillPoint = layerPoint; pillResult = null;for (int i = 0; i < items.Count; i++){+#if UNITY_EDITOR+ PillVisitsForTests++;+#endifvar it = items[i];- if (!it.IsLocality && it.ShownLast && it.Placed.Contains(layerPoint)) return it.Settlement.Id;+ if (!it.IsLocality && it.ShownLast && it.Placed.Contains(layerPoint)) { pillResult = it.Settlement.Id; break; }}- return null;+ return pillResult;}/// <summary>Lights the pill of game settlement <paramref name="id"/> (HoverClass) and puts out the one lit before; null@@ -705,12 +723,22 @@ namespace Statecraft.Game.UI/// something to say) that contains it, or none.</summary>public void HoverAt(Vector2 layerPoint){+ if (hoverGeneration == placementGeneration && hoverPoint == layerPoint)+ {+ ShowTooltipFor(hoverResult);+ return;+ }+ hoverGeneration = placementGeneration; hoverPoint = layerPoint; hoverResult = null;Item? over = null;for (int i = 0; i < items.Count && over == null; i++){+#if UNITY_EDITOR+ HoverVisitsForTests++;+#endifvar it = items[i];if (Hittable(it) && it.Placed.Contains(layerPoint)) over = it;}+ hoverResult = over;ShowTooltipFor(over);}@@ -783,13 +811,14 @@ namespace Statecraft.Game.UIremoveToggle?.Invoke(); removeToggle = null;foreach (var e in occluders) e.UnregisterCallback(onOccluderGeometry);container.UnregisterCallback(onContainerGeometry);+ foreach (var it in items) it.Label.UnregisterCallback(onLabelGeometry);occluders.Clear();foreach (var slot in Slots) slot.RemoveFromHierarchy();foreach (var slot in LocalitySlots) slot.RemoveFromHierarchy();foreach (var slot in LocationSlots) slot.RemoveFromHierarchy();foreach (var it in siteItems) it.Slot.RemoveFromHierarchy();siteItems.Clear();- foreach (var x in routeLabels) x.slot.RemoveFromHierarchy();+ foreach (var x in routeLabels) { x.label.UnregisterCallback(onLabelGeometry); x.slot.RemoveFromHierarchy(); }routeLabels.Clear(); labelledRoute = Array.Empty<(int, int, int)>();Tooltip.RemoveFromHierarchy();items.Clear(); settlementOrder.Clear();diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.csindex 2bfef1028..3d0f03e30 100644--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs@@ -548,6 +548,15 @@ public class GameSceneTestsroot.Labels.Refresh(force: true); yield return null;Assert.AreEqual(Visibility.Visible, label.parent.style.visibility.value, "precondition: Tel Aviv is named");+ int hoverPicks = 0; var realPillHex = pointer.PillHex;+ pointer.PillHex = p => { hoverPicks++; return realPillHex?.Invoke(p); };+ // LateUpdate reads Pointer.current, which cannot be placed at this projected fixture point without replacing+ // the test's live Input System device. Drive the exact helper that LateUpdate calls so the coordinate stays deterministic.+ root.UpdateMapHover(onHex);+ Assert.AreEqual(1, hoverPicks, "city, route and hex hover share one map pick");+ Assert.IsTrue(label.ClassListContains(MapLabelsPresenter.HoverClass), "the shared pick still lights the city pill");+ pointer.PillHex = realPillHex;+// The land under a screen point (camera pixels), asked of the terrain alone, as a click without the pills would be.(int q, int r)? Land(Vector2 px) =>map.Terrain.GetComponent<TerrainCollider>().Raycast(cam.ScreenPointToRay(px), out var hit, 1_000_000f) ? MapPointer.Pick(map, hit.point) : ((int, int)?)null;diff --git a/unity/Assets/Tests/EditMode/HexBoardPickingTests.cs b/unity/Assets/Tests/EditMode/HexBoardPickingTests.csindex 22892ff98..0f496050b 100644--- a/unity/Assets/Tests/EditMode/HexBoardPickingTests.cs+++ b/unity/Assets/Tests/EditMode/HexBoardPickingTests.cs@@ -40,6 +40,7 @@ public class HexBoardPickingTestsAssert.AreNotSame(map.Terrain, board);pointer = map.gameObject.AddComponent<MapPointer>();pointer.Map = map;+ pointer.View = cam;pointer.IsOverUi = _ => false;pointer.HexClicked += (q, r, cityPill) => clicked.Add((q, r));Physics.SyncTransforms();@@ -152,6 +153,13 @@ public class HexBoardPickingTestsvar point = new Vector3(0, 0, map.Frame.LengthM) + HexGeometry.Centre(1, 15, HexScale.HexM);try{+ point.y = board.transform.position.y + board.SampleHeight(point);+ rig.LookAt = point; rig.Distance = 20000f; rig.Yaw = 90f; rig.TopInset = 0f; rig.Apply();+ var unchanged = cam.WorldToScreenPoint(point);+ pointer.HexAt(unchanged); long initialBuilds = pointer.TerrainCacheBuildsForTests;+ pointer.HexAt(unchanged);+ Assert.AreEqual(initialBuilds, pointer.TerrainCacheBuildsForTests, "unchanged picks reuse terrain and collider discovery");+HexTilesLook.Apply(map, false);Physics.SyncTransforms();point.y = map.Terrain.transform.position.y + map.Terrain.SampleHeight(point);@@ -160,6 +168,7 @@ public class HexBoardPickingTestsAssert.IsTrue(map.Terrain.GetComponent<TerrainCollider>().Raycast(cam.ScreenPointToRay(screen), out var real, 1000000f));clicked.Clear(); Assert.IsTrue(pointer.HandleClick(screen));CollectionAssert.AreEqual(new[] { MapPointer.Pick(map, real.point) }, clicked);+ Assert.AreEqual(initialBuilds + 1, pointer.TerrainCacheBuildsForTests, "removing the displayed board invalidates discovery");HexTilesLook.Apply(map, true);HexTilesLook.Apply(map, true);board = map.transform.Find(HexTilesLook.RootName).GetComponentsInChildren<Terrain>().Single();@@ -169,6 +178,19 @@ public class HexBoardPickingTestsAssert.IsTrue(board.GetComponent<TerrainCollider>().Raycast(cam.ScreenPointToRay(screen), out var visible, 1000000f));clicked.Clear(); Assert.IsTrue(pointer.HandleClick(screen));CollectionAssert.AreEqual(new[] { MapPointer.Pick(map, visible.point) }, clicked);+ Assert.AreEqual(initialBuilds + 2, pointer.TerrainCacheBuildsForTests, "recreating the displayed board invalidates discovery again");++ // Codex review of 981951be0: the board replaced directly by one of the same shape, after a pick on it, keeps the+ // hierarchy count; the destroyed board's cached terrain must not be used.+ var replaced = board;+ HexTilesLook.Apply(map, true);+ board = map.transform.Find(HexTilesLook.RootName).GetComponentsInChildren<Terrain>().Single();+ Assert.AreNotSame(replaced, board, "fixture: a new board");+ Physics.SyncTransforms();+ Assert.IsTrue(board.GetComponent<TerrainCollider>().Raycast(cam.ScreenPointToRay(screen), out var again, 1000000f));+ clicked.Clear(); Assert.IsTrue(pointer.HandleClick(screen));+ CollectionAssert.AreEqual(new[] { MapPointer.Pick(map, again.point) }, clicked, "the new board's hex, not a stale surface");+ Assert.AreEqual(initialBuilds + 3, pointer.TerrainCacheBuildsForTests, "a same-shape replacement invalidates discovery too");}finally{@@ -177,4 +199,39 @@ public class HexBoardPickingTests}}+ [Test]+ public void ChangingGroundStateInvalidatesThePickAtAnUnmovedPointer()+ {+ Vector2 screen = default;+ (int q, int r) displayed = default, real = default;+ bool foundDifferentGrounds = false;+ foreach (var (q, r) in new[] { (1, 15), (4, 15), (4, 19) })+ foreach (float offset in new[] { -15f, 15f })+ {+ var origin = new Vector3(0f, Shader.GetGlobalVector(MapShaderGlobals.Map).z, map.Frame.LengthM);+ var edge = (origin + HexGeometry.Centre(q, r, HexScale.HexM)+ + origin + HexGeometry.Centre(q + 1, r, HexScale.HexM)) * 0.5f;+ var point = edge + Vector3.right * offset;+ point.y = board.transform.position.y + board.SampleHeight(point);+ rig.LookAt = point; rig.Distance = 20000f; rig.Yaw = 90f; rig.TopInset = 0f; rig.Apply();+ screen = cam.WorldToScreenPoint(point);+ var ray = cam.ScreenPointToRay(screen);+ if (!board.GetComponent<TerrainCollider>().Raycast(ray, out var boardHit, 1_000_000f)+ || !map.Terrain.GetComponent<TerrainCollider>().Raycast(ray, out var realHit, 1_000_000f)) continue;+ displayed = MapPointer.Pick(map, boardHit.point);+ real = MapPointer.Pick(map, realHit.point);+ if (displayed != real) { foundDifferentGrounds = true; break; }+ }+ Assert.IsTrue(foundDifferentGrounds, "precondition: the displayed board and lowered real terrain pick different hexes somewhere");++ Assert.AreEqual(displayed, pointer.HexAt(screen), "the displayed ground is initially nearest");+ try+ {+ board.drawHeightmap = false;+ Assert.AreEqual(real, pointer.HexAt(screen),+ "changing ground state invalidates the same-pointer, same-camera pick and falls through to the real terrain");+ }+ finally { board.drawHeightmap = true; }+ }+}diff --git a/unity/Assets/Tests/EditMode/MapLabelTests.cs b/unity/Assets/Tests/EditMode/MapLabelTests.csindex 75bd607f7..039f43476 100644--- a/unity/Assets/Tests/EditMode/MapLabelTests.cs+++ b/unity/Assets/Tests/EditMode/MapLabelTests.cs@@ -1585,6 +1585,74 @@ public class MapLabelTestsfinally { labels.Dispose(); hd.Dispose(); }}+ [UnityTest]+ public IEnumerator ASettledRefreshDoesNotReadEveryLabelSize()+ {+ var hd = new HdPanel(cam); var labels = new MapLabelsPresenter(hd.Root, map, cam);+ try+ {+ yield return Settle(labels);+ long reads = labels.LabelSizeReadsForTests, placements = labels.PlacementVisitsForTests;+ // This fixture owns a bare presenter, not a GameRoot component; Refresh is the production operation that+ // GameRoot.LateUpdate calls, without booting an unrelated scene-wide presenter into these counters.+ for (int i = 0; i < 5; i++) labels.Refresh();+ Assert.AreEqual(reads, labels.LabelSizeReadsForTests, "settled refreshes do not poll every label's resolved size");+ Assert.AreEqual(placements, labels.PlacementVisitsForTests, "settled refreshes do no placement work");++ labels.Labels[0].text += " wider";+ yield return null; // UI Toolkit delivers the label's real GeometryChangedEvent.+ labels.Refresh();+ Assert.Greater(labels.PlacementVisitsForTests, placements, "changed text invalidates real placement");+ Assert.Greater(labels.LabelSizeReadsForTests, reads, "sizes are read while that placement work runs");+ }+ finally { labels.Dispose(); hd.Dispose(); }+ }++ [UnityTest]+ public IEnumerator HoverAndPillHitsAreCachedUntilPointerOrPlacementChanges()+ {+ var hd = new HdPanel(cam); var labels = new MapLabelsPresenter(hd.Root, map, cam);+ try+ {+ Pose(35.50, 32.49, 30000f); yield return Settle(labels);+ var origin = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName).worldBound.position;+ var locality = labels.LocalitySlots.Single(x => x.name == "slot-beit_shean");+ var hover = locality.Q<Label>().worldBound.center - origin;+ var city = labels.Slots.First(Shown).Q<Label>().worldBound.center - origin;+ var panel = hd.Root.panel;+ Assert.IsNotNull(panel, "the labels have a live panel");+ Vector2 panelZero = UiPointer.ToPanel(panel, Vector2.zero, Screen.height);+ Vector2 panelX = UiPointer.ToPanel(panel, Vector2.right * 100f, Screen.height) - panelZero;+ Vector2 panelY = UiPointer.ToPanel(panel, Vector2.up * 100f, Screen.height) - panelZero;+ Vector2 ScreenPoint(Vector2 layerPoint)+ {+ var wanted = layerPoint + origin - panelZero;+ return new Vector2(wanted.x / panelX.x * 100f, wanted.y / panelY.y * 100f);+ }+ var hoverScreen = ScreenPoint(hover); var cityScreen = ScreenPoint(city);++ labels.Hover(hoverScreen); long hoverVisits = labels.HoverVisitsForTests;+ labels.Hover(hoverScreen);+ Assert.AreEqual(hoverVisits, labels.HoverVisitsForTests, "the unchanged hover reuses its hit");+ labels.Hover(ScreenPoint(hover + Vector2.right));+ Assert.Greater(labels.HoverVisitsForTests, hoverVisits, "a moved hover recomputes");++ labels.PillAt(cityScreen); long pillVisits = labels.PillVisitsForTests;+ labels.PillAt(cityScreen);+ Assert.AreEqual(pillVisits, labels.PillVisitsForTests, "the unchanged city-pill hit is reused");+ labels.PillAt(ScreenPoint(city + Vector2.right));+ Assert.Greater(labels.PillVisitsForTests, pillVisits, "a moved pill probe recomputes");++ // As above, the bare presenter has no player-loop method of its own; GameRoot owns this Refresh call in play.+ labels.Refresh(force: true);+ hoverVisits = labels.HoverVisitsForTests; pillVisits = labels.PillVisitsForTests;+ labels.Hover(hoverScreen); labels.PillAt(cityScreen);+ Assert.Greater(labels.HoverVisitsForTests, hoverVisits, "new placement invalidates hover hits");+ Assert.Greater(labels.PillVisitsForTests, pillVisits, "new placement invalidates pill hits");+ }+ finally { labels.Dispose(); hd.Dispose(); }+ }+/// <summary>Keeping clear of the unit tokens (#197) costs little next to placing the pills: one presenter, whose/// keep-clear list is switched between the units in play and none, runs interleaved sweeps (off, on, off, on, ...) of/// 240 refreshes along the same camera path; the median refresh with the units is at most 1.25 times the median without,diff --git a/unity/Assets/Tests/EditMode/TownLandmarksTests.cs b/unity/Assets/Tests/EditMode/TownLandmarksTests.csindex 2affc619c..29aaca57f 100644--- a/unity/Assets/Tests/EditMode/TownLandmarksTests.cs+++ b/unity/Assets/Tests/EditMode/TownLandmarksTests.cs@@ -684,6 +684,20 @@ public class TownLandmarksTestsfinally { Object.DestroyImmediate(camera.gameObject); }}+ [Test]+ public void ASettledWholeTownTickAllocatesNothing()+ {+ var map = OpenMap();+ TownLandmarks.Request = (id, detail, done) => { asked.Add((id, detail, done)); done(null); };+ var t = TownLandmarks.ShowAt(map, new DateTime(1949, 1, 1), Array.Empty<Placement>(), ContentLoader.Load(Statecraft.Game.Paths.Content))!;+ Assert.IsFalse(t.RefreshPending, "precondition: the layer is settled");+ // LateUpdate is private; invoking it reflectively allocates the argument array/result that this assertion must exclude.+ // Tick is LateUpdate's allocation-free production seam, while the neighbouring residency tests cover their wiring.+ t.Tick();+ Assert.That(() => { for (int i = 0; i < 8; i++) t.Tick(); }, UnityEngine.TestTools.Constraints.ConstraintExtensions.AllocatingGCMemory(Is.Not));+ Assert.IsFalse(t.RefreshPending, "settled ticks leave no work pending");+ }+static void Render(TownLandmarks t, Camera camera) => ResidencyCall(t, typeof(TownLandmarks), "OnBeginCameraRendering",default(UnityEngine.Rendering.ScriptableRenderContext), camera);diff --git a/unity/Assets/Tests/EditMode/UnitBadgeClickTests.cs b/unity/Assets/Tests/EditMode/UnitBadgeClickTests.csindex 779ef1409..4a8c44d3f 100644--- a/unity/Assets/Tests/EditMode/UnitBadgeClickTests.cs+++ b/unity/Assets/Tests/EditMode/UnitBadgeClickTests.cs@@ -66,4 +66,38 @@ public class UnitBadgeClickTestsAssert.Greater(clicked, 2, "the brigades are drawn");Assert.IsEmpty(misses, "a click on a unit's badge must pick the unit's hex");}++ [Test]+ public void RepeatedPickAtTheSamePointerAndCameraUsesOneSceneHit()+ {+ var content = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);+ var units = UnitData.Parse(File.ReadAllText(Path.Combine(Statecraft.Game.Paths.Content, "map", UnitData.DefaultFileName)));+ var layer = UnitLayer.Create(map, units, content.Hexes, still: true);+ layer.AnimateMoves = true;+ layer.Show(content, Statecraft.Sim.Simulation.NewGame(content, Statecraft.Sim.GoldenRun.Seed, Statecraft.Sim.Mode.Historical));+ var pointer = pointerGo.AddComponent<MapPointer>(); pointer.Map = map; pointer.View = cam;+ var badge = GameObject.Find(UnitLayer.RootName).transform.Find("Tokens").GetChild(0).Find("Badge");+ rig.LookAt = new Vector3(badge.position.x, 0f, badge.position.z); rig.Distance = 90000f; rig.Yaw = 0f; rig.TopInset = 0; rig.Apply();+ layer.FaceCamera(cam);+ var projected = cam.WorldToScreenPoint(badge.position); var at = new Vector2(projected.x, projected.y);+ long picks = pointer.UncachedPicksForTests, hits = layer.TokenHitQueriesForTests;++ pointer.HexAt(at); pointer.HexAt(at);+ Assert.AreEqual(picks + 1, pointer.UncachedPicksForTests, "the identical pointer and camera reuse the scene hit");+ Assert.AreEqual(hits + 1, layer.TokenHitQueriesForTests, "and scan token boxes once");+ pointer.HexAt(at + Vector2.right);+ Assert.AreEqual(picks + 2, pointer.UncachedPicksForTests, "a moved pointer recomputes");+ cam.transform.position += Vector3.right;+ pointer.HexAt(at + Vector2.right);+ Assert.AreEqual(picks + 3, pointer.UncachedPicksForTests, "a moved camera recomputes");+ layer.transform.Find("Tokens").GetChild(0).GetComponent<UnitTokenMotion>().Begin(Vector3.right * 100f);+ pointer.HexAt(at + Vector2.right);+ Assert.AreEqual(picks + 4, pointer.UncachedPicksForTests, "motion invalidates before the next hover pick");+ UnitFigures.GeometryChanged();+ pointer.HexAt(at + Vector2.right);+ Assert.AreEqual(picks + 5, pointer.UncachedPicksForTests, "new streamed figure geometry invalidates the pick");+ layer.gameObject.SetActive(false);+ pointer.HexAt(at + Vector2.right);+ Assert.AreEqual(picks + 6, pointer.UncachedPicksForTests, "a hidden unit layer recomputes without returning its stale hit");+ }}