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.

Units: keep unchanged unit tokens on End turn, build only the changed ones (Refs #3055) (#3064)

Eyal Golan94df67ec10a3
diff --git a/changelog.d/3055-unitlayer-diff.md b/changelog.d/3055-unitlayer-diff.md
new file mode 100644
index 000000000..0c9bd2b95
--- /dev/null
+++ b/changelog.d/3055-unitlayer-diff.md
@@ -0,0 +1,5 @@
+### Changed
+- End turn no longer rebuilds every unit token on the map: a token whose unit did not change is kept as it is, and only
+ the tokens of units that moved, changed or were lost are built again or removed. A moved unit's token still slides from
+ its old place, a lost unit still raises its dust, and an attack or a hit on an unchanged token plays on untouched
+ (Refs #3055).
diff --git a/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs b/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs
index 7d718e15e..080fbcd14 100644
--- a/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitFigureResidency.cs
@@ -20,6 +20,10 @@ namespace Statecraft.Game.Map.Units
CollectionResidencyView? view;
readonly List<(string key, Vector3 at, float radius)> residencyAnchors = new List<(string, Vector3, float)>(1);
bool nearWanted, initialized, draws = true, retainFar;
+ /// <summary>A Far original answered while this holder was inactive (its layer hidden): it is put on when the holder is
+ /// active again (<see cref="OnEnable"/>). An inactive Animator cannot be posed or measured, so a swap then would draw
+ /// the figure unposed and at its unposed height (#3055).</summary>
+ GameObject? farOnEnable;
Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? acquire;
internal void Initialize(string model, CollectionResidencyPolicy policy,
Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? source, bool draw = true, bool retainFar = false,
@@ -52,7 +56,11 @@ namespace Statecraft.Game.Map.Units
UnitFigures.AnswerOwned(model, detail, prefab);
// A gate answer can synchronously rebuild the layer and destroy this draw:false prefetch holder.
if (!draws) return;
- if (detail == CollectionDetail.Far && prefab != null) UnitFigures.Swap(transform, model, prefab);
+ if (detail == CollectionDetail.Far && prefab != null)
+ {
+ if (gameObject.activeInHierarchy) UnitFigures.Swap(transform, model, prefab);
+ else farOnEnable = prefab;
+ }
if (detail == CollectionDetail.Near) UnitFigureDetail.Of(transform).OwnedArrived(model);
// A holder dressed below an inactive layer acquires its cached Far only when the layer is reactivated. Mark
// that handoff for UnitLayer.LateUpdate: never destroy the gate holder inside this answer/lifecycle stack.
@@ -122,6 +130,7 @@ namespace Statecraft.Game.Map.Units
}
IReadOnlyList<UnityEngine.Object> Clear()
{
+ farOnEnable = null; // a released Far is not put on later
var gone = new List<UnityEngine.Object>();
var holder = transform.Find(UnitFigures.ModelName);
if (holder != null)
@@ -145,6 +154,8 @@ namespace Statecraft.Game.Map.Units
if (retainFar) Refresh(false);
else if (!Application.isPlaying) Refresh(true);
}
+ var far = farOnEnable; farOnEnable = null;
+ if (far != null && draws && UnitFigures.Arrived(id)) UnitFigures.Swap(transform, id, far);
}
void OnDisable()
{
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
index 12472cd8b..0900815c8 100644
--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
@@ -37,9 +37,11 @@ namespace Statecraft.Game.Map.Units
Material paint = null!, ringTemplate = null!, badgePlate = null!, badgeGlyph = null!, hitPlate = null!, rim = null!;
readonly Dictionary<string, Material[]> flagCloth = new Dictionary<string, Material[]>(); // per side, made on first use
readonly Dictionary<string, Mesh> meshes = new Dictionary<string, Mesh>();
- /// <summary>The meshes built for the tokens drawn now (each base's draped top, lip and ring follow its own ground):
- /// destroyed when the tokens are rebuilt and with the layer, so no roster change leaks them (review of #559, M1).</summary>
- readonly List<Mesh> tokenMeshes = new List<Mesh>();
+ /// <summary>The meshes built for each token drawn now (each base's draped top, lip and ring follow its own ground), in
+ /// the order of <see cref="badges"/>: destroyed when that token is built again or dropped and with the layer, so no
+ /// roster change leaks them (review of #559, M1).</summary>
+ readonly List<List<Mesh>> tokenMeshes = new List<List<Mesh>>();
+ List<Mesh>? buildingMeshes; // the token being built's
List<UnitToken>? roster;
readonly Dictionary<string, UnitFigureResidency> figurePrefetch = new Dictionary<string, UnitFigureResidency>();
readonly HashSet<string> wantedFigurePrefetch = new HashSet<string>(StringComparer.Ordinal);
@@ -133,6 +135,9 @@ namespace Statecraft.Game.Map.Units
/// <summary>The figures' and flags' share of their scale now (<see cref="UnitShowcase.ZoomScale"/>, #2430): only the game
/// camera sets it, as it turns them, and only a new value touches them.</summary>
float zoomShown = 1f;
+ /// <summary>A rebuild built new figures at their own scale beside kept ones at <see cref="zoomShown"/>: the next
+ /// <see cref="FaceCamera"/> scales them all.</summary>
+ bool rescaleDue;
/// <summary>A badge sits this share of its token's base radius behind the trio, seen from the camera, and
/// <see cref="BadgeAsideM"/> to the side away from its flag's pole on screen (a compact token's pole cannot stand
/// further out than its base's edge).</summary>
@@ -163,6 +168,11 @@ namespace Statecraft.Game.Map.Units
readonly List<UnitTokenMotion?> motions = new List<UnitTokenMotion?>();
/// <summary>Each token's sim unit (-1 for a row with no sim unit), in the order of <see cref="badges"/>.</summary>
readonly List<int> drawnSims = new List<int>();
+ /// <summary>Each token's root, what it was built from and its kit-tree hole (if any), in the order of
+ /// <see cref="badges"/>: a rebuild keeps a token whose unit did not change (#3055).</summary>
+ readonly List<Transform> tokenRoots = new List<Transform>();
+ List<PlacedToken> drawnPlaced = new List<PlacedToken>();
+ readonly List<(Vector2 centre, float radius)?> tokenHoles = new List<(Vector2, float)?>();
/// <summary>The sim units whose tokens the last rebuild dropped, and where each was drawn then: a destroyed unit's
/// dust rises there (<see cref="PlayDestroyed"/>).</summary>
readonly Dictionary<int, Vector3> gone = new Dictionary<int, Vector3>();
@@ -327,8 +337,8 @@ namespace Statecraft.Game.Map.Units
if (turn) turnedFor = yaw;
var turning = Quaternion.Euler(0f, turnedFor ?? 0f, 0f); // as the figures stand now (yaw 0 until first turned)
float zoom = cam == Camera.main ? UnitShowcase.ZoomScale(Kits.TownModelLayer.ViewDistance(cam)) : zoomShown;
- bool rescale = zoom != zoomShown;
- zoomShown = zoom;
+ bool rescale = rescaleDue || zoom != zoomShown;
+ zoomShown = zoom; rescaleDue = false;
for (int i = 0; i < badges.Count; i++)
{
var b = badges[i]; if (b == null) continue;
@@ -412,9 +422,10 @@ namespace Statecraft.Game.Map.Units
}
/// <summary>Draws the units for <paramref name="state"/> (read only). Rebuilds the tokens only when the roster
- /// changed; returns true when it did. A selected unit that is no longer drawn is deselected. A moved unit's token
- /// slides from where it was drawn (<see cref="AnimateMoves"/>) unless <paramref name="slide"/> is false: another game
- /// (New Game) reuses the sim ids, so its tokens are drawn where they stand.</summary>
+ /// changed, and then builds or destroys only the tokens that changed (#3055); returns true when it did. A selected
+ /// unit that is no longer drawn is deselected. A moved unit's token slides from where it was drawn
+ /// (<see cref="AnimateMoves"/>) unless <paramref name="slide"/> is false: another game (New Game) reuses the sim ids,
+ /// so its tokens are all built again, 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
@@ -714,15 +725,21 @@ namespace Statecraft.Game.Map.Units
return mats;
}
- /// <summary>Takes a mesh built for one token: freed with the tokens (<see cref="FreeTokenMeshes"/>).</summary>
- Mesh TokenMesh(Mesh m) { tokenMeshes.Add(UnitPlinth.Upload(m)); return m; }
+ /// <summary>Takes a mesh built for the token being built: freed with that token (<see cref="FreeMeshes"/>).</summary>
+ Mesh TokenMesh(Mesh m) { buildingMeshes!.Add(UnitPlinth.Upload(m)); return m; }
void FreeTokenMeshes()
{
- foreach (var m in tokenMeshes) if (m != null) { if (Application.isPlaying) Destroy(m); else DestroyImmediate(m); }
+ foreach (var list in tokenMeshes) FreeMeshes(list);
tokenMeshes.Clear();
}
+ static void FreeMeshes(List<Mesh> list)
+ {
+ foreach (var m in list) if (m != null) { if (Application.isPlaying) Destroy(m); else DestroyImmediate(m); }
+ list.Clear();
+ }
+
static UnitModels.Headgear Hat(string headgear) => headgear switch
{
UnitData.SlouchHat => UnitModels.Headgear.SlouchHat,
@@ -751,20 +768,48 @@ namespace Statecraft.Game.Map.Units
// Where each unit was drawn, so a unit the rebuild drops (destroyed, as the turn's lines say) raises its dust there.
gone.Clear();
for (int i = 0; i < drawnSims.Count && i < trios.Count; i++) if (drawnSims[i] >= 0) gone[drawnSims[i]] = DrawnAt(i);
+ // #3055: each unit drawn before keeps its token's root (same key as the hand-over above). A token built from the
+ // same unit, anchor, spot and looks (PlacedToken's equality) is kept whole; any other is built again on its root.
+ // Another game (slide false) reuses the sim ids, so nothing of the old one is kept.
+ var was = new Dictionary<(int sim, string row), int>();
+ int drawn = Math.Min(Math.Min(tokenRoots.Count, drawnSims.Count), Math.Min(Math.Min(drawnPlaced.Count, motions.Count), tokenMeshes.Count));
+ for (int i = 0; slide && i < drawn; i++)
+ if (tokenRoots[i] != null && !was.ContainsKey(Key(drawnSims[i], tokenRoots[i].name))) was[Key(drawnSims[i], tokenRoots[i].name)] = i;
+ var from = new int[placed.Count]; // the old token each one is drawn on, or -1 for a new one
+ var same = new bool[placed.Count]; // and whether it is kept whole
+ var taken = new bool[tokenRoots.Count];
+ for (int j = 0; j < placed.Count; j++)
+ {
+ from[j] = -1;
+ if (!was.TryGetValue(Key(placed[j].Token.StateUnit?.Id ?? -1, placed[j].Token.Unit.Id), out int i) || taken[i]) continue;
+ taken[i] = true; from[j] = i;
+ same[j] = drawnPlaced[i].Equals(placed[j]) && (motions[i] != null) == AnimateMoves;
+ }
var outgoing = new List<GameObject>();
- for (int i = tokensRoot.childCount - 1; i >= 0; i--)
+ void Retire(GameObject old)
{
- var old = tokensRoot.GetChild(i).gameObject;
// Roster holders retain Far through deactivation and release it only on destruction. Deactivate before
// deferred Destroy so these outgoing holders are never considered a live prefetch handoff target.
old.SetActive(false);
old.transform.SetParent(null);
outgoing.Add(old);
}
+ var kept = new HashSet<Transform>();
+ for (int i = 0; i < taken.Length; i++) if (taken[i]) kept.Add(tokenRoots[i]); else if (i < tokenMeshes.Count) FreeMeshes(tokenMeshes[i]);
+ for (int i = tokensRoot.childCount - 1; i >= 0; i--)
+ if (!kept.Contains(tokensRoot.GetChild(i))) Retire(tokensRoot.GetChild(i).gameObject);
+ for (int j = 0; j < placed.Count; j++)
+ {
+ if (from[j] < 0 || same[j]) continue;
+ var root = tokenRoots[from[j]];
+ FreeMeshes(tokenMeshes[from[j]]);
+ for (int c = root.childCount - 1; c >= 0; c--) Retire(root.GetChild(c).gameObject);
+ if (motions[from[j]] is UnitTokenMotion m && m != null) m.Restart(); // as a new token's (the hand-over follows)
+ }
// The outgoing holders are destroyed only after the new tokens have acquired their models, as the player's
// deferred Destroy already does: an edit-mode rebuild must not drop a model's last owner in between and ask the
// source again for a request still in flight (or release an arrived model) only to re-acquire it.
- try { BuildTokens(drawnAt, firing, hits); }
+ try { BuildTokens(drawnAt, firing, hits, from, same); }
finally { foreach (var old in outgoing) if (Application.isPlaying) Destroy(old); else DestroyImmediate(old); }
foreach (int id in drawnSims) gone.Remove(id);
}
@@ -777,24 +822,47 @@ namespace Statecraft.Game.Map.Units
void BuildTokens(IReadOnlyDictionary<(int sim, string row), Vector3> drawnAt,
IReadOnlyDictionary<(int sim, string row), float> firing,
- IReadOnlyDictionary<(int sim, string row), (float left, float delay)> hits)
+ IReadOnlyDictionary<(int sim, string row), (float left, float delay)> hits, int[] from, bool[] same)
{
pickVersion++;
- FreeTokenMeshes();
+ // What each old token holds, by its old index (from): a kept token takes its own entries over unchanged.
+ var oldRoots = tokenRoots.ToArray(); var oldMeshes = tokenMeshes.ToArray(); var oldHoles = tokenHoles.ToArray();
+ var oldMotions = motions.ToArray(); var oldBadges = badges.ToArray(); var oldHomes = badgeHomes.ToArray();
+ var oldTrios = trios.ToArray(); var oldBoxes = keepClear.ToArray();
+ tokenRoots.Clear(); tokenMeshes.Clear(); tokenHoles.Clear();
motions.Clear();
drawnSims.Clear();
foreach (var p in placed) drawnSims.Add(p.Token.StateUnit?.Id ?? -1);
+ drawnPlaced = placed;
badges.Clear(); badgeHomes.Clear(); facedFor = null;
- trios.Clear(); turnedFor = null; zoomShown = 1f; // the new figures stand as at yaw 0, at their own scale
+ // The new figures stand as at yaw 0 and at their own scale, the kept ones as the last camera turned them: FaceCamera
+ // turns and scales them all.
+ trios.Clear(); turnedFor = null; rescaleDue = true;
treeHoles.Clear();
keepClear = new List<Bounds[]>(); // a new list, so the labels see the change
keepClearSpare = new List<Bounds[]>(); slid = false; // and a spare no label pass has seen
float hex = map.Hexes.hex_size_km * 1000f;
- foreach (var p in placed)
+ for (int n = 0; n < placed.Count; n++)
{
+ var p = placed[n];
var t = p.Token;
- var go = new GameObject(t.Unit.Id);
- go.transform.SetParent(tokensRoot, false);
+ if (same[n])
+ {
+ int i = from[n];
+ tokenRoots.Add(oldRoots[i]); tokenMeshes.Add(oldMeshes[i]); tokenHoles.Add(oldHoles[i]);
+ if (oldHoles[i] is { } kept) treeHoles.Add(kept);
+ badges.Add(oldBadges[i]); badgeHomes.Add(oldHomes[i]); trios.Add(oldTrios[i]); keepClear.Add(oldBoxes[i]);
+ continue;
+ }
+ GameObject go;
+ if (from[n] >= 0) { go = oldRoots[from[n]].gameObject; go.name = t.Unit.Id; } // its old pieces are gone (Rebuild)
+ else
+ {
+ go = new GameObject(t.Unit.Id);
+ go.transform.SetParent(tokensRoot, false);
+ }
+ buildingMeshes = new List<Mesh>();
+ (Vector2 centre, float radius)? hole = null;
var centre = Centre(p.Spot);
var foot = centre; // where the badge's height is measured from
float top, plinth = 0f;
@@ -807,7 +875,7 @@ namespace Statecraft.Game.Map.Units
float k = UnitShowcase.DrawSpread * hex * Spread(p.Spot);
plinth = UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3), k));
foot.y = UnitPlinth.Build(map, go.transform, centre, plinth, t.Unit.Side, TokenMesh, MeshFor, paint, rim, FlagCloth);
- treeHoles.Add((new Vector2(centre.x, centre.z), plinth * UnitPlinth.RimOuter));
+ hole = (new Vector2(centre.x, centre.z), plinth * UnitPlinth.RimOuter);
var offsets = UnitShowcase.FigureOffsets(t.Figures);
float highest = foot.y; // the badge clears the highest figure (on a slope the uphill one stands higher)
bool israel = t.Unit.Side == UnitData.Israel;
@@ -865,7 +933,7 @@ namespace Statecraft.Game.Map.Units
if (!t.Flying && StillBox(go.transform, null, Array.Empty<MeshFilter>()) is Bounds aircraft)
{
var flat = new Vector2(aircraft.center.x, aircraft.center.z);
- treeHoles.Add((flat, new Vector2(aircraft.extents.x, aircraft.extents.z).magnitude));
+ hole = (flat, new Vector2(aircraft.extents.x, aircraft.extents.z).magnitude);
}
top = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;
break;
@@ -915,14 +983,26 @@ namespace Statecraft.Game.Map.Units
if (pieces is Bounds s) { if (flag != null) s.Encapsulate(WorldBox(flag)); foreach (var m in meshes) if (m != null && m.sharedMesh != null) s.Encapsulate(WorldBox(m)); pieces = s; }
keepClear.Add(pieces is Bounds p2 ? new[] { new Bounds(badge.transform.position, Vector3.one * UnitBadge.SizeM), p2 }
: new[] { new Bounds(badge.transform.position, Vector3.one * UnitBadge.SizeM) });
+ tokenHoles.Add(hole);
+ if (hole is { } h) treeHoles.Add(h);
+ tokenMeshes.Add(buildingMeshes);
+ tokenRoots.Add(go.transform);
}
+ buildingMeshes = null;
+ for (int n = 0; n < tokenRoots.Count; n++) tokenRoots[n].SetSiblingIndex(n); // the children in the tokens' order
FaceCamera(Camera.main); // the badges as the main camera sees them until a render turns them
HideTrees();
for (int i = 0; i < placed.Count; i++)
{
- if (!AnimateMoves) { motions.Add(null); continue; }
- var token = tokensRoot.GetChild(i);
- var motion = token.gameObject.AddComponent<UnitTokenMotion>();
+ if (same[i]) { motions.Add(oldMotions[from[i]]); continue; } // a kept token's move, attack or hit plays on
+ var token = tokenRoots[i];
+ var reused = from[i] >= 0 ? oldMotions[from[i]] : null;
+ if (!AnimateMoves)
+ {
+ if (reused != null) { if (Application.isPlaying) Destroy(reused); else DestroyImmediate(reused); }
+ motions.Add(null); continue;
+ }
+ var motion = reused != null ? reused : token.gameObject.AddComponent<UnitTokenMotion>();
motion.enabled = false; // runs only while it moves or attacks
motion.SimId = placed[i].Token.StateUnit?.Id ?? -1;
motion.Changed = () => { pickVersion++; facedFor = null; slid = true; }; // FaceCamera sets the badge and the boxes where the token is drawn
diff --git a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
index 5dc62d2b3..72eeeaa2d 100644
--- a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
@@ -305,6 +305,17 @@ namespace Statecraft.Game.Map.Units
if (Moving || Attacking || Reacting || HitPending) Snap();
}
+ /// <summary>Puts the component back as a new one, for a token UnitLayer builds again on the same root (#3055): what
+ /// the old pieces were playing stops as when a token is torn down (<see cref="OnDisable"/>), and UnitLayer then hands
+ /// the move, the attack and the hit on, as it does to a new token. Call it with the old pieces already taken off.</summary>
+ internal void Restart()
+ {
+ if (Moving || Attacking || Reacting || HitPending) Snap();
+ held = false; from = moveOffset = Vector3.zero; transform.position = Vector3.zero;
+ posed = 0; fired = false;
+ enabled = false;
+ }
+
void Snap()
{
bool moved = transform.position != Vector3.zero;
diff --git a/unity/Assets/Tests/EditMode/CombatEffectsTests.cs b/unity/Assets/Tests/EditMode/CombatEffectsTests.cs
index b325d4604..bbadcc0c9 100644
--- a/unity/Assets/Tests/EditMode/CombatEffectsTests.cs
+++ b/unity/Assets/Tests/EditMode/CombatEffectsTests.cs
@@ -426,10 +426,11 @@ public class CombatEffectsTests
finally { Object.DestroyImmediate(map.gameObject); }
}
- /// <summary>A rebuild while a defender shakes from a hit (another unit destroyed by the same attack) hands the shake to
- /// the defender's new token, as an attack is handed on (ContinueAttack): the survivor never moved, so it does not slide
- /// from where the shake had put it and raises no march dust, and the shake plays on to its end. A hit still on its way
- /// (HitPending) is handed on too.</summary>
+ /// <summary>A rebuild while a defender shakes from a hit (another unit destroyed by the same attack) leaves the shake
+ /// playing: the survivors did not change, so their tokens are kept (#3055) with their motions. The survivor never moved,
+ /// so it does not slide from where the shake had put it and raises no march dust, and the shake plays on to its end. A
+ /// hit still on its way (HitPending) still lands. AChangedDefenderMidShakeKeepsItsShakeOnItsRebuiltToken covers the hand-over
+ /// to a token built again.</summary>
[Test]
public void ARebuildMidShakeKeepsTheShakeAndSlidesNothing()
{
@@ -451,11 +452,11 @@ public class CombatEffectsTests
Assert.IsTrue(MotionOf(waiting).HitPending, "fixture: the second still waits for the hit");
s.Units.Remove(lost.Id);
- Assert.IsTrue(layer.Show(C, s), "fixture: the roster changed, so the tokens are rebuilt");
+ Assert.IsTrue(layer.Show(C, s), "fixture: the roster changed, so the layer rebuilds (the survivors are kept, #3055)");
var after = MotionOf(shaking);
- Assert.IsFalse(after.Moving, "the shaking defender never moved, so its new token does not slide");
- Assert.IsTrue(after.Reacting, "its shake goes on in the new token");
- Assert.IsTrue(MotionOf(waiting).HitPending, "and the hit still on its way to the second lands on its new token");
+ Assert.IsFalse(after.Moving, "the shaking defender never moved, so its kept token does not slide");
+ Assert.IsTrue(after.Reacting, "its shake goes on in its kept token");
+ Assert.IsTrue(MotionOf(waiting).HitPending, "and the hit still on its way to the second lands on its kept token");
int dust = layer.Combat!.MoveDust!.Busy;
for (int i = 0; i < 30; i++) { after.Tick(0.05f); MotionOf(waiting).Tick(0.05f); }
Assert.AreEqual(dust, layer.Combat.MoveDust.Busy, "no march dust from a unit that did not march");
@@ -464,4 +465,55 @@ public class CombatEffectsTests
}
finally { Object.DestroyImmediate(map.gameObject); }
}
+
+ /// <summary>#3055: a defender whose own strength changes mid-shake is built again on the same root. Its motion is reset
+ /// (UnitTokenMotion.Restart) and handed the shake it was showing (ContinueHit with the time left), not a new one from
+ /// the start; a second defender whose strength changes while its hit is on its way gets the rest of that delay.</summary>
+ [Test]
+ public void AChangedDefenderMidShakeKeepsItsShakeOnItsRebuiltToken()
+ {
+ var map = BuildMap();
+ try
+ {
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ layer.AnimateMoves = true;
+ layer.Show(C, s);
+ var drawn = s.Units.Values.Where(u => u.Side == Movement.PlayerSide && layer.Tokens.Any(t => t.Token.StateUnit?.Id == u.Id)).Take(2).ToArray();
+ Assert.AreEqual(2, drawn.Length, "fixture: two player units are drawn");
+ UnitTokenMotion MotionOf(Unit u) => layer.GetComponentsInChildren<UnitTokenMotion>().Single(m => m.SimId == u.Id);
+ var (shaking, waiting) = (drawn[0], drawn[1]);
+ Assert.IsTrue(layer.PlayDefenderHit(new CombatHit(shaking.Q, shaking.R, false, true, 1, new[] { shaking.Id, waiting.Id })));
+ var shaker = MotionOf(shaking); var waiter = MotionOf(waiting);
+ float shook = 0.1f;
+ shaker.Tick(CombatBursts.VolleyS + shook); // the hit landed `shook` s ago: that much of the shake has played
+ Assert.IsTrue(shaker.Reacting, "fixture: the first defender shakes");
+ float half = 0.5f * CombatBursts.VolleyS;
+ waiter.Tick(half); // half of the second's delay has passed
+ Assert.IsTrue(waiter.HitPending, "fixture: the second still waits for the hit");
+ var roots = (shaker.gameObject, waiter.gameObject);
+
+ foreach (var u in drawn)
+ {
+ Assert.Greater(u.Strength, 1, $"fixture: unit {u.Id} can lose strength");
+ s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength - 1, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);
+ }
+ Assert.IsTrue(layer.Show(C, s), "fixture: the strengths change the roster");
+ Assert.AreSame(roots.Item1, MotionOf(shaking).gameObject, "the shaking defender's root is kept");
+ Assert.AreSame(roots.Item2, MotionOf(waiting).gameObject, "and the waiting one's");
+ Assert.AreSame(shaker, MotionOf(shaking), "with its motion, reset and handed on");
+ Assert.IsFalse(shaker.Moving, "it never moved, so it does not slide");
+ Assert.IsTrue(shaker.Reacting, "its shake goes on on the rebuilt pieces");
+ Assert.IsTrue(waiter.HitPending, "the second's hit is still on its way");
+
+ float left = UnitTokenMotion.HitDurationS - shook;
+ shaker.Tick(left + 0.01f);
+ Assert.IsFalse(shaker.Reacting, "the shake ends when its time left runs out, not a full shake later");
+ Assert.AreEqual(Vector3.zero, shaker.transform.position, "back on its spot");
+ waiter.Tick(CombatBursts.VolleyS - half + 0.01f);
+ Assert.IsFalse(waiter.HitPending, "the hit lands after the rest of its delay, not a full delay later");
+ Assert.IsTrue(waiter.Reacting, "and the second defender shakes");
+ }
+ finally { Object.DestroyImmediate(map.gameObject); }
+ }
}
diff --git a/unity/Assets/Tests/EditMode/UnitLayerKeepTests.cs b/unity/Assets/Tests/EditMode/UnitLayerKeepTests.cs
new file mode 100644
index 000000000..d5919253d
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitLayerKeepTests.cs
@@ -0,0 +1,287 @@
+#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>#3055 (A of #2905): a rebuild keeps the GameObjects of the tokens that did not change and builds or destroys only
+/// the ones that did. #2957's ?turnlog probe put the full rebuild at 25, 145 and 330 ms of End turns 1, 2 and 5 in WebGL. A
+/// moved unit keeps its token's root and still slides from where it was drawn; a destroyed unit still raises its dust; a
+/// changed unit's pieces are built again; another game (New Game, a load) builds every token afresh. Presentation only.</summary>
+public class UnitLayerKeepTests
+{
+ 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");
+
+ Transform TokensRoot => layer.transform.Find("Tokens");
+
+ (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})");
+ }
+
+ /// <summary>Moves the unit one hex, every other field as it was (HomeCity and Strength are part of the token's identity).</summary>
+ 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, u.HomeCity, u.Full, u.CombatXp, u.Records);
+ }
+
+ void SetStrength(Unit unit, int strength)
+ {
+ var u = state.Units[unit.Id];
+ state.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);
+ }
+
+ 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);
+
+ int IndexOf(int simId) => layer.Tokens.Select((t, k) => (t, k)).Single(x => x.t.Token.StateUnit?.Id == simId).k;
+
+ /// <summary>The token root drawing <paramref name="simId"/>: the Tokens child in the order of <see cref="UnitLayer.Tokens"/>.</summary>
+ GameObject TokenOf(int simId) => TokensRoot.GetChild(IndexOf(simId)).gameObject;
+
+ UnitTokenMotion MotionOf(int simId) => TokenOf(simId).GetComponent<UnitTokenMotion>();
+
+ Vector2 SpotOf(int simId)
+ {
+ var spot = layer.Tokens[IndexOf(simId)].Spot;
+ return new Vector2((float)spot.X, (float)spot.Z);
+ }
+
+ static Vector2 XZ(Vector3 v) => new Vector2(v.x, v.z);
+
+ Vector2 DrawnAt(int simId) => SpotOf(simId) + XZ(MotionOf(simId).transform.position);
+
+ static (int sim, string row) KeyOf(PlacedToken p) => p.Token.StateUnit is Unit u ? (u.Id, "") : (-1, p.Token.Unit.Id);
+
+ /// <summary>Each drawn token's root and what it was built from, by its sim unit (else its row).</summary>
+ Dictionary<(int sim, string row), (GameObject go, PlacedToken placed)> Drawn()
+ {
+ var drawn = new Dictionary<(int, string), (GameObject, PlacedToken)>();
+ for (int i = 0; i < layer.Tokens.Count; i++) drawn[KeyOf(layer.Tokens[i])] = (TokensRoot.GetChild(i).gameObject, layer.Tokens[i]);
+ return drawn;
+ }
+
+ void AssertTokensInOrder(string what)
+ {
+ Assert.AreEqual(layer.Tokens.Count, TokensRoot.childCount, $"{what}: one root per drawn token, no leftover");
+ for (int i = 0; i < layer.Tokens.Count; i++)
+ Assert.AreEqual(layer.Tokens[i].Token.Unit.Id, TokensRoot.GetChild(i).name, $"{what}: the roots stand in the tokens' order ({i})");
+ }
+
+ /// <summary>(a) A moved unit keeps its token's root (the same instance, with its motion) and still slides from the old
+ /// place to the new one, as #2176's slide did on a new token.</summary>
+ [Test]
+ public void AMovedUnitKeepsItsTokenAndSlidesFromTheOldHex()
+ {
+ var unit = Israeli(0);
+ var before = TokenOf(unit.Id); var motion = before.GetComponent<UnitTokenMotion>();
+ var old = SpotOf(unit.Id);
+ layer.Select(layer.Tokens[IndexOf(unit.Id)].Token.Unit.Id);
+ Move(unit);
+ Assert.IsTrue(layer.Show(C, state), "fixture: the move changes the roster");
+ Assert.Greater((SpotOf(unit.Id) - old).magnitude, 1000f, "fixture: a real move, not a nudge");
+ Assert.AreSame(before, TokenOf(unit.Id), "the moved unit keeps its token's GameObject");
+ Assert.AreSame(motion, MotionOf(unit.Id), "and its motion");
+ Assert.IsTrue(motion.Moving && motion.enabled, "it slides");
+ Assert.Less((DrawnAt(unit.Id) - old).magnitude, 1f, "from where it was drawn");
+ Assert.AreEqual(layer.Tokens[IndexOf(unit.Id)].Token.Unit.Id, layer.Selected, "the selection follows the unit");
+ AssertTokensInOrder("after the move");
+ motion.Tick(UnitTokenMotion.Duration);
+ Assert.AreEqual(Vector3.zero, motion.transform.position, "it ends on its new spot");
+ Assert.Less((XZ(motion.GroundHome) - SpotOf(unit.Id)).magnitude, 1f, "its home is the new spot");
+ }
+
+ /// <summary>(b) A destroyed unit still raises its dust where its token stood, once, and the tokens of the units that
+ /// survived are the same GameObjects as before.</summary>
+ [Test]
+ public void ADestroyedUnitStillRaisesItsDustAndTheOthersKeepTheirTokens()
+ {
+ Assert.IsNotNull(layer.Combat, "fixture: the flipbooks ship");
+ var lost = Israeli(1); var was = SpotOf(lost.Id);
+ var drawn = Drawn();
+ state.Units.Remove(lost.Id);
+ Assert.IsTrue(layer.Show(C, state), "fixture: the roster changed");
+ Assert.IsFalse(layer.Draws(lost.Id));
+ Assert.IsTrue(drawn[(lost.Id, "")].go == null, "the lost unit's token is destroyed");
+ for (int i = 0; i < layer.Tokens.Count; i++)
+ Assert.AreSame(drawn[KeyOf(layer.Tokens[i])].go, TokensRoot.GetChild(i).gameObject, $"{layer.Tokens[i].Token.Unit.Id} keeps its token");
+ AssertTokensInOrder("after the loss");
+ Assert.IsTrue(layer.PlayDestroyed(lost.Id), "the lost unit raises its dust");
+ var dust = layer.Combat!.Dust!;
+ Assert.AreEqual(CombatBursts.DeathPuffs, dust.Busy);
+ for (int i = 0; i < dust.Capacity; i++)
+ if (!double.IsNaN(dust.StartOf(i)))
+ Assert.LessOrEqual((XZ(dust.Foot(i)) - was).magnitude, CombatBursts.SpreadShare * CombatBursts.DeathDustM + 1f, "where its token stood");
+ Assert.IsFalse(layer.PlayDestroyed(lost.Id), "once");
+ Assert.IsFalse(layer.PlayDestroyed(Israeli(0).Id), "a unit still drawn raises none");
+ }
+
+ /// <summary>(c) Across a real End turn (Simulation.Step) and a move, every token whose unit, anchor, spot and looks did
+ /// not change is the same GameObject, with its base's meshes alive.</summary>
+ [Test]
+ public void AnUnchangedUnitKeepsItsTokenAcrossAnEndTurn()
+ {
+ var drawn = Drawn();
+ var bases = drawn.ToDictionary(kv => kv.Key, kv => kv.Value.go.transform.Find(UnitPlinth.PlinthName)?.GetComponent<MeshFilter>()?.sharedMesh);
+ state = Simulation.Step(C, state, Array.Empty<Command>()).State.Clone();
+ Move(Israeli(0));
+ Assert.IsTrue(layer.Show(C, state), "fixture: the End turn and the move change the roster");
+ int kept = 0;
+ for (int i = 0; i < layer.Tokens.Count; i++)
+ {
+ var p = layer.Tokens[i];
+ if (!drawn.TryGetValue(KeyOf(p), out var was) || !was.placed.Equals(p)) continue;
+ Assert.AreSame(was.go, TokensRoot.GetChild(i).gameObject, $"{p.Token.Unit.Id}: unchanged, so the same token");
+ var mesh = TokensRoot.GetChild(i).Find(UnitPlinth.PlinthName)?.GetComponent<MeshFilter>()?.sharedMesh;
+ if (bases[KeyOf(p)] != null)
+ {
+ Assert.IsTrue(mesh != null, $"{p.Token.Unit.Id}: its base's mesh is not freed");
+ Assert.AreSame(bases[KeyOf(p)], mesh, $"{p.Token.Unit.Id}: nor built again");
+ }
+ kept++;
+ }
+ Assert.Greater(kept, 3, "fixture: most tokens did not change (not a vacuous pass)");
+ AssertTokensInOrder("after the End turn");
+ }
+
+ /// <summary>(d) A changed attribute the token is built from (the strength, which sets the figures) builds that token's
+ /// pieces again on its own root: the old pieces are destroyed, the new ones match the new strength.</summary>
+ [Test]
+ public void AChangedStrengthBuildsThatTokensPiecesAgain()
+ {
+ var unit = Israeli(0);
+ var root = TokenOf(unit.Id);
+ int Figures() => root.transform.Cast<Transform>().Count(t => t.name.StartsWith("Rifleman"));
+ int full = C.StartingForces[unit.Id].Strength;
+ int want = UnitRoster.FiguresForStrength(1, full);
+ Assert.AreNotEqual(want, Figures(), "fixture: strength 1 draws fewer figures");
+ var oldFigure = root.transform.Cast<Transform>().First(t => t.name.StartsWith("Rifleman"));
+ var other = TokenOf(Israeli(1).Id);
+ SetStrength(unit, 1);
+ Assert.IsTrue(layer.Show(C, state), "fixture: the strength changes the roster");
+ Assert.AreSame(root, TokenOf(unit.Id), "the root is kept");
+ Assert.IsTrue(oldFigure == null, "its old pieces are destroyed");
+ Assert.AreEqual(want, Figures(), "its pieces are built for the new strength");
+ Assert.AreEqual(1, root.transform.Cast<Transform>().Count(t => t.name == UnitPlinth.PlinthName), "one base, not the old one beside the new");
+ Assert.AreEqual(1, root.transform.Cast<Transform>().Count(t => t.name == "Badge"), "one badge");
+ Assert.AreSame(other, TokenOf(Israeli(1).Id), "another unit's token is untouched");
+ Assert.IsFalse(MotionOf(unit.Id).Moving, "a strength change does not slide");
+ AssertTokensInOrder("after the strength change");
+ }
+
+ /// <summary>Behaviour change of #3055: an attack waiting for a figure that can play it keeps its started/missed cue
+ /// through another unit's rebuild. Before, every rebuild deactivated every token, whose motion's OnDisable snapped and
+ /// dropped the cue, so UnitAttackPresenter heard "missed" at once. Now the attacker's token is kept, the cue stays
+ /// pending, and it reports "started" when a figure can play the take, as on a token no rebuild touched.</summary>
+ [Test]
+ public void AWaitingAttacksCueSurvivesAnotherUnitsRebuildAndStartsAsNormal()
+ {
+ var controller = new UnityEditor.Animations.AnimatorController(); controller.AddLayer("Base Layer");
+ var fire = new AnimationClip { name = "fire" };
+ fire.SetCurve("", typeof(Transform), "localScale.x", AnimationCurve.Linear(0f, 1f, 1f, 1f));
+ try
+ {
+ var machine = controller.layers[0].stateMachine;
+ machine.defaultState = machine.AddState("idle"); machine.AddState("attack").motion = fire;
+ var attacker = Israeli(0);
+ var figure = new GameObject("test figure").transform; figure.SetParent(TokenOf(attacker.Id).transform, false);
+ var animator = figure.gameObject.AddComponent<Animator>(); animator.runtimeAnimatorController = controller;
+ animator.Rebind(); animator.Update(0f);
+ animator.enabled = false; // no figure can play the take yet: the attack waits (UnitTokenMotion.AttackWaitS)
+ var motion = MotionOf(attacker.Id);
+ int started = 0, missed = 0;
+ layer.PlayAttack(attacker.Id, () => started++, () => missed++);
+ Assert.IsTrue(motion.Attacking, "fixture: the attack waits for a figure");
+ Assert.AreEqual((0, 0), (started, missed), "fixture: a waiting attack has made neither decision");
+
+ Move(Israeli(1));
+ Assert.IsTrue(layer.Show(C, state), "fixture: another unit's move rebuilds the layer");
+ Assert.AreEqual((0, 0), (started, missed), "its cue is still pending, not missed");
+ Assert.AreSame(motion, MotionOf(attacker.Id), "the attacker's token is kept");
+ Assert.IsTrue(motion.Attacking, "and its attack still waits");
+
+ animator.enabled = true; motion.RefreshPose(); // a figure turns near within the wait
+ Assert.AreEqual((1, 0), (started, missed), "the cue starts with the take, as normal");
+ }
+ finally { Object.DestroyImmediate(controller); Object.DestroyImmediate(fire); }
+ }
+
+ /// <summary>Another game (New Game or a load: SimBridge.Replace, Show with slide false) reuses the sim ids, so no token of
+ /// the old game is kept, even where the new game's unit looks the same.</summary>
+ [Test]
+ public void AnotherGameBuildsEveryTokenAfresh()
+ {
+ var before = new HashSet<GameObject>(TokensRoot.Cast<Transform>().Select(t => t.gameObject));
+ Move(Israeli(0));
+ layer.Show(C, state);
+ before.UnionWith(TokensRoot.Cast<Transform>().Select(t => t.gameObject));
+ Assert.IsTrue(layer.Show(C, NewGame(), slide: false), "fixture: the new game's roster differs");
+ foreach (Transform t in TokensRoot) Assert.IsFalse(before.Contains(t.gameObject), $"{t.name}: a new token for the new game");
+ AssertTokensInOrder("after another game");
+ }
+
+ /// <summary>A rebuild made from far draws the kept and the new tokens' figures at the same far scale (#2430): a new
+ /// token's figures are built at their own scale beside kept ones already grown.</summary>
+ [Test]
+ public void ARebuildFromFarDrawsKeptAndNewFiguresAtTheFarScale()
+ {
+ var cam = Camera.main; Assert.IsNotNull(cam, "the default scene's camera");
+ var unit = Israeli(0);
+ var centre = TokenOf(unit.Id).transform.Find(UnitPlinth.PlinthName).position; centre.y = 0f;
+ cam!.fieldOfView = CameraRig.Fov; cam.aspect = 16f / 9f; cam.farClipPlane = 1000000f;
+ cam.transform.rotation = Quaternion.Euler(CameraRig.Pitch, 0f, 0f);
+ cam.transform.position = centre - cam.transform.forward * 60000f;
+ float zoom = UnitShowcase.ZoomScale(Statecraft.Game.Map.Kits.TownModelLayer.ViewDistance(cam));
+ Assert.Greater(zoom, 1.05f, "fixture: a far view grows the figures");
+ layer.FaceCamera(cam);
+ Move(unit);
+ Assert.IsTrue(layer.Show(C, state), "fixture: the move changes the roster");
+ layer.FaceCamera(cam);
+ var figures = TokensRoot.GetComponentsInChildren<Transform>().Where(t => t.name.StartsWith("Rifleman")).ToList();
+ Assert.Greater(figures.Count, 10, "fixture: the figures of the opening day");
+ foreach (var f in figures)
+ Assert.AreEqual(zoom * UnitShowcase.FigureScale, f.localScale.x, 1e-3f * zoom * UnitShowcase.FigureScale, $"{f.parent.name}/{f.name} at the far scale");
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/UnitLayerKeepTests.cs.meta b/unity/Assets/Tests/EditMode/UnitLayerKeepTests.cs.meta
new file mode 100644
index 000000000..7e884369b
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitLayerKeepTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 05582ce5702740c0b92d683be67aed0d
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs b/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs
index fcb9f2710..9c79255b1 100644
--- a/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs
+++ b/unity/Assets/Tests/EditMode/UnitRosterResidencyTests.cs
@@ -203,6 +203,10 @@ public class UnitRosterResidencyTests
var holders = Tokens(layer).GetComponentsInChildren<UnitFigureResidency>(true);
Assert.Greater(layer.FigurePrefetchCount, NoOwners,
"reactivation marks the handoff without destroying a child inside the activation callback");
+ // A Far answered under the inactive layer is put on once the holder is shown again: an inactive Animator can be
+ // neither posed nor measured, and Unity warns at the try (#3055, the warning NoUnexpectedReceived catches).
+ foreach (var holder in holders.Where(h => UnitFigures.Arrived(h.ModelId)))
+ Assert.IsTrue(UnitFigures.Dressed(holder.transform), holder.name + ": its answered Far is put on when shown");
LogAssert.NoUnexpectedReceived();
layer.FlushPrefetchRetirement();
Assert.AreEqual(NoOwners, layer.FigurePrefetchCount,
diff --git a/unity/Assets/Tests/EditMode/UnitsFromStateTests.cs b/unity/Assets/Tests/EditMode/UnitsFromStateTests.cs
index dfc8a2b58..c62fcb0c0 100644
--- a/unity/Assets/Tests/EditMode/UnitsFromStateTests.cs
+++ b/unity/Assets/Tests/EditMode/UnitsFromStateTests.cs
@@ -465,8 +465,9 @@ public class UnitsFromStateTests
finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
}
- /// <summary>Another unit's order rebuilds every token (review of #2177, 3): a unit whose figures were firing goes on
- /// firing on its new token, from where it was.</summary>
+ /// <summary>Another unit's order must not cut an attack short (review of #2177, 3). Since #3055 it leaves the firing
+ /// unit's token as it was, so the take plays on untouched. A change to the firing unit itself (its strength) builds its
+ /// pieces again, and the new figures go on firing from where the take was.</summary>
[Test]
public void ARebuildForAnotherUnitsOrderKeepsAnAttackPlaying()
{
@@ -488,12 +489,30 @@ public class UnitsFromStateTests
var animator = figure.gameObject.AddComponent<Animator>(); animator.runtimeAnimatorController = controller;
animator.Rebind(); animator.Update(0f);
Assert.IsTrue(layer.PlayAttack(israel[0].Id), "fixture: the token plays the attack");
+ // An Animator takes a Play at its next update, which only enters the state (at time 0) and does not move its clock
+ // (as AnAttackPlaysTheBakedTakeOnTheFigure): that update first, then 0.3 s on the figure's clock, as on the motion's.
+ animator.Update(0f);
+ Assert.AreEqual(UnitFigureMotion.Attack, animator.GetCurrentAnimatorStateInfo(0).fullPathHash, "fixture: the figure fires");
TokenOf(map, firing).GetComponent<UnitTokenMotion>().Tick(0.3f);
+ var attacker = TokenOf(map, firing).GetComponent<UnitTokenMotion>();
+ animator.Update(0.3f); // 0.3 s into the 1 s take
+ float taken = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
+ Assert.AreEqual(0.3f, taken, 0.02f, "fixture: the take has run 0.3 s");
var to = FreeNeighbour(s, israel[1].Q, israel[1].R);
MoveTo(s, israel[1].Id, to.q, to.r);
Assert.IsTrue(layer.Show(C, s), "another unit's move rebuilds the tokens");
+ Assert.AreSame(attacker, TokenOf(map, firing).GetComponent<UnitTokenMotion>(), "the firing unit's token is kept (#3055)");
+ Assert.IsTrue(attacker.Attacking, "the attack goes on");
+ animator.Update(0f);
+ Assert.AreEqual(UnitFigureMotion.Attack, animator.GetCurrentAnimatorStateInfo(0).fullPathHash, "its figure still fires");
+ Assert.AreEqual(taken, animator.GetCurrentAnimatorStateInfo(0).normalizedTime, 0.02f, "where it was, not restarted");
+ // The firing unit's own strength changes: its pieces are built again on its root, and the attack is handed on.
+ var u0 = s.Units[israel[0].Id];
+ s.Units[u0.Id] = new Unit(u0.Id, u0.Type, u0.Q, u0.R, u0.Service, u0.Side, u0.Strength - 1, u0.Order, u0.OrderTarget, u0.HomeCity, u0.Full, u0.CombatXp, u0.Records);
+ Assert.IsTrue(layer.Show(C, s), "the strength change rebuilds the firing token");
var successor = TokenOf(map, firing).GetComponent<UnitTokenMotion>();
- Assert.IsTrue(successor.Attacking, "the attack goes on on the new token");
+ Assert.IsTrue(figure == null, "fixture: the old pieces are gone");
+ Assert.IsTrue(successor.Attacking, "the attack goes on on the rebuilt token");
// Its near figure turns on a frame later (UnitFigureDetail) and plays on from 0.3 s, not from the start
// (review of #2176, items 3 and 4).
var near = new GameObject("test figure").transform; near.SetParent(TokenOf(map, firing), false);