Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Map: play the enemy's turn side by side after End turn, with a flag-and-name footer bar (refs #2202) (#2967)

Eyal Golan78ce81f644a0
diff --git a/changelog.d/2202-enemy-move-playback.md b/changelog.d/2202-enemy-move-playback.md
new file mode 100644
index 000000000..c893f626e
--- /dev/null
+++ b/changelog.d/2202-enemy-move-playback.md
@@ -0,0 +1,8 @@
+- After End turn, the map plays the Arab forces' moves and attacks one at a time and the camera follows them, then
+ returns to your view (Refs #2202). The camera glides without turning or zooming, and a turn's moves take at most 12
+ seconds before it glides back. The sides play one after another, and a bar at the foot of the map shows the side
+ whose moves you are watching, with its 1948 flag (the flag its units fly; the Arab Liberation Army's units fly a plain
+ pennant), its name, and each move in words. Skip or Esc ends it; Settings can turn it off. End turn still closes an
+ open screen; the turn report and the decision card wait until the moves end, and a screen you open while they play
+ stays open: the report comes once you close it. Nothing in the game changes: it shows the turn the game has already
+ played.
diff --git a/unity/Assets/Scripts/Map/CameraGlide.cs b/unity/Assets/Scripts/Map/CameraGlide.cs
new file mode 100644
index 000000000..8d28adb40
--- /dev/null
+++ b/unity/Assets/Scripts/Map/CameraGlide.cs
@@ -0,0 +1,56 @@
+#nullable enable
+using Statecraft.Game.UI;
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 4): the camera's eased glide to a
+ /// replay's beat, as pure functions over the rig. It moves the look-at point only, never the yaw or the distance (owner,
+ /// 2 November 2026, Q5: "Keep the player's zoom"; the GDD camera never orbits). The caller sets LookAt from
+ /// <see cref="At"/> and lets CameraController.Settle hold the whole view on the map, as it holds a pan, so a beat by the
+ /// map's edge stops where the player's own pan would. A player's pan or zoom ends the glide (<see cref="TookOver"/>).</summary>
+ public static class CameraGlide
+ {
+ /// <summary>A pan this far (metres) or less is no pan: TookOver's tolerance for the look-at point.</summary>
+ public const float StillM = 1f;
+
+ /// <summary>The look-at point <paramref name="t"/> (clamped to 0..1) of the way from <paramref name="from"/> to
+ /// <paramref name="to"/>, eased in and out (smoothstep) in x and z. The height is <paramref name="from"/>'s:
+ /// CameraController.Step lifts the point over the ground again.</summary>
+ public static Vector3 At(Vector3 from, Vector3 to, float t)
+ {
+ t = Mathf.Clamp01(t);
+ float s = t * t * (3f - 2f * t);
+ return new Vector3(from.x + (to.x - from.x) * s, from.y, from.z + (to.z - from.z) * s);
+ }
+
+ /// <summary>How long a glide of <paramref name="metres"/> takes on hexes <paramref name="hexMetres"/> across: the
+ /// replay's pan pacing (UnitBeats.PanSeconds, owner Q3), so the planner and the glide share one clamp.</summary>
+ public static float Seconds(float metres, float hexMetres) => UnitBeats.PanSeconds(hexMetres > 0f ? metres / hexMetres : 0f);
+
+ /// <summary>Whether the camera, as the rig was last applied, shows <paramref name="point"/> inside the map area (below
+ /// the UI's top band, CameraRig.TopInset) with <paramref name="margin"/> of its width and height to spare on each
+ /// side: a beat there needs no pan. Projected through the camera itself, so the view's narrower near edge counts.</summary>
+ public static bool InView(CameraRig rig, Vector3 point, float margin = 0.15f)
+ {
+ var cam = rig.GetComponent<Camera>();
+ if (cam == null) return false;
+ var v = cam.WorldToViewportPoint(point);
+ float top = 1f - Mathf.Clamp(rig.TopInset, 0f, CameraRig.MaxTopInset);
+ return v.z > 0f && v.x >= margin && v.x <= 1f - margin && v.y >= margin * top && v.y <= (1f - margin) * top;
+ }
+
+ /// <summary>Whether someone other than the glide moved the camera since it last set <paramref name="lastLookAt"/> and
+ /// <paramref name="lastDistance"/> (as Settle left them): the look-at point moved more than <see cref="StillM"/> in x or
+ /// z, or the distance changed. The height is Step's own (the lift over the ground), so it is not compared.</summary>
+ public static bool TookOver(CameraRig rig, Vector3 lastLookAt, float lastDistance) =>
+ TookOver(rig.LookAt, rig.Distance, lastLookAt, lastDistance);
+
+ /// <summary><see cref="TookOver(CameraRig, Vector3, float)"/> on the rig's look-at point and distance as read now.</summary>
+ public static bool TookOver(Vector3 lookAt, float distance, Vector3 lastLookAt, float lastDistance)
+ {
+ float dx = lookAt.x - lastLookAt.x, dz = lookAt.z - lastLookAt.z;
+ return dx * dx + dz * dz > StillM * StillM || distance != lastDistance;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/CameraGlide.cs.meta b/unity/Assets/Scripts/Map/CameraGlide.cs.meta
new file mode 100644
index 000000000..c0e0280f0
--- /dev/null
+++ b/unity/Assets/Scripts/Map/CameraGlide.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: b882c163c15945fca666977828dc1c1e
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitFlags.cs b/unity/Assets/Scripts/Map/Units/UnitFlags.cs
index 3b646fe78..5b44f064d 100644
--- a/unity/Assets/Scripts/Map/Units/UnitFlags.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitFlags.cs
@@ -117,12 +117,22 @@ namespace Statecraft.Game.Map.Units
/// no colour of any side, and not white.</summary>
public const float PennantHeight = 0.36f;
+ /// <summary>The pennant cloth's shade row in the palette (<see cref="UnitPalette.Shade"/>).</summary>
+ public const float PennantShade = 0.9f;
+
+ /// <summary>The pennant's cloth outline in figure units (x along the cloth from the pole, y up): the one definition
+ /// <see cref="BuildPennant"/> plates and the enemy playback's footer draws (#2202, SideFlag).</summary>
+ public static IReadOnlyList<Vector2> PennantCloth() =>
+ new[] { new Vector2(FlagLeft, FlagTop - PennantHeight), new Vector2(FlagLeft + FlagWidth, FlagTop - PennantHeight / 2f), new Vector2(FlagLeft, FlagTop) };
+
+ /// <summary>The pennant cloth's colour as its plate is painted: the palette's neutral grey at <see cref="PennantShade"/>.</summary>
+ public static Color PennantColour => P.Shade(P.HullGrey, PennantShade);
+
/// <summary>The pole and the neutral pennant, one submesh in the units' palette.</summary>
public static Mesh BuildPennant()
{
var m = Pole();
- var cloth = new List<Vector2> { new Vector2(FlagLeft, FlagTop - PennantHeight), new Vector2(FlagLeft + FlagWidth, FlagTop - PennantHeight / 2f), new Vector2(FlagLeft, FlagTop) };
- m.Plate(Plane(0f), cloth, P.HullGrey, shade: 0.9f);
+ m.Plate(Plane(0f), PennantCloth(), P.HullGrey, shade: PennantShade);
return m.Build(PennantMeshName);
}
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
index 31abfc293..ee6db9cf5 100644
--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
@@ -171,6 +171,9 @@ namespace Statecraft.Game.Map.Units
internal CombatBursts? Combat => combat;
/// <summary>A rebuild slides a moved unit's token from where it was drawn (true in play; tests set it).</summary>
internal bool AnimateMoves;
+ /// <summary>The sim units whose tokens wait where they were drawn until <see cref="Release"/> (#2202): a rebuild
+ /// stands a held unit's token at its old place instead of sliding it.</summary>
+ readonly HashSet<int> held = new HashSet<int>();
/// <summary>The GDD loop's anchors for units that moved off their starting hex (UnitRoster.FromState), one per row and
/// sim hex, and their spots: placed once, the first time a unit stands there, so a rebuild after a move places only
@@ -414,6 +417,7 @@ namespace Statecraft.Game.Map.Units
/// (New Game) reuses the sim ids, so its tokens are drawn where they stand.</summary>
public bool Show(Content content, GameState state, bool slide = true)
{
+ if (!slide) ReleaseAll(snap: true); // another game: nothing waits from the last one
shownContent = content; shownState = state;
PrepareMapOnlySpots(content);
// The GDD loop draws the army from the sim's units (GDD Phase 5 PR 14); the legacy loop keeps the rows and the call-up.
@@ -909,12 +913,47 @@ namespace Statecraft.Game.Map.Units
motions.Add(motion);
// With the units hidden the token cannot be seen, and it would slide only once they are shown again.
if (tokensRoot.gameObject.activeInHierarchy && drawnAt.TryGetValue(Key(motion.SimId, token.name), out var was))
- motion.Begin(was - trios[i].centre);
+ {
+ if (motion.SimId >= 0 && held.Contains(motion.SimId)) motion.Hold(was - trios[i].centre); // waits for its beat
+ else motion.Begin(was - trios[i].centre);
+ }
if (firing.TryGetValue(Key(motion.SimId, token.name), out var played)) motion.ContinueAttack(played);
if (hits.TryGetValue(Key(motion.SimId, token.name), out var hit)) motion.ContinueHit(hit.left, hit.delay);
}
}
+ /// <summary>Holds the tokens of <paramref name="simIds"/> where they are drawn now (#2202): the next rebuilds stand
+ /// each at that place, its unit already moved by the sim, until <see cref="Release"/> or <see cref="ReleaseAll"/>.
+ /// A token mid-slide stops where it is. Ids the layer does not draw are kept, and hold nothing.</summary>
+ public void Hold(IEnumerable<int> simIds)
+ {
+ foreach (int id in simIds)
+ {
+ if (id < 0 || !held.Add(id)) continue;
+ foreach (var m in motions) if (m != null && m.SimId == id) { m.Hold(m.SlideOffset); break; }
+ }
+ }
+
+ /// <summary>Lets the held token of <paramref name="simId"/> slide from where it waits to its place, as any move.
+ /// False when it was not held, or no token of it waits.</summary>
+ public bool Release(int simId)
+ {
+ if (!held.Remove(simId)) return false;
+ foreach (var m in motions)
+ if (m != null && m.SimId == simId && m.Held) { m.Unhold(slide: true); return true; }
+ return false;
+ }
+
+ /// <summary>Releases every held token: each slides (<paramref name="snap"/> false) or stands on its place at once.</summary>
+ public void ReleaseAll(bool snap)
+ {
+ held.Clear();
+ foreach (var m in motions) if (m != null && m.Held) m.Unhold(slide: !snap);
+ }
+
+ /// <summary>Whether a token draws sim unit <paramref name="simId"/> now.</summary>
+ public bool Draws(int simId) => simId >= 0 && drawnSims.Contains(simId);
+
/// <summary>Plays the attack take of sim unit <paramref name="simId"/>'s figures (#1867). False when no token draws
/// that unit or none of its figures can play one now (a far zoom, the units hidden, or no fire take).</summary>
public bool PlayAttack(int simId)
diff --git a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
index be0730977..5dc62d2b3 100644
--- a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
@@ -39,6 +39,7 @@ namespace Statecraft.Game.Map.Units
internal Vector3 SlideOffset => moveOffset;
float elapsed = Duration, attackLeft, hitLeft, hitDelay;
int nextMoveDust;
+ bool held; // the token waits at its old place for its beat (#2202, UnitLayer.Hold)
bool firing; // a figure plays the attack (else it waits for one, up to AttackWaitS)
bool fired; // an attack just ended: its figures go back to walking or standing
float attackLength, resumeAt; // the playing take's length; where a continued attack picks up
@@ -49,6 +50,8 @@ namespace Statecraft.Game.Map.Units
Action? attackStarted, attackMissed;
public bool Moving => elapsed < Duration;
+ /// <summary>The token waits where it was drawn, its unit already moved by the sim, until UnitLayer releases it (#2202).</summary>
+ public bool Held => held;
/// <summary>An attack plays, or waits for a figure to play it.</summary>
public bool Attacking => attackLeft > 0f;
public bool Reacting => hitLeft > 0f;
@@ -58,7 +61,8 @@ namespace Statecraft.Game.Map.Units
/// <summary>Starts a slide from <paramref name="offset"/> (the old place less the new) to the unit's place.</summary>
public void Begin(Vector3 offset)
{
- if (offset.sqrMagnitude < MinMoveM * MinMoveM) { if (Moving || Attacking || Reacting || HitPending) Snap(); return; }
+ bool wasHeld = held; held = false;
+ if (offset.sqrMagnitude < MinMoveM * MinMoveM) { if (wasHeld || Moving || Attacking || Reacting || HitPending) Snap(); return; }
from = moveOffset = offset; elapsed = 0f; nextMoveDust = 0;
ApplyPosition();
enabled = true;
@@ -66,6 +70,32 @@ namespace Statecraft.Game.Map.Units
Changed?.Invoke();
}
+ /// <summary>Stands the token at <paramref name="offset"/> (the old place less the new) without sliding, until
+ /// <see cref="Unhold"/>: the move's slide stops, an attack or a hit plays on there. A token that cannot be seen does
+ /// not wait (it would slide only once shown, as <see cref="Begin"/>'s caller already skips it).</summary>
+ internal void Hold(Vector3 offset)
+ {
+ if (!gameObject.activeInHierarchy) return;
+ from = moveOffset = offset; elapsed = Duration; nextMoveDust = 0; held = true;
+ ApplyPosition();
+ if (!Attacking && !Reacting && !HitPending) enabled = false; // a waiting token costs nothing per frame
+ Pose();
+ Changed?.Invoke();
+ }
+
+ /// <summary>Ends the wait: slides from the old place to the token's place (<paramref name="slide"/>), else puts it
+ /// there at once.</summary>
+ internal void Unhold(bool slide)
+ {
+ if (!held) return;
+ held = false;
+ var offset = moveOffset;
+ if (slide && offset.sqrMagnitude >= MinMoveM * MinMoveM) { Begin(offset); return; }
+ from = moveOffset = Vector3.zero;
+ ApplyPosition();
+ Changed?.Invoke();
+ }
+
/// <summary>Plays the figures' attack take once from its start (again, if one is playing). True when a figure
/// plays it now; else it waits <see cref="AttackWaitS"/> for one to turn near, and then is dropped. A hidden token
/// does nothing. Nothing is kept to play later.</summary>
@@ -278,7 +308,7 @@ namespace Statecraft.Game.Map.Units
void Snap()
{
bool moved = transform.position != Vector3.zero;
- fired = firing;
+ fired = firing; held = false;
elapsed = Duration; attackLeft = hitLeft = hitDelay = 0f; firing = false; resumeAt = 0f;
from = moveOffset = Vector3.zero; nextMoveDust = 0;
DropAttackCue();
diff --git a/unity/Assets/Scripts/UI/EnemyPlaybackBar.cs b/unity/Assets/Scripts/UI/EnemyPlaybackBar.cs
new file mode 100644
index 000000000..77a1d6693
--- /dev/null
+++ b/unity/Assets/Scripts/UI/EnemyPlaybackBar.cs
@@ -0,0 +1,128 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Game.Map.Units;
+using Statecraft.Sim;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 6): the footer bar while the enemy's
+ /// moves play. The owner's answers (8 November 2026): "Flag + name (Recommended)", so it shows the side whose turn it is
+ /// as the flag its tokens fly (<see cref="SideFlag"/>, the neutral pennant for the Arab Liberation Army) beside the side's
+ /// name in words (playback.turn_&lt;side&gt;), and "One side at a time (Recommended)", so the picture changes once a side
+ /// (the beats come side by side, UnitBeats.From). Under the name, "Step n of m" and each beat's action in words, the turn
+ /// report's own lines (report.enemy_move, report.enemy_attack through UnitNames.Of), so the motion is never the only
+ /// signal (WRITING_UI UI-18). Skip ends the playback (as Esc does, GameRoot.Update); its tooltip holds the spoken text
+ /// for the later accessibility layer: no runtime tooltip is read by a screen reader yet.
+ /// <para>Never modal: it takes no focus when it opens, and only the Skip button takes the pointer. A clip (Game.uxml
+ /// order) is drawn over it. In Hebrew the row is mirrored (the flag at the right), the flag itself is not.</para></summary>
+ public sealed class EnemyPlaybackBar : IDisposable
+ {
+ public const string ElementName = "enemy-playback";
+ /// <summary>On the "root" element while the bar shows.</summary>
+ public const string OpenClass = "enemy-playback-open";
+
+ /// <summary>The units_1948.yaml rows that name the enemy's units (GameRoot sets them once the map has read them).</summary>
+ public IReadOnlyList<UnitEntry>? Units { get; set; }
+
+ readonly VisualElement hudRoot, bar, actions;
+ readonly SideFlag flag;
+ readonly Label side, step;
+ readonly Button skip;
+ readonly UiText text; readonly EnemyTurnPlayback playback; readonly SimBridge bridge;
+ readonly Action onRender;
+ string? shownSide;
+
+ public EnemyPlaybackBar(VisualElement root, UiText text, EnemyTurnPlayback playback, SimBridge bridge)
+ {
+ this.text = text ?? throw new ArgumentNullException(nameof(text));
+ this.playback = playback ?? throw new ArgumentNullException(nameof(playback));
+ this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));
+ hudRoot = root.Q("root") ?? root;
+ bar = root.Q<VisualElement>(ElementName);
+ var panel = bar.Q<VisualElement>("enemy-playback-panel");
+ flag = new SideFlag { name = "enemy-playback-flag" };
+ panel.Insert(0, flag);
+ side = bar.Q<Label>("enemy-playback-side");
+ step = bar.Q<Label>("enemy-playback-step");
+ actions = bar.Q<VisualElement>("enemy-playback-actions");
+ skip = bar.Q<Button>("enemy-playback-skip");
+ skip.text = text["playback.skip"];
+ skip.tooltip = text["playback.skip_tip"];
+ skip.focusable = true;
+ skip.clicked += OnSkip;
+ onRender = Render;
+ playback.Started += onRender;
+ playback.BeatChanged += onRender;
+ playback.Finished += onRender;
+ Render();
+ }
+
+ /// <summary>True while the bar shows.</summary>
+ public bool IsOpen => hudRoot.ClassListContains(OpenClass);
+ /// <summary>The side the bar names now, or null.</summary>
+ public string? Side => shownSide;
+ public SideFlag Flag => flag;
+
+ /// <summary>The side's name in words: playback.turn_&lt;side&gt;, or the Arab forces' as a whole for a side with no key.</summary>
+ public static string SideName(UiText text, string? side) =>
+ !string.IsNullOrEmpty(side) && text.Has("playback.turn_" + side) ? text["playback.turn_" + side] : text["playback.title"];
+
+ /// <summary>The beat's actions in words, one line each, in the sim's order: each move's unit, each engagement's enemy
+ /// attackers; a folded beat says so in one line.</summary>
+ public static IReadOnlyList<string> Lines(UnitBeat beat, Content content, IReadOnlyList<UnitEntry>? units, UiText text)
+ {
+ if (beat.Folded) return new[] { text["playback.folded"] };
+ var rows = units ?? Array.Empty<UnitEntry>();
+ string Name(Cause c, int id)
+ {
+ var snapshot = c.Units.FirstOrDefault(u => u.Id == id);
+ return snapshot != null ? UnitNames.Of(snapshot, content, rows, text) : text.Format("report.unit", id);
+ }
+ var lines = new List<string>();
+ foreach (var c in beat.Causes)
+ {
+ if (c.Key == WhyKeys.UnitMoved && c.Units.Count > 0) lines.Add(text.Format("report.enemy_move", Name(c, c.Units[0].Id)));
+ else if (c.Key == WhyKeys.Engagement)
+ foreach (var id in c.EnemyAttackers) lines.Add(text.Format("report.enemy_attack", Name(c, id)));
+ }
+ return lines;
+ }
+
+ void OnSkip() => playback.Skip();
+
+ void Render()
+ {
+ var beat = playback.Current;
+ bool open = playback.Active && beat != null;
+ hudRoot.EnableInClassList(OpenClass, open);
+ bar.style.display = open ? DisplayStyle.Flex : DisplayStyle.None;
+ if (!open) { shownSide = null; flag.Side = null; actions.Clear(); return; }
+ if (!string.Equals(shownSide, beat!.Side, StringComparison.Ordinal)) // the picture changes once a side
+ {
+ shownSide = beat.Side;
+ flag.Side = beat.Side;
+ side.text = SideName(text, beat.Side);
+ }
+ step.text = text.Format("playback.step", playback.Index + 1, playback.Count);
+ actions.Clear();
+ foreach (var line in Lines(beat, bridge.Content, Units, text))
+ {
+ var label = new Label(line); // one label a line, so each takes its own direction (UiDirection)
+ label.AddToClassList("enemy-playback-action");
+ actions.Add(label);
+ }
+ }
+
+ public void Dispose()
+ {
+ skip.clicked -= OnSkip;
+ playback.Started -= onRender;
+ playback.BeatChanged -= onRender;
+ playback.Finished -= onRender;
+ hudRoot.RemoveFromClassList(OpenClass);
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/EnemyPlaybackBar.cs.meta b/unity/Assets/Scripts/UI/EnemyPlaybackBar.cs.meta
new file mode 100644
index 000000000..79b9ae141
--- /dev/null
+++ b/unity/Assets/Scripts/UI/EnemyPlaybackBar.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f0a82d69ca0040ee851d992576895940
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/EnemyTurnPlayback.cs b/unity/Assets/Scripts/UI/EnemyTurnPlayback.cs
new file mode 100644
index 000000000..388f23235
--- /dev/null
+++ b/unity/Assets/Scripts/UI/EnemyTurnPlayback.cs
@@ -0,0 +1,316 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Game.Map;
+using Statecraft.Game.Map.Units;
+using Statecraft.Sim;
+using UnityEngine;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>What the replay needs of the map (GameRoot adapts UnitLayer, the attack presenter and the hexes).</summary>
+ public interface IPlaybackMap
+ {
+ /// <summary>Holds these sim units' tokens where they are drawn (UnitLayer.Hold).</summary>
+ void Hold(IEnumerable<int> ids);
+ /// <summary>Lets a held token slide to its place (UnitLayer.Release); false when it was not held.</summary>
+ bool Release(int id);
+ /// <summary>Releases every held token: each slides, or (<paramref name="snap"/>) stands on its place at once.</summary>
+ void ReleaseAll(bool snap);
+ /// <summary>Plays engagement lines and their Destroyed lines as UnitAttackPresenter plays them at End turn: the
+ /// attackers' fire take, the hit on the hex, the defenders' reaction and the dust.</summary>
+ void Fight(IReadOnlyList<Cause> lines);
+ /// <summary>Whether a token draws this sim unit now (UnitLayer.Draws).</summary>
+ bool Draws(int id);
+ /// <summary>Whether the units are shown (the "units" toggle, the capture runs' rule).</summary>
+ bool UnitsShown { get; }
+ /// <summary>The ground point of hex (q, r), or null for a hex the map does not have.</summary>
+ Vector3? World(int q, int r);
+ /// <summary>A hex's size in metres (the return glide's pacing, CameraGlide.Seconds).</summary>
+ float HexMetres { get; }
+ }
+
+ /// <summary>What the replay needs of the camera (GameRoot adapts CameraRig and CameraController.Settle).</summary>
+ public interface IPlaybackCamera
+ {
+ Vector3 LookAt { get; set; }
+ float Distance { get; }
+ /// <summary>Whether the point is well inside the map's view now (CameraGlide.InView).</summary>
+ bool InView(Vector3 point);
+ /// <summary>Holds the view on the map, as after a pan (CameraController.Settle).</summary>
+ void Settle();
+ }
+
+ /// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 5): after End turn, the map plays
+ /// the enemy's moves and attacks one beat at a time, in the sim's order, and the camera glides to each beat and back to
+ /// the player's view. Presentation only: the sim has already resolved the turn, and nothing here changes the state, the
+ /// save or a rule. The owner's answers (2 November 2026, "Q1-Q7 recommended, Q8 yes"; 8 November 2026, "All moves, as
+ /// approved (Recommended)"): every enemy move and attack plays, on screen or off (Q2 a); the turn report and an event card
+ /// wait for it (Q1 a, <see cref="Holding"/>); the player's zoom is kept (Q5 a).
+ /// <para>Never modal (#2070: "the game never waits on an animation to accept input"): it only holds tokens and moves the
+ /// look-at point. A player's pan or zoom ends its camera work for the turn (CameraGlide.TookOver). A plain class, ticked by
+ /// GameRoot.Update, so EditMode tests drive it with <see cref="Tick"/>. At End turn it does one pass over the turn's lines
+ /// (UnitBeats.From) and holds the tokens; the rest is spread over frames (#2905).</para>
+ /// <para>The seam for #2544 PR 2 (an operation's moves and attacks after the decision): the beats come from a
+ /// <see cref="BeatSource"/>, so another reader of a step's lines gets the same holds, pacing, camera and Skip.</para></summary>
+ public sealed class EnemyTurnPlayback : IDisposable
+ {
+ enum Phase { Pan, Act, Return }
+
+ readonly SimBridge bridge;
+ readonly IPlaybackMap map;
+ readonly IPlaybackCamera camera;
+ readonly Func<bool> enabled, waiting;
+ readonly BeatSource source;
+ readonly Action<StepResult> onStepped;
+ readonly Action<IReadOnlyList<Rejection>> onTurn;
+ readonly Action onChanged;
+
+ IReadOnlyList<UnitBeat> beats = Array.Empty<UnitBeat>();
+ GameSession? session; // the game the beats belong to
+ bool pending; // beats are held and wait for Start
+ Phase phase;
+ float t, length;
+ Vector3 from, to, saved; // the glide's ends, and the player's view at the start
+ bool retreated; // the beat's retreaters were released
+ int acted = -1; // the last beat whose units were released or fought
+ bool wrote, tookOver; // the playback moved the camera; the player moved it since
+ Vector3 lastLookAt;
+ float lastDistance;
+
+ /// <param name="enabled">Read at each End turn: the Settings switch, and never in a smoke run, a capture or
+ /// EditMode unless a test says so.</param>
+ /// <param name="waiting">True while something else holds the screen (an End turn outcome clip): the playback starts
+ /// once it is false.</param>
+ /// <param name="source">Which lines open a beat (the enemy's moves and attacks by default).</param>
+ public EnemyTurnPlayback(SimBridge bridge, IPlaybackMap map, IPlaybackCamera camera, Func<bool> enabled, Func<bool> waiting,
+ BeatSource? source = null)
+ {
+ this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));
+ this.map = map ?? throw new ArgumentNullException(nameof(map));
+ this.camera = camera ?? throw new ArgumentNullException(nameof(camera));
+ this.enabled = enabled ?? throw new ArgumentNullException(nameof(enabled));
+ this.waiting = waiting ?? throw new ArgumentNullException(nameof(waiting));
+ this.source = source ?? BeatSource.Enemy;
+ onStepped = Stepped;
+ onTurn = _ => Start();
+ onChanged = () => { if (session != null && !ReferenceEquals(bridge.Session, session)) Drop(); };
+ bridge.Stepped += onStepped;
+ bridge.TurnEnded += onTurn;
+ bridge.Changed += onChanged;
+ }
+
+ /// <summary>True while the beats play (from <see cref="Start"/> to the end, Skip or Finish).</summary>
+ public bool Active { get; private set; }
+ /// <summary>True from End turn until the playback starts: the tokens are held and the report waits.</summary>
+ public bool Pending => pending;
+ /// <summary>The beat playing now (0-based), or -1.</summary>
+ public int Index { get; private set; } = -1;
+ public int Count => beats.Count;
+ public IReadOnlyList<UnitBeat> Beats => beats;
+ public UnitBeat? Current => Active && Index >= 0 && Index < beats.Count ? beats[Index] : null;
+ /// <summary>The player moved the camera during this playback: it no longer steers it, nor returns it.</summary>
+ public bool TookOver => tookOver;
+
+ public event Action? Started, BeatChanged, Finished;
+ /// <summary>True when a turn's beats are held for the playback, false when it ends (the turn report and the event
+ /// card wait while it is true: owner, Q1 a).</summary>
+ public event Action<bool>? Holding;
+
+ void Stepped(StepResult r)
+ {
+ // End turn again while one plays: the old one ends at once, and only the new turn's moves play. When the new turn
+ // has moves, the hold goes on from the old playback to the new one (no Holding false in between): the waiting
+ // report opens once, for the new turn, when its moves end, never over them (#2967 review, M1).
+ var made = enabled() && map.UnitsShown && r.State.GameOver == null // the end screen is over the map
+ ? UnitBeats.From(r.Why, source) : Array.Empty<UnitBeat>();
+ End(release: made.Count == 0);
+ if (made.Count == 0) return;
+ beats = made; session = bridge.Session; pending = true; acted = -1;
+ map.Hold(made.SelectMany(b => b.Units).Distinct().ToList()); // before the map is rebuilt (Changed)
+ Holding?.Invoke(true);
+ }
+
+ /// <summary>A cause in a beat that has not played yet: UnitAttackPresenter leaves it for its beat.</summary>
+ public bool Claims(Cause c)
+ {
+ if (!Active && !pending) return false;
+ for (int i = acted + 1; i < beats.Count; i++)
+ foreach (var x in beats[i].Causes) if (ReferenceEquals(x, c)) return true;
+ return false;
+ }
+
+ /// <summary>Begins the held beats, unless something else holds the screen (GameRoot calls it again when the outcome
+ /// clips close; <see cref="Tick"/> also tries).</summary>
+ public void Start()
+ {
+ if (!pending || waiting()) return;
+ pending = false; Active = true; Index = -1; wrote = tookOver = false;
+ saved = camera.LookAt;
+ Started?.Invoke();
+ Next();
+ }
+
+ public void Tick(float dt)
+ {
+ if (pending) Start();
+ if (!Active) return;
+ if (dt > 0f) t += dt;
+ if (wrote && !tookOver && CameraGlide.TookOver(camera.LookAt, camera.Distance, lastLookAt, lastDistance)) tookOver = true;
+ switch (phase)
+ {
+ case Phase.Pan:
+ if (!tookOver) Steer(CameraGlide.At(from, to, length > 0f ? t / length : 1f));
+ if (tookOver || t >= length) Act();
+ break;
+ case Phase.Act:
+ var b = beats[Index];
+ if (!retreated && t >= length * 0.5f) ReleaseRetreats(b);
+ if (t >= length) Next();
+ break;
+ case Phase.Return:
+ if (!tookOver) Steer(CameraGlide.At(from, saved, length > 0f ? t / length : 1f));
+ if (tookOver || t >= length) Stop();
+ break;
+ }
+ }
+
+ /// <summary>Ends the playback now (the Skip button, Esc, the switch turned off): every held token stands on its
+ /// place, and the camera is back on the player's view at once unless the player moved it. True when one was on.</summary>
+ public bool Skip() => End(release: true);
+
+ /// <param name="release">False when another playback follows at once (End turn again): the report and the card stay
+ /// held.</param>
+ bool End(bool release)
+ {
+ if (!Active && !pending) return false;
+ if (Active && wrote && !tookOver) { camera.LookAt = saved; camera.Settle(); }
+ Stop(release); // every held token stands on its place
+ return true;
+ }
+
+ /// <summary>As <see cref="Skip"/>: End turn again, or the UI rebuilt (a language switch).</summary>
+ public void Finish() => Skip();
+
+ /// <summary>Another game (New Game, a load): its tokens are drawn where they stand, and its camera is its own.</summary>
+ void Drop() => Stop();
+
+ void Next()
+ {
+ while (++Index < beats.Count)
+ {
+ var b = beats[Index];
+ // A move beat whose units are all gone (destroyed later in the turn) has nothing to show: the next one plays.
+ if (b.Engagements == 0 && !b.Moves.Any(m => map.Draws(m.Unit))) { acted = Index; continue; }
+ t = 0f; phase = Phase.Pan; length = 0f;
+ var focus = b.Folded || tookOver ? null : map.World(b.FocusQ, b.FocusR);
+ bool pan = focus is Vector3 p && !camera.InView(p);
+ BeatChanged?.Invoke();
+ if (pan) { from = camera.LookAt; to = focus!.Value; length = b.Pan; }
+ else Act();
+ return;
+ }
+ Index = beats.Count - 1;
+ if (!wrote || tookOver) { Stop(); return; }
+ phase = Phase.Return; t = 0f; from = camera.LookAt;
+ float dx = saved.x - from.x, dz = saved.z - from.z;
+ float metres = Mathf.Sqrt(dx * dx + dz * dz);
+ if (metres <= CameraGlide.StillM) { Stop(); return; }
+ length = CameraGlide.Seconds(metres, map.HexMetres);
+ }
+
+ void Act()
+ {
+ var b = beats[Index];
+ acted = Index; phase = Phase.Act; t = 0f;
+ length = (b.Slides ? UnitTokenMotion.Duration : 0f) + b.Dwell;
+ foreach (var m in b.Moves) map.Release(m.Unit);
+ if (b.Engagements > 0)
+ map.Fight(b.Causes.Where(c => c.Key == WhyKeys.Engagement || c.Key == WhyKeys.Destroyed).ToList());
+ retreated = false;
+ // A folded beat plays everything at once; an engagement's retreaters slide off once its hit has landed.
+ if (b.Folded || b.Retreats.Count == 0) ReleaseRetreats(b);
+ }
+
+ void ReleaseRetreats(UnitBeat b)
+ {
+ retreated = true;
+ foreach (var r in b.Retreats) map.Release(r.Unit);
+ }
+
+ void Steer(Vector3 p)
+ {
+ camera.LookAt = p;
+ camera.Settle();
+ lastLookAt = camera.LookAt; lastDistance = camera.Distance; wrote = true;
+ }
+
+ void Stop(bool release = true)
+ {
+ bool was = Active || pending;
+ Active = false; pending = false; Index = -1; acted = -1; session = null;
+ beats = Array.Empty<UnitBeat>();
+ if (!was) return;
+ map.ReleaseAll(snap: true); // anything still held (a beat left out) stands on its place
+ if (release) Holding?.Invoke(false);
+ Finished?.Invoke();
+ }
+
+ /// <summary>Teardown (a language switch, OnDisable): as <see cref="Skip"/>, but the view goes back without
+ /// <see cref="IPlaybackCamera.Settle"/>, whose callback refreshes the map labels, which GameRoot disposes first (they are
+ /// built after the playback). The camera controller applies the look-at point on its next frame (#2967 review, S2).</summary>
+ public void Dispose()
+ {
+ bridge.Stepped -= onStepped;
+ bridge.TurnEnded -= onTurn;
+ bridge.Changed -= onChanged;
+ if (Active && wrote && !tookOver) camera.LookAt = saved;
+ Stop();
+ }
+ }
+
+ /// <summary>The map as the playback sees it in the game: UnitLayer's holds, UnitAttackPresenter's fights and the map's
+ /// hexes. Kept here, not in GameRoot, so GameRoot only builds it.</summary>
+ public sealed class UnitLayerPlaybackMap : IPlaybackMap
+ {
+ readonly UnitLayer layer; readonly UnitAttackPresenter attacks; readonly MapScene map; readonly SimBridge bridge;
+
+ public UnitLayerPlaybackMap(UnitLayer layer, UnitAttackPresenter attacks, MapScene map, SimBridge bridge)
+ {
+ this.layer = layer; this.attacks = attacks; this.map = map; this.bridge = bridge;
+ }
+
+ public void Hold(IEnumerable<int> ids) { if (layer != null) layer.Hold(ids); }
+ public bool Release(int id) => layer != null && layer.Release(id);
+ public void ReleaseAll(bool snap) { if (layer != null) layer.ReleaseAll(snap); }
+ public void Fight(IReadOnlyList<Cause> lines) => attacks.Play(lines);
+ public bool Draws(int id) => layer != null && layer.Draws(id);
+ /// <summary>The "units" toggle switches the layer's object (UnitLayer.ToggleName), and a capture run turns it off.</summary>
+ public bool UnitsShown => layer != null && layer.gameObject.activeInHierarchy;
+ public Vector3? World(int q, int r)
+ {
+ var hex = bridge.Content.HexAt(q, r);
+ return hex == null || map == null ? (Vector3?)null : map.Frame.ToWorld(hex.Lon, hex.Lat, 0);
+ }
+ public float HexMetres => map != null && map.Hexes != null ? map.Hexes.hex_size_km * 1000f : 0f;
+ }
+
+ /// <summary>The camera as the playback sees it in the game: the rig's look-at point and CameraController.Settle, as
+ /// GameRoot.FocusUnit moves it.</summary>
+ public sealed class RigPlaybackCamera : IPlaybackCamera
+ {
+ readonly CameraRig rig; readonly CameraController controller; readonly Action? moved;
+
+ /// <param name="moved">After each settle (the map labels follow the camera).</param>
+ public RigPlaybackCamera(CameraRig rig, CameraController controller, Action? moved = null)
+ {
+ this.rig = rig; this.controller = controller; this.moved = moved;
+ }
+
+ public Vector3 LookAt { get => rig.LookAt; set => rig.LookAt = value; }
+ public float Distance => rig.Distance;
+ public bool InView(Vector3 point) => CameraGlide.InView(rig, point);
+ public void Settle() { controller.Settle(); moved?.Invoke(); }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/EnemyTurnPlayback.cs.meta b/unity/Assets/Scripts/UI/EnemyTurnPlayback.cs.meta
new file mode 100644
index 000000000..ea2a5174b
--- /dev/null
+++ b/unity/Assets/Scripts/UI/EnemyTurnPlayback.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2b7cf12c164442c3b52b9aba4ecc5c5c
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/EventCardPresenter.cs b/unity/Assets/Scripts/UI/EventCardPresenter.cs
index 833f54c67..f0adf08c0 100644
--- a/unity/Assets/Scripts/UI/EventCardPresenter.cs
+++ b/unity/Assets/Scripts/UI/EventCardPresenter.cs
@@ -124,7 +124,7 @@ namespace Statecraft.Game.UI
// A cover has closed: render the first visible cue too; a start-screen photograph waits until now (#592).
photoWaits = false;
if (Shown != null) Render();
- focusedFor = null; if (!hiddenInCapture && Shown != null && !Collapsed) FocusCard(Shown.Id, force: true);
+ focusedFor = null; if (!hiddenInCapture && !heldForPlayback && Shown != null && !Collapsed) FocusCard(Shown.Id, force: true);
};
onHidePointer = _ => hideByPointer = true;
onHideSubmit = _ => hideByPointer = false;
@@ -221,6 +221,26 @@ namespace Statecraft.Game.UI
Render();
}
+ bool heldForPlayback;
+ /// <summary>#2202: true while End turn's enemy playback runs (EnemyTurnPlayback.Holding; owner, Q1 a: the card waits for
+ /// it). The card and "Decision waiting" stay out of view and a new card raises <see cref="Opened"/>, with its cue,
+ /// only once the playback ends. Nothing is answered or queued here: the card is the same card, shown later.</summary>
+ public bool HeldForPlayback
+ {
+ get => heldForPlayback;
+ set
+ {
+ if (heldForPlayback == value) return;
+ heldForPlayback = value;
+ if (value) { Render(); return; }
+ // Back in view: it takes the focus as from under a cover (#2967 review, N1), whatever had it before the hold.
+ focusedFor = null; restoring = true;
+ try { Render(); }
+ finally { restoring = false; }
+ }
+ }
+ bool restoring; // the held card is coming back (HeldForPlayback false): FocusCard takes the focus over any other
+
/// <summary>The event the card shows, or null when every pending event has a queued answer.</summary>
public GameEvent? Shown { get; private set; }
@@ -252,10 +272,10 @@ namespace Statecraft.Game.UI
Shown = open.FirstOrDefault();
if (Shown == null) { collapsedFor = null; openedFor = null; scrolledFor = null; }
if (bridge.Session != session) { session = bridge.Session; collapsedFor = null; focusedFor = null; openedFor = null; scrolledFor = null; }
- var shown = !hiddenInCapture && Shown != null && !Collapsed;
+ var shown = !hiddenInCapture && !heldForPlayback && Shown != null && !Collapsed;
ScreenNav.Show(card, shown); // #1106: grows in, shrinks away
card.SetEnabled(shown); // a child of an undisplayed element can still take the focus (#400): a collapsed card's options must not
- reopen.style.display = !hiddenInCapture && Collapsed ? DisplayStyle.Flex : DisplayStyle.None;
+ reopen.style.display = !hiddenInCapture && !heldForPlayback && Collapsed ? DisplayStyle.Flex : DisplayStyle.None;
hudRoot.EnableInClassList(OpenClass, shown);
ScreenNav.DisableCovered(hudRoot);
// An answer is an order and costs Attention (choose_event_option): the bridge prices it and checks it as Queue
@@ -370,7 +390,7 @@ namespace Statecraft.Game.UI
if (scrolledFor != e.Id) { scrolledFor = e.Id; scroll.scrollOffset = UnityEngine.Vector2.zero; }
card.Q<Label>("event-count").text = open.Count > 1 ? text.Format(open.Count == 2 ? "event.more_one" : "event.more", open.Count - 1) : "";
if (shown && !photoWaits && layer.enabledInHierarchy && openedFor != e.Id) { openedFor = e.Id; Opened?.Invoke(e.Id); }
- if (shown && focusedFor != e.Id) FocusCard(e.Id, force: false);
+ if (shown && focusedFor != e.Id) FocusCard(e.Id, force: restoring);
}
string OperationUnitName(string row)
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 36c95a9c7..9161c7225 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -89,6 +89,7 @@ namespace Statecraft.Game.UI
string? hoveredCity; // the city HoverCity lit (#1063)
readonly Dictionary<(int q, int r), List<string>> citiesByHex = new Dictionary<(int, int), List<string>>();
OutcomePresenter? outcomes;
+ EnemyTurnPlayback? playback;
TurnReportPresenter? report;
EndScreenPresenter? end;
/// <summary>Set by SwitchLanguage for its Begin: the player had closed the end screen, so the rebuilt one stays closed.</summary>
@@ -420,7 +421,7 @@ namespace Statecraft.Game.UI
music = new MenuMusic(root, Application.platform == RuntimePlatform.WebGLPlayer);
if (music != null) music.Duck = null;
Own(new SettingsPresenter(root, text, SettingsFile(), switchLanguage, panel: document.panelSettings, audio: audio, advisors: AdvisorSession.Settings,
- companion: companionSwitch, music: music));
+ companion: companionSwitch, music: music, enemyMoves: on => { if (!on) playback?.Skip(); }));
// "Report a bug or idea" (#1169), from Settings and the start screen: the version line names the content GameBoot logged.
feedback = Own(new FeedbackPresenter(root, text, ReportLinks.Version(Application.version, inputs.Content.Hash)));
var feedbackPanel = feedback;
@@ -500,8 +501,9 @@ namespace Statecraft.Game.UI
bridge.Changed += showUnits;
owned.Add(new Undo(() => bridge.Changed -= showUnits));
showUnits();
- owned.Add(new UnitAttackPresenter(bridge, unitLayer.PlayAttack, unitLayer.PlayHit, unitLayer.PlayDestroyed,
- unitLayer.PlayDefenderHit, unitLayer.PlayAttack)); // after showUnits: the map is redrawn first
+ var attacks = new UnitAttackPresenter(bridge, unitLayer.PlayAttack, unitLayer.PlayHit, unitLayer.PlayDestroyed,
+ unitLayer.PlayDefenderHit, unitLayer.PlayAttack); // after showUnits: the map is redrawn first
+ owned.Add(attacks);
DiagLog.BootPhase("units layer built");
// #1878: the turn report is up, the hexes the turn attacked show the under-attack look; closing it clears them.
var underAttack = new Statecraft.Game.Map.UnderAttackLayer(map);
@@ -597,6 +599,20 @@ namespace Statecraft.Game.UI
};
pointer.PillHex = pillHex;
var camRig = rig = cameraController.GetComponent<CameraRig>();
+ // #2202: after End turn the map plays the Arab forces' moves, the camera going to each, and the footer names the side
+ // (EnemyTurnPlayback, EnemyPlaybackBar). Never in a smoke run or EditMode; the Settings switch is read at each End
+ // turn. It starts once an outcome clip (or the opening) has gone, and the report and the card wait for it (Q1 a).
+ var play = playback = Own(new EnemyTurnPlayback(bridge, new UnitLayerPlaybackMap(unitLayer, attacks, map, bridge),
+ new RigPlaybackCamera(camRig, cameraController, () => labels?.Refresh()),
+ enabled: () => Application.isPlaying && !smokeRun && SettingsPresenter.EnemyMovesOn(SettingsFile()),
+ waiting: () => outcomes?.Showing != null || opening?.HoldsThePointer == true));
+ attacks.Claimed = play.Claims;
+ // The card first, then the report, as at an End turn with no playback: the card comes into view with its cue, then
+ // the report covers it.
+ Action<bool> holding = held => { if (card != null) card.HeldForPlayback = held; if (report != null) report.Held = held; };
+ play.Holding += holding;
+ owned.Add(new Undo(() => play.Holding -= holding)); // disposed before the playback: its last release touches neither
+ Own(new EnemyPlaybackBar(root, text, play, bridge)).Units = unitData;
Own(new TopBarInset(root, camRig)); // the map is framed below the top bar
Own(new SafeAreaFit(root)); // the HUD keeps clear of the phone's notch
// the map's keyboard stop (#41 B1b): Enter or Space picks the hex under the look-at point, as a click there would
@@ -876,6 +892,9 @@ namespace Statecraft.Game.UI
// #2340: the card or capture dialog the player hid; the rebuilt presenters would open it again.
var hiddenCard = card?.Collapsed == true ? card.Shown!.Id : null;
var hiddenCapture = capture?.Collapsed == true ? capture.Shown : null;
+ // #2202: a turn report waiting for the enemy's moves (or for the screen opened over them). The rebuild ends the
+ // moves, and the rebuilt report would never hear of the turn (#2967 review, S2).
+ bool reportWaiting = report?.Waiting == true;
// Cleared even if Begin throws, so the next ordinary Begin (a New game, a load) never picks it up.
try { Begin(inputs, 0, startScreen: fromStart, keep: Bridge); }
finally { keptBudgetDraft = null; }
@@ -896,6 +915,7 @@ namespace Statecraft.Game.UI
}
}
if (!fromStart) nav?.Open("settings");
+ if (reportWaiting) report?.Wait(); // after Settings is open again: the report opens when it closes
// Focus the choice again a frame later: a screen shown this same tick cannot take the focus until its
// styles resolve, and a bare Focus() then leaves it wherever it was (#1915's tour test read end-turn).
if (document.rootVisualElement.Q<Button>((fromStart ? "start-language-" : "settings-language-") + language) is Button choice)
@@ -1107,7 +1127,7 @@ namespace Statecraft.Game.UI
owned.Clear();
savePersistenceResult = null;
if (hoveredCity != null) { hoveredCity = null; HandCursor(false); } // the next Begin's pills start unlit
- companion = null; minimap = null; unseenSkipped = null; labels = null; nav = null; start = null; opening = null; raid = null; card = null; outcomes = null; report = null; end = null; advisor = null; cabinet = null; budgetScreen = null; newGame = null; encyclopedia = null; feedback = null; share = null; info = null; rig = null; drawn = null; drawnSites = null; units = null; Regions = null; logCamera = false;
+ companion = null; minimap = null; unseenSkipped = null; labels = null; nav = null; start = null; opening = null; raid = null; card = null; outcomes = null; playback = null; report = null; end = null; advisor = null; cabinet = null; budgetScreen = null; newGame = null; encyclopedia = null; feedback = null; share = null; info = null; rig = null; drawn = null; drawnSites = null; units = null; Regions = null; logCamera = false;
// A ?profile run cut short (a stopped coroutine never reaches its restore line) must not leave the terrain at the
// profile's pixel error (Task 24 review M1). Nothing else changes it, so restoring is always right.
if (map != null && map.Terrain != null) map.Terrain.heightmapPixelError = MapBuilder.TerrainPixelError;
@@ -1314,6 +1334,9 @@ namespace Statecraft.Game.UI
// Escape in the Cabinet's candidate list goes back to the seat, not out of the screen (#2340 M2). A screen the
// focused element's Cancel already closed this frame took the press too (ClosedThisFrame), as for end and report.
if (!done) done = cabinet?.Escape() == true || nav?.Close() == true || nav?.ClosedThisFrame == true;
+ // #2202: the Arab forces' moves play on the map, under every screen and overlay: with nothing above them left
+ // to close, Escape ends them, and nothing else (#2967 review, S1).
+ if (!done) done = playback?.Skip() == true;
// With nothing above it to close, Escape withdraws a New Game request armed from the top bar too, the start
// screen closed (#2340 L2, #2521), and is used up there, so it does not also clear the map selection. A
// decision card or capture dialog open over it is above it (the top bar stays usable under them): that
@@ -1343,6 +1366,7 @@ namespace Statecraft.Game.UI
if (report?.IsOpen != true && end?.IsOpen != true && (keys.upArrowKey.wasPressedThisFrame || keys.downArrowKey.wasPressedThisFrame))
navGuard?.Step(keys.upArrowKey.wasPressedThisFrame);
}
+ playback?.Tick(Time.deltaTime); // #2202
SyncMinimap();
if (!logCamera || rig == null || (rig.Distance == loggedDistance && rig.Yaw == loggedYaw)) return;
loggedDistance = rig.Distance; loggedYaw = rig.Yaw;
diff --git a/unity/Assets/Scripts/UI/ScreenNav.cs b/unity/Assets/Scripts/UI/ScreenNav.cs
index af381dcbe..f90657bc8 100644
--- a/unity/Assets/Scripts/UI/ScreenNav.cs
+++ b/unity/Assets/Scripts/UI/ScreenNav.cs
@@ -313,6 +313,9 @@ namespace Statecraft.Game.UI
/// <summary>The open screen's name, or null.</summary>
public string? Current { get; private set; }
+ /// <summary>Raised with <see cref="Current"/> each time a screen opens or closes (TurnReportPresenter: a report that
+ /// waited for the enemy's moves opens once the player closes the screen they opened meanwhile, #2202).</summary>
+ public event System.Action<string?>? Changed;
public void Toggle(string screen)
{
@@ -338,6 +341,7 @@ namespace Statecraft.Game.UI
// After the OnOpened action, which is what builds a screen's rows (CabinetPresenter, DefencePresenter):
// before it there is nothing in the screen to hand the focus to.
if (screen != null && presses.ByKeyboard) HandFocusTo(root.Q<VisualElement>("screen-" + screen));
+ Changed?.Invoke(screen);
}
/// <summary>Gives the keyboard focus to the screen just opened (accessibility audit, #41, the keyboard-only
diff --git a/unity/Assets/Scripts/UI/SettingsPresenter.cs b/unity/Assets/Scripts/UI/SettingsPresenter.cs
index a29d19753..c747d291a 100644
--- a/unity/Assets/Scripts/UI/SettingsPresenter.cs
+++ b/unity/Assets/Scripts/UI/SettingsPresenter.cs
@@ -20,7 +20,7 @@ namespace Statecraft.Game.UI
/// automatic fallback's tilt-shift step (TiltShift.FallbackOff), which it never changes.</summary>
public sealed class SettingsPresenter : IDisposable
{
- public const string TiltShiftKey = "tiltshift", QualityKey = "quality", LanguageKey = "lang", UiScaleKey = "uiscale", SoundKey = "sfx", MusicKey = "music", CompanionKey = "companion", SelectedClass = "settings-choice-selected";
+ public const string TiltShiftKey = "tiltshift", QualityKey = "quality", LanguageKey = "lang", UiScaleKey = "uiscale", SoundKey = "sfx", MusicKey = "music", CompanionKey = "companion", EnemyMovesKey = "enemymoves", SelectedClass = "settings-choice-selected";
/// <summary>The owner's UI scales (#40, 18 Oct 2026), in percent; the first is the default.</summary>
public static readonly int[] UiScales = { 100, 125, 150 };
/// <summary>The owner's ruling on #1011 (19 Oct 2026): Settings offers only the UI scales verified to fit, and 100% always,
@@ -60,6 +60,13 @@ namespace Statecraft.Game.UI
bool quitAsked;
readonly Button companionSwitch;
readonly (Func<bool> on, Action<bool> set)? companion;
+ readonly Button enemyMoves;
+ readonly Action<bool>? setEnemyMoves;
+ bool enemyMovesOn;
+
+ /// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 7): whether End turn plays the
+ /// enemy's moves on the map (EnemyTurnPlayback). On unless the player turned it off (the stored "off").</summary>
+ public static bool EnemyMovesOn(SettingsStore? store) => store?.Read(EnemyMovesKey) != "off";
/// <param name="store">Where the choice is kept; null keeps nothing (the option still works until the page closes).</param>
/// <param name="switchLanguage">Puts the UI in the language pressed (GameRoot builds the screens again); null changes
@@ -70,8 +77,10 @@ namespace Statecraft.Game.UI
/// <param name="companion">The WebGL companion (#1119, WebCompanion): whether it runs, and what turns it on or off at
/// once; null (no page to show it in) hides its row.</param>
/// <param name="music">The start menu's music the Music volume applies to; null keeps only the choice.</param>
+ /// <param name="enemyMoves">Told the enemy-moves switch's new value at once (#2202: off skips a playback that plays);
+ /// null keeps only the choice, read at the next End turn.</param>
public SettingsPresenter(VisualElement root, UiText text, SettingsStore? store, Action<string>? switchLanguage = null, PanelSettings? panel = null, GameAudio? audio = null, AdvisorSettings? advisors = null,
- (Func<bool> on, Action<bool> set)? companion = null, MenuMusic? music = null)
+ (Func<bool> on, Action<bool> set)? companion = null, MenuMusic? music = null, Action<bool>? enemyMoves = null)
{
this.store = store; this.text = text; this.root = root; this.audio = audio; this.advisors = advisors; this.companion = companion; this.music = music;
screen = root.Q<VisualElement>("screen-settings");
@@ -80,6 +89,11 @@ namespace Statecraft.Game.UI
tiltShift = screen.Q<Button>("settings-tiltshift");
if (store?.Read(TiltShiftKey) == "off") TiltShift.Enabled = false;
tiltShift.clicked += Flip;
+ screen.Q<Label>("settings-enemymoves-label").text = text["settings.enemymoves"];
+ this.enemyMoves = screen.Q<Button>("settings-enemymoves");
+ setEnemyMoves = enemyMoves;
+ enemyMovesOn = EnemyMovesOn(store);
+ this.enemyMoves.clicked += FlipEnemyMoves;
// Graphics quality (#40): three buttons, the one that is set marked. A stored choice is applied at start unless
// an instrument flag must see the tier's own look (GraphicsQuality.AtStart); Auto at start changes nothing.
screen.Q<Label>("settings-quality-label").text = text["settings.quality"];
@@ -185,6 +199,7 @@ namespace Statecraft.Game.UI
public void Dispose()
{
tiltShift.clicked -= Flip;
+ enemyMoves.clicked -= FlipEnemyMoves;
companionSwitch.clicked -= FlipCompanion;
foreach (var (b, _, pick) in quality) b.clicked -= pick;
languages.Dispose();
@@ -221,6 +236,18 @@ namespace Statecraft.Game.UI
}
}
+ void FlipEnemyMoves()
+ {
+ enemyMovesOn = !enemyMovesOn;
+ Show();
+ setEnemyMoves?.Invoke(enemyMovesOn);
+ try { store?.Write(EnemyMovesKey, enemyMovesOn ? "on" : "off"); }
+ catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
+ {
+ Debug.LogWarning($"Settings: could not keep the enemy-moves choice ({e.Message}); it holds until the page is closed");
+ }
+ }
+
void Flip()
{
TiltShift.Enabled = !TiltShift.Enabled;
@@ -323,6 +350,7 @@ namespace Statecraft.Game.UI
void Show()
{
tiltShift.text = text[TiltShift.Enabled ? "settings.on" : "settings.off"];
+ enemyMoves.text = text[enemyMovesOn ? "settings.on" : "settings.off"];
companionSwitch.text = text[companion?.on() == true ? "settings.on" : "settings.off"];
foreach (var (b, c, _) in quality) b.EnableInClassList(SelectedClass, c == GraphicsQuality.Current);
languages.Mark();
diff --git a/unity/Assets/Scripts/UI/SideFlag.cs b/unity/Assets/Scripts/UI/SideFlag.cs
new file mode 100644
index 000000000..ba67132fb
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SideFlag.cs
@@ -0,0 +1,138 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using Statecraft.Game.Map.Units;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>#2202: a side's flag in the UI, the enemy playback's footer picture (owner, 8 November 2026, "Flag + name
+ /// (Recommended)"). It draws the very cloth the side's tokens fly: a sourced 1948 flag is <see cref="UnitFlags.BuildCloth"/>'s
+ /// triangles in <see cref="UnitFlags.Colours"/>, seen face on; a side the map gives the neutral pennant
+ /// (<see cref="UnitFlags.HasPennant"/>, the Arab Liberation Army) gets <see cref="UnitFlags.PennantCloth"/> in
+ /// <see cref="UnitFlags.PennantColour"/>. So there is one definition of each design, and nothing here is drawn by hand.
+ /// The triangles go straight to the UI mesh (MeshGenerationContext.Allocate, as UiFrame's rules): Painter2D would fill
+ /// each triangle with an antialiased edge and show hairline seams across the cloth. The flag is never mirrored in Hebrew
+ /// (a flag has one right way round); the row it sits in is. It takes no clicks.</summary>
+ [UxmlElement]
+ public partial class SideFlag : VisualElement
+ {
+ /// <summary>A flag in figure units (x along the cloth from the pole, y up): its triangles, three points each, and one
+ /// colour per triangle, in drawing order (a later colour lies over an earlier one).</summary>
+ public sealed class Shape
+ {
+ public readonly IReadOnlyList<Vector2> Points;
+ public readonly IReadOnlyList<Color> Colours;
+ public readonly Rect Bounds;
+ public Shape(IReadOnlyList<Vector2> points, IReadOnlyList<Color> colours)
+ {
+ if (points.Count != colours.Count * 3) throw new ArgumentException("three points a triangle", nameof(points));
+ Points = points; Colours = colours;
+ float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;
+ foreach (var p in points) { x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y); }
+ Bounds = points.Count == 0 ? Rect.zero : Rect.MinMaxRect(x0, y0, x1, y1);
+ }
+ }
+
+ static readonly Dictionary<string, Shape?> Shapes = new Dictionary<string, Shape?>(StringComparer.Ordinal);
+
+ /// <summary>The flag <paramref name="side"/>'s tokens fly, or null for a side the map draws with no flag or pennant.
+ /// Built once a side from the token's own mesh and kept.</summary>
+ public static Shape? For(string? side)
+ {
+ if (string.IsNullOrEmpty(side)) return null;
+ if (Shapes.TryGetValue(side!, out var known)) return known;
+ Shape? made = null;
+ if (UnitFlags.Has(side))
+ {
+ var cloth = UnitFlags.BuildCloth(side);
+ if (cloth != null)
+ {
+ var colours = UnitFlags.Colours(side!);
+ var verts = cloth.vertices;
+ var points = new List<Vector2>(); var tints = new List<Color>();
+ for (int k = 0; k < cloth.subMeshCount && k < colours.Count; k++)
+ {
+ var tris = cloth.GetTriangles(k);
+ for (int i = 0; i + 2 < tris.Length; i += 3)
+ {
+ for (int j = 0; j < 3; j++) { var v = verts[tris[i + j]]; points.Add(new Vector2(v.x, v.y)); }
+ tints.Add(colours[k]);
+ }
+ }
+ if (Application.isPlaying) UnityEngine.Object.Destroy(cloth); else UnityEngine.Object.DestroyImmediate(cloth);
+ made = new Shape(points, tints);
+ }
+ }
+ else if (UnitFlags.HasPennant(side))
+ {
+ var outline = UnitFlags.PennantCloth();
+ var points = new List<Vector2>(); var tints = new List<Color>();
+ for (int i = 1; i + 1 < outline.Count; i++) // a fan from the first point, as MiniatureMesh.Plate
+ {
+ points.Add(outline[0]); points.Add(outline[i]); points.Add(outline[i + 1]);
+ tints.Add(UnitFlags.PennantColour);
+ }
+ made = new Shape(points, tints);
+ }
+ Shapes[side!] = made;
+ return made;
+ }
+
+ string? side;
+ Shape? shape;
+
+ public SideFlag()
+ {
+ pickingMode = PickingMode.Ignore;
+ AddToClassList("side-flag");
+ generateVisualContent += Draw;
+ }
+
+ /// <summary>The side whose flag is drawn; setting the same side again does not redraw.</summary>
+ public string? Side
+ {
+ get => side;
+ set
+ {
+ if (string.Equals(side, value, StringComparison.Ordinal)) return;
+ side = value; shape = For(value);
+ Changes++;
+ style.display = shape == null ? DisplayStyle.None : DisplayStyle.Flex;
+ MarkDirtyRepaint();
+ }
+ }
+
+ /// <summary>The flag being drawn, or null.</summary>
+ public Shape? Drawn => shape;
+ /// <summary>How many times the picture changed (a test seam: the flag changes once a side).</summary>
+ public int Changes { get; private set; }
+
+ void Draw(MeshGenerationContext mgc)
+ {
+ var s = shape; var r = contentRect;
+ if (s == null || s.Points.Count == 0 || r.width <= 0f || r.height <= 0f || s.Bounds.width <= 0f || s.Bounds.height <= 0f) return;
+ float scale = Mathf.Min(r.width / s.Bounds.width, r.height / s.Bounds.height);
+ float ox = r.x + (r.width - s.Bounds.width * scale) * 0.5f, oy = r.y + (r.height - s.Bounds.height * scale) * 0.5f;
+ Vector2 At(Vector2 p) => new Vector2(ox + (p.x - s.Bounds.xMin) * scale, oy + (s.Bounds.yMax - p.y) * scale); // y down
+ int tris = s.Colours.Count;
+ const int perBatch = 3 * 20000; // under UI Toolkit's 65535 vertices a mesh
+ for (int start = 0; start < tris; start += perBatch / 3)
+ {
+ int n = Mathf.Min(perBatch / 3, tris - start);
+ var m = mgc.Allocate(n * 3, n * 3);
+ for (int t = 0; t < n; t++)
+ {
+ int i = (start + t) * 3;
+ Vector2 a = At(s.Points[i]), b = At(s.Points[i + 1]), c = At(s.Points[i + 2]);
+ // UI Toolkit wants clockwise triangles on screen (y down): a positive cross product.
+ if ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) < 0f) (b, c) = (c, b);
+ Color32 tint = s.Colours[start + t];
+ foreach (var p in new[] { a, b, c }) m.SetNextVertex(new Vertex { position = new Vector3(p.x, p.y, Vertex.nearZ), tint = tint });
+ for (int j = 0; j < 3; j++) m.SetNextIndex((ushort)(t * 3 + j));
+ }
+ }
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/SideFlag.cs.meta b/unity/Assets/Scripts/UI/SideFlag.cs.meta
new file mode 100644
index 000000000..654bcb82f
--- /dev/null
+++ b/unity/Assets/Scripts/UI/SideFlag.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: c11d029d9194490c906342eb1a89a3ec
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.cs
index 2e55e1fb2..33ec690be 100644
--- a/unity/Assets/Scripts/UI/SimBridge.cs
+++ b/unity/Assets/Scripts/UI/SimBridge.cs
@@ -53,6 +53,10 @@ namespace Statecraft.Game.UI
/// End Turn only the turn's new ones, not the open turn's attack orders, which the turn runs again first. Never on a
/// load or a refused turn.</summary>
public event Action<IReadOnlyList<Cause>>? CombatResolved;
+ /// <summary>#2202: raised at End Turn with the step's result, after the step and before <see cref="Changed"/> redraws the
+ /// map, so the enemy's playback (EnemyTurnPlayback) holds the tokens where they stood. Only on a turn the simulation ran:
+ /// never on a refused turn, a load or a New Game. Its Why lines start with the open turn's own (the player's orders).</summary>
+ public event Action<StepResult>? Stepped;
/// <summary>Raised when Queue refuses an order, with the player-facing reason.</summary>
public event Action<string>? Refused;
/// <summary>A validated order was refused specifically for Attention; presentation-only advice signal.</summary>
@@ -545,6 +549,7 @@ namespace Statecraft.Game.UI
}
LastBatch = batch; LastBatchDate = date;
deferred.Clear(); skipped.Clear();
+ Notify(Stepped, r);
Notify(Changed);
Notify(CombatResolved, Engagements(r.Why.Skip(replayed)));
Notify(TurnEnded, r.Rejected);
diff --git a/unity/Assets/Scripts/UI/TurnReportPresenter.cs b/unity/Assets/Scripts/UI/TurnReportPresenter.cs
index 2a4db4a98..3621ce588 100644
--- a/unity/Assets/Scripts/UI/TurnReportPresenter.cs
+++ b/unity/Assets/Scripts/UI/TurnReportPresenter.cs
@@ -44,6 +44,7 @@ namespace Statecraft.Game.UI
readonly ScreenNav nav; readonly Button close, all;
readonly Action<IReadOnlyList<Rejection>> onTurn;
readonly Action onChanged;
+ readonly Action<string?> onScreen;
GameSession session; // the session the open report belongs to
readonly EventCallback<NavigationCancelEvent> onCancel;
/// <summary>The turn last reported (or the session's last turn when this was made: a loaded game reports nothing).</summary>
@@ -81,6 +82,11 @@ namespace Statecraft.Game.UI
var last = bridge.Session.Last;
if (last == null || ReferenceEquals(last, seen)) return;
seen = last;
+ // #2202: it opens when the enemy playback ends (Held). End turn still closes an open screen, as Show does
+ // without a playback, so the moves play on the open map (#2967 review, S1); a screen opened while they
+ // play stays (ShowWhenFree waits for it).
+ if (held) { nav.Close(); wantsShow = true; return; }
+ wantsShow = false; // this turn's report replaces one that waited for a screen
Show();
}
catch (Exception e) { UnityEngine.Debug.LogException(e); Hide(); }
@@ -89,8 +95,10 @@ namespace Statecraft.Game.UI
// Only a replaced session (New Game, a load: SimBridge.Replace) makes the report stale. Other changes keep it:
// answering the ending turn's card (SimBridge.SeeEndingCard) changes nothing and leaves it under the end screen.
session = bridge.Session;
- onChanged = () => { if (ReferenceEquals(bridge.Session, session)) return; session = bridge.Session; Hide(); };
+ onChanged = () => { if (ReferenceEquals(bridge.Session, session)) return; session = bridge.Session; wantsShow = false; Hide(); };
bridge.Changed += onChanged;
+ onScreen = screen => { if (screen == null) ShowWhenFree(); };
+ nav.Changed += onScreen;
Hide();
}
@@ -98,6 +106,43 @@ namespace Statecraft.Game.UI
/// shows the under-attack look on the hexes the turn attacked for as long as the report is up).</summary>
public event Action<StepResult?>? Showing;
+ bool held, wantsShow;
+ /// <summary>#2202: true while End turn's enemy playback runs (EnemyTurnPlayback.Holding; owner, Q1 a: the report waits
+ /// for it). A turn that ends meanwhile is reported when it turns false; another game drops the wait.</summary>
+ public bool Held
+ {
+ get => held;
+ set
+ {
+ if (held == value) return;
+ held = value;
+ ShowWhenFree();
+ }
+ }
+
+ /// <summary>#2202: true while a turn's report waits to open: for the enemy playback (<see cref="Held"/>), or for a
+ /// screen the player opened while it played, which the report does not close under them (#2967 review, S3).</summary>
+ public bool Waiting => wantsShow;
+
+ /// <summary>#2202: the session's last turn is reported once nothing holds it (GameRoot's language switch: the rebuilt
+ /// report takes over a wait the old one had, #2967 review, S2).</summary>
+ public void Wait()
+ {
+ var last = bridge.Session.Last;
+ if (last == null) return;
+ seen = last;
+ wantsShow = true;
+ ShowWhenFree();
+ }
+
+ void ShowWhenFree()
+ {
+ if (held || !wantsShow || nav.Current != null) return;
+ wantsShow = false;
+ try { Show(); }
+ catch (Exception e) { UnityEngine.Debug.LogException(e); Hide(); }
+ }
+
/// <summary>True while the report shows.</summary>
public bool IsOpen => hudRoot.ClassListContains(OpenClass);
@@ -300,6 +345,7 @@ namespace Statecraft.Game.UI
{
bridge.Changed -= onChanged;
bridge.TurnEnded -= onTurn;
+ nav.Changed -= onScreen;
close.clicked -= OnClose;
all.clicked -= SeeAll;
report.UnregisterCallback(onCancel);
diff --git a/unity/Assets/Scripts/UI/UnitAttackPresenter.cs b/unity/Assets/Scripts/UI/UnitAttackPresenter.cs
index 483795134..cb6e22833 100644
--- a/unity/Assets/Scripts/UI/UnitAttackPresenter.cs
+++ b/unity/Assets/Scripts/UI/UnitAttackPresenter.cs
@@ -41,14 +41,25 @@ namespace Statecraft.Game.UI
bridge.CombatResolved += Resolved;
}
+ /// <summary>#2202: an engagement the enemy's playback (EnemyTurnPlayback.Claims) plays on its own beat, so End Turn
+ /// leaves it, and the Destroyed lines after it, for <see cref="Play"/>. Null (no playback, or the playback off): every
+ /// engagement plays at once, as before. A property, not a constructor argument, since the playback is built after it.</summary>
+ public Func<Cause, bool>? Claimed { get; set; }
+
+ /// <summary>#2202: plays these engagement lines and their Destroyed lines now, as End Turn plays a fresh engagement:
+ /// the fire take, the hit, the defenders' reaction and the dust (the playback's attack beat).</summary>
+ public void Play(IReadOnlyList<Cause> lines) => Resolved(lines ?? throw new ArgumentNullException(nameof(lines)));
+
void Resolved(IReadOnlyList<Cause> lines)
{
FireCue? cue = null; // the timed engagement just before: Combat.Engage adds its Destroyed lines right after it
float impactS = 0f; // and when its hit lands after its fire take starts
+ bool claimed = false; // the engagement just before is the playback's, and so are its Destroyed lines
foreach (var line in lines)
{
if (line.Key == WhyKeys.Destroyed)
{
+ if (claimed) continue;
if (destroyed is Func<int, float, bool> dust && line.Units.Count > 0)
{
int dead = line.Units[0].Id; float delay = impactS;
@@ -57,6 +68,8 @@ namespace Statecraft.Game.UI
continue;
}
cue = null; impactS = 0f;
+ claimed = line.Key == WhyKeys.Engagement && Claimed?.Invoke(line) == true;
+ if (claimed) continue;
var parsed = HitOf(line, IsGuns);
if (parsed is CombatHit h && timedPlay != null && Count(line, out int attackerCount))
{
diff --git a/unity/Assets/Scripts/UI/UnitBeats.cs b/unity/Assets/Scripts/UI/UnitBeats.cs
new file mode 100644
index 000000000..c41591e43
--- /dev/null
+++ b/unity/Assets/Scripts/UI/UnitBeats.cs
@@ -0,0 +1,261 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using Statecraft.Game.Map.Units;
+using Statecraft.Sim;
+
+namespace Statecraft.Game.UI
+{
+ public enum BeatKind { Move, Attack }
+
+ /// <summary>One unit's move as a cause records it: the hex it stood on (UnitRef.Q, R, #2230) and the hex it reached.</summary>
+ public readonly struct UnitStep
+ {
+ public readonly int Unit, FromQ, FromR, ToQ, ToR;
+ public UnitStep(int unit, int fromQ, int fromR, int toQ, int toR) { Unit = unit; FromQ = fromQ; FromR = fromR; ToQ = toQ; ToR = toR; }
+ public override string ToString() => FormattableString.Invariant($"{Unit}: ({FromQ},{FromR}) to ({ToQ},{ToR})");
+ }
+
+ /// <summary>Which of a step's Why lines open a beat: a move line (UnitMoved, the destination in Args[0]) or an
+ /// engagement line (Engagement, as Combat.Engage writes it). <see cref="Enemy"/> reads the enemy's orders (resolver steps 1
+ /// and 2); another reader of the same lines (#2544 PR 2, an operation's moves and attacks) brings its own two tests and
+ /// gets the same grouping, focus and pacing.</summary>
+ public sealed class BeatSource
+ {
+ readonly Func<Cause, bool> isMove, isAttack;
+
+ public BeatSource(Func<Cause, bool> isMove, Func<Cause, bool> isAttack)
+ {
+ this.isMove = isMove ?? throw new ArgumentNullException(nameof(isMove));
+ this.isAttack = isAttack ?? throw new ArgumentNullException(nameof(isAttack));
+ }
+
+ /// <summary>The enemy's moves (Movement.Move with enemy: true) and attacks (an engagement whose attackers are the
+ /// enemy's). The player's own lines carry no enemy order, so a turn's earlier player lines are never read.</summary>
+ public static readonly BeatSource Enemy = new BeatSource(
+ c => c.Key == WhyKeys.UnitMoved && c.EnemyOrder == Movement.Kind,
+ c => c.Key == WhyKeys.Engagement && c.EnemyOrder == Combat.Attack);
+
+ internal bool IsMove(Cause c) => c.Key == WhyKeys.UnitMoved && isMove(c);
+ internal bool IsAttack(Cause c) => c.Key == WhyKeys.Engagement && isAttack(c);
+ }
+
+ /// <summary>One beat of a replay: up to <see cref="UnitBeats.Timing.MaxUnitsPerBeat"/> nearby moves, or one engagement
+ /// with its retreats and losses, or (<see cref="Folded"/>) every action past the last full beat at once.</summary>
+ public sealed class UnitBeat
+ {
+ internal readonly List<UnitStep> moves = new List<UnitStep>(), retreats = new List<UnitStep>();
+ internal readonly List<int> attackers = new List<int>();
+ internal readonly List<Cause> causes = new List<Cause>();
+
+ public BeatKind Kind { get; internal set; }
+ /// <summary>The side whose beat it is (UnitRef.Side): a move's unit's, an engagement's first-named attacker's (Combat.Fight
+ /// names the attackers first, by id). A beat never holds two sides' actions (owner, 8 November 2026: "One side at a time
+ /// (Recommended)").</summary>
+ public string Side { get; internal set; } = "";
+ public IReadOnlyList<UnitStep> Moves => moves;
+ /// <summary>The engagements' attackers (UnitAttackPresenter.Attackers), whose fire take plays on this beat.</summary>
+ public IReadOnlyList<int> Attackers => attackers;
+ /// <summary>The defenders an engagement pushed back (Retreated lines), from the hex they held to the one they reached.</summary>
+ public IReadOnlyList<UnitStep> Retreats => retreats;
+ /// <summary>The units whose tokens wait for this beat (UnitLayer.Hold): the movers, then the retreaters.</summary>
+ public IReadOnlyList<int> Units => moves.Select(m => m.Unit).Concat(retreats.Select(m => m.Unit)).ToList();
+ /// <summary>The hex the camera goes to: the cube-rounded middle of a move beat's destinations, an engagement's hex.</summary>
+ public int FocusQ { get; internal set; }
+ public int FocusR { get; internal set; }
+ /// <summary>One side's actions past the beats a long turn keeps (at most <see cref="UnitBeats.Timing.MaxBeats"/> - 1),
+ /// played together, with no pan.</summary>
+ public bool Folded { get; internal set; }
+ /// <summary>The Why lines the beat plays, in the sim's order: its moves, or its engagements and their results.</summary>
+ public IReadOnlyList<Cause> Causes => causes;
+ /// <summary>How many engagements the beat plays (1 on an attack beat, 0 on a move beat, any number when folded).</summary>
+ public int Engagements { get; internal set; }
+ /// <summary>Seconds the camera takes to reach the focus (0 when folded).</summary>
+ public float Pan { get; internal set; }
+ /// <summary>Seconds the beat holds after its slide (a move) or for its fire take (an attack).</summary>
+ public float Dwell { get; internal set; }
+ /// <summary>Whether the beat's tokens slide (UnitTokenMotion.Duration) before its dwell: any beat with moves.</summary>
+ public bool Slides => moves.Count > 0;
+ public float Length => Pan + (Slides ? UnitTokenMotion.Duration : 0f) + Dwell;
+ }
+
+ /// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 2): the beats of a replay, from a
+ /// step's recorded unit actions (StepResult.Why) in the sim's own order. Presentation only: it groups and paces what the
+ /// sim already resolved and decides nothing. One pass over the lines with no allocation per frame (#2905: a caller builds
+ /// them on the replay's first frame, not inside End turn). The owner's answers (2 November 2026, "Q1-Q7 recommended, Q8
+ /// yes"): every move plays, on screen or off (Q2 a); the pacing below (Q3); nearby moves share a beat, beats past the
+ /// eighth fold into one (Q4). The owner's answer of 8 November 2026, "One side at a time (Recommended)": the beats play side
+ /// by side, the sides in the order they first act in the step's lines, each side's beats in the sim's order; beats group
+ /// and fold within a side only. Only the playback's order changes: the sim, its lines and every number stay as they are.</summary>
+ public static class UnitBeats
+ {
+ /// <summary>The pacing (Q3) and grouping (Q4), in seconds and hexes. The slide itself is #2176's
+ /// UnitTokenMotion.Duration (0.65 s), unchanged.</summary>
+ public static class Timing
+ {
+ public const float PanMin = 0.3f, PanMax = 0.8f, PanPerHex = 0.05f;
+ public const float MoveDwell = 0.35f, AttackMin = 0.8f, AttackMax = 1.5f;
+ /// <summary>The whole replay's longest (Q3: "a 12 s cap on the whole playback").</summary>
+ public const float Cap = 12f;
+ /// <summary>How far the cap may shrink a pan and a move's dwell; an attack's hold never drops below AttackMin.</summary>
+ public const float MinPan = 0.25f, MinDwell = 0.1f;
+ public const int BatchRadiusHexes = 3, MaxUnitsPerBeat = 4, MaxBeats = 8;
+ }
+
+ /// <summary>The pan to a point <paramref name="hexes"/> away: PanPerHex a hex, between PanMin and PanMax.</summary>
+ public static float PanSeconds(float hexes) => Math.Clamp(Timing.PanPerHex * hexes, Timing.PanMin, Timing.PanMax);
+
+ /// <summary>The beats of <paramref name="why"/> that <paramref name="source"/> reads, paced and capped. A move joins
+ /// the move beat before it while that beat has room and the move's destination lies within BatchRadiusHexes of the
+ /// beat's first destination. An engagement opens its own beat, which takes the Destroyed, Retreated and Surrendered
+ /// lines after it, up to the next engagement (anyone's: a player's strike's retreats are never an enemy beat's).</summary>
+ public static IReadOnlyList<UnitBeat> From(IReadOnlyList<Cause> why, BeatSource source)
+ {
+ if (why == null) throw new ArgumentNullException(nameof(why));
+ if (source == null) throw new ArgumentNullException(nameof(source));
+ var beats = new List<UnitBeat>();
+ var moving = new Dictionary<string, UnitBeat>(StringComparer.Ordinal); // per side, the beat its next move may join
+ UnitBeat? attack = null; // the engagement whose results follow
+ foreach (var c in why)
+ {
+ if (source.IsMove(c))
+ {
+ attack = null;
+ if (c.Units.Count == 0 || c.Args.Count == 0 || !TryHex(c.Args[0], out int q, out int r)) continue;
+ var step = new UnitStep(c.Units[0].Id, c.Units[0].Q, c.Units[0].R, q, r);
+ var side = c.Units[0].Side ?? "";
+ if (!moving.TryGetValue(side, out var beat) || beat.moves.Count >= Timing.MaxUnitsPerBeat
+ || MapActions.Distance(beat.moves[0].ToQ, beat.moves[0].ToR, q, r) > Timing.BatchRadiusHexes)
+ {
+ moving[side] = beat = new UnitBeat { Kind = BeatKind.Move, Side = side };
+ beats.Add(beat);
+ }
+ beat.moves.Add(step);
+ beat.causes.Add(c);
+ }
+ else if (c.Key == WhyKeys.Engagement)
+ {
+ moving.Clear(); attack = null;
+ if (!source.IsAttack(c) || c.Args.Count == 0 || !TryHex(c.Args[0], out int q, out int r)) continue;
+ attack = new UnitBeat { Kind = BeatKind.Attack, FocusQ = q, FocusR = r, Engagements = 1,
+ Side = c.Units.Count > 0 ? c.Units[0].Side ?? "" : "" };
+ attack.attackers.AddRange(UnitAttackPresenter.Attackers(c));
+ attack.causes.Add(c);
+ beats.Add(attack);
+ }
+ else if (attack != null && Result(c.Key))
+ {
+ attack.causes.Add(c);
+ if (c.Key == WhyKeys.Retreated && c.Units.Count > 0 && c.Args.Count > 0 && TryHex(c.Args[0], out int q, out int r))
+ attack.retreats.Add(new UnitStep(c.Units[0].Id, c.Units[0].Q, c.Units[0].R, q, r));
+ }
+ }
+ foreach (var b in beats) if (b.Kind == BeatKind.Move) Focus(b);
+ var sides = new List<string>();
+ foreach (var b in beats) if (!sides.Contains(b.Side)) sides.Add(b.Side);
+ var ordered = beats.OrderBy(b => sides.IndexOf(b.Side)).ToList(); // OrderBy is stable: the sim's order within a side
+ ordered = Fold(ordered);
+ Pace(ordered);
+ return ordered;
+ }
+
+ /// <summary>The replay's length: every beat's pan, slide and dwell.</summary>
+ public static float Total(IReadOnlyList<UnitBeat> beats)
+ {
+ float total = 0f;
+ foreach (var b in beats) total += b.Length;
+ return total;
+ }
+
+ /// <summary>An engagement's own results (Combat.Fight writes them right after its line).</summary>
+ static bool Result(string key) => key == WhyKeys.Destroyed || key == WhyKeys.Retreated
+ || key == WhyKeys.SurrenderedPrisoners || key == WhyKeys.SurrenderedHeld;
+
+ static bool TryHex(string hex, out int q, out int r)
+ {
+ q = r = 0;
+ var parts = hex.Split(',');
+ return parts.Length == 2
+ && int.TryParse(parts[0], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out q)
+ && int.TryParse(parts[1], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out r);
+ }
+
+ /// <summary>A move beat looks at the middle of its destinations, rounded to a hex in cube coordinates.</summary>
+ static void Focus(UnitBeat b)
+ {
+ double q = b.moves.Average(m => m.ToQ), r = b.moves.Average(m => m.ToR), s = -q - r;
+ double rq = Math.Round(q, MidpointRounding.AwayFromZero), rr = Math.Round(r, MidpointRounding.AwayFromZero);
+ double rs = Math.Round(s, MidpointRounding.AwayFromZero);
+ double dq = Math.Abs(rq - q), dr = Math.Abs(rr - r), ds = Math.Abs(rs - s);
+ if (dq > dr && dq > ds) rq = -rr - rs;
+ else if (dr > ds) rr = -rq - rs;
+ b.FocusQ = (int)rq; b.FocusR = (int)rr;
+ }
+
+ /// <summary>Past MaxBeats, the first beats stay and every later one is played at once, where the camera stays (Q4):
+ /// one folded beat per side among them, so a fold never mixes sides. As many beats stay as leave room for those folded
+ /// ones within MaxBeats (MaxBeats - 1 on a one-side turn), so the cap below always holds. A folded beat's focus is the
+ /// beat before it, so a later beat's pan is measured from where the camera is.</summary>
+ static List<UnitBeat> Fold(List<UnitBeat> beats)
+ {
+ if (beats.Count <= Timing.MaxBeats) return beats;
+ int keep = Timing.MaxBeats - 1;
+ while (keep > 1 && keep + SidesFrom(beats, keep) > Timing.MaxBeats) keep--;
+ var kept = beats.Take(keep).ToList();
+ UnitBeat? folded = null;
+ foreach (var b in beats.Skip(keep))
+ {
+ if (folded == null || folded.Side != b.Side)
+ {
+ var before = kept[kept.Count - 1];
+ folded = new UnitBeat { Folded = true, Side = b.Side, FocusQ = before.FocusQ, FocusR = before.FocusR };
+ kept.Add(folded);
+ }
+ folded.moves.AddRange(b.moves); folded.retreats.AddRange(b.retreats);
+ folded.attackers.AddRange(b.attackers); folded.causes.AddRange(b.causes);
+ folded.Engagements += b.Engagements;
+ }
+ foreach (var f in kept) if (f.Folded) f.Kind = f.moves.Count > 0 ? BeatKind.Move : BeatKind.Attack;
+ return kept;
+ }
+
+ /// <summary>How many sides the beats from <paramref name="from"/> on belong to (they come side by side).</summary>
+ static int SidesFrom(List<UnitBeat> beats, int from)
+ {
+ int n = 0;
+ for (int i = from; i < beats.Count; i++) if (i == from || beats[i].Side != beats[i - 1].Side) n++;
+ return n;
+ }
+
+ /// <summary>The pans and dwells at full pace (Q3), then, if the whole passes Cap, each pan and dwell shrunk by the
+ /// same share of the way to its minimum, so the replay is exactly Cap long; the slides never shrink. With at most
+ /// MaxBeats beats the minimums sum to well under Cap (8 x 1.05 s at the most), so the cap is always met.</summary>
+ static void Pace(List<UnitBeat> beats)
+ {
+ float slides = 0f, full = 0f, least = 0f;
+ for (int i = 0; i < beats.Count; i++)
+ {
+ var b = beats[i];
+ b.Pan = b.Folded ? 0f
+ : i == 0 ? Timing.PanMax // where the camera starts is not known here: the longest
+ : PanSeconds(MapActions.Distance(beats[i - 1].FocusQ, beats[i - 1].FocusR, b.FocusQ, b.FocusR));
+ b.Dwell = b.Engagements > 0 ? (b.Folded ? Timing.AttackMin : Timing.AttackMax) : Timing.MoveDwell;
+ if (b.Slides) slides += UnitTokenMotion.Duration;
+ full += b.Pan + b.Dwell;
+ least += MinPan(b) + MinDwell(b);
+ }
+ if (slides + full <= Timing.Cap || full <= least) return;
+ float share = Math.Max(0f, (Timing.Cap - slides - least) / (full - least));
+ foreach (var b in beats)
+ {
+ b.Pan = MinPan(b) + share * (b.Pan - MinPan(b));
+ b.Dwell = MinDwell(b) + share * (b.Dwell - MinDwell(b));
+ }
+ }
+
+ static float MinPan(UnitBeat b) => b.Folded ? 0f : Timing.MinPan;
+ static float MinDwell(UnitBeat b) => b.Engagements > 0 ? Timing.AttackMin : Timing.MinDwell;
+ }
+}
diff --git a/unity/Assets/Scripts/UI/UnitBeats.cs.meta b/unity/Assets/Scripts/UI/UnitBeats.cs.meta
new file mode 100644
index 000000000..c3c985ee8
--- /dev/null
+++ b/unity/Assets/Scripts/UI/UnitBeats.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 06cf09fe9d224e188f4385d95d0a74b8
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/CameraGlideTests.cs b/unity/Assets/Tests/EditMode/CameraGlideTests.cs
new file mode 100644
index 000000000..f9225c78b
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CameraGlideTests.cs
@@ -0,0 +1,141 @@
+#nullable enable
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using Statecraft.Game.UI;
+using UnityEngine;
+
+/// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 4): the camera's eased glide to a
+/// beat. It moves the look-at point only (owner, Q5: "Keep the player's zoom"; the GDD camera never orbits), the map's
+/// edge holds it as it holds the player's pan (CameraController.Step), and a player's pan or zoom takes the camera back.</summary>
+public class CameraGlideTests
+{
+ GameObject go = null!;
+ CameraRig rig = null!;
+ static readonly Rect Bounds = new Rect(0, 0, 1000000, 1000000);
+ static readonly Vector3 Centre = new Vector3(500000, 0, 500000);
+
+ [SetUp]
+ public void Open()
+ {
+ go = new GameObject("GlideCamera", typeof(Camera), typeof(CameraRig));
+ rig = go.GetComponent<CameraRig>();
+ rig.LookAt = Centre; rig.Distance = CameraRig.StartDistance; rig.Yaw = 0f;
+ CameraController.Step(rig, default, 0f, Bounds);
+ }
+
+ [TearDown]
+ public void Close() { if (go != null) Object.DestroyImmediate(go); }
+
+ [Test]
+ public void TheGlideStartsAndEndsWhereAsked()
+ {
+ var from = new Vector3(100, 7, 200); var to = new Vector3(5100, 0, -800);
+ Assert.AreEqual(from, CameraGlide.At(from, to, 0f));
+ Assert.AreEqual(new Vector3(to.x, from.y, to.z), CameraGlide.At(from, to, 1f), "the height is Step's to set");
+ Assert.AreEqual(from, CameraGlide.At(from, to, -1f), "t is clamped");
+ Assert.AreEqual(new Vector3(to.x, from.y, to.z), CameraGlide.At(from, to, 2f));
+ }
+
+ [Test]
+ public void ThePointMidwayIsHalfway()
+ {
+ var from = Vector3.zero; var to = new Vector3(1000, 0, -400);
+ var mid = CameraGlide.At(from, to, 0.5f);
+ Assert.AreEqual(500f, mid.x, 1e-3f); Assert.AreEqual(-200f, mid.z, 1e-3f);
+ var early = CameraGlide.At(from, to, 0.1f);
+ Assert.Less(early.x, 100f, "it eases in");
+ Assert.Greater(CameraGlide.At(from, to, 0.9f).x, 900f, "and out");
+ }
+
+ [Test]
+ public void TheGlideTakesLongerForAFartherPoint()
+ {
+ const float hex = 4400f;
+ Assert.AreEqual(UnitBeats.Timing.PanMin, CameraGlide.Seconds(0f, hex), 1e-4f);
+ Assert.AreEqual(UnitBeats.Timing.PanMax, CameraGlide.Seconds(1000f * hex, hex), 1e-4f);
+ Assert.AreEqual(UnitBeats.Timing.PanPerHex * 10f, CameraGlide.Seconds(10f * hex, hex), 1e-4f);
+ Assert.AreEqual(UnitBeats.PanSeconds(10), CameraGlide.Seconds(10f * hex, hex), 1e-4f, "one clamp for the planner and the glide");
+ }
+
+ [Test]
+ public void APointInTheMiddleOfTheViewNeedsNoPan()
+ {
+ Assert.IsTrue(CameraGlide.InView(rig, rig.LookAt));
+ Assert.IsTrue(CameraGlide.InView(rig, rig.LookAt + new Vector3(2000, 0, 0)));
+ }
+
+ [Test]
+ public void APointOffScreenNeedsOne()
+ {
+ Assert.IsFalse(CameraGlide.InView(rig, rig.LookAt + new Vector3(200000, 0, 0)));
+ Assert.IsFalse(CameraGlide.InView(rig, rig.LookAt + new Vector3(0, 0, -200000)));
+ Assert.IsFalse(CameraGlide.InView(rig, rig.LookAt + new Vector3(0, 0, 200000)));
+ // The camera looks north, so the left edge of the view lies west. A point just inside the edge is inside the view
+ // but not inside its margin: the glide brings it in, so a unit never moves at the screen's very edge.
+ var cam = go.GetComponent<Camera>();
+ var nearEdge = PointAt(cam, 0.05f, 0.5f);
+ Assert.Less(cam.WorldToViewportPoint(nearEdge).x, 0.15f, "fixture: near the left edge");
+ Assert.IsFalse(CameraGlide.InView(rig, nearEdge));
+ Assert.IsTrue(CameraGlide.InView(rig, nearEdge, margin: 0f));
+ }
+
+ [Test]
+ public void TheBarAtTheTopIsNotTheView()
+ {
+ rig.TopInset = 0.3f;
+ CameraController.Step(rig, default, 0f, Bounds);
+ var cam = go.GetComponent<Camera>();
+ // Viewport y above 1 - TopInset lies under the UI's band.
+ var under = PointAt(cam, 0.5f, 0.85f);
+ Assert.IsFalse(CameraGlide.InView(rig, under, margin: 0f), "a point under the bar is not seen");
+ Assert.IsTrue(CameraGlide.InView(rig, PointAt(cam, 0.5f, 0.4f), margin: 0f));
+ }
+
+ /// <summary>The ground point (y = 0) the camera shows at viewport (x, y).</summary>
+ static Vector3 PointAt(Camera cam, float x, float y)
+ {
+ var ray = cam.ViewportPointToRay(new Vector3(x, y, 0f));
+ return ray.origin + ray.direction * (-ray.origin.y / ray.direction.y);
+ }
+
+ [Test]
+ public void APlayerMoveHandsTheCameraBack()
+ {
+ var set = rig.LookAt; float distance = rig.Distance;
+ CameraController.Step(rig, default, 0.1f, Bounds);
+ Assert.IsFalse(CameraGlide.TookOver(rig, set, distance), "a frame with no input is not the player's");
+ CameraController.Step(rig, new CameraInput { Pan = new Vector2(1f, 0f) }, 0.1f, Bounds);
+ Assert.IsTrue(CameraGlide.TookOver(rig, set, distance), "a pan");
+
+ rig.LookAt = set; CameraController.Step(rig, default, 0f, Bounds);
+ CameraController.Step(rig, new CameraInput { Zoom = 1f }, 0.1f, Bounds);
+ Assert.IsTrue(CameraGlide.TookOver(rig, set, distance), "a zoom");
+ }
+
+ [Test]
+ public void AGlideTargetPastTheMapEdgeStopsWhereSettleHoldsIt()
+ {
+ var from = rig.LookAt; var past = new Vector3(-50000, 0, Centre.z);
+ rig.LookAt = CameraGlide.At(from, past, 1f);
+ CameraController.Step(rig, default, 0f, Bounds); // as CameraController.Settle
+ var view = CameraController.ViewFootprint(rig);
+ Assert.Greater(rig.LookAt.x, past.x, "it stops short of a point past the edge");
+ Assert.AreEqual(Bounds.xMin, rig.LookAt.x + view.xMin, 1f, "with the view's edge on the map's");
+ Assert.IsFalse(CameraGlide.TookOver(rig, rig.LookAt, rig.Distance),
+ "measured from the held point, the edge's hold is not taken for the player's move");
+ }
+
+ [Test]
+ public void TheGlideNeverTurnsOrZooms()
+ {
+ rig.Yaw = 0f; float distance = rig.Distance;
+ var from = rig.LookAt; var to = from + new Vector3(30000, 0, -20000);
+ for (int i = 0; i <= 10; i++)
+ {
+ rig.LookAt = CameraGlide.At(from, to, i / 10f);
+ CameraController.Step(rig, default, 0.05f, Bounds, fixedNorth: true);
+ Assert.AreEqual(0f, rig.Yaw); Assert.AreEqual(distance, rig.Distance);
+ }
+ Assert.AreEqual(to.x, rig.LookAt.x, 1e-2f); Assert.AreEqual(to.z, rig.LookAt.z, 1e-2f);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/CameraGlideTests.cs.meta b/unity/Assets/Tests/EditMode/CameraGlideTests.cs.meta
new file mode 100644
index 000000000..b68cc4f83
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CameraGlideTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1a945a6daa5e4f85ab46eefb68acf44a
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/DecisionCardTests.cs b/unity/Assets/Tests/EditMode/DecisionCardTests.cs
index 9ee48b663..c88ff8cb4 100644
--- a/unity/Assets/Tests/EditMode/DecisionCardTests.cs
+++ b/unity/Assets/Tests/EditMode/DecisionCardTests.cs
@@ -273,6 +273,33 @@ public class DecisionCardTests
Assert.AreSame(r.CardElement, r.Focused, "and puts the focus on the card");
}
+ /// <summary>#2202 (owner, 8 November 2026: "Hide it, bring back (Recommended)"): a card held out of view while the enemy's
+ /// moves play comes back with the keyboard focus, as from under a cover, also when a screen opened and closed meanwhile
+ /// (that close must not mark the hidden card as focused; #2967 review 9 November, N1).</summary>
+ [UnityTest]
+ public IEnumerator ACardHeldForTheEnemyMovesComesBackWithTheFocus()
+ {
+ using var r = new Rig(1920, 1080, "law_of_return");
+ yield return Frames(4);
+ Assert.AreSame(r.CardElement, r.Focused, "precondition: the open card has the focus");
+ var endTurn = r.Root.Q<Button>("end-turn");
+ endTurn.Focus(); // End turn pressed from the keyboard
+ r.Card.HeldForPlayback = true;
+ yield return Frames(3);
+ Assert.IsFalse(r.Shows("event-card"), "precondition: held out of view");
+ r.Nav.Open("cabinet");
+ yield return Frames(3);
+ r.Nav.Open(null);
+ yield return Frames(3);
+ Assert.IsFalse(r.Shows("event-card"), "precondition: still held after the screen closed");
+ endTurn.Focus();
+ Assert.AreSame(endTurn, r.Focused, "precondition");
+ r.Card.HeldForPlayback = false;
+ yield return Frames(3);
+ Assert.IsTrue(r.Shows("event-card"), "the moves ended: the card is back");
+ Assert.AreSame(r.CardElement, r.Focused, "with the keyboard focus");
+ }
+
[UnityTest]
public IEnumerator AnOpenEventDoesNotTakeTheFocusBack()
{
diff --git a/unity/Assets/Tests/EditMode/EnemyPlaybackUiTests.cs b/unity/Assets/Tests/EditMode/EnemyPlaybackUiTests.cs
new file mode 100644
index 000000000..6e9e0d926
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/EnemyPlaybackUiTests.cs
@@ -0,0 +1,496 @@
+#nullable enable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Map.Units;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+using Object = UnityEngine.Object;
+using Fakes = EnemyTurnPlaybackTests;
+
+/// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Tasks 6 and 7): the footer bar while the
+/// enemy's moves play, the turn report and the event card waiting for it, and the Settings switch. The owner's answers on the
+/// footer (8 November 2026): "Flag + name (Recommended)", so the bar shows the side's flag, the very design its tokens fly,
+/// beside its name; and "One side at a time (Recommended)", so the picture changes once a side.</summary>
+public class EnemyPlaybackUiTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
+ static IReadOnlyList<UnitEntry> Rows() => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
+
+ static readonly string[] Sourced = { "jordan", "egypt", "iraq", "syria", "lebanon" };
+
+ /// <summary>Game.uxml with the card, the report, the playback (fakes for the map and the camera) and its bar, built in
+ /// GameRoot's order, and the hold wired as GameRoot wires it.</summary>
+ sealed class Kit : IDisposable
+ {
+ public readonly UiTestKit Ui = new UiTestKit();
+ public readonly SimBridge Bridge;
+ public readonly EventCardPresenter Card;
+ public readonly TurnReportPresenter Report;
+ public readonly EnemyTurnPlayback Playback;
+ public readonly EnemyPlaybackBar Bar;
+ public readonly ScreenNav Nav;
+ public readonly Fakes.FakeMap Map = new Fakes.FakeMap();
+ public bool On = true;
+ readonly List<IDisposable> owned = new List<IDisposable>();
+
+ public Kit(UiText text, Func<GameSession, IReadOnlyList<Command>, StepResult>? step = null, GameSession? session = null)
+ {
+ Bridge = new SimBridge(session ?? GameSession.New(C, GoldenRun.Seed, Mode.Historical), text, step);
+ var nav = Nav = new ScreenNav(Ui.Root);
+ owned.Add(new HudPresenter(Ui.Root, Bridge, text));
+ owned.Add(nav);
+ owned.Add(Card = new EventCardPresenter(Ui.Root, Bridge, text, null));
+ owned.Add(Report = new TurnReportPresenter(Ui.Root, Bridge, text, nav));
+ owned.Add(Playback = new EnemyTurnPlayback(Bridge, Map, new Fakes.FakeCamera(), () => On, () => false));
+ Playback.Holding += held => { Card.HeldForPlayback = held; Report.Held = held; }; // as GameRoot
+ owned.Add(Bar = new EnemyPlaybackBar(Ui.Root, text, Playback, Bridge));
+ }
+
+ public void RunOut()
+ {
+ for (int n = 0; (Playback.Active || Playback.Pending) && n < 4000; n++) Playback.Tick(0.05f);
+ Assert.IsFalse(Playback.Active || Playback.Pending, "the playback ends");
+ }
+
+ public void Dispose()
+ {
+ for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
+ Ui.Dispose();
+ }
+ }
+
+ static readonly Cause[] ThreeSides =
+ {
+ Fakes.Move(901, 0, 0, 1, 0, side: "jordan"), Fakes.Move(902, 30, 0, 31, 0, side: "jordan"),
+ Fakes.Move(903, 60, 0, 61, 0, side: "egypt"), Fakes.Move(904, 90, 0, 91, 0, side: "ala"),
+ };
+
+ // ---- The flag: one definition, the tokens' ----
+
+ [Test]
+ public void TheUiFlagIsTheTokensFlag([ValueSource(nameof(Sourced))] string side)
+ {
+ Assert.IsTrue(UnitFlags.Has(side), "fixture: a sourced 1948 flag");
+ var shape = SideFlag.For(side)!;
+ Assert.IsNotNull(shape);
+ var cloth = UnitFlags.BuildCloth(side)!;
+ try
+ {
+ var colours = UnitFlags.Colours(side);
+ var points = new List<Vector2>(); var tints = new List<Color>();
+ for (int k = 0; k < cloth.subMeshCount; k++)
+ {
+ var tris = cloth.GetTriangles(k);
+ foreach (var i in tris) points.Add(new Vector2(cloth.vertices[i].x, cloth.vertices[i].y));
+ for (int t = 0; t < tris.Length / 3; t++) tints.Add(colours[k]);
+ }
+ CollectionAssert.AreEqual(points, shape.Points, "every triangle of the token's cloth, face on");
+ CollectionAssert.AreEqual(tints, shape.Colours, "in the token's own colours");
+ Assert.AreEqual(colours.Count, cloth.subMeshCount, "one colour a part, as the token's materials");
+ }
+ finally { Object.DestroyImmediate(cloth); }
+ Assert.Greater(shape.Bounds.width, shape.Bounds.height, "a flag, wider than tall");
+ }
+
+ [Test]
+ public void TheArabLiberationArmyFliesThePennant()
+ {
+ Assert.IsFalse(UnitFlags.Has("ala"), "no sourced flag: nothing is invented");
+ Assert.IsTrue(UnitFlags.HasPennant("ala"));
+ var shape = SideFlag.For("ala")!;
+ var outline = UnitFlags.PennantCloth();
+ CollectionAssert.AreEqual(new[] { outline[0], outline[1], outline[2] }, shape.Points, "the map's pennant, as UnitFlags.BuildPennant");
+ CollectionAssert.AreEqual(new[] { UnitFlags.PennantColour }, shape.Colours);
+ // The token's mesh is its pole and finial, then the cloth: the last two triangles, its front and its back (a two-sided
+ // plate), each on the same three points, in the cloth's plane at z = 0.
+ var mesh = UnitFlags.BuildPennant();
+ try
+ {
+ var tris = mesh.GetTriangles(0); var verts = mesh.vertices;
+ Assert.GreaterOrEqual(tris.Length, 6, "fixture: a pole and a cloth");
+ for (int side = 0; side < 2; side++)
+ {
+ var corners = Enumerable.Range(0, 3).Select(i => verts[tris[tris.Length - 6 + side * 3 + i]]).ToList();
+ foreach (var p in outline.Take(3))
+ Assert.IsTrue(corners.Any(v => Vector3.Distance(v, new Vector3(p.x, p.y, 0f)) < 1e-5f),
+ $"the token's pennant is one triangle too: side {side} has the cloth's point {p}");
+ }
+ }
+ finally { Object.DestroyImmediate(mesh); }
+ Assert.IsNull(SideFlag.For("nobody"), "a side the map gives nothing gets nothing");
+ Assert.IsNull(SideFlag.For(null));
+ }
+
+ // ---- The bar ----
+
+ [Test]
+ public void TheBarsFlagAndNameChangeExactlyAtSideBoundaries()
+ {
+ using var k = new Kit(En, Fakes.Step(ThreeSides));
+ Assert.IsFalse(k.Bar.IsOpen, "closed before End turn");
+ var seen = new List<(string? side, int changes, string name)>();
+ k.Playback.BeatChanged += () => seen.Add((k.Bar.Side, k.Bar.Flag.Changes, k.Ui.Q<Label>("enemy-playback-side").text));
+ k.Bridge.EndTurn();
+ Assert.IsTrue(k.Bar.IsOpen);
+ k.RunOut();
+ CollectionAssert.AreEqual(new[] { "jordan", "jordan", "egypt", "ala" }, seen.Select(s => s.side).ToArray());
+ CollectionAssert.AreEqual(new[] { 1, 1, 2, 3 }, seen.Select(s => s.changes).ToArray(), "the picture changes once a side");
+ CollectionAssert.AreEqual(new[] { "Jordan's turn", "Jordan's turn", "Egypt's turn", "The Arab Liberation Army's turn" },
+ seen.Select(s => s.name).ToArray());
+ Assert.IsFalse(k.Bar.IsOpen, "closed at the end");
+ Assert.AreEqual(DisplayStyle.None, k.Ui.Q<VisualElement>(EnemyPlaybackBar.ElementName).style.display.value);
+ }
+
+ [Test]
+ public void TheBarCountsTheMoves()
+ {
+ using var k = new Kit(En, Fakes.Step(ThreeSides));
+ var steps = new List<string>();
+ k.Playback.BeatChanged += () => steps.Add(k.Ui.Q<Label>("enemy-playback-step").text);
+ k.Bridge.EndTurn();
+ k.RunOut();
+ CollectionAssert.AreEqual(new[] { "Step 1 of 4", "Step 2 of 4", "Step 3 of 4", "Step 4 of 4" }, steps);
+ }
+
+ [Test]
+ public void TheCaptionNamesTheBeatsUnit([Values(false, true)] bool hebrew)
+ {
+ var text = hebrew ? He : En;
+ var rows = Rows();
+ using var k = new Kit(text);
+ k.Bar.Units = rows;
+ var lines = new List<string>();
+ k.Playback.BeatChanged += () =>
+ {
+ if (k.Playback.Current!.Folded) return;
+ lines.AddRange(k.Ui.Q<VisualElement>("enemy-playback-actions").Query<Label>(className: "enemy-playback-action").ToList().Select(l => l.text));
+ };
+ var turn = k.Bridge.EndTurn();
+ k.RunOut();
+ // The report's own lines for the same turn (TurnReportTests.TheEnemysOrdersAreReportedInBothLanguages).
+ var expected = turn.Why.Where(w => w.EnemyOrder == Movement.Kind).Select(w =>
+ {
+ var row = rows.First(u => u.Id == C.StartingForces[int.Parse(w.Target, System.Globalization.CultureInfo.InvariantCulture)].Row);
+ return text.Format("report.enemy_move", hebrew ? row.NameHe : row.Name);
+ }).ToList();
+ Assert.IsNotEmpty(lines);
+ CollectionAssert.IsSubsetOf(lines, expected, "each line is the report's line for that unit");
+ CollectionAssert.Contains(lines, hebrew ? "הלגיון הערבי עבר לעמדה חדשה" : "Arab Legion moved to a new position", "the Legion's march on Latrun");
+ if (hebrew) Assert.IsTrue(lines.All(UiDirection.RightToLeft), "each line reads right to left");
+ }
+
+ [Test]
+ public void AnAttackBeatNamesItsAttackers()
+ {
+ var fight = Fakes.Engagement(40, 0, new[] { 921, 922 }, new[] { 929 });
+ using var k = new Kit(En, Fakes.Step(fight));
+ k.Bridge.EndTurn();
+ k.Playback.Tick(0.05f);
+ var lines = k.Ui.Q<VisualElement>("enemy-playback-actions").Query<Label>(className: "enemy-playback-action").ToList().Select(l => l.text).ToArray();
+ CollectionAssert.AreEqual(new[] { En.Format("report.enemy_attack", "infantry"), En.Format("report.enemy_attack", "infantry") }, lines,
+ "one line an attacker (a type with no name: the type, as UnitNames.Of)");
+ }
+
+ [Test]
+ public void TheSkipButtonIsFocusableAndSkips()
+ {
+ using var k = new Kit(En, Fakes.Step(ThreeSides));
+ var skip = k.Ui.Q<Button>("enemy-playback-skip");
+ Assert.AreEqual(En["playback.skip"], skip.text);
+ Assert.AreEqual(En["playback.skip_tip"], skip.tooltip);
+ Assert.IsTrue(skip.focusable);
+ Assert.AreEqual(0, skip.tabIndex, "in the tab order");
+ k.Bridge.EndTurn();
+ Assert.IsTrue(k.Playback.Active);
+ Assert.IsNull(k.Ui.Root.panel.focusController.focusedElement, "it opens without taking the focus (never modal)");
+ skip.Focus();
+ UiTestKit.Press(skip);
+ Assert.IsFalse(k.Playback.Active);
+ Assert.IsFalse(k.Bar.IsOpen);
+ Assert.IsEmpty(k.Map.Held, "every token on its place");
+ Assert.IsFalse(k.Playback.Skip(), "Esc after it skips nothing: the Escape chain goes on to the next screen");
+ }
+
+ [Test]
+ public void EveryPlaybackKeyIsInBothLanguages()
+ {
+ var en = En; var he = He;
+ var keys = en.Keys.Where(x => x.StartsWith("playback.", StringComparison.Ordinal)).Append("settings.enemymoves").ToList();
+ CollectionAssert.IsSupersetOf(keys, new[] { "playback.title", "playback.step", "playback.skip", "playback.skip_tip", "playback.folded" });
+ foreach (var side in Sourced.Append("ala")) CollectionAssert.Contains(keys, "playback.turn_" + side, "a name for each side with a flag");
+ CollectionAssert.AreEquivalent(keys.Where(x => x != "settings.enemymoves"),
+ he.Keys.Where(x => x.StartsWith("playback.", StringComparison.Ordinal)), "the same keys in Hebrew");
+ foreach (var key in keys)
+ {
+ Assert.IsTrue(he.Has(key), key);
+ Assert.AreEqual(Placeholders(en[key]), Placeholders(he[key]), key + ": the same placeholders (UI-15)");
+ Assert.IsTrue(UiDirection.HasRightToLeft(he[key]), $"{key} is Hebrew: {he[key]}");
+ }
+ }
+
+ static string[] Placeholders(string s) => System.Text.RegularExpressions.Regex.Matches(s, @"\{\d+\}").Select(m => m.Value).OrderBy(x => x, StringComparer.Ordinal).ToArray();
+
+ // ---- The report and the card wait (Q1 a) ----
+
+ [Test]
+ public void TheReportWaitsForThePlaybackAndOpensWhenItEnds()
+ {
+ using var k = new Kit(En);
+ k.Bridge.EndTurn();
+ Assert.IsTrue(k.Playback.Active, "fixture: the opening turn has enemy moves");
+ Assert.IsFalse(k.Report.IsOpen, "the report waits");
+ k.Playback.Tick(0.5f);
+ Assert.IsFalse(k.Report.IsOpen);
+ k.RunOut();
+ Assert.IsTrue(k.Report.IsOpen, "it opens when the playback ends");
+ Assert.IsFalse(k.Report.Held);
+ }
+
+ [Test]
+ public void SkipOpensTheReportAtOnce()
+ {
+ using var k = new Kit(En);
+ k.Bridge.EndTurn();
+ Assert.IsFalse(k.Report.IsOpen);
+ Assert.IsTrue(k.Playback.Skip());
+ Assert.IsTrue(k.Report.IsOpen);
+ }
+
+ /// <summary>End turn pressed again while the moves play (End turn is never blocked): the old playback ends, the new
+ /// turn's plays, and the report goes on waiting. It opens once, when the new playback ends, for the new turn: the turn
+ /// whose moves were just shown. It never opens in between, over the new playback, with the new turn's lines (#2967
+ /// review, M1: the old playback's release opened it at once).</summary>
+ [Test]
+ public void EndTurnMidPlaybackKeepsTheReportWaitingForTheNewTurnsMoves()
+ {
+ var extra = Fakes.Move(911, 0, 0, 1, 0, side: "egypt"); // every turn has a move to play, whatever the sim did
+ using var k = new Kit(En, (s, o) => { var r = s.EndTurn(o); return new StepResult(r.State, r.Why.Append(extra).ToArray(), r.Rejected); });
+ var shown = new List<StepResult?>();
+ k.Report.Showing += r => shown.Add(r);
+ var held = new List<bool>();
+ k.Playback.Holding += h => held.Add(h);
+ k.Bridge.EndTurn();
+ var first = k.Bridge.Session.Last;
+ k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active, "fixture: the first turn's moves play");
+ k.Bridge.EndTurn();
+ var latest = k.Bridge.Session.Last;
+ Assert.AreNotSame(first, latest, "fixture: a second turn ran");
+ Assert.IsTrue(k.Playback.Active || k.Playback.Pending, "the new turn's moves play");
+ Assert.IsEmpty(shown, "the report never opened over the new playback");
+ Assert.IsFalse(k.Report.IsOpen, "it still waits");
+ Assert.IsTrue(k.Report.Held);
+ Assert.IsFalse(held.Contains(false), "the hold carried over from one playback to the next");
+ k.RunOut();
+ Assert.IsTrue(k.Report.IsOpen, "it opens when the new playback ends");
+ Assert.AreEqual(1, shown.Count, "once");
+ Assert.AreSame(latest, shown[0], "for the turn whose moves were just shown");
+ Assert.AreEqual(false, held.Last(), "and the hold is let go once, at the end");
+ Assert.AreEqual(1, held.Count(h => !h));
+ }
+
+ /// <summary>End turn pressed with a screen open (the top bar stays enabled under a side screen): End turn closes the
+ /// screen, as it did before the playback, so the moves play on the open map and the report opens when they end,
+ /// without waiting for the player to close a screen they never asked to keep (#2967 review 9 November, S1).</summary>
+ [Test]
+ public void EndTurnWithAScreenOpenClosesItAndTheReportOpensAfterTheMoves()
+ {
+ using var k = new Kit(En);
+ k.Nav.Open("cabinet");
+ Assert.AreEqual("cabinet", k.Nav.Current, "fixture: a screen is open at End turn");
+ k.Bridge.EndTurn();
+ Assert.IsTrue(k.Playback.Active || k.Playback.Pending, "fixture: the opening turn has enemy moves");
+ Assert.AreEqual(null, k.Nav.Current, "End turn closes the open screen");
+ Assert.IsFalse(k.Report.IsOpen, "the report waits for the moves");
+ k.RunOut();
+ Assert.IsTrue(k.Report.IsOpen, "the moves ended: the report opens");
+ Assert.IsFalse(k.Report.Waiting);
+ }
+
+ /// <summary>The moves are not modal: the player may open a screen while they play (Settings, to turn them off; the
+ /// Cabinet). When they end, the report does not close that screen under the player's hand; it opens once the player
+ /// closes it, as long as nothing else holds it (#2967 review, S3).</summary>
+ [Test]
+ public void AScreenOpenedDuringThePlaybackStaysAndTheReportWaitsForItsClose([Values("settings", "cabinet")] string screen,
+ [Values(false, true)] bool skipped)
+ {
+ using var k = new Kit(En);
+ k.Bridge.EndTurn();
+ k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active, "fixture: the opening turn has enemy moves");
+ k.Nav.Open(screen);
+ if (skipped) Assert.IsTrue(k.Playback.Skip()); // the Settings switch turned off, or Skip
+ else k.RunOut();
+ Assert.IsFalse(k.Playback.Active || k.Playback.Pending);
+ Assert.AreEqual(screen, k.Nav.Current, "the screen stays open");
+ Assert.IsFalse(k.Report.IsOpen, "the report waits for it");
+ Assert.IsTrue(k.Report.Waiting);
+ k.Nav.Open(screen == "settings" ? "cabinet" : "settings");
+ Assert.IsFalse(k.Report.IsOpen, "another screen opened from it: still waiting");
+ k.Nav.Close();
+ Assert.IsTrue(k.Report.IsOpen, "the screens closed: the report opens");
+ Assert.IsFalse(k.Report.Waiting);
+ Assert.AreEqual(null, k.Nav.Current);
+ }
+
+ [Test]
+ public void ANewGameDropsAReportWaitingForAScreen()
+ {
+ using var k = new Kit(En);
+ k.Bridge.EndTurn();
+ k.Nav.Open("settings");
+ k.RunOut();
+ Assert.IsTrue(k.Report.Waiting, "fixture: the report waits for Settings");
+ k.Bridge.Replace(GameSession.New(C, GoldenRun.Seed, Mode.Historical));
+ Assert.IsFalse(k.Report.Waiting, "another game: its report is not this one");
+ k.Nav.Close();
+ Assert.IsFalse(k.Report.IsOpen);
+ }
+
+ [Test]
+ public void WithNoEnemyMovesTheReportOpensAtOnce()
+ {
+ using var k = new Kit(En, (s, o) =>
+ {
+ var r = s.EndTurn(o);
+ return new StepResult(r.State, r.Why.Where(w => w.EnemyOrder == "").ToArray(), r.Rejected);
+ });
+ k.Bridge.EndTurn();
+ Assert.IsFalse(k.Playback.Active || k.Playback.Pending);
+ Assert.IsTrue(k.Report.IsOpen);
+ }
+
+ [Test]
+ public void ACardThatOpenedThisTurnWaitsThenOpensWithItsCue()
+ {
+ // The first turn whose End turn brings a card where none was waiting.
+ int turns = 0;
+ var probe = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ for (bool found = false; !found; turns++)
+ {
+ Assert.Less(turns, 80, "fixture: a turn that brings a card");
+ bool none = probe.State.PendingEvents.Count == 0;
+ probe.Step(new Command[0]);
+ found = none && probe.State.PendingEvents.Count > 0;
+ }
+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ for (int i = 0; i < turns - 1; i++) g.Step(new Command[0]);
+ Assert.IsEmpty(g.State.PendingEvents);
+ // The real turn, with enemy moves added so that it plays whatever the sim did that turn.
+ using var k = new Kit(En, (s, o) => { var r = s.EndTurn(o); return new StepResult(r.State, r.Why.Concat(ThreeSides).ToArray(), r.Rejected); }, g);
+ var opened = new List<string>();
+ k.Card.Opened += id => opened.Add(id);
+ var card = k.Ui.Q<VisualElement>("event-card");
+ Assert.IsNull(k.Card.Shown);
+ k.Bridge.EndTurn();
+ Assert.IsNotNull(k.Card.Shown, "fixture: End turn brought a card");
+ Assert.IsTrue(k.Playback.Active);
+ Assert.AreEqual(DisplayStyle.None, card.style.display.value, "the card waits for the playback");
+ Assert.IsEmpty(opened, "and so does its cue");
+ k.RunOut();
+ Assert.AreEqual(DisplayStyle.Flex, card.style.display.value, "then it opens");
+ CollectionAssert.AreEqual(new[] { k.Card.Shown!.Id }, opened, "with its cue, once");
+ }
+
+ // ---- The Settings switch (Q6 a; the switch itself: SettingsScreenTests) ----
+
+ string dir = "";
+ [SetUp] public void SetUp() => dir = Path.Combine(Path.GetTempPath(), "sc-enemymoves-" + Guid.NewGuid().ToString("N"));
+ [TearDown] public void TearDown() { if (Directory.Exists(dir)) Directory.Delete(dir, true); }
+
+ [Test]
+ public void WithItOffEndTurnPlaysNothing()
+ {
+ new SettingsStore(dir).Write(SettingsPresenter.EnemyMovesKey, "off");
+ // The real opening turn: the enemy moves, and the bar moves too, so the report has lines (a Fakes.Step turn changes
+ // no number, and an empty report never opens).
+ using var k = new Kit(En);
+ k.On = SettingsPresenter.EnemyMovesOn(new SettingsStore(dir));
+ k.Bridge.EndTurn();
+ Assert.IsNotEmpty(UnitBeats.From(k.Bridge.Session.Last!.Why, BeatSource.Enemy), "fixture: the turn has enemy moves");
+ k.Playback.Tick(0.05f);
+ Assert.IsFalse(k.Playback.Active || k.Playback.Pending);
+ Assert.IsEmpty(k.Map.Log, "no token held");
+ Assert.IsFalse(k.Bar.IsOpen);
+ Assert.IsTrue(k.Report.IsOpen, "the report opens at End turn, as before");
+ }
+
+ // ---- The layout ----
+
+ /// <summary>At 360 px wide (the narrowest the game supports) and at 1920, in English and in Hebrew, mid playback: the bar
+ /// lies inside the window, below the End turn button; its flag, name and Skip fit inside it; in Hebrew the row is mirrored
+ /// (the flag on the right), and the side's name reads right to left.</summary>
+ [UnityTest]
+ public IEnumerator TheSkipBarFitsAndMirrorsInHebrew([Values(360, 1920)] int w, [Values(false, true)] bool hebrew)
+ {
+ var text = hebrew ? He : En;
+ var rt = new RenderTexture(w, 800, 0);
+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
+ ps.targetTexture = rt;
+ var go = new GameObject("EnemyPlaybackUiTest");
+ go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>();
+ doc.panelSettings = ps;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ var root = doc.rootVisualElement;
+ root.Q("root").RemoveFromClassList("loading");
+ if (hebrew) root.Q("root").AddToClassList(UiLanguage.HebrewClass);
+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text, Fakes.Step(ThreeSides));
+ var hud = new HudPresenter(root, bridge, text);
+ var playback = new EnemyTurnPlayback(bridge, new Fakes.FakeMap(), new Fakes.FakeCamera(), () => true, () => false);
+ var bar = new EnemyPlaybackBar(root, text, playback, bridge);
+ try
+ {
+ bridge.EndTurn();
+ for (int i = 0; i < 30 && !(root.Q("enemy-playback-skip").layout.width > 0); i++) yield return null;
+ for (int i = 0; i < 3; i++) yield return null;
+ Assert.IsTrue(bar.IsOpen);
+ var window = root.worldBound;
+ var panel = root.Q("enemy-playback-panel").worldBound;
+ var flag = root.Q("enemy-playback-flag").worldBound;
+ var side = root.Q<Label>("enemy-playback-side");
+ var skip = root.Q("enemy-playback-skip").worldBound;
+ var endTurn = root.Q("end-turn").worldBound;
+ string at = $"{w} px, {(hebrew ? "he" : "en")}";
+ bool Inside(Rect inner, Rect outer) => inner.xMin >= outer.xMin - 0.5f && inner.xMax <= outer.xMax + 0.5f
+ && inner.yMin >= outer.yMin - 0.5f && inner.yMax <= outer.yMax + 0.5f;
+ Assert.IsTrue(Inside(panel, window), $"{at}: the bar {panel} is inside the window {window}");
+ foreach (var (name, r) in new[] { ("flag", flag), ("name", side.worldBound), ("skip", skip) })
+ {
+ Assert.Greater(r.width, 0f, $"{at}: {name} is drawn");
+ Assert.IsTrue(Inside(r, panel), $"{at}: the {name} {r} is inside the bar {panel}");
+ }
+ Assert.IsFalse(panel.Overlaps(endTurn), $"{at}: the bar {panel} leaves End turn {endTurn} clear");
+ Assert.IsFalse(flag.Overlaps(skip) || flag.Overlaps(side.worldBound) || skip.Overlaps(side.worldBound), $"{at}: nothing overlaps");
+ Assert.GreaterOrEqual(flag.width, 40f, $"{at}: the flag is large");
+ if (hebrew)
+ {
+ Assert.Greater(flag.xMin, side.worldBound.xMax - 0.5f, $"{at}: the flag on the right");
+ Assert.Less(skip.xMax, side.worldBound.xMin + 0.5f, $"{at}: Skip on the left");
+ Assert.IsTrue(UiDirection.RightToLeft(side.text), $"{at}: {side.text}");
+ }
+ else
+ {
+ Assert.Less(flag.xMax, side.worldBound.xMin + 0.5f, $"{at}: the flag on the left");
+ Assert.Greater(skip.xMin, side.worldBound.xMax - 0.5f, $"{at}: Skip on the right");
+ }
+ }
+ finally
+ {
+ bar.Dispose(); playback.Dispose(); hud.Dispose();
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/EnemyPlaybackUiTests.cs.meta b/unity/Assets/Tests/EditMode/EnemyPlaybackUiTests.cs.meta
new file mode 100644
index 000000000..af6cfd576
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/EnemyPlaybackUiTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 701cbe1274ec4b52bcc00ac776b163b4
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/EnemyTurnPlaybackTests.cs b/unity/Assets/Tests/EditMode/EnemyTurnPlaybackTests.cs
new file mode 100644
index 000000000..1fedc5cf2
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/EnemyTurnPlaybackTests.cs
@@ -0,0 +1,426 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Map.Units;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+
+/// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 5; owner, 2 November 2026: "Q1-Q7
+/// recommended, Q8 yes", and 8 November 2026: "All moves, as approved (Recommended)"): after End turn the driver plays the
+/// enemy's beats one at a time with the camera going to each and back, and never changes the game. The bridge is built over a
+/// real session, as UnitAttackPresenterTests does; the map and the camera are fakes that record what they are asked.</summary>
+public class EnemyTurnPlaybackTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static GameSession NewSession() => GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ static string Hex(int q, int r) => string.Format(CultureInfo.InvariantCulture, "{0},{1}", q, r);
+
+ /// <summary>An enemy move line as Movement.Move writes it (as UnitBeatsTests.Move).</summary>
+ internal static Cause Move(int id, int fromQ, int fromR, int toQ, int toR, string side = "egypt") =>
+ new Cause("map", id.ToString(CultureInfo.InvariantCulture), 0, "Report text is never read", Movement.Kind,
+ key: WhyKeys.UnitMoved, units: new[] { new UnitRef(new Unit(id, "infantry", fromQ, fromR, side: side)) },
+ args: new[] { Hex(toQ, toR), "1" });
+
+ /// <summary>An enemy engagement as Combat.Engage writes it (as UnitBeatsTests.Engagement), with a loss on the defenders.</summary>
+ internal static Cause Engagement(int q, int r, int[] attackers, int[] defenders, string side = "egypt")
+ {
+ var units = attackers.Select(a => new UnitRef(new Unit(a, "infantry", q + 1, r, side: side)))
+ .Concat(defenders.Select(d => new UnitRef(new Unit(d, "infantry", q, r, side: Movement.PlayerSide)))).ToList();
+ return new Cause("map", Hex(q, r), 0, "Report text is never read", Combat.Attack, enemyAttackers: attackers,
+ key: WhyKeys.Engagement, units: units,
+ args: new[] { Hex(q, r), "150", "100", "1", attackers.Length.ToString(CultureInfo.InvariantCulture) });
+ }
+
+ /// <summary>A step that returns these lines after the open turn's, with the state unchanged (UnitAttackPresenterTests).</summary>
+ internal static Func<GameSession, IReadOnlyList<Command>, StepResult> Step(params Cause[] lines) =>
+ (session, orders) => new StepResult(session.State, session.Now.Why.Concat(lines).ToArray(), Array.Empty<Rejection>());
+
+ internal sealed class FakeMap : IPlaybackMap
+ {
+ public readonly List<string> Log = new List<string>();
+ public readonly List<int> Released = new List<int>();
+ public readonly HashSet<int> Held = new HashSet<int>();
+ public readonly HashSet<int> Gone = new HashSet<int>();
+ public bool Shown = true;
+ public Action<IReadOnlyList<Cause>>? OnFight;
+ public void Hold(IEnumerable<int> ids) { var list = ids.ToList(); foreach (var id in list) Held.Add(id); Log.Add("hold " + string.Join(",", list)); }
+ public bool Release(int id) { Released.Add(id); Log.Add("release " + id); return Held.Remove(id); }
+ public void ReleaseAll(bool snap) { Log.Add("releaseall " + snap); Held.Clear(); }
+ public void Fight(IReadOnlyList<Cause> lines) { Log.Add("fight " + lines.Count); OnFight?.Invoke(lines); }
+ public bool Draws(int id) => !Gone.Contains(id);
+ public bool UnitsShown => Shown;
+ public Vector3? World(int q, int r) => new Vector3(q * 1000f, 0f, r * 1000f);
+ public float HexMetres => 1000f;
+ }
+
+ internal sealed class FakeCamera : IPlaybackCamera
+ {
+ public Vector3 LookAt { get; set; } = new Vector3(-5000f, 0f, -5000f);
+ public float Distance { get; set; } = 30000f;
+ public Func<Vector3, bool> Sees = _ => false; // every beat is off screen: each one pans
+ public int Settles;
+ public bool InView(Vector3 point) => Sees(point);
+ public void Settle() => Settles++;
+ }
+
+ sealed class Kit : IDisposable
+ {
+ public readonly SimBridge Bridge;
+ public readonly FakeMap Map = new FakeMap();
+ public readonly FakeCamera Camera = new FakeCamera();
+ public readonly EnemyTurnPlayback Playback;
+ public bool On = true, Clip;
+ public Kit(Func<GameSession, IReadOnlyList<Command>, StepResult>? step = null, GameSession? session = null)
+ {
+ Bridge = new SimBridge(session ?? NewSession(), Text, step);
+ Playback = new EnemyTurnPlayback(Bridge, Map, Camera, () => On, () => Clip);
+ }
+ /// <summary>Ticks until the playback ends; the number of ticks.</summary>
+ public int RunOut(float dt = 0.05f, int max = 4000)
+ {
+ int n = 0;
+ while ((Playback.Active || Playback.Pending) && n < max) { Playback.Tick(dt); n++; }
+ Assert.Less(n, max, "the playback ends");
+ return n;
+ }
+ public void Dispose() => Playback.Dispose();
+ }
+
+ static readonly Cause[] ThreeMoves = { Move(901, 0, 0, 1, 0), Move(902, 30, 0, 31, 0), Move(903, 60, 0, 61, 0) };
+
+ [Test]
+ public void TheBridgeRaisesSteppedThenChangedThenCombatResolvedThenTurnEnded()
+ {
+ var bridge = new SimBridge(NewSession(), Text, Step(ThreeMoves));
+ var order = new List<string>();
+ bridge.Stepped += r => order.Add("stepped " + r.Why.Count(w => w.Key == WhyKeys.UnitMoved && w.Units[0].Id > 900));
+ bridge.Changed += () => order.Add("changed");
+ bridge.CombatResolved += _ => order.Add("combat");
+ bridge.TurnEnded += _ => order.Add("turn");
+ bridge.EndTurn();
+ CollectionAssert.AreEqual(new[] { "stepped 3", "changed", "combat", "turn" }, order);
+ }
+
+ [Test]
+ public void SteppedIsNotRaisedOnARefusedTurnOrANewGame()
+ {
+ var bridge = new SimBridge(NewSession(), Text, (s, orders) => throw new ArgumentException("refused for the test"));
+ int stepped = 0;
+ bridge.Stepped += _ => stepped++;
+ LogAssert.Expect(LogType.Warning, "End Turn refused: refused for the test");
+ bridge.EndTurn();
+ bridge.Replace(NewSession());
+ Assert.AreEqual(0, stepped);
+ }
+
+ [Test]
+ public void ThePlaybackVisitsEveryEnemyMoveInTheSimsOrder()
+ {
+ using var k = new Kit();
+ k.Bridge.EndTurn();
+ var why = k.Bridge.Session.Last!.Why;
+ var moves = why.Where(w => w.Key == WhyKeys.UnitMoved && w.EnemyOrder == Movement.Kind).ToList();
+ Assert.IsNotEmpty(moves, "fixture: the first 1948 turn has enemy moves");
+ // Owner, 8 November 2026, "One side at a time (Recommended)": side by side, in the order the sides first act, each
+ // side in the sim's order.
+ var expected = moves.Select(w => w.Units[0].Side).Distinct()
+ .SelectMany(side => moves.Where(w => w.Units[0].Side == side).Select(w => w.Units[0].Id)).ToArray();
+ Assert.IsTrue(k.Playback.Active || k.Playback.Pending, "End turn started it");
+ k.RunOut();
+ var ids = new HashSet<int>(expected);
+ CollectionAssert.AreEqual(expected, k.Map.Released.Where(ids.Contains).ToArray());
+ }
+
+ [Test]
+ public void HeldTokensAreHeldBeforeTheMapRebuilds()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ k.Bridge.Changed += () => k.Map.Log.Add("changed");
+ k.Bridge.EndTurn();
+ Assert.AreEqual("hold 901,902,903", k.Map.Log[0]);
+ Assert.Less(k.Map.Log.IndexOf("hold 901,902,903"), k.Map.Log.IndexOf("changed"));
+ }
+
+ [Test]
+ public void TheReportAndTheCardAreHeldFromTheStepUntilTheEnd()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ var log = new List<string>();
+ k.Playback.Holding += h => log.Add(h ? "held" : "released");
+ k.Bridge.TurnEnded += _ => log.Add("turn");
+ k.Bridge.EndTurn();
+ CollectionAssert.AreEqual(new[] { "held", "turn" }, log, "held at the step, before the report hears of the turn");
+ k.RunOut();
+ CollectionAssert.AreEqual(new[] { "held", "turn", "released" }, log, "released once, at the end");
+ }
+
+ [Test]
+ public void SkipReleasesEverythingAtOnceAndReturnsTheCamera()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ var saved = k.Camera.LookAt;
+ k.Bridge.EndTurn();
+ for (int i = 0; i < 10; i++) k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active);
+ Assert.AreNotEqual(saved, k.Camera.LookAt, "fixture: the camera has gone to the first beat");
+ int finished = 0; k.Playback.Finished += () => finished++;
+ Assert.IsTrue(k.Playback.Skip());
+ Assert.AreEqual("releaseall True", k.Map.Log.First(l => l.StartsWith("releaseall", StringComparison.Ordinal)));
+ Assert.IsEmpty(k.Map.Held);
+ Assert.AreEqual(saved, k.Camera.LookAt, "back on the player's view in the same call");
+ Assert.IsFalse(k.Playback.Active);
+ Assert.AreEqual(1, finished);
+ Assert.IsFalse(k.Playback.Skip(), "nothing to skip now");
+ }
+
+ [Test]
+ public void TheCameraReturnsToThePlayersViewAfterTheLastBeat()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ var saved = k.Camera.LookAt;
+ k.Bridge.EndTurn();
+ k.RunOut();
+ Assert.Less(Vector3.Distance(saved, k.Camera.LookAt), 1f);
+ CollectionAssert.AreEqual(new[] { 901, 902, 903 }, k.Map.Released.ToArray());
+ Assert.IsEmpty(k.Map.Held);
+ }
+
+ [Test]
+ public void APlayerPanMidPlaybackIsNotUndone()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ k.Bridge.EndTurn();
+ for (int i = 0; i < 6; i++) k.Playback.Tick(0.05f);
+ var mine = new Vector3(12345f, 0f, 6789f);
+ k.Camera.LookAt = mine; // the player pans
+ int settles = k.Camera.Settles;
+ k.RunOut();
+ Assert.AreEqual(mine, k.Camera.LookAt, "no further writes, no return glide");
+ Assert.AreEqual(settles, k.Camera.Settles);
+ Assert.IsTrue(k.Map.Released.Contains(903), "the moves still play");
+ }
+
+ [Test]
+ public void AZoomMidPlaybackIsTheirsToo()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ k.Bridge.EndTurn();
+ for (int i = 0; i < 6; i++) k.Playback.Tick(0.05f);
+ var at = k.Camera.LookAt;
+ k.Camera.Distance = 12000f; // the player zooms
+ k.RunOut();
+ Assert.AreEqual(at, k.Camera.LookAt);
+ Assert.IsTrue(k.Playback.TookOver);
+ }
+
+ [Test]
+ public void ThePlaybackChangesNoState()
+ {
+ // The real turns, with one more enemy move each, so that every turn has a playback whatever the sim did.
+ var extra = Move(911, 0, 0, 1, 0);
+ using var k = new Kit((s, o) => { var r = s.EndTurn(o); return new StepResult(r.State, r.Why.Append(extra).ToArray(), r.Rejected); });
+ k.Bridge.EndTurn();
+ Assert.IsTrue(k.Playback.Active || k.Playback.Pending, "fixture: a playback runs");
+ string hash = k.Bridge.State.Hash(), save = k.Bridge.Session.Save.Write();
+ var last = k.Bridge.Session.Last;
+ var queued = k.Bridge.Queued.ToList();
+ void Same(string when)
+ {
+ Assert.AreEqual(hash, k.Bridge.State.Hash(), when);
+ Assert.AreEqual(save, k.Bridge.Session.Save.Write(), when);
+ Assert.AreSame(last, k.Bridge.Session.Last, when);
+ CollectionAssert.AreEqual(queued, k.Bridge.Queued, when + ": no order queued for the next End turn");
+ }
+ for (int i = 0; i < 20; i++) k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active, "fixture: still playing after 20 ticks");
+ Same("during");
+ k.RunOut();
+ Same("after");
+ k.Bridge.EndTurn();
+ hash = k.Bridge.State.Hash(); save = k.Bridge.Session.Save.Write(); last = k.Bridge.Session.Last; queued = k.Bridge.Queued.ToList();
+ k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active || k.Playback.Pending, "fixture: the second turn's playback runs");
+ Assert.IsTrue(k.Playback.Skip(), "Skip ended a playback");
+ Same("after Skip");
+ }
+
+ [Test]
+ public void ADestroyedMoversBeatIsSkippedAndThePlaybackGoesOn()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ k.Map.Gone.Add(902);
+ var beats = new List<int>();
+ k.Playback.BeatChanged += () => beats.Add(k.Playback.Current!.Moves[0].Unit);
+ k.Bridge.EndTurn();
+ k.RunOut();
+ CollectionAssert.AreEqual(new[] { 901, 903 }, beats);
+ CollectionAssert.AreEqual(new[] { 901, 903 }, k.Map.Released.ToArray());
+ }
+
+ [Test]
+ public void EndTurnMidPlaybackFinishesTheOldOneFirst()
+ {
+ var second = new[] { Move(911, 0, 0, 1, 0) };
+ int turn = 0;
+ using var k = new Kit((s, o) => Step(turn++ == 0 ? ThreeMoves : second)(s, o));
+ k.Bridge.EndTurn();
+ k.Playback.Tick(0.05f);
+ k.Map.Log.Clear();
+ k.Bridge.EndTurn();
+ Assert.AreEqual("releaseall True", k.Map.Log[0], "the old one ends first");
+ Assert.AreEqual("hold 911", k.Map.Log[1], "then only the new turn's units are held");
+ CollectionAssert.AreEquivalent(new[] { 911 }, k.Map.Held);
+ Assert.AreEqual(1, k.Playback.Count);
+ }
+
+ [Test]
+ public void NewGameMidPlaybackDropsIt()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ k.Bridge.EndTurn();
+ k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active);
+ k.Bridge.Replace(NewSession());
+ Assert.IsFalse(k.Playback.Active);
+ Assert.IsFalse(k.Playback.Pending);
+ Assert.IsEmpty(k.Map.Held);
+ }
+
+ [Test]
+ public void DisposingMidPlaybackReleasesEveryTokenAndReturnsTheCamera()
+ {
+ var k = new Kit(Step(ThreeMoves));
+ var saved = k.Camera.LookAt;
+ k.Bridge.EndTurn();
+ for (int i = 0; i < 10; i++) k.Playback.Tick(0.05f);
+ k.Playback.Dispose();
+ Assert.IsEmpty(k.Map.Held);
+ Assert.AreEqual(saved, k.Camera.LookAt);
+ k.Map.Log.Clear();
+ k.Bridge.EndTurn();
+ Assert.IsEmpty(k.Map.Log, "a disposed playback no longer listens");
+ k.Playback.Dispose();
+ }
+
+ /// <summary>Teardown mid-glide (a language switch, OnDisable): GameRoot disposes the map labels before the playback (they
+ /// are built after it), and the game camera's Settle refreshes them. So the playback puts the player's view back without
+ /// Settle; the camera controller applies the look-at point on its next frame (#2967 review 9 November, S2).</summary>
+ [Test]
+ public void DisposingMidGlideReturnsTheCameraWithoutSettlingIt()
+ {
+ var k = new Kit(Step(ThreeMoves));
+ var saved = k.Camera.LookAt;
+ k.Bridge.EndTurn();
+ for (int i = 0; i < 10; i++) k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active, "fixture: the playback runs");
+ Assert.AreNotEqual(saved, k.Camera.LookAt, "fixture: the camera has left the player's view");
+ int settles = k.Camera.Settles;
+ Assert.Greater(settles, 0, "fixture: the glide settled the camera");
+ k.Playback.Dispose();
+ Assert.AreEqual(settles, k.Camera.Settles, "no Settle at teardown: its callback reaches presenters already disposed");
+ Assert.AreEqual(saved, k.Camera.LookAt, "the player's view is back");
+ Assert.IsEmpty(k.Map.Held, "every token stands on its place");
+ Assert.IsFalse(k.Playback.Active || k.Playback.Pending);
+ }
+
+ [Test]
+ public void ItWaitsForTheOutcomeClips()
+ {
+ using var k = new Kit(Step(ThreeMoves)) { Clip = true };
+ k.Bridge.EndTurn();
+ k.Playback.Start();
+ k.Playback.Tick(0.05f);
+ Assert.IsFalse(k.Playback.Active, "a clip shows: it waits");
+ Assert.IsTrue(k.Playback.Pending);
+ CollectionAssert.AreEquivalent(new[] { 901, 902, 903 }, k.Map.Held, "the tokens wait where they stood");
+ k.Clip = false;
+ k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active, "it begins once the clip has gone");
+ }
+
+ [Test]
+ public void AClaimedEngagementPlaysOnItsBeatNotAtOnce()
+ {
+ var fight = Engagement(40, 0, new[] { 921, 922 }, new[] { 929 });
+ using var k = new Kit(Step(Move(901, 0, 0, 1, 0), fight));
+ var played = new List<int>();
+ using var attacks = new UnitAttackPresenter(k.Bridge, id => { played.Add(id); return true; }) { Claimed = k.Playback.Claims };
+ k.Map.OnFight = attacks.Play;
+ k.Bridge.EndTurn();
+ Assert.IsEmpty(played, "End turn leaves it for its beat");
+ Assert.IsTrue(k.Playback.Claims(fight));
+ k.RunOut();
+ CollectionAssert.AreEqual(new[] { 921, 922 }, played, "once per attacker, on its beat");
+ Assert.IsFalse(k.Playback.Claims(fight));
+ }
+
+ [Test]
+ public void WithThePlaybackOffAttacksPlayAsBefore()
+ {
+ var fight = Engagement(40, 0, new[] { 921, 922 }, new[] { 929 });
+ using var k = new Kit(Step(Move(901, 0, 0, 1, 0), fight)) { On = false };
+ var played = new List<int>();
+ using var attacks = new UnitAttackPresenter(k.Bridge, id => { played.Add(id); return true; }) { Claimed = k.Playback.Claims };
+ k.Bridge.EndTurn();
+ CollectionAssert.AreEqual(new[] { 921, 922 }, played, "at End turn, as #2177 plays them");
+ Assert.IsFalse(k.Playback.Active || k.Playback.Pending);
+ Assert.IsEmpty(k.Map.Log, "nothing held, nothing released");
+ }
+
+ [Test]
+ public void AnInstantAttackOrderIsNeverClaimed()
+ {
+ var session = NewSession();
+ using var k = new Kit(Step(ThreeMoves), session);
+ var played = new List<int>();
+ using var attacks = new UnitAttackPresenter(k.Bridge, id => { played.Add(id); return true; }) { Claimed = k.Playback.Claims };
+ k.Bridge.EndTurn();
+ k.Playback.Tick(0.05f);
+ Assert.IsTrue(k.Playback.Active, "fixture: an order given while the enemy's moves play");
+ UnitOrder? order = null; int attacker = -1;
+ foreach (var u in k.Bridge.State.Units.Values.Where(u => u.Side == Movement.PlayerSide))
+ {
+ var enemy = k.Bridge.State.Units.Values.FirstOrDefault(x => x.Side != Movement.PlayerSide && x.Side != ""
+ && MapActions.Distance(x.Q, x.R, u.Q, u.R) == 1);
+ if (enemy == null) continue;
+ order = new UnitOrder(u.Id, Combat.Attack, enemy.Q, enemy.R); attacker = u.Id; break;
+ }
+ Assert.IsNotNull(order, "fixture: a player unit next to an enemy");
+ Assert.IsNull(k.Bridge.Queue(order!));
+ CollectionAssert.Contains(played, attacker, "the player's own attack plays at once");
+ }
+
+ [Test]
+ public void NoPlaybackWhileTheUnitsAreHidden()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ k.Map.Shown = false;
+ int holding = 0; k.Playback.Holding += _ => holding++;
+ k.Bridge.EndTurn();
+ k.Playback.Tick(0.05f);
+ Assert.IsFalse(k.Playback.Active || k.Playback.Pending);
+ Assert.IsEmpty(k.Map.Log);
+ Assert.AreEqual(0, holding, "the report is never held");
+ }
+
+ [Test]
+ public void ABeatInViewDoesNotPan()
+ {
+ using var k = new Kit(Step(ThreeMoves));
+ k.Camera.Sees = _ => true;
+ var saved = k.Camera.LookAt;
+ k.Bridge.EndTurn();
+ k.RunOut();
+ Assert.AreEqual(saved, k.Camera.LookAt, "the camera never moved");
+ Assert.AreEqual(0, k.Camera.Settles);
+ CollectionAssert.AreEqual(new[] { 901, 902, 903 }, k.Map.Released.ToArray());
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/EnemyTurnPlaybackTests.cs.meta b/unity/Assets/Tests/EditMode/EnemyTurnPlaybackTests.cs.meta
new file mode 100644
index 000000000..52ed6a92d
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/EnemyTurnPlaybackTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 7d993607ca1141f7bf9daf0a59ee62ab
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/GameRootEscapeLayerTests.cs b/unity/Assets/Tests/EditMode/GameRootEscapeLayerTests.cs
index a7064eee8..fa9a6f4da 100644
--- a/unity/Assets/Tests/EditMode/GameRootEscapeLayerTests.cs
+++ b/unity/Assets/Tests/EditMode/GameRootEscapeLayerTests.cs
@@ -132,6 +132,57 @@ public class GameRootEscapeLayerTests : SharedCameraActionsFixture
Assert.AreEqual(text["newgame.confirm"], Ui.Q<Label>("toast").text, "and its prompt stays on the toast");
}
+ /// <summary>#2202: the Arab forces' moves play on the map, under every screen. A screen the player opened while they play
+ /// is the topmost layer: the first Escape closes it and leaves the moves playing, and the next one skips them (#2967
+ /// review, S1). The same holds when the focused element's Cancel closed the screen in this frame. GameRoot plays nothing in
+ /// EditMode (Application.isPlaying), so the test puts a playback of its own, on a bridge of its own, in GameRoot's field.</summary>
+ [Test]
+ public void EscapeClosesAScreenOverTheEnemyMovesBeforeSkippingThem([Values(false, true)] bool focusedCancel)
+ {
+ var root = Open(GameInputs.FromDisk(Paths.Content, Paths.StreamingMap), startScreen: false);
+ GameSceneTests.HideTheOpeningCard(Ui);
+ var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ var bridge = new SimBridge(GameSession.New(ContentLoader.Load(Paths.Content), GoldenRun.Seed, Mode.Historical), text,
+ EnemyTurnPlaybackTests.Step(EnemyTurnPlaybackTests.Move(901, 0, 0, 1, 0), EnemyTurnPlaybackTests.Move(902, 30, 0, 31, 0)));
+ using var playback = new EnemyTurnPlayback(bridge, new EnemyTurnPlaybackTests.FakeMap(), new EnemyTurnPlaybackTests.FakeCamera(),
+ () => true, () => false);
+ var field = typeof(GameRoot).GetField("playback", BindingFlags.NonPublic | BindingFlags.Instance)!;
+ var own = field.GetValue(root);
+ field.SetValue(root, playback);
+ try
+ {
+ bridge.EndTurn();
+ playback.Tick(0.05f);
+ Assert.IsTrue(playback.Active, "precondition: the moves play");
+ UiTestKit.Press(Ui.Q<Button>("nav-budget"));
+ Assert.AreEqual(DisplayStyle.Flex, Ui.Q("screen-budget").style.display.value, "precondition: a side screen is open over them");
+
+ if (focusedCancel)
+ {
+ var at = Ui.Q<Button>("nav-budget");
+ using (var e = NavigationCancelEvent.GetPooled()) { e.target = at; at.SendEvent(e); }
+ Assert.AreNotEqual(DisplayStyle.Flex, Ui.Q("screen-budget").style.display.value, "precondition: the Cancel closed the screen");
+ Press(keyboard.escapeKey); // the same press, as GameRoot's poll reads it
+ typeof(GameRoot).GetMethod("Update", BindingFlags.NonPublic | BindingFlags.Instance)!.Invoke(root, null);
+ Release(keyboard.escapeKey);
+ }
+ else
+ {
+ Escape(root);
+ Assert.AreNotEqual(DisplayStyle.Flex, Ui.Q("screen-budget").style.display.value, "the first Escape closes the screen");
+ }
+ Assert.IsTrue(playback.Active, "and only the screen: the moves go on");
+
+ // A later frame: the screen's close counts as this press's only in the frame it happened (ScreenNav.ClosedThisFrame),
+ // and an EditMode test cannot advance Time.frameCount between two presses.
+ var nav = typeof(GameRoot).GetField("nav", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(root)!;
+ typeof(ScreenNav).GetField("closedFrame", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(nav, -1);
+ Escape(root);
+ Assert.IsFalse(playback.Active || playback.Pending, "the next Escape skips the moves");
+ }
+ finally { field.SetValue(root, own); }
+ }
+
/// <summary>An ended autosave opens the end screen before the start screen goes up over it. Escape on the start screen
/// is the start screen's: it withdraws an armed New Game, and never closes the hidden end screen under it.</summary>
[Test]
diff --git a/unity/Assets/Tests/EditMode/HebrewUiTests.cs b/unity/Assets/Tests/EditMode/HebrewUiTests.cs
index d9db19158..6e21def46 100644
--- a/unity/Assets/Tests/EditMode/HebrewUiTests.cs
+++ b/unity/Assets/Tests/EditMode/HebrewUiTests.cs
@@ -370,6 +370,42 @@ public class HebrewUiTests
TheDeclarationStaysRightToLeft("an English restart");
}
+ /// <summary>#2202: the turn report waits while the Arab forces' moves play, and the player may switch the language in
+ /// Settings meanwhile. The rebuild ends the moves; the rebuilt report takes over the wait, and opens in the new language
+ /// once Settings (open again on the new choice) closes (#2967 review, S2). GameRoot plays no moves in EditMode
+ /// (Application.isPlaying), so the test holds the report as the playback does (EnemyTurnPlayback.Holding).</summary>
+ [Test]
+ public void AReportWaitingForTheEnemyMovesOpensAfterTheLanguageSwitch()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ Object.FindFirstObjectByType<MapScene>().Build(Inputs.Map);
+ var game = Object.FindFirstObjectByType<GameRoot>();
+ game.Store = new SaveStore(saveDir);
+ game.Settings = new SettingsStore(Path.Combine(saveDir, "settings"));
+ game.Begin(Inputs, 0);
+ var field = typeof(GameRoot).GetField("report", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!;
+ TurnReportPresenter Report() => (TurnReportPresenter)field.GetValue(game)!;
+ Report().Held = true;
+ game.Bridge!.EndTurn();
+ var turn = game.Bridge.Session.Last;
+ Assert.IsTrue(Report().Waiting, "precondition: the report waits for the moves");
+ Assert.IsFalse(Report().IsOpen);
+ UiTestKit.Press(Ui.Q<Button>("nav-settings"));
+ var old = Report();
+
+ UiTestKit.Press(Ui.Q<Button>("settings-language-he"));
+ Assert.IsTrue(Ui.Q("root").ClassListContains(UiLanguage.HebrewClass), "precondition: the UI was rebuilt in Hebrew");
+ Assert.AreNotSame(old, Report(), "precondition: a new report");
+ Assert.AreSame(turn, game.Bridge!.Session.Last, "the same turn");
+ Assert.IsTrue(ScreenNav.IsOpen(Ui.Q("screen-settings")), "Settings stays open");
+ Assert.IsTrue(Report().Waiting, "the rebuilt report waits for the turn");
+ Assert.IsFalse(Report().IsOpen, "and does not close Settings under the player");
+ var nav = (ScreenNav)typeof(GameRoot).GetField("nav", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(game)!;
+ Assert.IsTrue(nav.Close(), "the player closes Settings");
+ Assert.IsTrue(Report().IsOpen, "the turn's report opens");
+ Assert.AreEqual(He["report.title"], Ui.Q<Label>("turn-report-title").text, "in Hebrew");
+ }
+
/// <summary>The language switch in Settings (#1036): a press rebuilds the UI in the other language at once, over the same
/// game (this turn's orders kept), with Settings still open on the new choice; the choice is kept in settings.txt, so
/// the next start (Language unset, as a reload leaves it) comes up in it.</summary>
@@ -975,6 +1011,7 @@ public class HebrewUiTests
("settings-music-low", "settings.music.low"), ("settings-music-high", "settings.music.high"),
("settings-advisors-label", "settings.advisors"), ("settings-language-label", "settings.language"),
("settings-uiscale-label", "settings.uiscale"), ("settings-companion-label", "settings.companion"), // #1119
+ ("settings-enemymoves-label", "settings.enemymoves"), // #2202
("settings-community-label", "settings.community"), ("settings-star", "community.star"), ("start-star", "community.star"),
("settings-report", "feedback.open"), ("start-report", "feedback.open"), ("feedback-title", "feedback.open"), // #1169
("hud-star", "community.star"), ("hud-report", "feedback.open"), ("hud-share", "share.open"), // #1236
diff --git a/unity/Assets/Tests/EditMode/SettingsScreenTests.cs b/unity/Assets/Tests/EditMode/SettingsScreenTests.cs
index 0b09bc81d..37afc6b42 100644
--- a/unity/Assets/Tests/EditMode/SettingsScreenTests.cs
+++ b/unity/Assets/Tests/EditMode/SettingsScreenTests.cs
@@ -691,4 +691,63 @@ public class SettingsScreenTests
static bool Inside(Rect inner, Rect outer) =>
inner.xMin >= outer.xMin - 0.5f && inner.xMax <= outer.xMax + 0.5f && inner.yMin >= outer.yMin - 0.5f && inner.yMax <= outer.yMax + 0.5f;
+
+ /// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 7; owner, 2 November 2026: "Q1-Q7
+ /// recommended, Q8 yes"): the enemy's moves on the map can be turned off; on by default, kept across a reload.</summary>
+ [Test]
+ public void TheEnemyMovesSwitchDefaultsOnAndIsRemembered([Values(false, true)] bool hebrew)
+ {
+ var text = hebrew ? He : En;
+ var seen = new List<bool>();
+ Assert.IsTrue(SettingsPresenter.EnemyMovesOn(new SettingsStore(dir)), "on with no file");
+ Assert.IsTrue(SettingsPresenter.EnemyMovesOn(null), "on with no store");
+ using (var ui = new UiTestKit())
+ using (new SettingsPresenter(ui.Root, text, new SettingsStore(dir), enemyMoves: seen.Add))
+ {
+ var button = ui.Q<Button>("settings-enemymoves");
+ Assert.AreEqual(text["settings.enemymoves"], ui.Q<Label>("settings-enemymoves-label").text);
+ Assert.AreEqual(text["settings.on"], button.text);
+ UiTestKit.Press(button);
+ Assert.AreEqual(text["settings.off"], button.text);
+ CollectionAssert.AreEqual(new[] { false }, seen);
+ }
+ Assert.IsFalse(SettingsPresenter.EnemyMovesOn(new SettingsStore(dir)), "off survives a reload");
+ using (var ui = new UiTestKit())
+ using (new SettingsPresenter(ui.Root, text, new SettingsStore(dir), enemyMoves: seen.Add))
+ {
+ var button = ui.Q<Button>("settings-enemymoves");
+ Assert.AreEqual(text["settings.off"], button.text);
+ UiTestKit.Press(button);
+ Assert.AreEqual(text["settings.on"], button.text);
+ }
+ Assert.IsTrue(SettingsPresenter.EnemyMovesOn(new SettingsStore(dir)));
+ CollectionAssert.AreEqual(new[] { false, true }, seen);
+ }
+
+ [Test]
+ public void TurningItOffMidPlaybackSkips()
+ {
+ using var ui = new UiTestKit();
+ var bridge = new SimBridge(GameSession.New(ContentLoader.Load(Paths.Content), GoldenRun.Seed, Mode.Historical), En,
+ EnemyTurnPlaybackTests.Step(EnemyTurnPlaybackTests.Move(901, 0, 0, 1, 0), EnemyTurnPlaybackTests.Move(902, 30, 0, 31, 0)));
+ var map = new EnemyTurnPlaybackTests.FakeMap();
+ var store = new SettingsStore(dir);
+ using var playback = new EnemyTurnPlayback(bridge, map, new EnemyTurnPlaybackTests.FakeCamera(),
+ () => SettingsPresenter.EnemyMovesOn(store), () => false);
+ var released = new List<bool>();
+ playback.Holding += held => released.Add(held);
+ // As GameRoot wires it: turning it off skips the playback at once.
+ using var settings = new SettingsPresenter(ui.Root, En, store, enemyMoves: on => { if (!on) playback.Skip(); });
+ bridge.EndTurn();
+ playback.Tick(0.05f);
+ Assert.IsTrue(playback.Active);
+ UiTestKit.Press(ui.Q<Button>("settings-enemymoves"));
+ Assert.IsFalse(playback.Active, "it ends at once");
+ Assert.IsEmpty(map.Held, "every token on its place");
+ CollectionAssert.AreEqual(new[] { true, false }, released, "the report and the card are let go");
+ map.Log.Clear();
+ bridge.EndTurn();
+ Assert.IsFalse(playback.Active || playback.Pending, "and the next End turn plays nothing");
+ Assert.IsEmpty(map.Log);
+ }
}
diff --git a/unity/Assets/Tests/EditMode/UnitBeatsTests.cs b/unity/Assets/Tests/EditMode/UnitBeatsTests.cs
new file mode 100644
index 000000000..5a5be467a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitBeatsTests.cs
@@ -0,0 +1,293 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Map.Units;
+using Statecraft.Game.UI;
+using Statecraft.Sim;
+
+/// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 2; owner, 2 November 2026: "Q1-Q7
+/// recommended, Q8 yes"): the turn's recorded unit actions become beats in the sim's own order. Presentation only: the
+/// planner orders and groups the sim's causes, it never decides what a unit did (R-ENEMY-001 names the enemy's).</summary>
+public class UnitBeatsTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+
+ static string Hex(int q, int r) => string.Format(CultureInfo.InvariantCulture, "{0},{1}", q, r);
+
+ /// <summary>An enemy move line as Movement.Move writes it: the unit before the move, the destination in Args[0].</summary>
+ static Cause Move(int id, int fromQ, int fromR, int toQ, int toR, string enemyOrder = Movement.Kind, string side = "egypt") =>
+ new Cause("map", id.ToString(CultureInfo.InvariantCulture), 0, "Report text is never read", enemyOrder,
+ key: WhyKeys.UnitMoved, units: new[] { new UnitRef(new Unit(id, "infantry", fromQ, fromR, side: side)) },
+ args: new[] { Hex(toQ, toR), "1" });
+
+ /// <summary>An engagement as Combat.Engage writes it: attackers then defenders, the hex first, the attacker count fifth.</summary>
+ static Cause Engagement(int q, int r, int[] attackers, int[] defenders, string enemyOrder = Combat.Attack, string side = "egypt")
+ {
+ var units = attackers.Select(a => new UnitRef(new Unit(a, "infantry", q + 1, r, side: side)))
+ .Concat(defenders.Select(d => new UnitRef(new Unit(d, "infantry", q, r, side: Movement.PlayerSide)))).ToList();
+ return new Cause("map", Hex(q, r), 0, "Report text is never read", enemyOrder,
+ enemyAttackers: enemyOrder == Combat.Attack ? attackers : null, key: WhyKeys.Engagement, units: units,
+ args: new[] { Hex(q, r), "150", "100", "0", attackers.Length.ToString(CultureInfo.InvariantCulture) });
+ }
+
+ static Cause Retreat(int id, int q, int r, int toQ, int toR) =>
+ new Cause("map", id.ToString(CultureInfo.InvariantCulture), 0, "Report text is never read", key: WhyKeys.Retreated,
+ units: new[] { new UnitRef(new Unit(id, "infantry", q, r, side: Movement.PlayerSide)) }, args: new[] { Hex(toQ, toR) });
+
+ static Cause Destroyed(int id, int q, int r) =>
+ new Cause("map", id.ToString(CultureInfo.InvariantCulture), 0, "Report text is never read", key: WhyKeys.Destroyed,
+ units: new[] { new UnitRef(new Unit(id, "infantry", q, r, side: Movement.PlayerSide)) });
+
+ static Cause Other(string key, string enemyOrder = "") =>
+ new Cause("map", "5", 0, "Report text is never read", enemyOrder, key: key,
+ units: new[] { new UnitRef(new Unit(5, "infantry", 0, 0, side: "egypt")) });
+
+ static IEnumerable<int> Movers(IEnumerable<UnitBeat> beats) => beats.SelectMany(b => b.Moves.Select(m => m.Unit));
+
+ [Test]
+ public void NoEnemyCausesMakeNoBeats()
+ {
+ var why = new[] { Move(1, 0, 0, 1, 0, enemyOrder: ""), Engagement(4, 4, new[] { 1 }, new[] { 9 }, enemyOrder: ""),
+ new Cause("economy", "money", 5, "Tax") };
+ Assert.IsEmpty(UnitBeats.From(why, BeatSource.Enemy));
+ Assert.IsEmpty(UnitBeats.From(Array.Empty<Cause>(), BeatSource.Enemy));
+ }
+
+ [Test]
+ public void MovesKeepTheSimsOrder()
+ {
+ // Far apart, so each is its own beat: the planner never sorts.
+ var why = new[] { Move(3, 0, 0, 1, 0), Move(1, 20, 0, 21, 0), Move(2, 40, 0, 41, 0) };
+ var beats = UnitBeats.From(why, BeatSource.Enemy);
+ CollectionAssert.AreEqual(new[] { 3, 1, 2 }, Movers(beats).ToArray());
+ Assert.AreEqual(3, beats.Count);
+ }
+
+ [Test]
+ public void AMoveRecordsTheHexItLeftAndTheHexItReached()
+ {
+ var beat = UnitBeats.From(new[] { Move(7, 2, 3, 3, 3) }, BeatSource.Enemy).Single();
+ Assert.AreEqual(BeatKind.Move, beat.Kind);
+ Assert.AreEqual(0, beat.Engagements);
+ var step = beat.Moves.Single();
+ Assert.AreEqual((7, 2, 3, 3, 3), (step.Unit, step.FromQ, step.FromR, step.ToQ, step.ToR));
+ Assert.AreEqual((3, 3), (beat.FocusQ, beat.FocusR));
+ CollectionAssert.AreEqual(new[] { 7 }, beat.Units);
+ }
+
+ [Test]
+ public void NearbyMovesShareABeatUpToFour()
+ {
+ var why = new[]
+ {
+ Move(1, 0, 0, 1, 0), Move(2, 0, 1, 2, 0), Move(3, 0, 2, 1, 1), Move(4, 0, 3, 3, 0), Move(5, 0, 4, 1, 2),
+ Move(6, 20, 0, 11, 0), // 10 hexes from the first destination
+ };
+ var beats = UnitBeats.From(why, BeatSource.Enemy);
+ CollectionAssert.AreEqual(new[] { 4, 1, 1 }, beats.Select(b => b.Moves.Count).ToArray());
+ CollectionAssert.AreEqual(new[] { 1, 2, 3, 4 }, beats[0].Moves.Select(m => m.Unit).ToArray());
+ CollectionAssert.AreEqual(new[] { 5 }, beats[1].Moves.Select(m => m.Unit).ToArray());
+ CollectionAssert.AreEqual(new[] { 6 }, beats[2].Moves.Select(m => m.Unit).ToArray());
+ Assert.AreEqual(UnitBeats.Timing.MaxUnitsPerBeat, beats[0].Moves.Count);
+ }
+
+ [Test]
+ public void AGroupedBeatLooksAtTheMiddleOfItsDestinations()
+ {
+ var beat = UnitBeats.From(new[] { Move(1, 0, 0, 0, 0), Move(2, 0, 0, 2, 0) }, BeatSource.Enemy).Single();
+ Assert.AreEqual((1, 0), (beat.FocusQ, beat.FocusR));
+ }
+
+ [Test]
+ public void AnEngagementIsItsOwnBeatAndTakesItsRetreatersAndLosses()
+ {
+ var why = new[]
+ {
+ Move(1, 0, 0, 1, 0),
+ Engagement(4, 4, new[] { 1, 2 }, new[] { 9, 10 }), Retreat(9, 4, 4, 3, 5), Destroyed(10, 4, 4),
+ Engagement(8, 8, new[] { 3 }, new[] { 11 }), Retreat(11, 8, 8, 7, 9),
+ };
+ var beats = UnitBeats.From(why, BeatSource.Enemy);
+ CollectionAssert.AreEqual(new[] { BeatKind.Move, BeatKind.Attack, BeatKind.Attack }, beats.Select(b => b.Kind).ToArray());
+ var first = beats[1];
+ CollectionAssert.AreEqual(new[] { 1, 2 }, first.Attackers);
+ Assert.AreEqual((4, 4), (first.FocusQ, first.FocusR));
+ Assert.AreEqual((9, 4, 4, 3, 5), (first.Retreats.Single().Unit, first.Retreats[0].FromQ, first.Retreats[0].FromR,
+ first.Retreats[0].ToQ, first.Retreats[0].ToR));
+ CollectionAssert.AreEqual(new[] { why[1], why[2], why[3] }, first.Causes, "its own line, then its retreat and loss");
+ CollectionAssert.AreEqual(new[] { 9 }, first.Units, "only a retreater moves on an attack beat");
+ CollectionAssert.AreEqual(new[] { 11 }, beats[2].Retreats.Select(m => m.Unit).ToArray(), "the next engagement's own");
+ }
+
+ [Test]
+ public void FortifyAndAttackOrdersMakeNoBeat()
+ {
+ var why = new[] { Other(WhyKeys.Fortifying, Orders.Fortify), Other(WhyKeys.AttackOrdered, Combat.Attack), Other(WhyKeys.Holds) };
+ Assert.IsEmpty(UnitBeats.From(why, BeatSource.Enemy));
+ }
+
+ [Test]
+ public void APlayerEngagementIsNotABeat()
+ {
+ var why = new[] { Engagement(4, 4, new[] { 9 }, new[] { 1 }, enemyOrder: ""), Retreat(1, 4, 4, 5, 4) };
+ Assert.IsEmpty(UnitBeats.From(why, BeatSource.Enemy));
+ }
+
+ [Test]
+ public void ARetreatAfterAPlayerEngagementIsNotTakenByTheNextEnemyBeat()
+ {
+ var why = new[]
+ {
+ Engagement(4, 4, new[] { 9 }, new[] { 1 }, enemyOrder: ""), Retreat(1, 4, 4, 5, 4),
+ Engagement(8, 8, new[] { 2 }, new[] { 10 }),
+ };
+ var beat = UnitBeats.From(why, BeatSource.Enemy).Single();
+ Assert.IsEmpty(beat.Retreats);
+ }
+
+ [Test]
+ public void ALongTurnIsCappedAndFolded()
+ {
+ var why = Enumerable.Range(1, 20).Select(i => Move(i, i * 10, 0, i * 10 + 1, 0)).ToArray();
+ var beats = UnitBeats.From(why, BeatSource.Enemy);
+ Assert.AreEqual(UnitBeats.Timing.MaxBeats, beats.Count);
+ Assert.IsTrue(beats.Take(beats.Count - 1).All(b => !b.Folded));
+ var folded = beats[beats.Count - 1];
+ Assert.IsTrue(folded.Folded);
+ CollectionAssert.AreEqual(Enumerable.Range(UnitBeats.Timing.MaxBeats, 20 - UnitBeats.Timing.MaxBeats + 1).ToArray(),
+ folded.Moves.Select(m => m.Unit).ToArray(), "every remaining unit, in the sim's order");
+ Assert.AreEqual(0f, folded.Pan, "a folded beat moves no camera");
+ CollectionAssert.AreEqual(Enumerable.Range(1, 20).ToArray(), Movers(beats).ToArray(), "each unit exactly once");
+ Assert.LessOrEqual(UnitBeats.Total(beats), UnitBeats.Timing.Cap + 1e-4f);
+ foreach (var b in beats)
+ {
+ if (!b.Folded) Assert.GreaterOrEqual(b.Pan, UnitBeats.Timing.MinPan - 1e-5f);
+ Assert.GreaterOrEqual(b.Dwell, UnitBeats.Timing.MinDwell - 1e-5f);
+ }
+ }
+
+ [Test]
+ public void AnOverlongTurnShrinksItsPansAndHoldsNoFurtherThanTheirMinimums()
+ {
+ var why = Enumerable.Range(0, UnitBeats.Timing.MaxBeats)
+ .Select(i => Engagement(i * 30, 0, new[] { i + 1 }, new[] { 100 + i })).ToArray();
+ var beats = UnitBeats.From(why, BeatSource.Enemy);
+ Assert.AreEqual(UnitBeats.Timing.MaxBeats, beats.Count, "fixture: no fold");
+ Assert.Greater(UnitBeats.Timing.MaxBeats * (UnitBeats.Timing.PanMax + UnitBeats.Timing.AttackMax), UnitBeats.Timing.Cap,
+ "fixture: at full pacing the turn would pass the cap");
+ Assert.AreEqual(UnitBeats.Timing.Cap, UnitBeats.Total(beats), 1e-3f, "shrunk to the cap, no further");
+ foreach (var b in beats)
+ {
+ Assert.That(b.Pan, NUnit.Framework.Is.InRange(UnitBeats.Timing.MinPan, UnitBeats.Timing.PanMax));
+ Assert.That(b.Dwell, NUnit.Framework.Is.InRange(UnitBeats.Timing.AttackMin, UnitBeats.Timing.AttackMax));
+ }
+ }
+
+ [Test]
+ public void AShortTurnKeepsTheFullPacing()
+ {
+ var beats = UnitBeats.From(new[] { Move(1, 0, 0, 1, 0), Engagement(30, 0, new[] { 2 }, new[] { 9 }) }, BeatSource.Enemy);
+ Assert.AreEqual(UnitBeats.Timing.PanMax, beats[0].Pan, "the first beat's pan is not known from the camera: the longest");
+ Assert.AreEqual(UnitBeats.Timing.MoveDwell, beats[0].Dwell);
+ Assert.AreEqual(UnitBeats.Timing.PanMax, beats[1].Pan, 1e-5f, "29 hexes away: the longest pan");
+ Assert.AreEqual(UnitBeats.Timing.AttackMax, beats[1].Dwell, "an attack is held for its fire take");
+ Assert.AreEqual(beats[0].Pan + UnitTokenMotion.Duration + beats[0].Dwell, beats[0].Length, 1e-5f, "a move beat slides");
+ Assert.AreEqual(beats[1].Pan + beats[1].Dwell, beats[1].Length, 1e-5f);
+ Assert.AreEqual(beats[0].Length + beats[1].Length, UnitBeats.Total(beats), 1e-5f);
+ }
+
+ [Test]
+ public void ANearPanIsShorter()
+ {
+ var beats = UnitBeats.From(new[] { Move(1, 0, 0, 0, 0), Move(2, 9, 0, 8, 0) }, BeatSource.Enemy);
+ Assert.AreEqual(2, beats.Count, "fixture: 8 hexes apart, two beats");
+ Assert.AreEqual(Math.Max(UnitBeats.Timing.PanMin, Math.Min(UnitBeats.Timing.PanMax, 8 * UnitBeats.Timing.PanPerHex)),
+ beats[1].Pan, 1e-5f);
+ }
+
+ /// <summary>The seam #2544 PR 2 takes: another source of beats over the same Why list, with the same grouping and pacing.</summary>
+ [Test]
+ public void AnotherSourceReadsItsOwnLines()
+ {
+ var mine = new BeatSource(c => c.Key == WhyKeys.UnitMoved && c.EnemyOrder == "", c => c.Key == WhyKeys.Engagement && c.EnemyOrder == "");
+ var why = new[] { Move(1, 0, 0, 1, 0, enemyOrder: ""), Move(2, 30, 0, 31, 0), Engagement(4, 4, new[] { 1 }, new[] { 9 }, enemyOrder: "") };
+ var beats = UnitBeats.From(why, mine);
+ CollectionAssert.AreEqual(new[] { BeatKind.Move, BeatKind.Attack }, beats.Select(b => b.Kind).ToArray());
+ CollectionAssert.AreEqual(new[] { 1 }, Movers(beats).ToArray());
+ }
+
+ [Test]
+ public void TheFirst1948TurnPlaysEveryEnemyMove()
+ {
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+ var r = Simulation.Step(C, s, Array.Empty<Command>());
+ var expected = r.Why.Where(w => w.Key == WhyKeys.UnitMoved && w.EnemyOrder == Movement.Kind).Select(w => w.Units[0].Id).ToArray();
+ Assert.IsNotEmpty(expected, "fixture: the first 1948 turn has enemy moves");
+ var beats = UnitBeats.From(r.Why, BeatSource.Enemy);
+ CollectionAssert.AreEquivalent(expected, Movers(beats).ToArray(), "every enemy move once");
+ var sides = r.Why.Where(w => w.Key == WhyKeys.UnitMoved && w.EnemyOrder == Movement.Kind).Select(w => w.Units[0].Side).Distinct().ToList();
+ CollectionAssert.AreEqual(sides.SelectMany(side => r.Why
+ .Where(w => w.Key == WhyKeys.UnitMoved && w.EnemyOrder == Movement.Kind && w.Units[0].Side == side).Select(w => w.Units[0].Id)).ToArray(),
+ Movers(beats).ToArray(), "side by side, each in the sim's order");
+ Assert.IsTrue(beats.All(b => b.Moves.All(m => r.Why.First(w => w.Key == WhyKeys.UnitMoved && w.Units[0].Id == m.Unit).Units[0].Side == b.Side)),
+ "no beat mixes sides");
+ Assert.LessOrEqual(UnitBeats.Total(beats), UnitBeats.Timing.Cap + 1e-4f);
+ var attacks = r.Why.Count(w => w.Key == WhyKeys.Engagement && w.EnemyOrder == Combat.Attack);
+ Assert.AreEqual(attacks, beats.Count(b => b.Kind == BeatKind.Attack && !b.Folded) + beats.Where(b => b.Folded).Sum(b => b.Engagements),
+ "every enemy engagement once");
+ }
+ // Owner, 8 November 2026, on the playback's footer: "One side at a time (Recommended)". The beats are ordered by side, in the
+ // order the sides first act in the sim's lines this turn, each side keeping the sim's order; beats group within a side only.
+
+ [Test]
+ public void SidesPlayOneAtATimeInTheOrderTheyFirstAct()
+ {
+ var why = new[]
+ {
+ Move(1, 0, 0, 1, 0, side: "jordan"), Move(2, 0, 0, 1, 1, side: "egypt"), Move(3, 0, 0, 2, 0, side: "jordan"),
+ Engagement(20, 0, new[] { 4 }, new[] { 9 }, side: "egypt"), Move(5, 30, 0, 31, 0, side: "iraq"),
+ Engagement(40, 0, new[] { 6 }, new[] { 10 }, side: "jordan"),
+ };
+ var beats = UnitBeats.From(why, BeatSource.Enemy);
+ CollectionAssert.AreEqual(new[] { "jordan", "jordan", "egypt", "egypt", "iraq" }, beats.Select(b => b.Side).ToArray(),
+ "Jordan acts first, then Egypt, then Iraq; each side's beats together");
+ CollectionAssert.AreEqual(new[] { 1, 3 }, beats[0].Moves.Select(m => m.Unit).ToArray(), "a side's nearby moves share a beat");
+ CollectionAssert.AreEqual(new[] { why[5] }, beats[1].Causes, "Jordan's attack after its moves");
+ CollectionAssert.AreEqual(new[] { 2 }, beats[2].Moves.Select(m => m.Unit).ToArray());
+ CollectionAssert.AreEqual(new[] { why[3] }, beats[3].Causes);
+ }
+
+ [Test]
+ public void NearbyMovesOfTwoSidesNeverShareABeat()
+ {
+ var beats = UnitBeats.From(new[] { Move(1, 0, 0, 1, 0, side: "syria"), Move(2, 0, 0, 1, 0, side: "lebanon") }, BeatSource.Enemy);
+ CollectionAssert.AreEqual(new[] { "syria", "lebanon" }, beats.Select(b => b.Side).ToArray());
+ }
+
+ [Test]
+ public void AnEngagementIsItsFirstAttackersSide()
+ {
+ var beat = UnitBeats.From(new[] { Engagement(4, 4, new[] { 1 }, new[] { 9 }, side: "ala") }, BeatSource.Enemy).Single();
+ Assert.AreEqual("ala", beat.Side);
+ }
+
+ [Test]
+ public void AFoldNeverMixesSidesAndTheTurnStaysWithinItsBeats()
+ {
+ var why = Enumerable.Range(1, 12).Select(i => Move(i, i * 10, 0, i * 10 + 1, 0, side: "egypt"))
+ .Concat(Enumerable.Range(13, 6).Select(i => Move(i, i * 10, 0, i * 10 + 1, 0, side: "syria")))
+ .Concat(Enumerable.Range(19, 4).Select(i => Move(i, i * 10, 0, i * 10 + 1, 0, side: "iraq"))).ToArray();
+ var beats = UnitBeats.From(why, BeatSource.Enemy);
+ Assert.LessOrEqual(beats.Count, UnitBeats.Timing.MaxBeats, "the cap's guarantee needs at most MaxBeats beats");
+ foreach (var b in beats)
+ Assert.IsTrue(b.Moves.All(m => why.First(w => w.Units[0].Id == m.Unit).Units[0].Side == b.Side), "beat of " + b.Side);
+ CollectionAssert.AreEqual(Enumerable.Range(1, 22).ToArray(), Movers(beats).ToArray(), "each unit once, side by side");
+ var folded = beats.Where(b => b.Folded).Select(b => b.Side).ToArray();
+ CollectionAssert.AreEqual(new[] { "egypt", "syria", "iraq" }, folded, "one folded beat per side past the cut");
+ Assert.LessOrEqual(UnitBeats.Total(beats), UnitBeats.Timing.Cap + 1e-4f);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/UnitBeatsTests.cs.meta b/unity/Assets/Tests/EditMode/UnitBeatsTests.cs.meta
new file mode 100644
index 000000000..ba3b4b39a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitBeatsTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 521f6f204957463e9c5880ddd427d84f
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/UnitLayerHoldTests.cs b/unity/Assets/Tests/EditMode/UnitLayerHoldTests.cs
new file mode 100644
index 000000000..bdda64d6d
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitLayerHoldTests.cs
@@ -0,0 +1,249 @@
+#nullable enable
+using System;
+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.Sim;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+/// <summary>#2202 (plan docs/superpowers/plans/2026-11-02-enemy-move-playback.md, Task 3): a token can wait at the place it
+/// was drawn while the sim has already moved its unit, and slide from there when its beat comes. It extends #2176's slide
+/// (UnitsFromStateTests.AMovedTokenSlidesFromWhereItWasDrawnAndStops), with no second offset path. Presentation only.</summary>
+public class UnitLayerHoldTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static List<UnitEntry> Units => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
+ static GameState NewGame() => Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+
+ MapScene map = null!;
+ UnitLayer layer = null!;
+ GameState state = null!;
+
+ [SetUp]
+ public void Build()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
+ map = new GameObject("MapScene").AddComponent<MapScene>();
+ map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));
+ Statecraft.Game.Map.Kits.KitPopulation.Use(Statecraft.Game.Map.Kits.KitPopulation.Parse(
+ File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))));
+ map.Build();
+ state = NewGame();
+ layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ layer.AnimateMoves = true;
+ layer.Show(C, state);
+ }
+
+ [TearDown]
+ public void Free() { if (map != null) Object.DestroyImmediate(map.gameObject); }
+
+ static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");
+
+ (int q, int r) FreeNeighbour(int q, int r)
+ {
+ foreach (var (dq, dr) in new[] { (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1) })
+ {
+ var h = C.HexAt(q + dq, r + dr);
+ if (h != null && h.Land && !state.Units.Values.Any(u => u.Q == h.Q && u.R == h.R)) return (h.Q, h.R);
+ }
+ throw new InvalidOperationException($"no free land hex next to ({q},{r})");
+ }
+
+ void Move(Unit unit)
+ {
+ var u = state.Units[unit.Id];
+ var to = FreeNeighbour(u.Q, u.R);
+ state.Units[u.Id] = new Unit(u.Id, u.Type, to.q, to.r, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget);
+ }
+
+ Unit Israeli(int index) => state.Units.Values.Where(u => u.Side == Movement.PlayerSide)
+ .Where(u => layer.Tokens.Any(t => t.Token.StateUnit?.Id == u.Id)).OrderBy(u => u.Id).ElementAt(index);
+
+ UnitTokenMotion MotionOf(int simId) =>
+ layer.GetComponentsInChildren<UnitTokenMotion>(true).Single(m => m.SimId == simId);
+
+ Vector2 SpotOf(int simId)
+ {
+ var spot = layer.Tokens.Single(t => t.Token.StateUnit?.Id == simId).Spot;
+ return new Vector2((float)spot.X, (float)spot.Z);
+ }
+
+ static Vector2 XZ(Vector3 v) => new Vector2(v.x, v.z);
+
+ /// <summary>Where the token of <paramref name="simId"/> is drawn: its spot plus its root's offset (UnitTokenMotion).</summary>
+ Vector2 DrawnAt(int simId) => SpotOf(simId) + XZ(MotionOf(simId).transform.position);
+
+ [Test]
+ public void AHeldTokenStandsAtItsOldPlaceThroughARebuild()
+ {
+ var unit = Israeli(0);
+ var old = SpotOf(unit.Id);
+ layer.Hold(new[] { unit.Id });
+ Move(unit);
+ Assert.IsTrue(layer.Show(C, state), "fixture: the move rebuilds the tokens");
+ Assert.Greater((SpotOf(unit.Id) - old).magnitude, 1000f, "fixture: a real move");
+ var motion = MotionOf(unit.Id);
+ Assert.IsTrue(motion.Held);
+ Assert.IsFalse(motion.Moving, "it waits, it does not slide");
+ Assert.IsFalse(motion.enabled, "a waiting token runs nothing per frame");
+ Assert.Less((DrawnAt(unit.Id) - old).magnitude, 1f, "it stands where it was drawn");
+
+ Move(Israeli(1)); // another unit's order rebuilds every token
+ Assert.IsTrue(layer.Show(C, state));
+ Assert.IsTrue(MotionOf(unit.Id).Held);
+ Assert.Less((DrawnAt(unit.Id) - old).magnitude, 1f, "still there after another rebuild");
+ }
+
+ [Test]
+ public void ReleaseSlidesItFromThereLikeAnyMove()
+ {
+ var unit = Israeli(0);
+ var old = SpotOf(unit.Id);
+ layer.Hold(new[] { unit.Id });
+ Move(unit);
+ layer.Show(C, state);
+ Assert.IsTrue(layer.Release(unit.Id));
+ var motion = MotionOf(unit.Id);
+ Assert.IsFalse(motion.Held);
+ Assert.IsTrue(motion.Moving && motion.enabled, "the slide starts");
+ Assert.Less((DrawnAt(unit.Id) - old).magnitude, 1f, "from the old place");
+ motion.Tick(UnitTokenMotion.Duration);
+ Assert.AreEqual(Vector3.zero, motion.transform.position, "it ends on its spot");
+ Assert.IsFalse(motion.Moving);
+ Assert.IsFalse(layer.Release(unit.Id), "released once: it is no longer held");
+ }
+
+ [Test]
+ public void ReleaseAllWithSnapPutsEveryHeldTokenAtItsPlaceAtOnce()
+ {
+ var a = Israeli(0); var b = Israeli(1);
+ layer.Hold(new[] { a.Id, b.Id });
+ Move(a); Move(b);
+ layer.Show(C, state);
+ Assert.IsTrue(MotionOf(a.Id).Held && MotionOf(b.Id).Held, "fixture");
+ layer.ReleaseAll(snap: true);
+ foreach (var id in new[] { a.Id, b.Id })
+ {
+ var m = MotionOf(id);
+ Assert.IsFalse(m.Held, id.ToString()); Assert.IsFalse(m.Moving, id.ToString());
+ Assert.AreEqual(Vector3.zero, m.transform.position, "on its spot at once");
+ }
+ Move(Israeli(2));
+ layer.Show(C, state);
+ Assert.AreEqual(Vector3.zero, MotionOf(a.Id).transform.position, "the held set is empty after ReleaseAll");
+ }
+
+ [Test]
+ public void ReleaseAllWithoutSnapSlidesThem()
+ {
+ var a = Israeli(0);
+ layer.Hold(new[] { a.Id });
+ Move(a);
+ layer.Show(C, state);
+ layer.ReleaseAll(snap: false);
+ Assert.IsTrue(MotionOf(a.Id).Moving);
+ }
+
+ [Test]
+ public void AnUnheldMovedTokenStillSlidesAtOnce()
+ {
+ var held = Israeli(0); var free = Israeli(1);
+ layer.Hold(new[] { held.Id });
+ Move(held); Move(free);
+ layer.Show(C, state);
+ Assert.IsTrue(MotionOf(free.Id).Moving, "#2176's slide is unchanged for a unit nothing holds");
+ Assert.IsFalse(MotionOf(free.Id).Held);
+ Assert.IsFalse(MotionOf(held.Id).Moving);
+ }
+
+ [Test]
+ public void MidHoldTheBadgeAndItsBoxesAreAtTheOldPlace()
+ {
+ var unit = Israeli(0);
+ var old = SpotOf(unit.Id);
+ var eye = new GameObject("HoldCamera").AddComponent<Camera>();
+ try
+ {
+ eye.farClipPlane = 1e6f;
+ layer.FaceCamera(eye);
+ var badgeBefore = XZ(MotionOf(unit.Id).transform.Find("Badge").position);
+ layer.Hold(new[] { unit.Id });
+ Move(unit);
+ layer.Show(C, state);
+ layer.FaceCamera(eye);
+ var badge = XZ(MotionOf(unit.Id).transform.Find("Badge").position);
+ float moved = (SpotOf(unit.Id) - old).magnitude;
+ // A compact spot sets the badge a little nearer its figures than a full one (UnitLayer.Spread), so the badge is
+ // compared with the length of the move, not to the metre.
+ Assert.Less((badge - badgeBefore).magnitude, 0.1f * moved, "the badge waits with the token");
+ int i = layer.Tokens.Select((t, k) => (t, k)).Single(x => x.t.Token.StateUnit?.Id == unit.Id).k;
+ Assert.Less((XZ(layer.KeepClear[i][0].center) - badge).magnitude, 1f, "and so does the box a click finds");
+ }
+ finally { Object.DestroyImmediate(eye.gameObject); }
+ }
+
+ [Test]
+ public void ANewGameClearsTheHeldSet()
+ {
+ var unit = Israeli(0);
+ layer.Hold(new[] { unit.Id });
+ Move(unit);
+ layer.Show(C, state, slide: false); // SimBridge.Replace: another game, the same sim ids
+ Assert.IsFalse(MotionOf(unit.Id).Held);
+ Assert.AreEqual(Vector3.zero, MotionOf(unit.Id).transform.position);
+ // The unit goes back to where it started, a place the layer draws it apart from its moved one (the slide the tests
+ // above see). A second Move from the moved hex could be placed on the very spot it is drawn on (a moved anchor's spot
+ // is any clear one within a hex), and a token that has not moved does not slide.
+ var drawn = MotionOf(unit.Id).GroundHome;
+ state = NewGame();
+ layer.Show(C, state);
+ Assert.AreNotEqual(drawn, MotionOf(unit.Id).GroundHome, "the unit is drawn somewhere else");
+ Assert.IsFalse(MotionOf(unit.Id).Held, "nothing is left held for the new game");
+ Assert.IsTrue(MotionOf(unit.Id).Moving, "so it slides there, as any unheld move");
+ }
+
+ [Test]
+ public void AHiddenLayerHoldsNothing()
+ {
+ var unit = Israeli(0);
+ layer.transform.Find("Tokens").gameObject.SetActive(false);
+ layer.Hold(new[] { unit.Id });
+ Move(unit);
+ layer.Show(C, state);
+ var motion = MotionOf(unit.Id);
+ Assert.IsFalse(motion.Held, "a token no one can see does not wait");
+ Assert.IsFalse(motion.Moving);
+ Assert.AreEqual(Vector3.zero, motion.transform.position);
+ }
+
+ [Test]
+ public void ReleasingAnUndrawnUnitIsFalse()
+ {
+ Assert.IsFalse(layer.Release(987654));
+ Assert.IsFalse(layer.Draws(987654));
+ Assert.IsTrue(layer.Draws(Israeli(0).Id));
+ layer.Hold(new[] { 987654 });
+ Assert.IsFalse(layer.Release(987654), "held but never drawn");
+ }
+
+ [Test]
+ public void HoldingATokenMidSlideStopsItWhereItIsDrawn()
+ {
+ var unit = Israeli(0);
+ Move(unit);
+ layer.Show(C, state);
+ var motion = MotionOf(unit.Id);
+ motion.Tick(UnitTokenMotion.Duration / 2f);
+ var drawn = DrawnAt(unit.Id);
+ layer.Hold(new[] { unit.Id });
+ Assert.IsTrue(motion.Held); Assert.IsFalse(motion.Moving);
+ Assert.Less((DrawnAt(unit.Id) - drawn).magnitude, 1f);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/UnitLayerHoldTests.cs.meta b/unity/Assets/Tests/EditMode/UnitLayerHoldTests.cs.meta
new file mode 100644
index 000000000..ce2a45eba
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitLayerHoldTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f5bc8fbc976d4d5b9a1f0bf806fa845f
\ No newline at end of file
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index 315215133..98777ff65 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -456,6 +456,11 @@
<ui:Label name="settings-tiltshift-label" text="Blur at the top and bottom of the map" class="settings-name" />
<ui:Button name="settings-tiltshift" class="settings-switch" />
</ui:VisualElement>
+ <!-- #2202: whether End turn plays the Arab forces' moves on the map (EnemyTurnPlayback). -->
+ <ui:VisualElement class="row settings-row">
+ <ui:Label name="settings-enemymoves-label" text="Show the Arab forces' moves on the map" class="settings-name" />
+ <ui:Button name="settings-enemymoves" class="settings-switch" />
+ </ui:VisualElement>
<!-- Graphics quality (GraphicsQuality): three buttons, the one that is set carries .settings-choice-selected. -->
<ui:VisualElement class="row settings-row">
<ui:Label name="settings-quality-label" text="Quality" class="settings-name" />
@@ -596,6 +601,20 @@
<Statecraft.Game.UI.UiFrame />
</ui:VisualElement>
</ui:VisualElement>
+ <!-- #2202: the footer while the Arab forces' moves play (EnemyPlaybackBar): the side's flag (SideFlag, put first in
+ the panel in code), its name, "Step n of m" and the beat's actions in words, and Skip. Not modal: only the panel
+ takes the pointer, and it takes no focus when it opens. After the report and the end screen, before the outcome
+ clip, so a clip is drawn over it. -->
+ <ui:VisualElement name="enemy-playback" class="enemy-playback" picking-mode="Ignore">
+ <ui:VisualElement name="enemy-playback-panel" class="panel enemy-playback-panel">
+ <ui:VisualElement name="enemy-playback-lines" class="enemy-playback-lines" picking-mode="Ignore">
+ <ui:Label name="enemy-playback-side" class="title enemy-playback-side" picking-mode="Ignore" />
+ <ui:Label name="enemy-playback-step" class="muted enemy-playback-step" picking-mode="Ignore" />
+ <ui:VisualElement name="enemy-playback-actions" class="enemy-playback-actions" picking-mode="Ignore" />
+ </ui:VisualElement>
+ <ui:Button name="enemy-playback-skip" class="enemy-playback-skip" />
+ </ui:VisualElement>
+ </ui:VisualElement>
<!-- The End Turn outcome clip (OutcomePresenter): the historical order the player gave, as a 3.5 s silent clip in the
middle, captioned as the order; a click, Enter or Space skips it, Esc skips them all. After the screens, so it
is drawn over them (an open screen is also closed when a clip starts); only the start screen and the toast come
diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.uss
index c52c04a5a..e9d325ff9 100644
--- a/unity/Assets/UI/Statecraft.uss
+++ b/unity/Assets/UI/Statecraft.uss
@@ -581,6 +581,24 @@ Button.settings-choice-selected { -unity-font-definition: url("project://databas
.end-screen-note { white-space: normal; margin-bottom: 14px; color: var(--ink-dim); }
.turn-report-actions { justify-content: flex-end; margin-top: 8px; flex-shrink: 0; }
.turn-report-actions > Button { margin-left: 8px; }
+/* #2202: the footer while the Arab forces' moves play (EnemyPlaybackBar). A layer along the window's foot that takes no
+ pointer, and a panel in its middle that does (Skip). The flag is large beside the side's name (owner, 8 November 2026:
+ "Flag + name (Recommended)"), 3:2 as the sourced cloths are near; it never scales past its box. Short-lived and drawn over
+ the info panel and the minimap where they meet it; on a narrow window it takes the width less the 16 px gutters
+ (EnemyPlaybackUiTests.TheSkipBarFitsAndMirrorsInHebrew). In Hebrew the row is mirrored, the flag at the right. */
+.enemy-playback { display: none; position: absolute; left: 16px; right: 16px; bottom: 16px; align-items: center; }
+.enemy-playback-panel { flex-direction: row; align-items: center; max-width: 720px; padding: 10px 14px; background-color: rgb(11, 18, 32); }
+.side-flag { width: 96px; height: 64px; flex-shrink: 0; margin-right: 14px; }
+.enemy-playback-lines { flex-grow: 1; flex-shrink: 1; min-width: 0; }
+.enemy-playback-side { white-space: normal; margin: 0; }
+.enemy-playback-step, .enemy-playback-action { white-space: normal; margin: 0; padding: 0; }
+.enemy-playback-skip { flex-shrink: 0; margin-left: 14px; white-space: normal; max-width: 220px; }
+.lang-he .enemy-playback-panel { flex-direction: row-reverse; }
+.lang-he .side-flag { margin-right: 0; margin-left: 14px; }
+.lang-he .enemy-playback-skip { margin-left: 0; margin-right: 14px; }
+.hud-three-row .side-flag { width: 60px; height: 40px; margin-right: 10px; }
+.lang-he.hud-three-row .side-flag { margin-right: 0; margin-left: 10px; }
+.hud-three-row .enemy-playback-skip { max-width: 120px; }
/* The encyclopedia's button that opens the opening advice again: under the list, never squeezed by it. */
.encyclopedia-opening { flex-shrink: 0; align-self: flex-start; min-height: 44px; margin-top: 8px; }
.lang-he .encyclopedia-opening { align-self: flex-end; }
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index 4d7c73f19..59381398f 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -147,7 +147,7 @@ advisor.page.truces.text: "Accept a truce on its card, and our attack orders are
advisor.page.capture.title: "Capturing a place"
advisor.page.capture.text: "A military unit that stops on an enemy-held place open to capture takes it at once; passing through does not. The capture dialog then lists its answers in a fixed order, each with what it changes at once or the reason it is refused. Raid and withdraw brings our units out and returns the place to enemy control; Occupy keeps one unit there for a set number of turns, at a Money cost each turn. The choice is yours; it takes effect at End turn, and until it is given, the units stay."
advisor.page.enemy_phase.title: "The enemy's turn"
-advisor.page.enemy_phase.text: "When you end the turn, every enemy unit receives its orders, by the same rules as ours. In the historical game each Arab force follows its own script toward its historical target. A unit off its script attacks a neighbouring position only when it has a clear edge, and otherwise fortifies. The enemy's attacks are fought as the turn resolves, and none comes inside a truce window."
+advisor.page.enemy_phase.text: "When you end the turn, every enemy unit receives its orders, by the same rules as ours. In the historical game each Arab force follows its own script toward its historical target. A unit off its script attacks a neighbouring position only when it has a clear edge, and otherwise fortifies. The enemy's attacks are fought as the turn resolves, and none comes inside a truce window. After you end the turn, the map plays their moves one at a time; Esc skips them, and Settings can turn them off."
# The Objectives screen (#1189): every objective in objectives.yaml, done or not, the player's date beside the historical
# one, and no score (owner, 20 October 2026). The objective card's wording (#380). {0} the player's date,
# {1} the historical date (objectives.open: {0}). The names are objectives.yaml's (#1208).
@@ -175,6 +175,8 @@ settings.title: "Settings"
settings.tiltshift: "Blur at the top and bottom of the map"
settings.on: "On"
settings.off: "Off"
+# #2202 (owner, 2 November 2026, Q6 a): whether End turn plays the Arab forces' moves on the map.
+settings.enemymoves: "Show the Arab forces' moves on the map"
# The WebGL companion switch (#1119); the Hebrew awaits native review.
settings.companion: "Screen reader companion"
settings.quality: "Quality"
@@ -546,6 +548,23 @@ report.enemy_move: "{0} moved to a new position"
report.enemy_attack: "{0} launched an attack on one of your units"
report.enemy_fortify: "{0} fortified its position"
report.unit: "Force {0}"
+# The footer while the Arab forces' moves play (#2202, EnemyPlaybackBar): the side whose turn it is, by its side id (owner,
+# 8 November 2026: "Flag + name (Recommended)"; playback.title for a side with no key), the beat's place in the turn
+# ({0} of {1}), the folded last beat, and Skip with its tooltip (the spoken text). The beat's actions reuse report.enemy_move
+# and report.enemy_attack.
+playback.title: "The Arab forces' turn"
+playback.turn_egypt: "Egypt's turn"
+playback.turn_jordan: "Jordan's turn"
+playback.turn_syria: "Syria's turn"
+playback.turn_iraq: "Iraq's turn"
+playback.turn_lebanon: "Lebanon's turn"
+playback.turn_ala: "The Arab Liberation Army's turn"
+playback.turn_local_arab_forces: "Local Arab forces' turn"
+# The owner, 9 November 2026: "\"Step n of m\" (Recommended)": an attack also advances the count.
+playback.step: "Step {0} of {1}"
+playback.folded: "The other moves at once"
+playback.skip: "Skip the Arab forces' moves"
+playback.skip_tip: "Skip the Arab forces' moves and return the map to your view (Esc)"
# The arms workshops' lines (#1701 A1; owner, 2 November 2026: "Yes, in the panel (Recommended)", whose option gave both
# lines' wording): {0} the city's name. A no-worker pause is on the Why screen only.
report.workshops: "Arms workshops"
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index 7064d1663..7e365d038 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -162,7 +162,10 @@ advisor.page.truces.text: "אם מקבלים הפוגה בכרטיס שלה, פ
advisor.page.capture.title: "כיבוש מקום"
advisor.page.capture.text: "יחידה צבאית שעוצרת במקום שבידי האויב ושאפשר לכבוש אותו, כובשת אותו מיד; מעבר דרכו אינו כובש אותו. אז חלון הכיבוש מציג את התשובות בסדר קבוע, ולצד כל אחת מה היא משנה מיד או למה היא נדחית. ״פשיטה ונסיגה״ מוציאה את הכוחות שלנו ומחזירה את המקום לשליטת האויב; ״שחרור״ משאיר שם יחידה אחת מספר קבוע של תורות, בעלות כספית בכל תור. הבחירה שלכם; היא נכנסת לתוקף בסיום התור, ועד שהיא ניתנת, הכוחות נשארים."
advisor.page.enemy_phase.title: "התור של האויב"
-advisor.page.enemy_phase.text: "בסיום התור כל יחידת אויב מקבלת את הפקודות שלה, לפי אותם כללים שחלים עלינו. במשחק ההיסטורי כל כוח ערבי פועל לפי תסריט משלו, לעבר היעד ההיסטורי שלו. יחידה שיצאה מהתסריט תוקפת עמדה סמוכה רק כשיש לה יתרון ברור, ואחרת היא מתבצרת. ההתקפות של האויב נערכות כשהתור מוכרע, ואף אחת מהן אינה מגיעה בזמן הפוגה."
+# #2202: the last sentence, on the playback, is the plan's proposed Hebrew (docs/superpowers/plans/2026-11-02-enemy-move-playback.md,
+# Strings), which the owner answered "Q8 yes" (2 November 2026). Agent-drafted; the page stays he_review: approved
+# (advisor-messages.yaml), so this sentence asks the native reviewer to confirm it (#564).
+advisor.page.enemy_phase.text: "בסיום התור כל יחידת אויב מקבלת את הפקודות שלה, לפי אותם כללים שחלים עלינו. במשחק ההיסטורי כל כוח ערבי פועל לפי תסריט משלו, לעבר היעד ההיסטורי שלו. יחידה שיצאה מהתסריט תוקפת עמדה סמוכה רק כשיש לה יתרון ברור, ואחרת היא מתבצרת. ההתקפות של האויב נערכות כשהתור מוכרע, ואף אחת מהן אינה מגיעה בזמן הפוגה. אחרי סיום התור המפה מציגה את המהלכים שלהם אחד אחרי השני; Esc מדלג עליהם, ואפשר לכבות אותם בהגדרות."
# The Objectives screen (#1189). Native review: owner, 3 Nov 2026 (HE batch 2: "approved").
objectives.title: "יעדים"
objectives.done: "הושלם ב־{0}; בהיסטוריה ב־{1}"
@@ -190,6 +193,9 @@ settings.title: "הגדרות"
settings.tiltshift: "טשטוש בחלק העליון ובחלק התחתון של המפה"
settings.on: "מופעל"
settings.off: "כבוי"
+# #2202: whether End turn plays the Arab forces' moves on the map. Agent-drafted Hebrew: native-review-pending (#564).
+# native-review-pending
+settings.enemymoves: "הצגת המהלכים של הכוחות הערביים במפה"
# The WebGL companion switch (#1119); native review: owner, 3 Nov 2026 (HE batch 1: "All fine as they are").
settings.companion: "מלווה לקוראי מסך"
# The graphics quality choice (#40). Adjectives in the feminine, agreeing with "איכות". Approved by Beri, a native
@@ -633,6 +639,32 @@ report.enemy_move: "{0} עבר לעמדה חדשה"
report.enemy_attack: "{0} פתח בהתקפה על אחת היחידות שלכם"
report.enemy_fortify: "{0} התבצר בעמדתו"
report.unit: "כוח {0}"
+# The footer while the Arab forces' moves play (#2202, EnemyPlaybackBar). "התור של X" needs no agreement with the side's
+# gender; the names are the map's (map.front_*, control.holder_ala). Agent-drafted Hebrew, all: native-review-pending (#564).
+# native-review-pending
+playback.title: "התור של הכוחות הערביים"
+# native-review-pending
+playback.turn_egypt: "התור של מצרים"
+# native-review-pending
+playback.turn_jordan: "התור של ירדן"
+# native-review-pending
+playback.turn_syria: "התור של סוריה"
+# native-review-pending
+playback.turn_iraq: "התור של עיראק"
+# native-review-pending
+playback.turn_lebanon: "התור של לבנון"
+# native-review-pending
+playback.turn_ala: "התור של צבא ההצלה"
+# native-review-pending
+playback.turn_local_arab_forces: "התור של הכוחות הערביים המקומיים"
+# native-review-pending
+playback.step: "שלב {0} מתוך {1}"
+# native-review-pending
+playback.folded: "שאר המהלכים בבת אחת"
+# native-review-pending
+playback.skip: "דילוג על המהלכים של הכוחות הערביים"
+# native-review-pending
+playback.skip_tip: "דילוג על המהלכים של הכוחות הערביים וחזרה לתצוגה שלך במפה (Esc)"
# The arms workshops' lines (#1701 A1), {0} the city's name, in brackets so no prefix joins a name that may fall back to
# English (HE-07); the Arms count as "Label: N" (HE-04). Agent-drafted Hebrew; native review: owner, 3 Nov 2026
# (HE batch 3: "Approve all as they are").