A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: an animated arrow along the tiles an Israeli unit will move through (Fixes #2134) (#2184)
Eyal Golan2789e38ba558
diff --git a/changelog.d/2134.md b/changelog.d/2134.mdnew file mode 100644index 000000000..45d446c8d--- /dev/null+++ b/changelog.d/2134.md@@ -0,0 +1,4 @@+- Map: in an Israeli unit's Move pick, the hovered hex gets an animated arrow from the unit through every hex of the+ sim's path to it (Movement.Path for a lit hex, the go-to's Movement.Route beyond), gold chevrons flowing towards an+ arrowhead on the target, the same size on screen at every zoom; never for an enemy unit, and cleared when the move is+ made or the pick ends (#2134).diff --git a/unity/Assets/Resources/Map/MoveArrow.mat b/unity/Assets/Resources/Map/MoveArrow.matnew file mode 100644index 000000000..84366fd38--- /dev/null+++ b/unity/Assets/Resources/Map/MoveArrow.mat@@ -0,0 +1,34 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!21 &2100000+Material:+ serializedVersion: 8+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_Name: MoveArrow+ m_Shader: {fileID: 4800000, guid: 3e707a1ce7c64c20b615e67c6ee65630, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords: []+ m_InvalidKeywords: []+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 0+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: -1+ stringTagMap: {}+ disabledShaderPasses: []+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs: []+ m_Ints: []+ m_Floats:+ - _Speed: 1.2+ - _WidthPerDistance: 0.016+ m_Colors:+ - _BaseColor: {r: 1, g: 0.82, b: 0.25, a: 1}+ - _InkColor: {r: 0.06, g: 0.08, b: 0.14, a: 0.9}+ m_BuildTextureStacks: []+ m_AllowLocking: 1diff --git a/unity/Assets/Resources/Map/MoveArrow.mat.meta b/unity/Assets/Resources/Map/MoveArrow.mat.metanew file mode 100644index 000000000..a7877daa8--- /dev/null+++ b/unity/Assets/Resources/Map/MoveArrow.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: ad29683ed77a4bc1b95576252ff60324+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 3c9da8767..88fe68c9f 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -272,6 +272,133 @@ namespace Statecraft.Game.Mapgo.GetComponent<MeshRenderer>().enabled = verts.Count > 0;}+ /// <summary>The move arrow's mesh (#2134), beside <see cref="RouteName"/> under the terrain.</summary>+ public const string MoveArrowName = "MoveArrow";+ /// <summary>The arrow's material (Statecraft/MoveArrow), in Resources so a player keeps it and its shader.</summary>+ public const string MoveArrowMaterialResource = "Map/MoveArrow";+ /// <summary>The arrow's full width (its head's base) per metre of camera distance, as MoveArrow.mat gives the shader:+ /// about 27 px at 1080 px at every zoom (CameraRig.Fov 35 degrees), the shaft about a third of that.</summary>+ public const float MoveArrowWidthPerDistance = 0.016f;+ /// <summary>The arrow leaves the unit's hex this share of the hex size from its centre, clear of the unit's token.</summary>+ public const float MoveArrowStartShare = 0.35f;+ /// <summary>Spacing (m) of the arrow's cross-sections along a hex-to-hex leg, each on the ground under it: about the+ /// heightmap's spacing, so the arrow keeps to the relief as the camera's tilt sees it.</summary>+ public const float MoveArrowStepM = 250f;+ /// <summary>The widest half-width (m) the shader gives the arrow: at CameraController.MaxDistance, with half again for+ /// the vertices of a tilted view that lie farther from the camera than its look-at point. The cross-sections next to+ /// a bend stay beyond the reach of a band this wide (review of #2134, C1), and the bounds hold it (C4).</summary>+ public const float MoveArrowWidestHalfM = 0.5f * MoveArrowWidthPerDistance * CameraController.MaxDistance * 1.5f;+ /// <summary>The hexes last passed to <see cref="ShowMoveArrow"/>: the unit's hex, then the path's.</summary>+ public IReadOnlyList<(int q, int r)> ShownArrow => shownArrow;+ readonly List<(int q, int r)> shownArrow = new List<(int q, int r)>();+ /// <summary>The map's hexes by (q, r), for the arrow; made once per hex file (a Build loads a new one).</summary>+ Dictionary<(int, int), HexJson> arrowHexes;+ HexFile arrowHexesOf;+ readonly List<Vector2> arrowLine = new List<Vector2>();+ readonly List<Vector3> arrowVerts = new List<Vector3>();+ readonly List<Vector2> arrowUv = new List<Vector2>();+ readonly List<Vector4> arrowSide = new List<Vector4>();+ readonly List<int> arrowTris = new List<int>();++ /// <summary>Draws the move arrow (#2134) from the first hex's centre through every later hex's centre, in order, with+ /// its head on the last: <paramref name="hexes"/> is the unit's hex and the sim's path (InfoPanelPresenter.ArrowHexes:+ /// Movement.Path or Movement.Route, never computed here). Fewer than two hexes on the map hides it. Built once per call;+ /// the chevrons move in the shader (Statecraft/MoveArrow), so nothing runs per frame.</summary>+ public void ShowMoveArrow(IReadOnlyList<(int q, int r)> hexes)+ {+ shownArrow.Clear();+ if (hexes != null) shownArrow.AddRange(hexes);+ if (Terrain == null || Hexes == null) return;+ if (arrowHexes == null || arrowHexesOf != Hexes)+ {+ arrowHexes = new Dictionary<(int, int), HexJson>();+ foreach (var h in Hexes.hexes) arrowHexes[(h.q, h.r)] = h;+ arrowHexesOf = Hexes;+ }+ var found = Terrain.transform.Find(MoveArrowName);+ var go = found != null ? found.gameObject : null;+ if (go == null)+ {+ go = new GameObject(MoveArrowName);+ go.transform.SetParent(Terrain.transform, false);+ var mesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = MoveArrowName });+ go.AddComponent<MeshFilter>().sharedMesh = mesh;+ var renderer = go.AddComponent<MeshRenderer>();+ renderer.sharedMaterial = Resources.Load<Material>(MoveArrowMaterialResource)+ ?? throw new InvalidOperationException($"Resources/{MoveArrowMaterialResource}.mat is missing");+ renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;+ renderer.receiveShadows = false;+ }+ arrowLine.Clear(); arrowVerts.Clear(); arrowUv.Clear(); arrowSide.Clear(); arrowTris.Clear();+ foreach (var at in shownArrow)+ {+ if (!arrowHexes.TryGetValue((at.q, at.r), out var hex)) continue;+ var c = Frame.ToWorld(hex.lon, hex.lat, 0);+ var point = new Vector2(c.x, c.z);+ if (arrowLine.Count == 0 || (point - arrowLine[arrowLine.Count - 1]).sqrMagnitude > 1f) arrowLine.Add(point);+ }+ if (arrowLine.Count >= 2)+ {+ arrowLine[0] += (arrowLine[1] - arrowLine[0]).normalized * (MoveArrowStartShare * Hexes.hex_size_km * 1000f);+ float total = 0f;+ for (int i = 1; i < arrowLine.Count; i++) total += (arrowLine[i] - arrowLine[i - 1]).magnitude;+ var data = Terrain.terrainData;+ float along = 0f;+ for (int i = 0; i + 1 < arrowLine.Count; i++)+ {+ Vector2 a = arrowLine[i], b = arrowLine[i + 1];+ float len = (b - a).magnitude;+ int steps = Mathf.Max(1, Mathf.CeilToInt(len / MoveArrowStepM));+ var dir = (b - a) / len;+ // Near a bend the widest band's inner edge reaches back along the leg (the mitre's setback): no cross-section+ // there, or the band would fold back over itself and blend twice (review of #2134, C1).+ float back = i > 0 ? MoveArrowWidestHalfM * MitreSetback((a - arrowLine[i - 1]).normalized, dir) : 0f;+ float front = i + 2 < arrowLine.Count ? MoveArrowWidestHalfM * MitreSetback(dir, (arrowLine[i + 2] - b).normalized) : 0f;+ for (int k = i == 0 ? 0 : 1; k <= steps; k++)+ {+ if (k > 0 && k < steps && (len * k / steps <= back || len * k / steps >= len - front)) continue;+ var p = Vector2.Lerp(a, b, (float)k / steps);+ var side = new Vector2(dir.y, -dir.x);+ // A bend (a later leg's first point): the mitre of the two legs, so the band keeps its width round it.+ if (k == steps && i + 2 < arrowLine.Count)+ {+ var next = (arrowLine[i + 2] - b).normalized;+ var mitre = (side + new Vector2(next.y, -next.x)).normalized;+ side = mitre / Mathf.Max(0.5f, Vector2.Dot(mitre, side));+ }+ float y = data.GetInterpolatedHeight(Mathf.Clamp01(p.x / Frame.WidthM), Mathf.Clamp01(p.y / Frame.LengthM)) + SelectionClearanceM;+ float s = along + len * k / steps;+ int v = arrowVerts.Count;+ for (int u = 0; u <= 1; u++)+ {+ arrowVerts.Add(new Vector3(p.x, y, p.y));+ arrowUv.Add(new Vector2(u, s));+ arrowSide.Add(new Vector4(side.x, side.y, total, 0f));+ }+ if (v > 0) { arrowTris.Add(v - 2); arrowTris.Add(v); arrowTris.Add(v - 1); arrowTris.Add(v - 1); arrowTris.Add(v); arrowTris.Add(v + 1); }+ }+ along += len;+ }+ }+ var m = go.GetComponent<MeshFilter>().sharedMesh;+ m.Clear();+ m.SetVertices(arrowVerts); m.SetUVs(0, arrowUv); m.SetUVs(1, arrowSide); m.SetTriangles(arrowTris, 0);+ // The vertices lie on the centre line and the shader widens the band: grow the bounds by the widest it is drawn, a+ // mitre's twice the half-width included (Expand grows the size, so each side by half), so culling never drops a+ // band whose centre line is just off screen (review of #2134, C4).+ var bounds = m.bounds; bounds.Expand(4f * MoveArrowWidestHalfM);+ m.bounds = bounds;+ go.GetComponent<MeshRenderer>().enabled = arrowVerts.Count > 0;+ }++ /// <summary>How far back along a leg, per metre of half-width, a band's inner edge reaches at a bend from direction+ /// <paramref name="into"/> to <paramref name="outOf"/> (unit vectors): tan of half the turn. Capped near a U-turn.</summary>+ static float MitreSetback(Vector2 into, Vector2 outOf)+ {+ float cos = Mathf.Max(-0.9f, Vector2.Dot(into, outOf));+ return Mathf.Sqrt((1f - cos) / (1f + cos));+ }+public void Configure(Material terrain, Material marker, Material selection, Material sea, Material frame){terrainMaterial = terrain; markerMaterial = marker; selectionMaterial = selection;diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 88075d8dd..252da45f2 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -403,7 +403,7 @@ namespace Statecraft.Game.UIshowReachable: map.ShowReachable,unitName: id => unitLayer.Tokens.Where(p => UnitCard.SimUnit(bridge.Content, bridge.State, p.Token) == id).Select(p => UnitCard.For(p, bridge.State, text, bridge.Content.IsGdd, bridge.Content, townNamesHe).Title).FirstOrDefault(),- unitDone: FocusNextUnit, showRoute: map.ShowRoute, selectPioneer: FocusPioneer, clearSelection: () => { unitLayer.Select(null); map.ClearSelection(); }));+ unitDone: FocusNextUnit, showRoute: map.ShowRoute, showArrow: map.ShowMoveArrow, selectPioneer: FocusPioneer, clearSelection: () => { unitLayer.Select(null); map.ClearSelection(); }));toast.Units = unitData; toast.TownNamesHe = townNamesHe; why.TownNamesHe = townNamesHe; bridge.TownNamesHe = townNamesHe;report.TownNamesHe = townNamesHe; hudPresenter.TownNamesHe = townNamesHe;// A smoke session never touches the player's save: no autosave, and no New Game (which deletes the autosave).diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.csindex 578aaff7b..62e251327 100644--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs@@ -50,6 +50,11 @@ namespace Statecraft.Game.UIreadonly System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable;/// <summary>Draws a multi-turn go-to route and its arrival-turn numbers; null keeps picking functional without it.</summary>readonly System.Action<IReadOnlyList<(int q, int r, int turn)>>? showRoute;+ /// <summary>Draws the move arrow through the hexes given (none: hides it); null keeps picking functional without it.</summary>+ readonly System.Action<IReadOnlyList<(int q, int r)>>? showArrow;+ /// <summary>Whether the last arrow passed to showArrow had hexes: an empty arrow is passed only to clear a drawn one, so+ /// a pointer crossing the map with no arrow drawn never touches the map's mesh (review of #2134, C3).</summary>+ bool arrowDrawn;/// <summary>While the player picks a Move's or an Attack's hex: the unit, the hexes the sim gave (Movement.Reachable's,/// or those Combat.Check takes: the only ones a click takes), the session and turn they were read on (a turn or a/// load ends the pick, as the hexes change), and whether it is the attack's.</summary>@@ -95,6 +100,8 @@ namespace Statecraft.Game.UI/// <param name="showReachable">Lights the hexes a Move can go to while the player picks one, and clears them with none/// (GameRoot: MapScene.ShowReachable; null: the pick still works, with nothing lit). The Attack pick lights its hexes/// with it too.</param>+ /// <param name="showArrow">Draws the move arrow (#2134) through the unit's hex and the sim's path to the hovered hex,+ /// and hides it with none (GameRoot: MapScene.ShowMoveArrow; null: no arrow).</param>/// <param name="unitName">A sim unit's name on screen, by id (GameRoot: its token's card title), for the Attack pick's/// targets (null: the hex's coordinates).</param>public InfoPanelPresenter(VisualElement root, SimBridge bridge, UiText text, IReadOnlyDictionary<string, string> settlementNames,@@ -103,7 +110,8 @@ namespace Statecraft.Game.UISystem.Func<string, (int q, int r)>? townHex = null, IReadOnlyDictionary<string, string>? townNamesHe = null,System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable = null, System.Func<int, string?>? unitName = null,System.Action? unitDone = null,- System.Action<IReadOnlyList<(int q, int r, int turn)>>? showRoute = null, System.Action? clearSelection = null, System.Action<int>? selectPioneer = null)+ System.Action<IReadOnlyList<(int q, int r, int turn)>>? showRoute = null, System.Action? clearSelection = null, System.Action<int>? selectPioneer = null,+ System.Action<IReadOnlyList<(int q, int r)>>? showArrow = null){panel = root.Q<VisualElement>("info-panel"); this.bridge = bridge; this.text = text;// #40: the panel is a ScrollView, so Game.uxml's filigree frame lands in its scrolled content, inside the padding@@ -123,6 +131,7 @@ namespace Statecraft.Game.UIonPioneerReturn = ReturnPioneer;pioneerReturn.clicked += onPioneerReturn;this.clearSelection = clearSelection;+ this.showArrow = showArrow;onCancel = e => { if (!e.isPropagationStopped && Escape()) e.StopPropagation(); };panel.RegisterCallback(onCancel);this.settlementNames = settlementNames; this.regions = regions; this.localitiesAt = localitiesAt; this.townHex = townHex;@@ -405,6 +414,37 @@ namespace Statecraft.Game.UIif (bridge.NeedsOrders.Count > 0) unitDone?.Invoke();}+ /// <summary>#2134: the hexes the move arrow runs through: unit <paramref name="u"/>'s hex, then <paramref name="path"/>+ /// (the sim's Movement.Path or Movement.Route hexes, in order). None for an empty path, and none for a unit that is+ /// not Israel's (owner, 1 Nov 2026: "this needs to be for israeli units only"), by the sim's own rule (Movement:+ /// a side other than Israel's and the legacy loop's "" is the enemy's).</summary>+ internal static IReadOnlyList<(int q, int r)> ArrowHexes(Unit u, IEnumerable<(int Q, int R)> path)+ {+ if (u.Side != "" && u.Side != Movement.PlayerSide) return System.Array.Empty<(int, int)>();+ var hexes = new List<(int q, int r)> { (u.Q, u.R) };+ foreach (var (q, r) in path) hexes.Add((q, r));+ return hexes.Count > 1 ? hexes : (IReadOnlyList<(int q, int r)>)System.Array.Empty<(int, int)>();+ }++ /// <summary>The move arrow to (q, r) in pick <paramref name="p"/>: through Movement.Path's hexes for a lit hex (what+ /// Move spends), else through the go-to's <paramref name="route"/> (RouteTo's); none in an Attack pick.</summary>+ IReadOnlyList<(int q, int r)> ArrowTo(+ (int unit, HashSet<(int q, int r)> hexes, GameSession session, int turn, bool attack, (int q, int r)? touchRoute) p,+ int q, int r, IReadOnlyList<(int q, int r, int turn)> route)+ {+ if (p.attack || !bridge.State.Units.TryGetValue(p.unit, out var u)) return System.Array.Empty<(int, int)>();+ return p.hexes.Contains((q, r))+ ? ArrowHexes(u, Movement.Path(bridge.Content, bridge.State, p.unit, q, r, bridge.Spent))+ : ArrowHexes(u, route.Select(h => (h.q, h.r)));+ }++ void ShowArrow(IReadOnlyList<(int q, int r)> hexes)+ {+ if (hexes.Count == 0 && !arrowDrawn) return;+ arrowDrawn = hexes.Count > 0;+ showArrow?.Invoke(hexes);+ }+void EndPick(){DiscardMove();@@ -414,6 +454,7 @@ namespace Statecraft.Game.UIclickThrough = null;showReachable?.Invoke(System.Array.Empty<(int q, int r)>());showRoute?.Invoke(System.Array.Empty<(int q, int r, int turn)>());+ ShowArrow(System.Array.Empty<(int q, int r)>());}IReadOnlyList<(int q, int r, int turn)> RouteTo(@@ -432,15 +473,18 @@ namespace Statecraft.Game.UIif (shownRoute == null) return;shownRoute = null;showRoute?.Invoke(System.Array.Empty<(int q, int r, int turn)>());+ ShowArrow(System.Array.Empty<(int q, int r)>());}- /// <summary>Shows the route to the hovered unlit hex while Move is picking; otherwise clears it.</summary>+ /// <summary>Shows the route to the hovered unlit hex while Move is picking, and the move arrow to the hovered lit or+ /// routed hex (#2134); otherwise clears them. GameRoot asks every frame: the same hex again does nothing.</summary>public void ShowRouteTo(int q, int r){if (shownRoute == (q, r)) return;shownRoute = (q, r);var route = pick is { } p ? RouteTo(p, q, r) : System.Array.Empty<(int, int, int)>();showRoute?.Invoke(route);+ ShowArrow(pick is { } a ? ArrowTo(a, q, r, route) : System.Array.Empty<(int q, int r)>());}/// <summary>#1617 (player report): the lit hexes of an open Move or Attack pick show through this card (its navy is@@ -471,7 +515,9 @@ namespace Statecraft.Game.UIconfirmMove.style.display = DisplayStyle.None;}- void OnStateChanged() { DiscardMove(); Render(); }+ /// <summary>A new state (an order, a turn, a load): the hovered hex's route and arrow were read on the old one, so they+ /// are hidden, and GameRoot's next hover draws them from the new one.</summary>+ void OnStateChanged() { DiscardMove(); HideRoute(); Render(); }void OnInfoCovered(VisualElement root){@@ -560,6 +606,7 @@ namespace Statecraft.Game.UIpick = (p.unit, p.hexes, p.session, p.turn, p.attack, (q, r));shownRoute = (q, r);showRoute?.Invoke(route);+ ShowArrow(ArrowTo(p, q, r, route));Render();return true;}diff --git a/unity/Assets/Shaders/MoveArrow.shader b/unity/Assets/Shaders/MoveArrow.shadernew file mode 100644index 000000000..896d57c73--- /dev/null+++ b/unity/Assets/Shaders/MoveArrow.shader@@ -0,0 +1,92 @@+// The move arrow (#2134, MapScene.ShowMoveArrow): an animated arrow from a selected Israeli unit's hex through every hex+// of the sim's path to the hovered one. The mesh is the path's centre line, two vertices a cross-section (u 0 and 1, v+// metres along) carrying the section's sideways direction (a mitre at a bend) and the path's length; the vertex shader+// widens it in proportion to the camera's distance (_WidthPerDistance), so the arrow keeps the same size on screen at+// every zoom. The fragment shader draws a dark-edged shaft whose gold chevrons flow towards the target with _Time (no+// script runs per frame) and a solid arrowhead on the target hex's centre. Unlit and drawn over the ground, the tokens and+// the town models (ZTest Always): an order preview must never hide behind a ridge or a house.+Shader "Statecraft/MoveArrow"+{+ Properties+ {+ _WidthPerDistance ("Width (m) per metre of camera distance", Float) = 0.016+ _Speed ("Chevrons per second", Float) = 1.2+ [MainColor] _BaseColor ("Fill", Color) = (1, 0.82, 0.25, 1)+ _InkColor ("Ink", Color) = (0.06, 0.08, 0.14, 0.9)+ }+ SubShader+ {+ Tags { "RenderType" = "Transparent" "Queue" = "Transparent+50" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" }+ Pass+ {+ Name "Unlit"+ Tags { "LightMode" = "UniversalForward" }+ Cull Off+ ZWrite Off+ ZTest Always+ Blend SrcAlpha OneMinusSrcAlpha+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ CBUFFER_START(UnityPerMaterial)+ float _WidthPerDistance;+ float _Speed;+ half4 _BaseColor;+ half4 _InkColor;+ CBUFFER_END++ // Shares of the arrow's full width (the arrowhead's base): the shaft's half-width, the ink edge; the head's+ // length; a chevron's period along the shaft and how far its arms lean back.+ static const float ShaftHalf = 0.17, Ink = 0.07, HeadLength = 1.25, Period = 1.4, Lean = 0.9;++ struct Attributes { float4 positionOS : POSITION; float2 uv : TEXCOORD0; float4 side : TEXCOORD1; };+ struct Varyings+ {+ float4 positionCS : SV_POSITION;+ float across : TEXCOORD0; // -0.5 .. 0.5 of the width+ float along : TEXCOORD1; // metres from the arrow's start+ float width : TEXCOORD2; // metres+ float total : TEXCOORD3; // the path's length, metres+ };++ Varyings Vert(Attributes input)+ {+ float3 centre = TransformObjectToWorld(input.positionOS.xyz);+ float width = _WidthPerDistance * distance(GetCameraPositionWS(), centre);+ float across = input.uv.x - 0.5;+ float3 side = TransformObjectToWorldDir(float3(input.side.x, 0, input.side.y), false);+ Varyings o;+ o.positionCS = TransformWorldToHClip(centre + side * (across * width));+ o.across = across; o.along = input.uv.y; o.width = width; o.total = input.side.z;+ return o;+ }++ // Coverage of a signed distance (negative inside), box-filtered to the pixel.+ float Cover(float d) { return saturate(0.5 - d / max(fwidth(d), 1e-5)); }++ half4 Frag(Varyings input) : SV_Target+ {+ float a = abs(input.across);+ float w = max(input.width, 1e-3);+ float toTip = (input.total - input.along) / w; // in widths+ // The arrowhead: a triangle from the full width at HeadLength before the tip to a point at the tip. The shaft:+ // ShaftHalf either side of the line, up to the head's base. Distances in widths, negative inside.+ float head = max(a - 0.5 * toTip / HeadLength, toTip - HeadLength);+ float shaft = max(a - ShaftHalf, HeadLength - toTip);+ float d = min(head, shaft);+ float shape = Cover(d - Ink); // the whole arrow, ink edge included+ float fill = Cover(d);+ // The chevrons: bands whose arms trail behind their point on the line, flowing towards the tip; on the shaft only, the head solid.+ float phase = frac((input.along / w + a * Lean) / Period - _Time.y * _Speed);+ float chevron = Cover(abs(phase - 0.25) - 0.25) * step(HeadLength, toTip);+ float bright = max(fill * chevron, fill * Cover(head));+ half3 colour = lerp(_InkColor.rgb, _BaseColor.rgb, bright);+ // The start fades in over one width, so the arrow leaves the unit's token softly.+ float alpha = shape * lerp(_InkColor.a, _BaseColor.a, bright) * saturate(input.along / w);+ return half4(colour, alpha);+ }+ ENDHLSL+ }+ }+}diff --git a/unity/Assets/Shaders/MoveArrow.shader.meta b/unity/Assets/Shaders/MoveArrow.shader.metanew file mode 100644index 000000000..44cd43645--- /dev/null+++ b/unity/Assets/Shaders/MoveArrow.shader.meta@@ -0,0 +1,9 @@+fileFormatVersion: 2+guid: 3e707a1ce7c64c20b615e67c6ee65630+ShaderImporter:+ externalObjects: {}+ defaultTextures: []+ nonModifiableTextures: []+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/MoveArrowShots.cs b/unity/Assets/Tests/EditMode/MoveArrowShots.csnew file mode 100644index 000000000..3412aca1c--- /dev/null+++ b/unity/Assets/Tests/EditMode/MoveArrowShots.cs@@ -0,0 +1,114 @@+#nullable enable+using System;+using System.Collections;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>#2134's pull request stills: Golani's Move pick in the game scene, the camera on Golani, the arrow to a lit hex+/// two hexes away hidden (as main draws it: nothing) and shown, at two zooms, in English and Hebrew; the arrow to a go-to hex+/// two turns away beside the route's turn numbers; and frames of the chevrons' flow for a clip. To ShotDir. Explicit.</summary>+[Explicit("writes stills for a pull request, not a check")]+public class MoveArrowShots+{+ static string ShotDir => Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", ".superpowers", "move-arrow-shots"));+ string saveDir = "";+ RenderTexture? rt; PanelSettings? ps;++ [SetUp]+ public void TempSaves()+ {+ saveDir = Path.Combine(Path.GetTempPath(), "statecraft-move-arrow-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(ShotDir);+ Directory.CreateDirectory(CivMovementShots.ShotDir); // CivMovementShots.Shot writes there first+ }++ [TearDown]+ public void DiscardScene()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);+ }++ void Shot(string name)+ {+ CivMovementShots.Shot(rt!, name);+ var from = Path.Combine(CivMovementShots.ShotDir, name + ".png");+ File.Copy(from, Path.Combine(ShotDir, name + ".png"), true);+ File.Delete(from);+ }++ /// <summary>GameRoot.LateUpdate draws the route and arrow to the hex under the batch editor's own pointer whenever that+ /// hex changes (a new camera pose changes it): a few frames let it settle, so what a still draws next stays drawn.</summary>+ static IEnumerator Settle() { for (int i = 0; i < 5; i++) yield return null; }++ IEnumerator Shots(bool hebrew)+ {+ VisualElement ui = null!; GameRoot root = null!;+ yield return CivMovementShots.Boot(hebrew, saveDir, (t, p, u, g) => { rt = t; ps = p; ui = u; root = g; });+ var bridge = root.Bridge!; var units = root.Units!; var info = root.Info!;+ var map = Object.FindFirstObjectByType<MapScene>();+ var c = bridge.Content; var s = bridge.State;+ var golani = (s.Units[0].Q, s.Units[0].R);+ var reach = Movement.Reachable(c, s, 0, bridge.Spent);+ // The lit hex the arrow points at: the first in Reachable's order whose path enters two hexes (MoveArrowTests' pick).+ var lit = reach.Keys.First(h => Movement.Path(c, s, 0, h.Q, h.R, bridge.Spent).Count >= 2);+ var far = c.Hexes.Where(h => h.Land && !reach.ContainsKey((h.Q, h.R)) && (h.Q, h.R) != golani)+ .Select(h => (h.Q, h.R)).First(h => Movement.Route(c, s, 0, h.Q, h.R, bridge.Spent).LastOrDefault().Turn == 2);+ var lang = hebrew ? "he" : "en";+ GameRoot.OnHexClicked(map, units, info, golani.Item1, golani.Item2);+ for (int i = 0; i < 3; i++) yield return null;+ // GameRoot.LateUpdate follows the batch editor's own pointer, so the stills draw what a hover over the hex draws+ // (InfoPanelPresenter.ShowRouteTo) on the map directly, as CivRouteShots does.+ var arrow = InfoPanelPresenter.ArrowHexes(s.Units[0], Movement.Path(c, s, 0, lit.Q, lit.R, bridge.Spent));+ foreach (var zoom in new[] { 45000f, 120000f })+ {+ CivMovementShots.Aim(golani.Item1, golani.Item2, zoom);+ yield return Settle();+ map.ShowMoveArrow(Array.Empty<(int, int)>());+ map.ShowRoute(Array.Empty<(int, int, int)>());+ yield return null;+ Shot($"{lang}-{zoom / 1000:0}km-before");+ map.ShowMoveArrow(arrow);+ yield return null;+ Shot($"{lang}-{zoom / 1000:0}km-after");+ }+ var route = Movement.Route(c, s, 0, far.Item1, far.Item2, bridge.Spent);+ CivMovementShots.Aim(golani.Item1, golani.Item2, 120000f);+ yield return Settle();+ map.ShowRoute(route.Select(h => (h.Q, h.R, h.Turn)).ToList());+ map.ShowMoveArrow(InfoPanelPresenter.ArrowHexes(s.Units[0], route.Select(h => (h.Q, h.R))));+ root.Labels?.Refresh(true);+ for (int i = 0; i < 5; i++) yield return null;+ root.Labels?.Refresh(true);+ yield return null;+ Shot($"{lang}-120km-goto-after");+ if (hebrew) yield break;+ // The clip: the arrow to the lit hex at the closer zoom, a frame about every 80 ms of the editor's clock.+ CivMovementShots.Aim(golani.Item1, golani.Item2, 45000f);+ yield return Settle();+ map.ShowRoute(Array.Empty<(int, int, int)>());+ map.ShowMoveArrow(arrow);+ for (int f = 0; f < 16; f++)+ {+ var until = Time.realtimeSinceStartup + 0.08f;+ while (Time.realtimeSinceStartup < until) yield return null;+ Shot($"clip-{f:00}");+ }+ Debug.Log($"SHOT arrow {string.Join(" ", arrow.Select(h => $"{h.q},{h.r}"))}; goto {far.Item1},{far.Item2}");+ }++ [UnityTest] public IEnumerator English() { yield return Shots(false); }+ [UnityTest] public IEnumerator Hebrew() { yield return Shots(true); }+}diff --git a/unity/Assets/Tests/EditMode/MoveArrowShots.cs.meta b/unity/Assets/Tests/EditMode/MoveArrowShots.cs.metanew file mode 100644index 000000000..91cbe55cf--- /dev/null+++ b/unity/Assets/Tests/EditMode/MoveArrowShots.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: beb65b11d1b544afbc49935110b1ee2f\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/MoveArrowTests.cs b/unity/Assets/Tests/EditMode/MoveArrowTests.csnew file mode 100644index 000000000..e5315ffda--- /dev/null+++ b/unity/Assets/Tests/EditMode/MoveArrowTests.cs@@ -0,0 +1,438 @@+#nullable enable+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Units;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools.Constraints;+using UnityEngine.UIElements;+using Is = UnityEngine.TestTools.Constraints.Is;++/// <summary>#2134 (owner, 1 Nov 2026: "an arrow showing which tiles the unit is going to move to. this needs to be for+/// israeli units only"): in an Israeli unit's Move pick, the hovered hex gets an animated arrow from the unit's hex through+/// every hex of the sim's path (Movement.Path for a lit hex, Movement.Route for a go-to); never for an enemy unit; cleared+/// when the move is made or the pick ends; the per-frame hover allocates nothing and the animation is the shader's.</summary>+public class MoveArrowTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static List<UnitEntry> Units => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);+ static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");++ static MapScene BuildMap()+ {+ EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);+ var map = new GameObject("MapScene").AddComponent<MapScene>();+ map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));+ map.Build();+ return map;+ }++ sealed class Rig+ {+ public SimBridge Bridge = null!; public UnitLayer Layer = null!; public InfoPanelPresenter Info = null!;+ public readonly List<IReadOnlyList<(int q, int r)>> Arrows = new List<IReadOnlyList<(int q, int r)>>();+ public PlacedToken Golani; public int Id;+ public (int q, int r) Start => (Bridge.State.Units[Id].Q, Bridge.State.Units[Id].R);+ }++ static Rig Open(MapScene map, UiTestKit ui)+ {+ var rig = new Rig { Bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text) };+ rig.Layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ rig.Layer.Show(rig.Bridge.Content, rig.Bridge.State);+ var layer = rig.Layer;+ // The settlements' names, as UnitOrdersTests gives them: a hex the tests click may be a city's, whose card names it.+ var towns = SettlementPlacer.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", SettlementPlacer.DefaultFileName))).ToDictionary(t => t.Id, t => t.Name);+ rig.Info = new InfoPanelPresenter(ui.Root, rig.Bridge, Text, towns,+ selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null,+ showReachable: map.ShowReachable, showRoute: map.ShowRoute,+ showArrow: hexes => { rig.Arrows.Add(hexes.ToList()); map.ShowMoveArrow(hexes); },+ clearSelection: () => { layer.Select(null); map.ClearSelection(); }); // as GameRoot: Escape drops the unit too+ rig.Golani = layer.Tokens.Single(p => p.Token.Unit.Id == "golani");+ rig.Id = UnitCard.SimUnit(C, rig.Bridge.State, rig.Golani.Token.Unit)!.Value;+ return rig;+ }++ /// <summary>A lit hex two or more hexes away (Movement.Path enters at least two hexes), the first in Reachable's order.</summary>+ static (int q, int r) FarLit(Rig rig) => Movement.Reachable(C, rig.Bridge.State, rig.Id, rig.Bridge.Spent).Keys+ .Where(h => Movement.Path(C, rig.Bridge.State, rig.Id, h.Q, h.R, rig.Bridge.Spent).Count >= 2).Select(h => (h.Q, h.R)).First();++ static MeshRenderer ArrowRenderer(MapScene map) => map.Terrain.transform.Find(MapScene.MoveArrowName).GetComponent<MeshRenderer>();++ static Vector2 Centre(MapScene map, int q, int r)+ {+ var hex = map.Hexes.hexes.Single(h => h.q == q && h.r == r);+ var w = map.Frame.ToWorld(hex.lon, hex.lat, 0);+ return new Vector2(w.x, w.z);+ }++ /// <summary>(a) Hovering a lit hex draws the arrow from the unit's hex through Movement.Path's hexes, in order; the mesh's+ /// centre line passes through each of their centres. An unlit hex a go-to reaches gets Movement.Route's hexes.</summary>+ [Test]+ public void TheArrowFollowsTheSimsPathHexByHex()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var rig = Open(map, ui);+ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, rig.Golani.Q, rig.Golani.R);+ Assert.IsTrue(rig.Info.MovePicking, "precondition: selecting Golani opens its Move pick");+ var lit = FarLit(rig);+ var path = Movement.Path(C, rig.Bridge.State, rig.Id, lit.q, lit.r, rig.Bridge.Spent).Select(h => (h.Q, h.R)).ToList();+ rig.Info.ShowRouteTo(lit.q, lit.r);+ var expected = new[] { rig.Start }.Concat(path).ToList();+ CollectionAssert.AreEqual(expected, rig.Arrows.Last(), "the unit's hex, then the sim's path to the hovered hex");+ CollectionAssert.AreEqual(expected, map.ShownArrow);+ var renderer = ArrowRenderer(map);+ Assert.IsTrue(renderer.enabled);+ var go = renderer.transform;+ var line = renderer.GetComponent<MeshFilter>().sharedMesh.vertices.Select(v => { var w = go.TransformPoint(v); return new Vector2(w.x, w.z); }).ToList();+ foreach (var (q, r) in path)+ {+ var c = Centre(map, q, r);+ Assert.Less(line.Min(p => (p - c).magnitude), 1f, $"the arrow passes through hex {q},{r}'s centre");+ }++ var reach = Movement.Reachable(C, rig.Bridge.State, rig.Id, rig.Bridge.Spent).Keys.ToHashSet();+ var far = C.Hexes.Where(h => h.Land && !reach.Contains((h.Q, h.R)) && (h.Q, h.R) != rig.Start).Select(h => (h.Q, h.R))+ .First(h => Movement.Route(C, rig.Bridge.State, rig.Id, h.Q, h.R, rig.Bridge.Spent).LastOrDefault().Turn == 2);+ rig.Info.ShowRouteTo(far.Item1, far.Item2);+ var now = rig.Bridge.Session.Now;+ var route = Movement.Route(C, now.State, rig.Id, far.Item1, far.Item2, now.Spent).Select(h => (h.Q, h.R)).ToList();+ CollectionAssert.AreEqual(new[] { rig.Start }.Concat(route).ToList(), rig.Arrows.Last(), "a go-to's arrow follows the sim's route");+ Assert.IsTrue(renderer.enabled);+ rig.Info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>(b) An enemy unit never gets an arrow: its card opens no pick, so no hovered hex draws one; and the arrow's+ /// own rule refuses an enemy unit even with a path in hand.</summary>+ [Test]+ public void AnEnemyUnitGetsNoArrow()+ {+ using var ui = new UiTestKit();+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);+ var bridge = new SimBridge(g, Text);+ // Every row's token, as TheCardOffersMoveOnlyWhereTheSimHasAHex (UnitOrdersTests) picks its enemy force.+ var tokens = UnitRoster.FromState(Units, C, g.State, _ => true, (row, a, q, r) => a);+ PlacedToken? shown = null;+ var arrows = new List<IReadOnlyList<(int q, int r)>>();+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(), selectedUnit: () => shown,+ showArrow: hexes => arrows.Add(hexes.ToList()));+ var golani = tokens.Single(t => t.Unit.Id == "golani");+ var golaniId = UnitCard.SimUnit(C, g.State, golani.Unit)!.Value;+ shown = new PlacedToken(golani, new AnchorSpot(0, 0, 0, 0, false));+ info.ShowUnit();+ var lit = Movement.Reachable(C, g.State, golaniId).Keys.First();+ info.ShowRouteTo(lit.Q, lit.R);+ Assert.IsNotEmpty(arrows.Last(), "precondition: Golani's hover draws the arrow");++ var enemy = tokens.First(t => t.Unit.Side != UnitData.Israel && UnitCard.SimUnit(C, g.State, t.Unit) != null);+ var e = g.State.Units[UnitCard.SimUnit(C, g.State, enemy.Unit)!.Value];+ shown = new PlacedToken(enemy, new AnchorSpot(0, 0, 0, 0, false));+ info.ShowUnit();+ Assert.IsFalse(info.MovePicking, "precondition: an enemy unit's card opens no Move pick");+ Assert.IsEmpty(arrows.Last(), "selecting the enemy unit cleared Golani's arrow");+ var from = arrows.Count;+ foreach (var h in C.Hexes.Where(h => h.Land && System.Math.Abs(h.Q - e.Q) <= 3 && System.Math.Abs(h.R - e.R) <= 3))+ info.ShowRouteTo(h.Q, h.R);+ Assert.IsTrue(arrows.Skip(from).All(a => a.Count == 0), "no hover near the enemy unit draws an arrow");++ var path = new[] { (e.Q + 1, e.R) };+ Assert.IsEmpty(InfoPanelPresenter.ArrowHexes(e, path), "the arrow's own rule: never an enemy unit's, even with a path");+ var own = g.State.Units[golaniId];+ CollectionAssert.AreEqual(new[] { (own.Q, own.R), (own.Q + 1, own.R) }, InfoPanelPresenter.ArrowHexes(own, new[] { (own.Q + 1, own.R) }));+ info.Dispose();+ }++ /// <summary>(c) The arrow clears when the move is made, when the pick is cancelled (Escape), when the mouse leaves the map,+ /// and when another hex is selected.</summary>+ [Test]+ public void TheArrowClearsOnMoveAndOnCancel()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var rig = Open(map, ui);+ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, rig.Golani.Q, rig.Golani.R);+ var lit = FarLit(rig);+ rig.Info.ShowRouteTo(lit.q, lit.r);+ Assert.IsNotEmpty(rig.Arrows.Last(), "precondition: the hover draws the arrow");++ rig.Info.HideRoute();+ Assert.IsEmpty(rig.Arrows.Last(), "the mouse left the map");+ Assert.IsFalse(ArrowRenderer(map).enabled);++ rig.Info.ShowRouteTo(lit.q, lit.r);+ Assert.IsNotEmpty(rig.Arrows.Last(), "back on the hex");+ Assert.IsTrue(rig.Info.Escape());+ Assert.IsEmpty(rig.Arrows.Last(), "Escape cancels the pick");+ Assert.IsFalse(ArrowRenderer(map).enabled);++ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, rig.Golani.Q, rig.Golani.R);+ rig.Info.ShowRouteTo(lit.q, lit.r);+ Assert.IsNotEmpty(rig.Arrows.Last(), "precondition: a new pick, the arrow again");+ var water = C.Hexes.First(h => !h.Land);+ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, water.Q, water.R);+ Assert.IsEmpty(rig.Arrows.Last(), "selecting another hex ends the pick");++ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, rig.Golani.Q, rig.Golani.R);+ rig.Info.ShowRouteTo(lit.q, lit.r);+ Assert.IsNotEmpty(rig.Arrows.Last(), "precondition: the arrow before the move");+ map.Select(lit.q, lit.r);+ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, lit.q, lit.r);+ Assert.IsNotEmpty(rig.Bridge.Session.Committed.OfType<Move>(), "precondition: the move is made");+ Assert.IsEmpty(rig.Arrows.Last(), "the move is made");+ Assert.IsEmpty(map.ShownArrow);+ Assert.IsFalse(ArrowRenderer(map).enabled);+ rig.Info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>(d) GameRoot.LateUpdate asks for the hovered hex's route and arrow every frame: once drawn, asking again for+ /// the same hex allocates nothing. The arrow has no script of its own: its chevrons move in the shader.</summary>+ [Test]+ public void TheHoverEveryFrameAllocatesNothing()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var rig = Open(map, ui);+ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, rig.Golani.Q, rig.Golani.R);+ var lit = FarLit(rig);+ rig.Info.ShowRouteTo(lit.q, lit.r);+ Assert.IsNotEmpty(rig.Arrows.Last(), "precondition: the arrow is drawn");+ var calls = rig.Arrows.Count;+ Assert.That(() => rig.Info.ShowRouteTo(lit.q, lit.r), Is.Not.AllocatingGCMemory());+ Assert.AreEqual(calls, rig.Arrows.Count, "the same hex draws nothing again");+ Assert.IsEmpty(ArrowRenderer(map).GetComponents<MonoBehaviour>(), "no per-frame script on the arrow");+ rig.Info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The arrow's material comes from Resources with its shader (a player keeps it), the shader compiles for WebGL 2,+ /// and its width follows the camera distance so it stays about the same size on screen at every zoom the camera allows.</summary>+ [Test]+ public void TheArrowShaderShipsAndKeepsItsScreenWidthAtEveryZoom()+ {+ var mat = Resources.Load<Material>(MapScene.MoveArrowMaterialResource);+ Assert.IsNotNull(mat, $"Resources/{MapScene.MoveArrowMaterialResource}.mat");+ Assert.AreEqual("Statecraft/MoveArrow", mat.shader.name);+ Assert.IsTrue(mat.shader.isSupported);+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(mat.shader));+ Assert.AreEqual(MapScene.MoveArrowWidthPerDistance, mat.GetFloat("_WidthPerDistance"), 1e-6f, "the material and the code agree");+ // The shader widens the arrow in proportion to the camera's distance, so its on-screen width is the same from+ // CameraController.MinDistance to MaxDistance: at 1080 px, its width over the visible height at that distance+ // (CameraRig.Fov), the distance cancelling out.+ float px = MapScene.MoveArrowWidthPerDistance / (2f * Mathf.Tan(CameraRig.Fov * Mathf.Deg2Rad / 2f)) * 1080f;+ Assert.That(px, NUnit.Framework.Is.InRange(20f, 40f), "the arrowhead's width on screen");+ }++ /// <summary>The map hexes whose centres are a step from (q, r): neighbours by distance (a step is sqrt(3) hex sizes),+ /// so the tests need no assumption about the coordinates' axes.</summary>+ static List<(int q, int r)> Neighbours(MapScene map, int q, int r)+ {+ float step = Mathf.Sqrt(3f) * map.Hexes.hex_size_km * 1000f;+ var c = Centre(map, q, r);+ return map.Hexes.hexes.Where(h => (h.q, h.r) != (q, r) && Mathf.Abs((Centre(map, h.q, h.r) - c).magnitude - step) < 0.05f * step)+ .Select(h => (h.q, h.r)).ToList();+ }++ static float Turn(MapScene map, (int q, int r) a, (int q, int r) b, (int q, int r) c) =>+ Vector2.Angle(Centre(map, b.q, b.r) - Centre(map, a.q, a.r), Centre(map, c.q, c.r) - Centre(map, b.q, b.r));++ /// <summary>A path with a 60-degree bend then a 120-degree bend, from the map's own hexes.</summary>+ static List<(int q, int r)> BendyPath(MapScene map)+ {+ foreach (var h in map.Hexes.hexes)+ {+ var b = (h.q, h.r); var around = Neighbours(map, b.q, b.r);+ if (around.Count < 6) continue;+ foreach (var a in around)+ foreach (var c in around)+ {+ if (Mathf.Abs(Turn(map, a, b, c) - 60f) > 1f) continue;+ var next = Neighbours(map, c.q, c.r).FirstOrDefault(d => Mathf.Abs(Turn(map, b, c, d) - 120f) < 1f && d != b);+ if (next != default) return new List<(int q, int r)> { a, b, c, next };+ }+ }+ throw new AssertionException("no hex on the map has a 60 then 120 degree bend");+ }++ /// <summary>Review of #2134 (C1): the shader widens the band with the camera's distance, so at a bend the cross-sections+ /// next to the mitre must lie beyond where the widest band's inner edge reaches, or the band folds back over itself and+ /// blends twice. At the farthest zoom with a margin (the half-width the shader gives a vertex 1.5 times+ /// CameraController.MaxDistance away), each side's edge moves forward from every cross-section to the next.</summary>+ [Test]+ public void TheBandNeverFoldsAtABend()+ {+ var map = BuildMap();+ try+ {+ var path = BendyPath(map);+ map.ShowMoveArrow(path);+ var mesh = ArrowRenderer(map).GetComponent<MeshFilter>().sharedMesh;+ var v = mesh.vertices; var side = new List<Vector4>(); mesh.GetUVs(1, side);+ float half = 0.5f * MapScene.MoveArrowWidthPerDistance * CameraController.MaxDistance * 1.5f;+ for (int i = 0; i + 3 < v.Length; i += 2)+ {+ Vector2 p0 = new Vector2(v[i].x, v[i].z), p1 = new Vector2(v[i + 2].x, v[i + 2].z);+ Vector2 s0 = new Vector2(side[i].x, side[i].y), s1 = new Vector2(side[i + 2].x, side[i + 2].y);+ var along = p1 - p0;+ foreach (var sign in new[] { -1f, 1f })+ Assert.Greater(Vector2.Dot((p1 + sign * half * s1) - (p0 + sign * half * s0), along), 0f,+ $"section {i / 2} to {i / 2 + 1}, side {sign}: the band folds back");+ }+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Review of #2134 (C4): the mesh holds the centre line and the shader widens it, so the bounds must hold the+ /// widest band (a mitre doubles the half-width at most; a vertex up to 1.5 times CameraController.MaxDistance away), or+ /// a bend just off screen is culled while its band is on screen.</summary>+ [Test]+ public void TheBoundsHoldTheWidestBand()+ {+ var map = BuildMap();+ try+ {+ map.ShowMoveArrow(BendyPath(map));+ var mesh = ArrowRenderer(map).GetComponent<MeshFilter>().sharedMesh;+ var v = mesh.vertices; var side = new List<Vector4>(); mesh.GetUVs(1, side);+ float half = 0.5f * MapScene.MoveArrowWidthPerDistance * CameraController.MaxDistance * 1.5f;+ var b = mesh.bounds;+ for (int i = 0; i < v.Length; i++)+ foreach (var sign in new[] { -1f, 1f })+ {+ var p = v[i] + sign * half * new Vector3(side[i].x, 0f, side[i].y);+ Assert.IsTrue(b.Contains(new Vector3(p.x, b.center.y, p.z)), $"vertex {i}, side {sign}: {p} is outside {b}");+ }+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Review of #2134 (C3): with no pick open, moving over the map never touches the arrow (no rebuild, no upload,+ /// no call), however many hexes the pointer crosses.</summary>+ [Test]+ public void HoveringWithNoPickLeavesTheArrowAlone()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var rig = Open(map, ui);+ Assert.IsFalse(rig.Info.MovePicking, "precondition: nothing selected");+ foreach (var h in C.Hexes.Where(h => h.Land).Take(40)) rig.Info.ShowRouteTo(h.Q, h.R);+ Assert.IsEmpty(rig.Arrows, "no pick: the arrow is never asked to draw or clear");+ rig.Info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Review of #2134 (C2): a new state (here another unit's order, the pick staying open) hides the hovered+ /// arrow, read on the old state, and the next hover draws it again from the new one.</summary>+ [Test]+ public void ANewStateHidesTheArrowAndTheNextHoverRedrawsIt()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var rig = Open(map, ui);+ GameRoot.OnHexClicked(map, rig.Layer, rig.Info, rig.Golani.Q, rig.Golani.R);+ var lit = FarLit(rig);+ rig.Info.ShowRouteTo(lit.q, lit.r);+ var drawn = rig.Arrows.Last().ToList();+ Assert.IsNotEmpty(drawn, "precondition: the arrow is drawn");+ var (other, order) = rig.Bridge.State.Units.Values.Where(u => u.Id != rig.Id && u.Side == Movement.PlayerSide)+ .SelectMany(u => new[] { Orders.Hold, Orders.Fortify }.Select(o => (u.Id, o)))+ .First(x => Orders.Check(C, rig.Bridge.State, x.Id, x.o) == null);+ Assert.IsNull(rig.Bridge.Queue(new UnitOrder(other, order)), "precondition: another unit's order is taken");+ Assert.IsTrue(rig.Info.MovePicking, "precondition: Golani's pick is still open");+ Assert.IsEmpty(rig.Arrows.Last(), "the state changed: the arrow read on the old one is hidden");+ Assert.IsFalse(ArrowRenderer(map).enabled);+ rig.Info.ShowRouteTo(lit.q, lit.r);+ var path = Movement.Path(C, rig.Bridge.State, rig.Id, lit.q, lit.r, rig.Bridge.Spent).Select(h => (h.Q, h.R));+ CollectionAssert.AreEqual(new[] { rig.Start }.Concat(path).ToList(), rig.Arrows.Last(), "the hover draws it from the new state");+ rig.Info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Review of #2134 (C2): the arrow's width on screen, measured in a render (not reckoned from the constants):+ /// a straight path across the screen, its shaft's thickness at the middle hex, the same at the nearest and the farthest+ /// zoom the camera allows, and clearly visible at both. The editor renders with its own graphics API, not WebGL;+ /// ShaderChecks.Gles3Errors covers the WebGL 2 compile.</summary>+ [Test]+ public void TheArrowKeepsItsScreenWidthFromNearestToFarthestZoom()+ {+ var map = BuildMap();+ RenderSample.TiltShift(false);+ try+ {+ // Three hexes in a line, the middle one with every neighbour on the map.+ List<(int q, int r)>? line = null;+ foreach (var h in map.Hexes.hexes)+ {+ var around = Neighbours(map, h.q, h.r);+ if (around.Count < 6) continue;+ var a = around[0];+ var c = around.First(n => Mathf.Abs(Turn(map, a, (h.q, h.r), n)) < 1f);+ line = new List<(int q, int r)> { a, (h.q, h.r), c };+ break;+ }+ Assert.IsNotNull(line);+ var mid = Centre(map, line![1].q, line[1].r);+ var dir = (Centre(map, line[2].q, line[2].r) - Centre(map, line[0].q, line[0].r)).normalized;+ float ground = map.Terrain.terrainData.GetInterpolatedHeight(Mathf.Clamp01(mid.x / map.Frame.WidthM), Mathf.Clamp01(mid.y / map.Frame.LengthM));+ var look = map.Terrain.transform.TransformPoint(new Vector3(mid.x, ground + MapScene.SelectionClearanceM, mid.y));+ var cam = Camera.main; var camRig = cam.GetComponent<CameraRig>();+ float Thickness(float distance)+ {+ // Looking square across the path, so it runs left to right on screen.+ camRig.LookAt = look; camRig.Distance = distance; camRig.TopInset = 0;+ camRig.Yaw = Mathf.Atan2(dir.y, -dir.x) * Mathf.Rad2Deg; camRig.Apply();+ map.ShowMoveArrow(System.Array.Empty<(int, int)>());+ var without = RenderSample.RenderSteady(cam, 1920, 1080, 3);+ map.ShowMoveArrow(line);+ var at = new Vector2[1];+ RenderSample.Render(cam, 1920, 1080, new[] { look }, at);+ var with = RenderSample.RenderSteady(cam, 1920, 1080, 3);+ bool Changed(int x, int y) { var a = with.At(x, y); var b = without.At(x, y); return Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b)) > 0.08f; }+ int cx = Mathf.RoundToInt(at[0].x), cy = Mathf.RoundToInt(at[0].y);+ var runs = new List<int>();+ for (int x = cx - 8; x <= cx + 8; x++)+ {+ int y0 = Enumerable.Range(cy - 30, 61).Where(y => Changed(x, y)).DefaultIfEmpty(int.MinValue).OrderBy(y => Mathf.Abs(y - cy)).First();+ if (y0 == int.MinValue) { runs.Add(0); continue; }+ int lo = y0, hi = y0;+ while (Changed(x, lo - 1)) lo--;+ while (Changed(x, hi + 1)) hi++;+ runs.Add(hi - lo + 1);+ }+ runs.Sort();+ TestContext.WriteLine($"{distance} m: shaft {runs[runs.Count / 2]} px (columns {string.Join(",", runs)})");+ return runs[runs.Count / 2];+ }+ float near = Thickness(CameraController.MinDistance), far = Thickness(CameraController.MaxDistance);+ Assert.GreaterOrEqual(near, 6f, "the shaft is clearly visible at the nearest zoom");+ Assert.GreaterOrEqual(far, 6f, "the shaft is clearly visible at the farthest zoom");+ Assert.LessOrEqual(Mathf.Abs(near - far), 2f, $"the same on screen at every zoom: {near} px near, {far} px far");+ }+ finally { RenderSample.TiltShift(true); Object.DestroyImmediate(map.gameObject); }+ }+}diff --git a/unity/Assets/Tests/EditMode/MoveArrowTests.cs.meta b/unity/Assets/Tests/EditMode/MoveArrowTests.cs.metanew file mode 100644index 000000000..adb6bd026--- /dev/null+++ b/unity/Assets/Tests/EditMode/MoveArrowTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ef233d7cda6547ea96b33fd25a0c3a74\ No newline at end of file