A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Fix: town names keep clear of the settlement kits; the quality fallback ignores hidden tabs (fixes #214, fixes #216) (#241)
Eyal Golan41e373f473c7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ab441b516..0997cb5ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -116,6 +116,14 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBIt decodes to the same bytes, so the terrain is unchanged (#44).### Fixed+- Place names no longer cover the buildings of small settlements such as Degania Alef and Zikhron Ya'akov (#214). A name+ now sits above its town's buildings, or beside or below them when that space is taken, and covers at most a tenth of+ any town. With the "kits" visual toggle off, names keep clear of the marker boxes instead. Presentation only.+- The web build's quality fallback no longer lowers the quality while the page is hidden (#216). A background tab or a+ minimised window (and in Chromium a window covered by others) runs at a few frames a second, which had counted as+ load. Presentation only.+- The border determinism test no longer fails now and then on a pixel or two: it shows the proof pattern once, renders a+ warm-up frame, and compiles shaders synchronously, so both compared frames draw the same font atlas and shaders.- The 1948 Cabinet no longer shows four vacant seats for offices that did not exist yet. Offices can now carry a `from`date, and before it the office is not a Cabinet seat and cannot be filled. The dates are Education and Culture 10 March1949, rationing 26 April 1949, President of Israel 16 February 1949 and Minister without Portfolio 8 October 1951. Thediff --git a/unity/Assets/Scripts/Map/DocumentVisibility.jslib b/unity/Assets/Scripts/Map/DocumentVisibility.jslibnew file mode 100644index 000000000..0d7de2def--- /dev/null+++ b/unity/Assets/Scripts/Map/DocumentVisibility.jslib@@ -0,0 +1,6 @@+// Whether the page is hidden (a background tab or a minimised window; in Chromium on Windows and macOS also a window+// covered by others, which Firefox and Safari leave visible): QualityFallbackDriver does not measure frames then, since+// the browser throttles them (issue #216).+mergeInto(LibraryManager.library, {+ StatecraftDocumentHidden: function () { return typeof document !== "undefined" && document.hidden ? 1 : 0; },+});diff --git a/unity/Assets/Scripts/Map/DocumentVisibility.jslib.meta b/unity/Assets/Scripts/Map/DocumentVisibility.jslib.metanew file mode 100644index 000000000..016007945--- /dev/null+++ b/unity/Assets/Scripts/Map/DocumentVisibility.jslib.meta@@ -0,0 +1,32 @@+fileFormatVersion: 2+guid: 08e97c8f6ce44dfd8e1fc8bfcbe11c3c+PluginImporter:+ externalObjects: {}+ serializedVersion: 2+ iconMap: {}+ executionOrder: {}+ defineConstraints: []+ isPreloaded: 0+ isOverridable: 0+ isExplicitlyReferenced: 0+ validateReferences: 1+ platformData:+ - first:+ Any:+ second:+ enabled: 0+ settings: {}+ - first:+ Editor: Editor+ second:+ enabled: 0+ settings:+ DefaultValueInitialized: true+ - first:+ WebGL: WebGL+ second:+ enabled: 1+ settings: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/Kits/KitLayer.cs b/unity/Assets/Scripts/Map/Kits/KitLayer.csindex 13c9a19de..3dbf5560e 100644--- a/unity/Assets/Scripts/Map/Kits/KitLayer.cs+++ b/unity/Assets/Scripts/Map/Kits/KitLayer.cs@@ -9,7 +9,8 @@ namespace Statecraft.Game.Map.Kits/// buildings, merged: one draw each, culled by its bounds) drawn with the editor-made Kit.mat, and the instanced trees/// (<see cref="VegetationLayer"/>) drawn with Tree.mat. Meshes are owned by the map's MapRuntimeAssets, so a rebuild/// frees them. Hides the marker boxes under <paramref name="markers"/> while the kits show. Registers the "kits" and- /// "trees" visual toggles, so the frame-time profile prices each ("kits" off shows the markers again).</summary>+ /// "trees" visual toggles, so the frame-time profile prices each ("kits" off shows the markers again). Fills+ /// <paramref name="columns"/>, when given, with each kit's columns (world space: the kits sit at the root's origin).</summary>public static class KitLayer{public const string RootName = "Kits", VegetationName = "Vegetation";@@ -23,7 +24,7 @@ namespace Statecraft.Game.Map.Kitspublic static GameObject Build(IReadOnlyList<Settlement> settlements, Terrain terrain, GeoFrame frame, HexFile hexes, float elevMinM,Material kitMaterial, Material treeMaterial, MapRuntimeAssets assets, GameObject markers, out Stats stats,- IReadOnlyList<(List<Vector2> line, float halfWidth)>? corridors = null)+ IReadOnlyList<(List<Vector2> line, float halfWidth)>? corridors = null, Dictionary<string, Bounds[]>? columns = null){stats = new Stats();var root = new GameObject(RootName);@@ -33,7 +34,7 @@ namespace Statecraft.Game.Map.Kitsif (corridors != null) foreach (var (line, half) in corridors) ground.AddCorridor(line, half);stats.CorridorSegments = ground.CorridorSegments;var clock = System.Diagnostics.Stopwatch.StartNew();- var built = SettlementKits.Build(settlements, ground, out var lots);+ var built = SettlementKits.Build(settlements, ground, out var lots, columns); // the labels' kit footprints (issue #214)foreach (var l in lots) ground.Lots.Add((l.centre, l.radius));foreach (var (s, mesh, n) in built){diff --git a/unity/Assets/Scripts/Map/Kits/KitMesh.cs b/unity/Assets/Scripts/Map/Kits/KitMesh.csindex 85879e4ce..05d5b26df 100644--- a/unity/Assets/Scripts/Map/Kits/KitMesh.cs+++ b/unity/Assets/Scripts/Map/Kits/KitMesh.cs@@ -34,6 +34,38 @@ namespace Statecraft.Game.Map.Kitsreturn m;}+ /// <summary>The grid a kit's columns are counted on (Columns).</summary>+ public const int ColumnGrid = 4;++ /// <summary>This mesh's vertices as columns (see the static Columns); empty for an empty mesh. Read before+ /// ToMesh's upload drops the CPU copy.</summary>+ public Bounds[] Columns() => pos.Count == 0 ? new Bounds[0] : Columns(pos);++ /// <summary>The occupied columns of a point set: for each cell of a <paramref name="grid"/>-square grid over the points'+ /// footprint that holds any, a box over its points from the lowest point of the set to the cell's highest (the map+ /// labels keep clear of these, issue #214; MapScene.TryKitColumns).</summary>+ public static Bounds[] Columns(IReadOnlyList<Vector3> points, int grid = ColumnGrid)+ {+ var min = points[0]; var max = points[0];+ foreach (var p in points) { min = Vector3.Min(min, p); max = Vector3.Max(max, p); }+ var lo = new Vector3[grid * grid]; var hi = new Vector3[grid * grid]; var used = new bool[grid * grid];+ float sx = Mathf.Max(max.x - min.x, 1e-3f) / grid, sz = Mathf.Max(max.z - min.z, 1e-3f) / grid;+ foreach (var p in points)+ {+ int i = Mathf.Min(grid - 1, (int)((p.x - min.x) / sx)) + grid * Mathf.Min(grid - 1, (int)((p.z - min.z) / sz));+ if (!used[i]) { used[i] = true; lo[i] = p; hi[i] = p; }+ else { lo[i] = Vector3.Min(lo[i], p); hi[i] = Vector3.Max(hi[i], p); }+ }+ var result = new List<Bounds>();+ for (int i = 0; i < used.Length; i++)+ if (used[i])+ {+ var b = new Bounds(); b.SetMinMax(new Vector3(lo[i].x, min.y, lo[i].z), hi[i]);+ result.Add(b);+ }+ return result.ToArray();+ }+int V(Vector3 p, Vector3 n, Color32 c, Vector2 t) { pos.Add(p); nrm.Add(n); col.Add(c); uv.Add(t); return pos.Count - 1; }void Quad(int a, int b, int c, int d) { tri.Add(a); tri.Add(b); tri.Add(c); tri.Add(a); tri.Add(c); tri.Add(d); }diff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs b/unity/Assets/Scripts/Map/Kits/SettlementKits.csindex 57dd501bb..ea0aff0ef 100644--- a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.cs@@ -49,9 +49,10 @@ namespace Statecraft.Game.Map.KitsBuild(list, ground, out _);/// <summary>As Build, also returning every claimed lot (centre, radius, owning settlement id): buildings and landmarks- /// of all towns, none overlapping another (tests).</summary>+ /// of all towns, none overlapping another (tests); and, when <paramref name="columns"/> is given, filling it with each+ /// non-empty kit's columns by settlement id (KitMesh.Columns, read before the mesh's CPU copy is dropped).</summary>public static List<(Settlement s, Mesh mesh, int buildings)> Build(IReadOnlyList<Settlement> list, KitGround ground,- out List<(Vector2 centre, float radius, string id)> claimed)+ out List<(Vector2 centre, float radius, string id)> claimed, Dictionary<string, Bounds[]>? columns = null){var order = new List<Settlement>(list);order.Sort((a, b) => KitPopulation.Of(b.Id).CompareTo(KitPopulation.Of(a.Id)) != 0@@ -70,6 +71,7 @@ namespace Statecraft.Game.Map.Kits{var km = new KitMesh();int n = BuildOne(s, centres[s.Id], ground, km, lots);+ if (columns != null && km.VertexCount > 0) columns[s.Id] = km.Columns();result.Add((s, km.ToMesh(s.Id + "_kit"), n));}claimed = lots.ConvertAll(l => (centre: l.c, radius: l.r, id: l.id));diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 24f5f7884..9c1754abb 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -106,6 +106,21 @@ namespace Statecraft.Game.Map/// <summary>The last Build's kit numbers (buildings, vertices, trees, build time), or null without kits.</summary>public Kits.KitLayer.Stats KitStats { get; private set; }+ readonly Dictionary<string, Bounds[]> kitColumns = new Dictionary<string, Bounds[]>();++ /// <summary>A settlement's kit (its buildings' merged mesh, as the last Build made it) as a few world boxes that hold+ /// all of it: the occupied cells of a KitMesh.ColumnGrid-square grid over its footprint, each from the ground+ /// under the kit to its tallest vertex in the cell. Much tighter on screen than the kit's one bounding box under a+ /// tilted camera (a water tower at the back no longer lifts the whole box). False without kits or for a kit with no+ /// buildings. The map labels keep clear of it (issue #214).</summary>+ public bool TryKitColumns(string id, out Bounds[] columns) => kitColumns.TryGetValue(id, out columns);++ MeshRenderer kitProbe; // one kit's renderer: the "kits" toggle enables or disables them all together++ /// <summary>Whether the kits are drawn (built, and the "kits" toggle on); when not, the marker boxes are, and the map+ /// labels keep clear of those instead.</summary>+ public bool KitsShown => kitProbe != null && kitProbe.enabled;+/// <summary>Builds from the repository files with System.IO (editor and desktop only).</summary>public void Build() => Build(GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap));@@ -121,6 +136,7 @@ namespace Statecraft.Game.Mapif (cam == null) throw new InvalidOperationException("MapScene needs a camera tagged MainCamera");Clear();+ kitColumns.Clear(); kitProbe = null;var (meta, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z, MetaPath);DiagLog.BootPhase("heightmap decoded");Hexes = MapBuilder.LoadHexes(inputs.HexesJson, HexesPath);@@ -171,8 +187,9 @@ namespace Statecraft.Game.Map// The kits replace the marker boxes; the boxes stay as the labels' and tests' anchors, and come back when the// "kits" toggle turns the kits off (so settlements are never left undrawn).var kits = Kits.KitLayer.Build(list, Terrain, Frame, Hexes, meta.elev_min_m, kitMaterial, treeMaterial,- terrainGo.GetComponent<MapRuntimeAssets>(), markers, out var stats, Routes.RouteLayer.Corridors(Frame, routes));+ terrainGo.GetComponent<MapRuntimeAssets>(), markers, out var stats, Routes.RouteLayer.Corridors(Frame, routes), kitColumns);kits.transform.SetParent(transform, true);+ kitProbe = kits.GetComponentInChildren<MeshRenderer>(true);KitStats = stats;DiagLog.BootPhase("kits built");Debug.Log(stats.ToString());diff --git a/unity/Assets/Scripts/Map/QualityFallback.cs b/unity/Assets/Scripts/Map/QualityFallback.csindex 83e234d17..0355b3272 100644--- a/unity/Assets/Scripts/Map/QualityFallback.cs+++ b/unity/Assets/Scripts/Map/QualityFallback.cs@@ -27,7 +27,15 @@ namespace Statecraft.Game.Map/// under the floor; the tilt-shift costs under 1.5 ms. Between 20 and 34 ms nothing changes (the dead band)./// - Settle: frames in the first 0.5 s after a change are not measured (the change reallocates render targets), nor/// the first 3 s after start (scene load and shader compiles).- /// - A frame over 1 s is a pause (a hidden tab, a stalled load), not load: it drops the window.+ /// - A frame over 1 s is a pause (a stalled load, a tab coming back), not load: it drops the window.+ /// - A hidden page is not measured (issue #216, integration B18): a browser throttles a background tab or a minimised+ /// window to a few frames a second (170-200 ms frames, each under the 1 s pause line), which says nothing about the+ /// device. Chromium on Windows and macOS also marks a window covered by others hidden (B18 was one); Firefox and+ /// Safari do not, and there only the 1 s pause line catches a stall. While Background is set+ /// (QualityFallbackDriver reads document.hidden) frames are ignored and+ /// the partial window is dropped; on coming back the first ResumeSettleSeconds are not measured either. The level and+ /// the count of good windows towards a step up are kept, so a level that a real shortfall set recovers as usual+ /// once the page is in front: RecoverNeeded windows in a row under RecoverMs./// - A window needs MinWindowFrames = 3 frames. With every counted frame at most 1 s, a full 3 s window always has 3,/// so every window counts down to 1 fps (review M2: a minimum of 10 left 1-3 fps devices, the ones that need the/// fallback most, with no decision at all). Few frames make the p95 the slowest frame, but a window that holds under@@ -47,7 +55,7 @@ namespace Statecraft.Game.Map/// 0.8-1.0 dynamic range (notes 2.3), then the tilt-shift.</summary>public static readonly IReadOnlyList<Step> Steps = new[] { new Step(1f, true), new Step(0.9f, true), new Step(0.8f, true), new Step(0.8f, false) };- public const float FloorMs = 33f, OverMs = 34f, RecoverMs = 20f, WindowSeconds = 3f, SettleSeconds = 0.5f, StartupSeconds = 3f, PauseMs = 1000f;+ public const float FloorMs = 33f, OverMs = 34f, RecoverMs = 20f, WindowSeconds = 3f, SettleSeconds = 0.5f, StartupSeconds = 3f, PauseMs = 1000f, ResumeSettleSeconds = 1f;public const int MinWindowFrames = 3, RecoverWindows = 3, MaxRecoverWindows = 48, FailedRecoveryWindows = 2;public int Level { get; private set; }@@ -59,6 +67,20 @@ namespace Statecraft.Game.Map/// <summary>Windows in a row under RecoverMs that the next step up needs (doubles after a failed step up).</summary>public int RecoverNeeded { get; private set; } = RecoverWindows;+ /// <summary>Whether the page is hidden (document.hidden: a background tab or a minimised window, and in Chromium a+ /// covered one): frames are not measured.</summary>+ public bool Background { get; private set; }++ /// <summary>Sets <see cref="Background"/>. Going hidden drops the partial window; coming back starts a+ /// ResumeSettleSeconds settle (the first frames back redraw and refill caches).</summary>+ public void SetBackground(bool hidden)+ {+ if (hidden == Background) return;+ Background = hidden;+ window.Clear(); windowMs = 0f;+ if (!hidden) settleMs = Math.Max(settleMs, ResumeSettleSeconds * 1000f);+ }+readonly List<float> window = new List<float>();float windowMs, settleMs = StartupSeconds * 1000f;int goodWindows, windowsSinceStepUp = int.MaxValue;@@ -66,7 +88,7 @@ namespace Statecraft.Game.Map/// <summary>Feeds one frame's time in ms; true when it moved Level (the caller then applies Current).</summary>public bool Feed(float frameMs){- if (float.IsNaN(frameMs) || frameMs < 0f) return false;+ if (float.IsNaN(frameMs) || frameMs < 0f || Background) return false;if (frameMs > PauseMs) { window.Clear(); windowMs = 0f; return false; }if (settleMs > 0f) { settleMs -= frameMs; return false; }window.Add(frameMs); windowMs += frameMs;@@ -104,12 +126,15 @@ namespace Statecraft.Game.Mappublic string Line() => string.Format(CultureInfo.InvariantCulture, "QUALITY level={0} {1} p95_ms={2:0.00}", Level, Current, LastP95);}- /// <summary>Feeds QualityFallback the player's frame times (unscaled, so a paused game still counts) and applies its step:+ /// <summary>Feeds QualityFallback the player's frame times (unscaled, so a paused game still counts) and whether the page+ /// is hidden (document.hidden through DocumentVisibility.jslib, read every frame; never hidden outside the WebGL player), and applies its step:/// the active URP asset's render scale (never above the tier's own) and TiltShift.FallbackOff. CameraRig.Init attaches it/// to the map camera through Attach, whose undo (run by the map's teardown) removes it and puts both back.</summary>public sealed class QualityFallbackDriver : MonoBehaviour{public QualityFallback Controller { get; } = new QualityFallback();+ /// <summary>Whether the page is hidden now (tests replace it).</summary>+ public Func<bool> Hidden { get; set; } = DocumentHidden;float tierScale = 1f;Action<float> setScale = _ => { };@@ -141,6 +166,13 @@ namespace Statecraft.Game.MapDebug.Log(Controller.Line());}- void Update() => Feed(Time.unscaledDeltaTime * 1000f);+ void Update() { Controller.SetBackground(Hidden()); Feed(Time.unscaledDeltaTime * 1000f); }++#if UNITY_WEBGL && !UNITY_EDITOR+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern int StatecraftDocumentHidden();+ static bool DocumentHidden() => StatecraftDocumentHidden() != 0;+#else+ static bool DocumentHidden() => false;+#endif}}diff --git a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs b/unity/Assets/Scripts/UI/MapLabelsPresenter.csindex 613262252..dea03cb46 100644--- a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs+++ b/unity/Assets/Scripts/UI/MapLabelsPresenter.cs@@ -10,52 +10,69 @@ namespace Statecraft.Game.UI/// <summary>Settlement names as UI Toolkit pills (EB Garamond SemiBold on navy with a gold edge, Statecraft.uss/// ".map-label") in the click-through "map-labels" layer under the panels. Each pill sits in a zero-size absolute slot;/// Refresh (GameRoot.LateUpdate, after the camera has moved) moves each slot with an inline pixel translate to its- /// marker's top as the camera sees it, LiftPx above it, so no layout pass runs per frame, and returns early when+ /// kit's top edge as the camera sees it, LiftPx above it, so no layout pass runs per frame, and returns early when/// nothing it reads has changed (the camera's view-projection and rect, the panel's size, the layer's origin, the zoom,/// which panels are shown, the pills' sizes, and no GeometryChangedEvent since). A GeometryChangedEvent on the layer or/// on a panel re-places the pills at once, inside the layout pass and before the repaint. The mapping assumes the camera's view fills the panel,/// as it does in the game (both span the canvas), so DPR, render scale and the panel's scale cancel out.///+ /// Kits (issue #214): a pill keeps clear of its settlement's kit, as the promo hangs its names above the towns. Each+ /// refresh projects the kit's columns (MapScene.TryKitColumns, a few world boxes that hold its buildings; the marker+ /// box when there is no kit, or while the "kits" toggle is off and the boxes are drawn) to a screen rectangle, and+ /// every spot a pill may take is placed against that rectangle: above it (centred, or to the left or right of its+ /// centre), then beside it on the right or the left, then below it. Only when none of those fits may a pill sit over+ /// its kit, its bottom centre LiftPx above the settlement's point, and only if it covers at most MaxKitCover of the+ /// kit's rectangle (a big city's name over its own streets, never a kibbutz's roofs under a pill).+ ////// Declutter: pills are placed in priority order (city, then town and Arab town, then the rest, each in file order). A/// pill is hidden (visibility, so it keeps its size and the choice does not flicker) when its marker is behind the- /// camera, off screen or under a panel (the top bar, the info panel, the minimap, the event card), when it is a minor- /// place (village, kibbutz, moshav) beyond DeclutterDistanceM, or when no anchor fits. Its anchor class (USS) is tried- /// first, then the others (lower right, lower left, lower centre, then centred below the marker), applied as a pixel- /// shift on the slot's translate (no class change, so no style pass). An anchor fits when the pill lies wholly on- /// screen and clear of every panel, does not overlap an already placed pill (its last laid-out size plus MarginPx), and is more than twice- /// as far from every other visible marker's top as from its own, plus MarginPx, so no name reads as a neighbour's. A- /// city whose anchors all crowd a neighbour keeps the first that is clear of panels and pills. A pill hidden in the- /// last refresh needs HysteresisPx more room to come back, so it does not blink at a threshold. Refresh allocates- /// nothing. The dense Tel Aviv - Lod cluster keeps M2's anchor classes and Ramla's nudge west. The anchors are read- /// once, when the presenter is created (a later MapScene.Build needs a new presenter; GameRoot makes one per Begin).</summary>+ /// camera, off screen or under a panel (OccluderNames), when it is a minor+ /// place (village, kibbutz, moshav) beyond DeclutterDistanceM, or when no spot fits. Its anchor class (USS) picks which+ /// of the three spots above the kit is tried first; the spots are applied as a pixel shift on the slot's translate (no+ /// class change, so no style pass). A spot fits when the pill lies wholly on screen and clear of every panel+ /// (OccluderNames: the top bar, the info panel, the minimap and its map-layer caption, the event card), does not+ /// overlap an already placed pill (its last laid-out size plus MarginPx), covers at most MaxKitCover of its own kit's+ /// rectangle and of every other visible kit's, and is more than twice as far from every other visible marker's top as+ /// from its own kit, plus MarginPx, so no name reads as a neighbour's. A city whose spots all crowd a neighbour keeps+ /// the first that is clear of panels, pills and its own kit. A pill hidden in the last refresh needs HysteresisPx more+ /// room to come back, so it does not blink at a threshold. Refresh allocates nothing. The dense Tel Aviv - Lod cluster+ /// keeps M2's anchor classes. The kits' bounds are read once, when the presenter is created (a later MapScene.Build+ /// needs a new presenter; GameRoot makes one per Begin).</summary>public sealed class MapLabelsPresenter : IDisposable{public const string ContainerName = "map-labels", SlotClass = "map-label-slot", LabelClass = "map-label";public const float LiftPx = 6f, MarginPx = 4f, DeclutterDistanceM = 150000f;/// <summary>Extra room a pill hidden in the last refresh needs before it is shown again (review M7).</summary>public const float HysteresisPx = 2f;+ /// <summary>The most of a kit's screen rectangle a pill may cover (issue #214): its own kit's, and any other+ /// visible kit's.</summary>+ public const float MaxKitCover = 0.1f;/// <summary>The panels a pill never sits under (Game.uxml names).</summary>- public static readonly string[] OccluderNames = { "top-bar", "info-panel", "minimap", "event-card" };+ public static readonly string[] OccluderNames = { "top-bar", "info-panel", "minimap", "map-layer", "event-card" };++ const string Centre = "anchor-lower-centre", Left = "anchor-lower-left", Right = "anchor-lower-right";- const string Centre = "anchor-lower-centre", Left = "anchor-lower-left", Right = "anchor-lower-right", Below = "below";- static readonly string[] Fallbacks = { Right, Left, Centre, Below };+ /// <summary>Where a pill sits against its kit's screen rectangle: above it (centred on it, starting at its centre,+ /// or ending at it), beside it, below it, or over it (its bottom centre above the settlement's point).</summary>+ public enum Spot { AboveCentre, AboveLeft, AboveRight, BesideRight, BesideLeft, Below, Over }+ static readonly Spot[] Fallbacks = { Spot.AboveRight, Spot.AboveLeft, Spot.AboveCentre, Spot.BesideRight, Spot.BesideLeft, Spot.Below, Spot.Over };static readonly HashSet<string> MinorTypes = new HashSet<string> { "village", "kibbutz", "moshav" };static readonly Dictionary<string, string> AnchorClass = new Dictionary<string, string>{["jaffa"] = Right, ["rishon_lezion"] = Right, ["lod"] = Left,["petah_tikva"] = Left, ["safed"] = Right, ["rosh_pinna"] = Left,};- static readonly Dictionary<string, float> OffsetEastM = new Dictionary<string, float> { ["ramla"] = -1500f };sealed class Item{- public Settlement Settlement = null!; public Vector3 Anchor, MarkerTop, MarkerBase; public VisualElement Slot = null!;- public Label Label = null!; public string AnchorClass = ""; public bool IsCity, TopVisible, AnchorInFront, ShownLast = true;- public Vector2 TopPanel, AnchorPanel, BasePanel;+ public Settlement Settlement = null!; public Vector3 MarkerTop; public Bounds[] Kit = null!, Marker = null!; public VisualElement Slot = null!;+ public Label Label = null!; public Spot First; public bool IsCity, TopVisible, KitInFront, ShownLast = true;+ public Vector2 TopPanel; public Rect KitPanel;}readonly VisualElement container;readonly Camera camera;+ readonly MapScene map;readonly CameraRig? rig;readonly Func<float>? zoomDistance;readonly List<Item> items = new List<Item>(); // in placing (priority) order@@ -66,6 +83,7 @@ namespace Statecraft.Game.UIRect layerRect; // the panel in the layer's coordinates: a pill stays inside itreadonly EventCallback<GeometryChangedEvent> onOccluderGeometry, onContainerGeometry;Matrix4x4 lastViewProjection; Rect lastCameraRect; Vector2 lastPanelSize, lastOrigin; float lastZoom = float.NaN;+ bool lastKitsShown;int lastOccluderMask = -1; float lastLabelSizes = float.NaN; bool sizesKnown, geometryDirty = true;Action? removeToggle; // the labels switch's removal token (VisualToggles.Register): a disposed presenter never removes a newer one@@ -76,6 +94,7 @@ namespace Statecraft.Game.UI{container = root.Q<VisualElement>(ContainerName) ?? throw new InvalidOperationException($"Game.uxml has no '{ContainerName}' element");this.camera = camera;+ this.map = map;this.zoomDistance = zoomDistance;rig = camera.TryGetComponent(out CameraRig r) ? r : null;container.Clear(); // one layer, one owner: the newest presenter (GameRoot makes one per Begin)@@ -92,12 +111,11 @@ namespace Statecraft.Game.UIslot.Add(label);container.Add(slot);labels.Add(label); slots.Add(slot);- var anchor = Anchor(map, s);- var top = map.Frame.ToWorld(s.Lon, s.Lat, 0); top.y = anchor.y;+ var top = MarkerTop(map, s);settlementOrder.Add(new Item{- Settlement = s, Anchor = anchor, MarkerTop = top, MarkerBase = top - Vector3.up * SettlementPlacer.MarkerHeightM(s.Type),- Slot = slot, Label = label, AnchorClass = anchorClass, IsCity = s.Type == "city",+ Settlement = s, MarkerTop = top, Kit = KitBounds(map, s, top), Marker = MarkerBox(s, top), Slot = slot, Label = label, IsCity = s.Type == "city",+ First = anchorClass == Left ? Spot.AboveLeft : anchorClass == Right ? Spot.AboveRight : Spot.AboveCentre,});}// Stable sort: priority, then file order.@@ -120,15 +138,52 @@ namespace Statecraft.Game.UIRefresh(force: true);}- /// <summary>The world point a settlement's label hangs from: its marker's top, nudged east or west for a few crowded names.</summary>- public static Vector3 Anchor(MapScene map, Settlement s)+ /// <summary>The top of a settlement's marker box: the point a pill over its kit hangs from, and the point that says+ /// whether the place is on screen.</summary>+ public static Vector3 MarkerTop(MapScene map, Settlement s){var p = map.Frame.ToWorld(s.Lon, s.Lat, 0);- p.x += OffsetEastM.TryGetValue(s.Id, out var dx) ? dx : 0f;p.y = map.Terrain.SampleHeight(p) + map.Terrain.transform.position.y + SettlementPlacer.MarkerHeightM(s.Type);return p;}+ /// <summary>The world boxes a settlement's pill keeps clear of while the kits are drawn: its kit's columns, or+ /// without a kit its marker box.</summary>+ public static Bounds[] KitBounds(MapScene map, Settlement s, Vector3 markerTop) =>+ map.TryKitColumns(s.Id, out var columns) ? columns : MarkerBox(s, markerTop);++ /// <summary>A settlement's marker box (what is drawn while the "kits" toggle is off).</summary>+ public static Bounds[] MarkerBox(Settlement s, Vector3 markerTop)+ {+ float h = SettlementPlacer.MarkerHeightM(s.Type);+ return new[] { new Bounds(markerTop - Vector3.up * (h / 2f), new Vector3(h, h, h)) };+ }++ /// <summary>The pill's rectangle at <paramref name="spot"/> against the kit's screen rectangle <paramref name="kit"/>+ /// (LiftPx clear of it); Over hangs it LiftPx above <paramref name="point"/> instead.</summary>+ public static Rect SpotRect(Spot spot, Rect kit, Vector2 point, Vector2 size)+ {+ float above = kit.yMin - LiftPx - size.y, cx = kit.center.x, cy = kit.center.y;+ return spot switch+ {+ Spot.AboveCentre => new Rect(cx - size.x / 2f, above, size.x, size.y),+ Spot.AboveLeft => new Rect(cx, above, size.x, size.y),+ Spot.AboveRight => new Rect(cx - size.x, above, size.x, size.y),+ Spot.BesideRight => new Rect(kit.xMax + LiftPx, cy - size.y / 2f, size.x, size.y),+ Spot.BesideLeft => new Rect(kit.xMin - LiftPx - size.x, cy - size.y / 2f, size.x, size.y),+ Spot.Below => new Rect(cx - size.x / 2f, kit.yMax + LiftPx, size.x, size.y),+ _ => new Rect(point.x - size.x / 2f, point.y - LiftPx - size.y, size.x, size.y),+ };+ }++ /// <summary>The share of <paramref name="kit"/>'s area that <paramref name="pill"/> covers (0 for an empty kit).</summary>+ public static float Cover(Rect pill, Rect kit)+ {+ float w = Mathf.Min(pill.xMax, kit.xMax) - Mathf.Max(pill.xMin, kit.xMin), h = Mathf.Min(pill.yMax, kit.yMax) - Mathf.Max(pill.yMin, kit.yMin);+ float area = kit.width * kit.height;+ return w <= 0f || h <= 0f || area <= 0f ? 0f : w * h / area;+ }+/// <summary>Placing order: lower first. Cities, then towns and Arab towns, then villages, kibbutzim and moshavim.</summary>public static int Priority(string type) => type == "city" ? 0 : type == "town" || type == "arab_town" ? 1 : 2;@@ -165,13 +220,14 @@ namespace Statecraft.Game.UIvar screen = panel.visualTree.layout.size; // the whole panel, which the camera's view fillsvar origin = container.worldBound.position; // slots translate from the layer's top-leftfloat distance = Zoom();+ bool kitsShown = map != null && 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)for (int i = 0; i < items.Count; i++) { 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- && screen == lastPanelSize && origin == lastOrigin && distance == lastZoom && mask == lastOccluderMask) return;+ && screen == lastPanelSize && origin == lastOrigin && distance == lastZoom && mask == lastOccluderMask && kitsShown == lastKitsShown) return;lastViewProjection = viewProjection; lastCameraRect = cameraRect; lastPanelSize = screen; lastOrigin = origin;- lastZoom = distance; lastOccluderMask = mask; lastLabelSizes = labelSizes; geometryDirty = false;+ lastZoom = distance; lastOccluderMask = mask; lastKitsShown = kitsShown; lastLabelSizes = labelSizes; 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@@ -192,18 +248,15 @@ namespace Statecraft.Game.UIvar t = camera.WorldToViewportPoint(it.MarkerTop);it.TopPanel = ToPanel(t, cameraRect, screen, origin);it.TopVisible = t.z > 0f && t.x >= 0f && t.x <= 1f && t.y >= 0f && t.y <= 1f && !UnderAPanel(it.TopPanel); // a marker under a panel is no one's neighbour- var v = camera.WorldToViewportPoint(it.Anchor);- it.AnchorInFront = OnScreen(v);- it.AnchorPanel = ToPanel(v, cameraRect, screen, origin);- it.BasePanel = ToPanel(camera.WorldToViewportPoint(it.MarkerBase), cameraRect, screen, origin);+ it.KitInFront = ProjectBoxes(kitsShown ? it.Kit : it.Marker, viewProjection, cameraRect, screen, origin, out it.KitPanel);}placed.Clear();for (int i = 0; i < items.Count; i++){var it = items[i];- bool shown = it.AnchorInFront && it.TopVisible && !HiddenByZoom(it.Settlement.Type, distance);- var at = new Vector2(it.AnchorPanel.x, it.AnchorPanel.y - LiftPx);+ bool shown = it.KitInFront && it.TopVisible && !HiddenByZoom(it.Settlement.Type, distance);+ var at = new Vector2(it.KitPanel.center.x, it.KitPanel.yMin - LiftPx); // the slot: the USS anchor puts the pill above the kitvar shift = Vector2.zero;if (shown){@@ -212,15 +265,15 @@ namespace Statecraft.Game.UIelse{float extra = it.ShownLast ? 0f : HysteresisPx;- var home = PillRect(at, size, it.AnchorClass);- bool found = TryPlace(it, at, size, home, it.AnchorClass, extra, true, ref shift);+ var home = SpotRect(it.First, it.KitPanel, it.TopPanel, size); // where the USS anchor class draws it+ bool found = TryPlace(it, size, home, it.First, extra, true, ref shift);for (int k = 0; !found && k < Fallbacks.Length; k++)- if (Fallbacks[k] != it.AnchorClass) found = TryPlace(it, at, size, home, Fallbacks[k], extra, true, ref shift);+ if (Fallbacks[k] != it.First) found = TryPlace(it, size, home, Fallbacks[k], extra, true, ref shift);if (!found && it.IsCity){- found = TryPlace(it, at, size, home, it.AnchorClass, extra, false, ref shift);+ found = TryPlace(it, size, home, it.First, extra, false, ref shift);for (int k = 0; !found && k < Fallbacks.Length; k++)- if (Fallbacks[k] != it.AnchorClass) found = TryPlace(it, at, size, home, Fallbacks[k], extra, false, ref shift);+ if (Fallbacks[k] != it.First) found = TryPlace(it, size, home, Fallbacks[k], extra, false, ref shift);}shown = found;}@@ -231,25 +284,25 @@ namespace Statecraft.Game.UI}}- /// <summary>Whether the pill fits with <paramref name="anchor"/>; if so records it as placed and sets the shift from+ /// <summary>Whether the pill fits at <paramref name="spot"/>; if so records it as placed and sets the shift from/// its USS anchor's rectangle <paramref name="home"/>.</summary>- bool TryPlace(Item it, Vector2 at, Vector2 size, Rect home, string anchor, float extra, bool clearOfNeighbours, ref Vector2 shift)+ bool TryPlace(Item it, Vector2 size, Rect home, Spot spot, float extra, bool clearOfNeighbours, ref Vector2 shift){- var r = anchor == Below- ? new Rect(it.BasePanel.x - size.x / 2f, it.BasePanel.y + LiftPx, size.x, size.y)- : PillRect(at, size, anchor);+ var r = SpotRect(spot, it.KitPanel, it.TopPanel, size);float m = MarginPx + extra;var grown = new Rect(r.x - m, r.y - m, r.width + 2f * m, r.height + 2f * m);if (r.xMin < layerRect.xMin || r.yMin < layerRect.yMin || r.xMax > layerRect.xMax || r.yMax > layerRect.yMax) return false;for (int i = 0; i < occluderRects.Count; i++) if (occluderRects[i].Overlaps(r)) return false;for (int i = 0; i < placed.Count; i++) if (placed[i].Overlaps(grown)) return false;+ if (Cover(r, it.KitPanel) > MaxKitCover) return false;if (clearOfNeighbours){- float need = 2f * Gap(r, it.TopPanel) + MarginPx + extra;+ float need = 2f * Gap(r, it.KitPanel) + MarginPx + extra;for (int i = 0; i < items.Count; i++){var other = items[i];- if (other != it && other.TopVisible && Gap(r, other.TopPanel) <= need) return false;+ if (other == it || !other.TopVisible) continue;+ if (Gap(r, other.TopPanel) <= need || (other.KitInFront && Cover(r, other.KitPanel) > MaxKitCover)) return false;}}placed.Add(r);@@ -263,7 +316,27 @@ namespace Statecraft.Game.UIreturn false;}- static bool OnScreen(Vector3 v) => v.z > 0f && v.x > -0.05f && v.x < 1.05f && v.y > -0.05f && v.y < 1.05f;+ /// <summary>The screen rectangle of world boxes (their corners' hull in the layer's coordinates), projected with the+ /// camera's view-projection as Camera.WorldToViewportPoint does; false when a corner is behind the camera.</summary>+ static bool ProjectBoxes(Bounds[] boxes, Matrix4x4 vp, Rect cameraRect, Vector2 screen, Vector2 origin, out Rect rect)+ {+ float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;+ for (int k = 0; k < boxes.Length; k++)+ {+ var min = boxes[k].min; var max = boxes[k].max;+ for (int c = 0; c < 8; c++)+ {+ float x = (c & 1) == 0 ? min.x : max.x, y = (c & 2) == 0 ? min.y : max.y, z = (c & 4) == 0 ? min.z : max.z;+ float w = vp.m30 * x + vp.m31 * y + vp.m32 * z + vp.m33;+ if (w <= 0f) { rect = default; return false; }+ var v = new Vector3(((vp.m00 * x + vp.m01 * y + vp.m02 * z + vp.m03) / w + 1f) * 0.5f, ((vp.m10 * x + vp.m11 * y + vp.m12 * z + vp.m13) / w + 1f) * 0.5f, w);+ var p = ToPanel(v, cameraRect, screen, origin);+ x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y);+ }+ }+ rect = Rect.MinMaxRect(x0, y0, x1, y1);+ return true;+ }/// <summary>Viewport to the layer's coordinates through the camera's own rect, not/// RuntimePanelUtils.CameraTransformWorldToPanel: that flips y with Screen.height, which is wrong whenever the camera@@ -274,6 +347,10 @@ namespace Statecraft.Game.UIstatic float Gap(Rect r, Vector2 p) =>new Vector2(Mathf.Max(0f, Mathf.Max(r.xMin - p.x, p.x - r.xMax)), Mathf.Max(0f, Mathf.Max(r.yMin - p.y, p.y - r.yMax))).magnitude;+ /// <summary>The distance between two rectangles (0 when they touch or overlap).</summary>+ static float Gap(Rect a, Rect b) =>+ new Vector2(Mathf.Max(0f, Mathf.Max(a.xMin - b.xMax, b.xMin - a.xMax)), Mathf.Max(0f, Mathf.Max(a.yMin - b.yMax, b.yMin - a.yMax))).magnitude;+/// <summary>Removes only this presenter's own pills and callbacks, so an older presenter disposed after a newer one/// was made leaves the newer one's pills (review M2).</summary>public void Dispose()diff --git a/unity/Assets/Tests/EditMode/BorderTests.cs b/unity/Assets/Tests/EditMode/BorderTests.csindex 49ab287c1..118ba90ec 100644--- a/unity/Assets/Tests/EditMode/BorderTests.cs+++ b/unity/Assets/Tests/EditMode/BorderTests.cs@@ -449,19 +449,28 @@ public class BorderTestsAssert.That(share, Is.InRange(0.01f, 0.15f));}- /// <summary>The same layer and pose give the same pixels (no time, no randomness in the borders).</summary>+ /// <summary>The same layer and pose give the same pixels (no time, no randomness in the borders). The pattern is shown+ /// once and a warm-up frame is drawn first, with shaders compiled synchronously: showing it again re-created the+ /// banner's TextMesh, which can repack the dynamic font's atlas, and an editor shader variant could finish compiling+ /// between the two frames; either changed a pixel or two now and then, not the borders.</summary>[UnityTest]public IEnumerator BordersAreDeterministic(){- var (map, cam, rig) = Open();- yield return null;- RenderSample.TiltShift(false);- PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();- BorderProof.Show(map);- var a = RenderSample.Render(cam, 480, 270);- BorderProof.Show(map);- var b = RenderSample.Render(cam, 480, 270);- Assert.AreEqual(0f, Changed(a, b, 0f));+ bool async = UnityEditor.ShaderUtil.allowAsyncCompilation;+ UnityEditor.ShaderUtil.allowAsyncCompilation = false;+ try+ {+ var (map, cam, rig) = Open();+ yield return null;+ RenderSample.TiltShift(false);+ PromoPose.Gameplay03.Apply(rig, map.Frame); rig.TopInset = 0; rig.Apply();+ BorderProof.Show(map);+ RenderSample.Render(cam, 480, 270); // warm-up: the banner's glyphs and every variant in place+ var a = RenderSample.Render(cam, 480, 270);+ var b = RenderSample.Render(cam, 480, 270);+ Assert.AreEqual(0f, Changed(a, b, 0f));+ }+ finally { UnityEditor.ShaderUtil.allowAsyncCompilation = async; }}static float Median(List<float> v) { var s = v.OrderBy(x => x).ToList(); return s[s.Count / 2]; }diff --git a/unity/Assets/Tests/EditMode/MapLabelTests.cs b/unity/Assets/Tests/EditMode/MapLabelTests.csindex 7635c44ef..e78f22441 100644--- a/unity/Assets/Tests/EditMode/MapLabelTests.cs+++ b/unity/Assets/Tests/EditMode/MapLabelTests.cs@@ -81,6 +81,101 @@ public class MapLabelTestsreturn box.position + Vector3.up * box.lossyScale.y / 2;}+ /// <summary>A settlement's kit (its drawn buildings) as a panel rectangle, independently of the presenter: the hull of+ /// every vertex of its mesh through the camera's pixels.</summary>+ static Rect KitRectOf(HdPanel hd, string id)+ {+ var kit = GameObject.Find(Statecraft.Game.Map.Kits.KitLayer.RootName).transform.Find(id);+ Assert.IsNotNull(kit, id + " has a kit");+ float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;+ foreach (var v in kit.GetComponent<MeshFilter>().sharedMesh.vertices)+ {+ var p = hd.ToPanel(kit.localToWorldMatrix.MultiplyPoint3x4(v), out _);+ x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y);+ }+ return Rect.MinMaxRect(x0, y0, x1, y1);+ }++ static float Cover(Rect pill, Rect kit)+ {+ float w = Mathf.Min(pill.xMax, kit.xMax) - Mathf.Max(pill.xMin, kit.xMin), h = Mathf.Min(pill.yMax, kit.yMax) - Mathf.Max(pill.yMin, kit.yMin);+ return w <= 0 || h <= 0 ? 0f : w * h / (kit.width * kit.height);+ }++ /// <summary>Issue #214: a kit's columns hold every vertex, stand on the kit's lowest point, and keep a tall landmark's+ /// height to its own cell (a low house beside a tall tower gets a low column).</summary>+ [Test]+ public void KitColumnsHoldTheKitAndKeepATowerToItsCell()+ {+ var pts = new[] { new Vector3(0, 0, 0), new Vector3(10, 8, 10), new Vector3(90, 0, 90), new Vector3(100, 60, 100) }; // a house, a tower+ var cols = Statecraft.Game.Map.Kits.KitMesh.Columns(pts);+ Assert.AreEqual(2, cols.Length, "two occupied cells");+ foreach (var p in pts) Assert.IsTrue(cols.Any(c => c.min.x <= p.x && p.x <= c.max.x && c.min.y <= p.y && p.y <= c.max.y && c.min.z <= p.z && p.z <= c.max.z), p.ToString());+ foreach (var c in cols) Assert.AreEqual(0f, c.min.y, "from the ground");+ Assert.AreEqual(8f, cols.Min(c => c.max.y), "the house's column is as tall as the house");+ // The built map's columns come from the kit build, not from the uploaded mesh: the player has no CPU copy to read+ // (a WebGL boot read mesh.vertices and failed).+ var tlv = GameObject.Find(Statecraft.Game.Map.Kits.KitLayer.RootName).transform.Find("tel_aviv").GetComponent<MeshFilter>().sharedMesh;+ Assert.IsFalse(tlv.isReadable, "the kit meshes keep no CPU copy");+ foreach (var s in map.Settlements) Assert.IsTrue(map.TryKitColumns(s.Id, out var c) && c.Length > 0, s.Id + " has kit columns");+ }++ /// <summary>Review C-m3: with the "kits" toggle off the marker boxes are drawn, and a pill sits just above its box, not+ /// above the hidden kit; turning the kits back on moves it back above the kit.</summary>+ [UnityTest]+ public IEnumerator WithTheKitsOffAPillSitsAboveItsMarker()+ {+ var hd = new HdPanel(cam);+ var labels = new MapLabelsPresenter(hd.Root, map, cam);+ try+ {+ var deg = map.Settlements.Single(s => s.Id == "degania_alef");+ Pose(deg.Lon, deg.Lat, 10000f);+ var pill = labels.Labels.Single(l => l.name == "label-degania_alef");+ Assert.IsTrue(map.KitsShown);+ yield return Settle(labels);+ var withKit = pill.worldBound;+ VisualToggles.Set("kits", false);+ Assert.IsFalse(map.KitsShown);+ labels.Refresh(); yield return null;+ var box = GameObject.Find("Settlements").transform.Find("degania_alef");+ float top = float.MaxValue;+ for (int c = 0; c < 8; c++)+ {+ var corner = box.position + Vector3.Scale(box.lossyScale, new Vector3((c & 1) - 0.5f, ((c >> 1) & 1) - 0.5f, ((c >> 2) & 1) - 0.5f));+ top = Mathf.Min(top, hd.ToPanel(corner, out _).y);+ }+ var withMarker = pill.worldBound;+ TestContext.WriteLine($"Degania pill with the kit {withKit}, with the marker {withMarker}, marker top {top:F0}");+ Assert.AreEqual(top - MapLabelsPresenter.LiftPx, withMarker.yMax, 2f, "LiftPx above the marker box");+ Assert.Greater(withMarker.yMax, withKit.yMax + 2f, "lower than above the (hidden) kit");+ VisualToggles.Set("kits", true);+ labels.Refresh(); yield return null;+ Assert.AreEqual(withKit.yMax, pill.worldBound.yMax, 0.5f, "back above the kit");+ }+ finally { labels.Dispose(); hd.Dispose(); }+ }++ /// <summary>Issue #214: the spots a pill may take against its kit's screen rectangle, LiftPx clear of it.</summary>+ [Test]+ public void SpotsSitClearOfTheKit()+ {+ var kit = new Rect(100, 200, 60, 40); var size = new Vector2(30, 10); var point = new Vector2(130, 215);+ float lift = MapLabelsPresenter.LiftPx;+ Assert.AreEqual(new Rect(115, 200 - lift - 10, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.AboveCentre, kit, point, size));+ Assert.AreEqual(new Rect(130, 200 - lift - 10, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.AboveLeft, kit, point, size));+ Assert.AreEqual(new Rect(100, 200 - lift - 10, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.AboveRight, kit, point, size));+ Assert.AreEqual(new Rect(160 + lift, 215, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.BesideRight, kit, point, size));+ Assert.AreEqual(new Rect(100 - lift - 30, 215, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.BesideLeft, kit, point, size));+ Assert.AreEqual(new Rect(115, 240 + lift, 30, 10), MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.Below, kit, point, size));+ foreach (var spot in new[] { MapLabelsPresenter.Spot.AboveCentre, MapLabelsPresenter.Spot.AboveLeft, MapLabelsPresenter.Spot.AboveRight,+ MapLabelsPresenter.Spot.BesideRight, MapLabelsPresenter.Spot.BesideLeft, MapLabelsPresenter.Spot.Below })+ Assert.AreEqual(0f, MapLabelsPresenter.Cover(MapLabelsPresenter.SpotRect(spot, kit, point, size), kit), spot.ToString());+ var over = MapLabelsPresenter.SpotRect(MapLabelsPresenter.Spot.Over, kit, point, size);+ Assert.AreEqual(new Rect(115, 215 - lift - 10, 30, 10), over);+ Assert.AreEqual(30f * 9f / (60f * 40f), MapLabelsPresenter.Cover(over, kit), 1e-4f, "over the kit: its bottom 9 rows, 270 of its 2400 px");+ Assert.AreEqual(0f, MapLabelsPresenter.Cover(over, new Rect(0, 0, 0, 0)), "an empty kit is never covered");+ }[Test]public void EverySettlementHasOneGaramondPillThatIgnoresThePointer(){@@ -126,8 +221,6 @@ public class MapLabelTestsAssert.AreEqual("anchor-lower-right", AnchorOf("jaffa")); Assert.AreEqual("anchor-lower-right", AnchorOf("rishon_lezion"));Assert.AreEqual("anchor-lower-left", AnchorOf("lod")); Assert.AreEqual("anchor-lower-left", AnchorOf("petah_tikva"));Assert.AreEqual("anchor-lower-centre", AnchorOf("tel_aviv"));- var ramla = map.Settlements.Single(s => s.Id == "ramla");- Assert.AreEqual(map.Frame.ToWorld(ramla.Lon, ramla.Lat, 0).x - 1500f, MapLabelsPresenter.Anchor(map, ramla).x, 1f, "Ramla's label nudged west");Assert.Less(MapLabelsPresenter.Priority("city"), MapLabelsPresenter.Priority("town"));Assert.AreEqual(MapLabelsPresenter.Priority("town"), MapLabelsPresenter.Priority("arab_town"));Assert.Less(MapLabelsPresenter.Priority("arab_town"), MapLabelsPresenter.Priority("kibbutz"));@@ -213,14 +306,15 @@ public class MapLabelTestslabels.Refresh(force: true); yield return null;}- /// <summary>Independent of the presenter's own projection call: the Tel Aviv pill's bottom centre is within 2 px of its- /// marker box's top, projected with Camera.WorldToScreenPoint and the panel's scale, LiftPx above it. Also on a 2880x1620- /// target (panel scale 1.5, Retina-like) with the game's top-bar inset (review I5).</summary>+ /// <summary>Independent of the presenter's own projection call: the Tel Aviv pill sits centred over its kit and just+ /// above it (issue #214): its bottom at least LiftPx and at most 30 px above the top of the kit's drawn buildings (every+ /// vertex projected with Camera.WorldToScreenPoint and the panel's scale; the presenter's columns are a little looser). Also on a 2880x1620 target (panel scale 1.5, Retina-like) with the game's top-bar+ /// inset (review I5).</summary>[UnityTest]- public IEnumerator APillSitsJustAboveItsMarkerTop() => PillOnMarker(1920, 1080, 0f);+ public IEnumerator APillSitsJustAboveItsKit() => PillOnMarker(1920, 1080, 0f);[UnityTest]- public IEnumerator APillSitsJustAboveItsMarkerTopAtScaleOneAndAHalfWithTheTopInset() => PillOnMarker(2880, 1620, 0.088f);+ public IEnumerator APillSitsJustAboveItsKitAtScaleOneAndAHalfWithTheTopInset() => PillOnMarker(2880, 1620, 0.088f);IEnumerator PillOnMarker(int width, int height, float topInset){@@ -230,17 +324,66 @@ public class MapLabelTeststry{yield return Settle(labels);- var expected = hd.ToPanel(MarkerTopOf("tel_aviv"), out _) - new Vector2(0, MapLabelsPresenter.LiftPx);+ var kit = KitRectOf(hd, "tel_aviv");var wb = labels.Labels.Single(l => l.name == "label-tel_aviv").worldBound;- TestContext.WriteLine($"{width}x{height} inset {topInset}: Tel Aviv pill {wb}, expected bottom centre {expected}, panel {hd.Root.worldBound.size}");+ TestContext.WriteLine($"{width}x{height} inset {topInset}: Tel Aviv pill {wb}, kit {kit}, panel {hd.Root.worldBound.size}");Assert.AreEqual(1920f, hd.Root.worldBound.width, 1f, $"the panel is 1920 points wide: a scale of {width / 1920f}");- Assert.AreEqual(expected.x, wb.center.x, 2f, "centred on the marker");- Assert.AreEqual(expected.y, wb.yMax, 2f, "LiftPx above the marker's top");+ Assert.AreEqual(kit.center.x, wb.center.x, 0.05f * kit.width + 2f, "centred on the kit");+ Assert.LessOrEqual(wb.yMax, kit.yMin - MapLabelsPresenter.LiftPx + 1f, "clear of the kit, LiftPx above it");+ Assert.GreaterOrEqual(wb.yMax, kit.yMin - 30f, "just above the kit, not floating");}finally { labels.Dispose(); hd.Dispose(); }}static float Gap(Rect r, Vector2 p) => new Vector2(Mathf.Max(0, Mathf.Max(r.xMin - p.x, p.x - r.xMax)), Mathf.Max(0, Mathf.Max(r.yMin - p.y, p.y - r.yMax))).magnitude;+ static float RectGap(Rect a, Rect b) => new Vector2(Mathf.Max(0, Mathf.Max(a.xMin - b.xMax, b.xMin - a.xMax)), Mathf.Max(0, Mathf.Max(a.yMin - b.yMax, b.yMin - a.yMax))).magnitude;++ /// <summary>Issue #214 (integration B16): at the gameplay03 promo pose (with the game's top-bar inset), and close over+ /// Degania Alef (10 km) and Zikhron Ya'akov (25 km), no shown pill covers more than MaxKitCover of its own kit's screen+ /// rectangle or of any other visible kit's, and no two shown pills overlap; both small places are labelled close up.</summary>+ [UnityTest]+ public IEnumerator NoPillHidesAKit()+ {+ var hd = new HdPanel(cam);+ var labels = new MapLabelsPresenter(hd.Root, map, cam);+ var inset = new TopBarInset(hd.Root, rig);+ try+ {+ var degania = map.Settlements.Single(s => s.Id == "degania_alef");+ var zikhron = map.Settlements.Single(s => s.Id == "zikhron_yaakov");+ foreach (var (name, lon, lat, distance, yaw, must) in new[]+ {+ ("gameplay03", PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, PromoPose.Gameplay03.Distance, PromoPose.Gameplay03.Yaw, ""),+ ("degania 10 km", degania.Lon, degania.Lat, 10000f, 0f, "degania_alef"),+ ("zikhron 25 km", zikhron.Lon, zikhron.Lat, 25000f, 0f, "zikhron_yaakov"),+ })+ {+ rig.LookAt = map.Frame.ToWorld(lon, lat, 0); rig.Distance = distance; rig.Yaw = yaw; rig.Apply();+ yield return null;+ inset.Update();+ yield return Settle(labels);+ var tops = VisibleMarkerTops(hd, map);+ var shown = labels.Slots.Where(Shown).Select(s => (id: s.name.Substring("slot-".Length), rect: s.Q<Label>().worldBound)).ToList();+ TestContext.WriteLine($"{name}: {shown.Count} shown: {string.Join(" ", shown.Select(x => $"{x.id}{x.rect} kit {KitRectOf(hd, x.id)}"))}");+ Assert.Greater(shown.Count, 0, $"{name}: pills are shown");+ if (must != "") Assert.IsTrue(shown.Any(x => x.id == must), $"{name}: {must} is labelled");+ foreach (var (id, rect) in shown)+ {+ float own = Cover(rect, KitRectOf(hd, id));+ Assert.LessOrEqual(own, MapLabelsPresenter.MaxKitCover + 0.01f, $"{name}: {id}'s pill {rect} covers {own:P0} of its kit {KitRectOf(hd, id)}");+ foreach (var other in tops.Keys.Where(o => o != id))+ {+ float c = Cover(rect, KitRectOf(hd, other));+ Assert.LessOrEqual(c, MapLabelsPresenter.MaxKitCover + 0.01f, $"{name}: {id}'s pill {rect} covers {c:P0} of {other}'s kit");+ }+ }+ for (int i = 0; i < shown.Count; i++)+ for (int j = i + 1; j < shown.Count; j++)+ Assert.IsFalse(shown[i].rect.Overlaps(shown[j].rect), $"{name}: {shown[i].id} {shown[i].rect} overlaps {shown[j].id} {shown[j].rect}");+ }+ }+ finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }+ }static readonly string[] Occluders = { "top-bar", "info-panel", "minimap" };@@ -293,9 +436,11 @@ public class MapLabelTestsforeach (var (id, rect) in shown){Assert.IsTrue(tops.ContainsKey(id), $"{name}: {id} is shown but its marker is not visible");- float own = Gap(rect, tops[id]);+ // The pill's gap to its own kit (issue #214), as the presenter measures it: at most LiftPx, since its+ // kit columns may reach a few px past the drawn vertices this test projects.+ float own = Mathf.Min(RectGap(rect, KitRectOf(hd, id)), MapLabelsPresenter.LiftPx);foreach (var other in tops.Where(o => o.Key != id))- Assert.Greater(Gap(rect, other.Value), 2f * own + 4f, $"{name}: {id} pill is {own:F0} px from its marker but closer to {other.Key}'s");+ Assert.Greater(Gap(rect, other.Value), 2f * own + 4f, $"{name}: {id} pill is {own:F0} px from its kit but closer to {other.Key}'s marker");}foreach (var s in map.Settlements.Where(s => tops.ContainsKey(s.Id) && !MapLabelsPresenter.HiddenByZoom(s.Type, distance))){@@ -381,6 +526,7 @@ public class MapLabelTestsvar bar = hd.Root.Q<VisualElement>("top-bar").worldBound;var info = hd.Root.Q<VisualElement>("info-panel").worldBound;var mini = hd.Root.Q<VisualElement>("minimap").worldBound;+ var layer = hd.Root.Q<VisualElement>("map-layer").worldBound; // the minimap's caption (#234)int count = 0;foreach (var slot in labels.Slots.Where(Shown)){@@ -388,6 +534,7 @@ public class MapLabelTestsAssert.GreaterOrEqual(r.yMin, bar.yMax - 0.5f, $"{pose.Name}: {slot.name} {r} reaches under the top bar {bar}");Assert.IsFalse(r.Overlaps(info), $"{pose.Name}: {slot.name} {r} under the info panel {info}");Assert.IsFalse(r.Overlaps(mini), $"{pose.Name}: {slot.name} {r} under the minimap {mini}");+ Assert.IsFalse(layer.width > 0 && r.Overlaps(layer), $"{pose.Name}: {slot.name} {r} under the map-layer caption {layer}");}var zikhron = labels.Slots.Single(s => s.name == "slot-zikhron_yaakov");TestContext.WriteLine($"{pose.Name}: {count} shown; Zikhron Ya'akov shown={Shown(zikhron)} {zikhron.Q<Label>().worldBound}; bar {bar}");diff --git a/unity/Assets/Tests/EditMode/QualityFallbackTests.cs b/unity/Assets/Tests/EditMode/QualityFallbackTests.csindex 6fc032ee2..5d4ec2c44 100644--- a/unity/Assets/Tests/EditMode/QualityFallbackTests.cs+++ b/unity/Assets/Tests/EditMode/QualityFallbackTests.cs@@ -109,6 +109,59 @@ public class QualityFallbackTestsAssert.IsNotEmpty(steps, "35 ms is over"); Assert.AreEqual(1, steps[0]);}+ /// <summary>Issue #216 (integration B18): a Chromium window behind others (document.hidden) ran at about 5 fps (168-204 ms frames, each under the+ /// 1 s pause line) and stepped to level 3 within 90 s. Frame times alone cannot tell that from a slow device (the same+ /// frames with the page in front do step down), so the hidden page is not measured at all.</summary>+ [Test]+ public void AHiddenThrottledPageIsNotMeasured()+ {+ var shown = Started();+ Assert.IsNotEmpty(Run(shown, 200f, 90f), "control: 200 ms frames in front are load, and step down");++ var q = Started();+ int windows = q.Windows;+ q.SetBackground(true);+ Assert.IsTrue(q.Background);+ Assert.IsEmpty(Run(q, 200f, 90f), "B18: 90 s of a throttled background window");+ Assert.IsEmpty(Run(q, 170f, 90f));+ Assert.AreEqual(0, q.Level); Assert.AreEqual(windows, q.Windows, "no window was measured while hidden");+ q.SetBackground(false);+ Assert.IsEmpty(Run(q, Slow, QualityFallback.ResumeSettleSeconds - 0.1f), "the first frames back settle");+ Assert.AreEqual(windows, q.Windows);+ CollectionAssert.AreEqual(new[] { 1 }, Windows(q, Slow, 1), "a real shortfall in front still steps down");+ }++ /// <summary>Issue #216: going hidden drops the partial window, so slow frames just before a tab switch and fine ones+ /// after it are never mixed into one p95; repeated calls with the same state change nothing.</summary>+ [Test]+ public void GoingHiddenDropsThePartialWindow()+ {+ var q = Started();+ Run(q, Slow, QualityFallback.WindowSeconds - 0.5f); // most of a slow window+ q.SetBackground(true); q.SetBackground(true);+ q.SetBackground(false); q.SetBackground(false);+ Assert.IsEmpty(Windows(q, Fine, 3), "the slow frames before the switch were dropped");+ Assert.AreEqual(0, q.Level);+ Assert.Less(q.LastP95, QualityFallback.RecoverMs);+ }++ /// <summary>Issue #216: a level set by a real shortfall is kept while hidden and recovers in reverse once the page is+ /// back in front, after the usual RecoverWindows good windows (a hidden stretch counts neither for nor against).</summary>+ [Test]+ public void AFallenLevelRecoversOnceThePageIsBackInFront()+ {+ var q = Started();+ CollectionAssert.AreEqual(new[] { 1, 2 }, Windows(q, Slow, 2));+ q.SetBackground(true);+ Assert.IsEmpty(Run(q, 200f, 120f));+ Assert.AreEqual(2, q.Level, "kept while hidden: nothing is known about the device then");+ q.SetBackground(false);+ int n = QualityFallback.RecoverWindows;+ Assert.IsEmpty(Windows(q, Fine, n - 1));+ CollectionAssert.AreEqual(new[] { 1 }, Windows(q, Fine, 1), "back in front, good windows step up as usual");+ CollectionAssert.AreEqual(new[] { 0 }, Windows(q, Fine, n));+ }+[Test]public void ItRecoversInReverseOnlyAfterSustainedComfortableFrames(){