A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: stream existing Collection figures in the opt-in hex player, a one-hex WebGL prototype, stacked on #1153 (refs #18) (#1213)
pixelrenderai-hashe41b0b8f6fe9
diff --git a/changelog.d/hex-runtime-collection-20261020.md b/changelog.d/hex-runtime-collection-20261020.mdnew file mode 100644index 000000000..3d2395265--- /dev/null+++ b/changelog.d/hex-runtime-collection-20261020.md@@ -0,0 +1 @@+- Opt-in hex player: stream existing Collection figure aliases after the first frame, replace loading stand-ins without rebuilding terrain, and cancel refreshes on board teardown.diff --git a/docs/hex-tiles/runtime-figures.md b/docs/hex-tiles/runtime-figures.mdnew file mode 100644index 000000000..defacf758--- /dev/null+++ b/docs/hex-tiles/runtime-figures.md@@ -0,0 +1,50 @@+# Runtime Collection figures — prototype follow-up to #1153++- [x] **TASK-000** library check: reuse existing `CollectionCatalog` and `CollectionStream.Request`; the local library dashboard was unavailable. No new dependency or model.+- [x] Establish cause at #1153 head `06c80f37`: Collection aliases are Editor-only, the proto/null cache is sticky, and placed visuals do not refresh after arrival.+- [x] Reproduce capsules in an actual one-hex WebGL player.+- [x] Add a hex-only owner-scoped adapter, fallback and asynchronous refresh.+- [x] Check failure, repeated requests, teardown, reload, pose, scale and picking with focused native tests and player checks.+- [x] Obtain independent source/image review and matched actual-player screenshots.++## Boundary and behavior++The adapter uses `CollectionStream.Request(id, CollectionDetail, done)` and the existing alias/detail table. `UnitFigures`, `UnitFigureDetail`, `RuralLife`, controllers, catalog, bundle import and loader internals remain unchanged (#665/#667). No models move into Resources.++Pending or failed requests keep their Resources/stand-in fallback. Arrivals refresh only alias visuals; terrain and picking geometry retain their identity. A unit retains its latest distance, moving state, facing and formation. This is presentation code and does not read or change simulation state.++The adapter borrows streamed prefabs and cancels its callbacks on teardown/destruction. Generated fallback meshes/materials have local owners and are released on replacement/removal. Cancellation of shared downloads and unloading the game-wide cache remain the Collection API's responsibility; hex owners must not destroy those borrowed assets.++The first candidate player exposed unsupported non-Legacy `AnimationClip.SampleAnimation` calls. Both hex sampling paths now use one hex-local guard: Editor/Legacy sampling remains available; player non-Legacy figures keep their authored Animator/controller playback. Runtime stride sampling is not provided. This does not implement or change the maintainer's main-map animation work.++## Actual validation++Unity 6000.3.25f1, Development WebGL, local diagnostic scene using the production hex renderer. Camera, light, board, unit formation and default civilian alias match before/after. The scene is one bare hex with an authored eight-member squad, not the full game or a sim roster.++| Check | Result |+| --- | --- |+| Baseline #1153 player | Eight capsules and a civilian stand-in; 0 skins in all 3 phases; expected-8 assertion fails. |+| Lifetime regressions before fixes | 17/20 native cases pass; the 3 added cancellation/material-lifetime cases fail. |+| Final focused native run | 20/20 pass, exit 0, no C# warnings/errors. Covers request/failure/cancellation, synchronous arrival, pose/scale, picking and generated/borrowed ownership. |+| First candidate player | Real figures load, but runtime sampling errors appear; strengthened player checker fails. |+| Final default player | 8 skins/8 Animators plus textured far civilian in all 3 phases; no sampling errors or exceptions. |+| Near-placement variant | Existing C01 near civilian plus squad: 9 skins/9 Animators in all 3 phases; both sampling paths exercised without player errors. |+| Missing people bundle, final-build copy | Capsules remain; 0 skins, exactly 1 bundle warning, all 3 phases complete. Original build/bundles remain intact. |++Every final player case retains one terrain collider and the same pick `(0, 73.87, 0)`. Destroy/rebuild reports zero remaining board owners and zero retained generated meshes. These are focused ownership checks, not a full memory-profile claim. Separate-context Sol review inspected source, XML/logs and actual images. Baseline engine/browser WebGL capability warnings remain; the runs are not described as warning-free. Existing optimized-sampling messages remain in the Editor fixture; runtime errors are absent after the guard.++Non-Unity checks: .NET 10.0.401 sim **1,967 passed**, no warnings; policy tests **305 passed**; repository policy and rule-ID checks pass. Tools full sandbox run: **1,437 passed, 4 skipped**, with 10 failures/3 teardown errors from process/server and NuGet access restrictions; affected-file recheck with SDK/cache and required access: **154 passed**. Tools used Python 3.12.10 and available Rasterio 1.4.3 rather than pinned 1.5.2.++## Loading and performance limits++The existing people bundle is **6,309,797 bytes**, byte-identical before/after; successful cold profiles request it once through the runtime stream. All five existing Collection bundles total 15,321,910 bytes. The final Development probe has 19,027,122 data bytes and 123,203,755 Wasm bytes (baseline 19,013,856 / 123,193,808); the difference includes probe instrumentation. No new model payload is added.++Runtime timing logs were collected on a busy host and are excluded from performance comparisons. No frame-time improvement, WAN loading budget, full-map budget, zoom LOD, full locomotion or production acceptance is established. The alias table still selects near squads at every hex zoom. Arrivals coalesce per frame, but the aliased portion of an emitted layer is rebuilt when needed. A quiet production profile remains separate work.++## Live integration boundaries++Checked on 20 October 2026: [#1153](https://github.com/eyalgolan/statecraft-israel/pull/1153) remains draft at `06c80f37`, [#1131](https://github.com/eyalgolan/statecraft-israel/pull/1131) is `668580cf`, and main was checked at `107a45bb`. This follow-up starts at #1153; it does not validate the newly updated combined stack. The maintainer's painter/material, terrain and editor-reload fixes remain in #1131.++Read-only check of draft [#1205](https://github.com/eyalgolan/statecraft-israel/pull/1205), head `288c84117ca8c023ba21a6814c5d75b646b36ec6`, finds no overlapping production file or consumed API change. Its `UnitRoster.FromState`, strength-based 3/2/1 figures and moved-anchor/spot caches apply to the main-map `UnitLayer`/`UnitPlacer` path. This prototype builds authored `BoardHex.unit` entries through `HexUnitTypes` and `HexUnitMotion`; the adapter resolves supplied members and does not choose count or placement.++This neither replaces nor integrates #1205/#1186. The eight-member probe proves neither sim-roster membership nor strength changes/moved-token placement. Wiring that roster into the opt-in hex board remains separate work; combined behavior has not been run. The public Collection request API is unchanged by the inspected roster diff.diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.csindex f298b0070..aaf81999e 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.cs@@ -356,6 +356,7 @@ namespace Statecraft.HexTilespublic void Release(Object? o) { if (o != null && owned.Remove(o)) { if (Application.isPlaying) Destroy(o); else DestroyImmediate(o); } }/// <summary>Runs when the board is destroyed, last registered first (e.g. restoring the real map's heights).</summary>public void OnTeardown(Action undo) => teardown.Add(undo);+ internal void ForgetTeardown(Action undo) => teardown.Remove(undo);void OnDestroy() => Teardown();/// <summary>Restores everything the board changed, now and once (Destroy is deferred to the frame's end, so a@@ -385,8 +386,12 @@ namespace Statecraft.HexTilespublic static class HexBoardRenderer{public static Transform Emit(Transform root, IEnumerable<HexPlacement> placements, HexBoardAssets assets, string name = HexBoardBuilder.PiecesName)+ => Emit(root, placements, assets, name, null);++ internal static Transform Emit(Transform root, IEnumerable<HexPlacement> placements, HexBoardAssets assets, string name, Func<string, GameObject?>? prefabOf){var parent = new GameObject(name).transform; parent.SetParent(root, false);+ var streamed = new List<HexPlacement>();var groups = new Dictionary<Material, List<CombineInstance>>();var parts = new Dictionary<(string, Fit), HexModels.Part[]>();var tints = new Dictionary<Color, Material>();@@ -427,7 +432,9 @@ namespace Statecraft.HexTilesforeach (var p in placements){var id = HexModels.Resolve(p.Model, p.Position);- var prefab = p.StandIn == StandIn.Flat ? null : HexModels.Prefab(id);+ if (prefabOf == null && HexCollectionFigures.Available && p.StandIn != StandIn.Flat+ && HexModels.CollectionAlias(id, out _, out _)) { streamed.Add(p); continue; }+ var prefab = p.StandIn == StandIn.Flat ? null : (prefabOf ?? HexModels.Prefab)(id);if (prefab != null && HexModels.Skinned(prefab)){var go = Object.Instantiate(prefab, parent);@@ -459,6 +466,11 @@ namespace Statecraft.HexTilesgo.GetComponent<MeshFilter>().sharedMesh = mesh;go.GetComponent<MeshRenderer>().sharedMaterial = m;}+ if (streamed.Count > 0)+ {+ var figures = new GameObject("Hex streamed placements"); figures.transform.SetParent(parent, false);+ figures.AddComponent<HexStreamedPlacements>().Initialise(streamed, assets);+ }return parent;}}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexCollectionFigures.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexCollectionFigures.csnew file mode 100644index 000000000..2ae0dfd53--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexCollectionFigures.cs@@ -0,0 +1,47 @@+#nullable enable+using System;+using System.Collections.Generic;+using Statecraft.Game.Map.Collection;+using UnityEngine;++namespace Statecraft.HexTiles+{+ /// <summary>A hex visual owner's borrowed Collection prefabs. Requests only placed aliases, once per owner, through+ /// the game's public stream; pending/failed requests keep their Resources or stand-in fallback. No bundle is owned+ /// here. Dispose on immediate board teardown as well as destruction: a late answer must not revive an old board.</summary>+ internal sealed class HexCollectionFigures : IDisposable+ {+ internal static Action<string, CollectionDetail, Action<GameObject?>>? Source;+ static Action<string, CollectionDetail, Action<GameObject?>>? Requester =>+ Source ?? (Application.isPlaying ? CollectionStream.Request : (Action<string, CollectionDetail, Action<GameObject?>>?)null);+ internal static bool Available => HexModels.DrawCollectionFigures && Requester != null;++ readonly Dictionary<string, GameObject?> prefabs = new Dictionary<string, GameObject?>(StringComparer.Ordinal);+ readonly HashSet<string> answered = new HashSet<string>(StringComparer.Ordinal);+ Action? changed;+ bool disposed;++ internal HexCollectionFigures(Action changed) { this.changed = changed; }++ internal GameObject? Prefab(string id)+ {+ if (!Available || !HexModels.CollectionAlias(id, out var figure, out var detail)) return HexModels.Prefab(id);+ if (!disposed && !prefabs.ContainsKey(id))+ {+ prefabs[id] = null; // before Request: a source is allowed to answer synchronously+ var weak = new WeakReference<HexCollectionFigures>(this);+ Requester!(figure, detail, prefab =>+ {+ if (!weak.TryGetTarget(out var owner) || owner.disposed || !owner.answered.Add(id)) return;+ owner.prefabs[id] = prefab;+ if (prefab != null) owner.changed?.Invoke();+ });+ }+ if (prefabs.TryGetValue(id, out var loaded) && loaded != null) return loaded;+ // Bypass HexModels' Editor alias and its permanent miss/proto cache. Stream owns the real prefab.+ return Resources.Load<GameObject>(HexModels.PathOf(id));+ }++ public void Dispose() { disposed = true; changed = null; prefabs.Clear(); answered.Clear(); }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexCollectionFigures.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Core/HexCollectionFigures.cs.metanew file mode 100644index 000000000..114ce5fd0--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexCollectionFigures.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 472c0f965e2443f98d1c673ac497ad74diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.csindex 1e496fb95..47008bcef 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexModels.cs@@ -3,6 +3,7 @@ using System;using System.Collections.Generic;using System.Linq;using Statecraft.Game.Map.Kits;+using Statecraft.Game.Map.Collection;using UnityEngine;using Object = UnityEngine.Object;@@ -92,8 +93,8 @@ namespace Statecraft.HexTiles/// own decimations and show the ground through clothes, boots and faces, 2.7-6.5% of view rays; the Collection's/// are whole, HexUnitTests' report). The soldiers take the rigged near prefab (about 7,200 triangles, idle clip);/// the Tel Aviv townspeople the static far one (about 1,350, so the tile keeps its budget), but c01, whose far mesh- /// is holed (1.8%), the near one. A player keeps the proto prefab, then the stand-in: the Collection streams from- /// AssetBundles there, not Resources.</summary>+ /// is holed (1.8%), the near one. A player asks the same public Collection stream through HexCollectionFigures;+ /// the proto prefab or stand-in stays visible until it arrives.</summary>public static readonly (string id, string figure, string level)[] FigureAliases ={("proto:figure-palmach-scout-c12f-1948-v2", "figure-c12f-palmach-scout-v2", "near"),@@ -118,6 +119,15 @@ namespace Statecraft.HexTilesstatic readonly Dictionary<string, (string figure, string level)> figureOf =FigureAliases.ToDictionary(a => a.id, a => (a.figure, a.level), StringComparer.Ordinal);+ internal static bool CollectionAlias(string id, out string figure, out CollectionDetail detail)+ {+ if (figureOf.TryGetValue(id, out var alias))+ {+ figure = alias.figure; detail = alias.level == "far" ? CollectionDetail.Far : CollectionDetail.Near; return true;+ }+ figure = ""; detail = CollectionDetail.Far; return false;+ }+/// <summary>The Collection prefab a figure id draws in the editor (AssetDatabase), or null: in a player, without/// the Collection folder, or switched off.</summary>static GameObject? CollectionFigure(string id)@@ -263,13 +273,12 @@ namespace Statecraft.HexTilesreturn b;}- /// <summary>A renderer's world bounds. In the editor a skinned renderer without exposed bones (the Collection's near+ /// <summary>A renderer's world bounds. A skinned renderer without exposed bones (the Collection's near/// figures: their rig hides its transforms) reports nearly empty bounds until it has drawn, which scaled a squad to/// hundreds of kilometres: measure its baked vertices instead (BakeMesh already applies the scale, so only the/// renderer's position and rotation place them).</summary>static Bounds RendererBounds(Renderer r){-#if UNITY_EDITORif (r is SkinnedMeshRenderer s && s.sharedMesh != null && s.bones.Length == 0){var baked = new Mesh();@@ -287,7 +296,6 @@ namespace Statecraft.HexTiles}finally { Object.DestroyImmediate(baked); }}-#endifreturn r.bounds;}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexStandIns.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexStandIns.csindex 5ddac152d..2563d8fb3 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexStandIns.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexStandIns.cs@@ -59,14 +59,21 @@ namespace Statecraft.HexTilesreturn m;}- /// <summary>Poses an animated model at its idle's first frame (the first clip whose name has "idle", else the first).</summary>+ /// <summary>Samples the idle's first frame for authoring/Legacy clips; player non-Legacy rigs keep their authored Animator.</summary>public static void SampleIdle(Animator a){var clips = a.runtimeAnimatorController != null ? a.runtimeAnimatorController.animationClips : System.Array.Empty<AnimationClip>();AnimationClip? clip = null;foreach (var c in clips) if (c != null && c.name.IndexOf("idle", System.StringComparison.OrdinalIgnoreCase) >= 0) { clip = c; break; }if (clip == null && clips.Length > 0) clip = clips[0];- if (clip != null) clip.SampleAnimation(a.gameObject, 0f);+ if (clip != null) SampleClip(clip, a.gameObject, 0f);+ }++ // Collection's non-Legacy player rigs run their authored Animator controller. Manual sampling is reserved for+ // Editor previews and Legacy clips; sampling these streamed rigs in a player logs an error on every pose.+ internal static void SampleClip(AnimationClip clip, GameObject rig, float time)+ {+ if (Application.isEditor || clip.legacy) clip.SampleAnimation(rig, time);}}}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexStreamedPlacements.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexStreamedPlacements.csnew file mode 100644index 000000000..c58d11a63--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexStreamedPlacements.cs@@ -0,0 +1,65 @@+#nullable enable+using System;+using System.Collections.Generic;+using UnityEngine;++namespace Statecraft.HexTiles+{+ /// <summary>Only the aliased figures of one emitted layer. Coalesces arrivals into one refresh per frame; its own+ /// generated geometry can be replaced without rebuilding terrain, unrelated pieces or picking geometry.</summary>+ public sealed class HexStreamedPlacements : MonoBehaviour+ {+ HexCollectionFigures? models;+ IReadOnlyList<HexPlacement> placements = Array.Empty<HexPlacement>();+ HexBoardAssets? boardAssets;+ Transform? drawn;+ bool dirty, stopped;++ internal void Initialise(IReadOnlyList<HexPlacement> placements, HexBoardAssets assets)+ {+ this.placements = placements; boardAssets = assets;+ models = new HexCollectionFigures(() => dirty = true);+ assets.OnTeardown(Stop);+ Draw(); dirty = false;+ }++ void LateUpdate() => RefreshNow();+ internal void RefreshNow()+ {+ if (stopped || !dirty) return;+ dirty = false; Draw();+ }++ void Draw()+ {+ ReleaseDrawn();+ var holder = new GameObject("Hex figure geometry"); holder.transform.SetParent(transform, false);+ var assets = holder.AddComponent<HexBoardAssets>();+ drawn = holder.transform;+ HexBoardRenderer.Emit(drawn, placements, assets, "figures", models!.Prefab);+ }++ void ReleaseDrawn()+ {+ if (drawn == null) return;+ drawn.gameObject.SetActive(false);+ drawn.GetComponent<HexBoardAssets>().Teardown();+ if (Application.isPlaying) Destroy(drawn.gameObject); else DestroyImmediate(drawn.gameObject);+ drawn = null;+ }++ void Stop()+ {+ if (stopped) return;+ stopped = true; models?.Dispose(); models = null;+ placements = Array.Empty<HexPlacement>(); ReleaseDrawn();+ }++ void OnDestroy()+ {+ Stop();+ if (boardAssets != null) boardAssets.ForgetTeardown(Stop);+ boardAssets = null;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexStreamedPlacements.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Core/HexStreamedPlacements.cs.metanew file mode 100644index 000000000..2374fe972--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexStreamedPlacements.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 90f4b190369348c8a29d9f97ce659d00diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnitFigureRefresh.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnitFigureRefresh.csnew file mode 100644index 000000000..fbe170720--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnitFigureRefresh.cs@@ -0,0 +1,49 @@+#nullable enable+using System;+using UnityEngine;++namespace Statecraft.HexTiles+{+ /// <summary>The lifetime and deferred refresh of one hex unit's figures, including units whose motion is not ticked+ /// again after placement. Board teardown cancels before Unity's deferred destruction.</summary>+ public sealed class HexUnitFigureRefresh : MonoBehaviour+ {+ HexCollectionFigures? models;+ HexBoardAssets? boardAssets, localAssets;+ Action? refresh, teardown;+ bool dirty, stopped;+ internal void Dirty() { if (!stopped) dirty = true; }+ internal void Initialise(HexCollectionFigures models, Action refresh, HexBoardAssets local, HexBoardAssets? board)+ {+ this.models = models; this.refresh = refresh; localAssets = local; boardAssets = board;+ // The local owner cancels first, then releases this unit's generated assets. The board invokes that same+ // teardown; Stop itself never re-enters it. Collection prefabs/materials are borrowed, not owned here.+ local.OnTeardown(Stop);+ teardown = local.Teardown;+ if (board != null) board.OnTeardown(teardown);+ }+ void LateUpdate() => RefreshNow();+ internal void RefreshNow()+ {+ if (stopped || !dirty) return;+ dirty = false; refresh?.Invoke();+ }+ void Stop()+ {+ if (stopped) return;+ stopped = true; models?.Dispose(); models = null; refresh = null;+ gameObject.SetActive(false);+ }+ void OnDestroy()+ {+ Stop();+ if (boardAssets != null && teardown != null) boardAssets.ForgetTeardown(teardown);+ if (localAssets != null)+ {+ localAssets.ForgetTeardown(Stop);+ localAssets.Teardown();+ }+ boardAssets = null; localAssets = null; teardown = null;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnitFigureRefresh.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnitFigureRefresh.cs.metanew file mode 100644index 000000000..f87b6394f--- /dev/null+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnitFigureRefresh.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: e910fc811df1482f827ce8c3235c140cdiff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.csindex 1689f8be7..c7deb584a 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnits.cs@@ -83,12 +83,12 @@ namespace Statecraft.HexTiles}/// <summary>Moves a unit along a path of hex centres. Presentation only: the simulation decides the move (A to B);- /// this glides the group between centres, turning smoothly at each, and drives each member's clip by distance- /// travelled (stride-locked: the feet and wheels never slide), with the idle clip when it stands. Tripo clips are- /// exported in place (no root motion), so position is the code's and every move ends exactly on a hex centre.</summary>+ /// this glides the group between centres, turning smoothly at each. Editor/Legacy clips sample by distance; player+ /// non-Legacy figures keep their authored Animator playback (runtime stride sampling is not provided here). Tripo+ /// clips are exported in place, so position is the code's and every move ends exactly on a hex centre.</summary>public sealed class HexUnitMotion{- sealed class Live { public HexUnitMember M = null!; public GameObject Go = null!, Rig = null!; public AnimationClip? Move, Idle; public float Scale; }+ sealed class Live { public HexUnitMember M = null!; public GameObject Go = null!, Rig = null!; public AnimationClip? Move, Idle; public float Scale; public GameObject? Prefab; }readonly List<Live> live = new List<Live>();readonly List<Vector3> path;@@ -98,6 +98,12 @@ namespace Statecraft.HexTilespublic float ModelYaw = 0f;readonly float facing;+ readonly Transform visualParent;+ readonly HexCollectionFigures models;+ readonly HexBoardAssets? streamedAssets;+ Material? fallbackMaterial;+ float lastDistance;+ bool lastMoving;public IReadOnlyList<GameObject> Objects => live.Select(l => l.Go).ToList();/// <summary><paramref name="facingDeg"/> is the heading (degrees from north) of a unit standing on a one-hex path.</summary>@@ -106,39 +112,71 @@ namespace Statecraft.HexTilesthis.surface = surface; size = sizeM; facing = facingDeg;path = hexes.Select(h => HexGeometry.Centre(h.q, h.r, sizeM)).ToList();for (int i = 1; i < path.Count; i++) length += Vector3.Distance(path[i - 1], path[i]);- Material? fallbackMaterial = null;- foreach (var m in unit.Members)+ visualParent = parent;+ HexUnitFigureRefresh? refresh = null;+ if (HexCollectionFigures.Available && unit.Members.Any(m => HexModels.CollectionAlias(m.Model, out _, out _))){- var prefab = HexModels.Prefab(m.Model);- GameObject go;- if (prefab != null)- {- go = Object.Instantiate(prefab, parent);- }- else+ var holder = new GameObject("Hex streamed unit"); holder.transform.SetParent(parent, false);+ visualParent = holder.transform;+ streamedAssets = holder.AddComponent<HexBoardAssets>();+ refresh = holder.AddComponent<HexUnitFigureRefresh>();+ }+ models = new HexCollectionFigures(() => { if (refresh != null) refresh.Dirty(); });+ if (refresh != null) refresh.Initialise(models, RefreshFigures, streamedAssets!, parent.GetComponentInParent<HexBoardAssets>());+ foreach (var member in unit.Members)+ {+ var l = new Live { M = member }; live.Add(l);+ SetModel(l, models.Prefab(member.Model));+ }+ }++ void SetModel(Live l, GameObject? prefab)+ {+ GameObject go;+ if (prefab != null) go = Object.Instantiate(prefab, visualParent);+ else+ {+ go = GameObject.CreatePrimitive(l.M.StandIn == StandIn.Box ? PrimitiveType.Cube : PrimitiveType.Capsule);+ go.transform.SetParent(visualParent, false);+ Object.DestroyImmediate(go.GetComponent<Collider>());+ if (fallbackMaterial == null){- go = GameObject.CreatePrimitive(m.StandIn == StandIn.Box ? PrimitiveType.Cube : PrimitiveType.Capsule);- go.transform.SetParent(parent, false);- Object.DestroyImmediate(go.GetComponent<Collider>());- if (fallbackMaterial == null)- {- var assets = parent.GetComponentInParent<HexBoardAssets>() ?? parent.gameObject.AddComponent<HexBoardAssets>();- fallbackMaterial = assets.Own(HexMaterials.New(HexMaterials.Lit));- }- go.GetComponent<MeshRenderer>().sharedMaterial = fallbackMaterial;+ var assets = visualParent.GetComponentInParent<HexBoardAssets>() ?? visualParent.gameObject.AddComponent<HexBoardAssets>();+ fallbackMaterial = assets.Own(HexMaterials.New(HexMaterials.Lit));}- var b = HexModels.Bounds(go);- float scale = m.ByWidth ? m.HeightShare * sizeM / Mathf.Max(b.size.x, b.size.z) : m.HeightShare * sizeM / Mathf.Max(b.size.y, 1e-4f);- go.transform.localScale = Vector3.one * scale;- var animator = go.GetComponentInChildren<Animator>();- var clips = animator != null && animator.runtimeAnimatorController != null ? animator.runtimeAnimatorController.animationClips : Array.Empty<AnimationClip>();- live.Add(new Live- {- M = m, Go = go, Rig = animator != null ? animator.gameObject : go, Scale = scale,- Move = clips.FirstOrDefault(c => c.name.IndexOf("walk", StringComparison.OrdinalIgnoreCase) >= 0) ?? clips.FirstOrDefault(c => c.name.IndexOf("idle", StringComparison.OrdinalIgnoreCase) < 0),- Idle = clips.FirstOrDefault(c => c.name.IndexOf("idle", StringComparison.OrdinalIgnoreCase) >= 0),- });+ go.GetComponent<MeshRenderer>().sharedMaterial = fallbackMaterial;+ }+ var b = HexModels.Bounds(go);+ float scale = l.M.ByWidth ? l.M.HeightShare * size / Mathf.Max(b.size.x, b.size.z) : l.M.HeightShare * size / Mathf.Max(b.size.y, 1e-4f);+ go.transform.localScale = Vector3.one * scale;+ var animator = go.GetComponentInChildren<Animator>();+ var clips = animator != null && animator.runtimeAnimatorController != null ? animator.runtimeAnimatorController.animationClips : Array.Empty<AnimationClip>();+ if (l.Go != null)+ {+ l.Go.SetActive(false);+ if (Application.isPlaying) Object.Destroy(l.Go); else Object.DestroyImmediate(l.Go);+ }+ l.Prefab = prefab; l.Go = go; l.Rig = animator != null ? animator.gameObject : go; l.Scale = scale;+ l.Move = clips.FirstOrDefault(c => c.name.IndexOf("walk", StringComparison.OrdinalIgnoreCase) >= 0)+ ?? clips.FirstOrDefault(c => c.name.IndexOf("idle", StringComparison.OrdinalIgnoreCase) < 0);+ l.Idle = clips.FirstOrDefault(c => c.name.IndexOf("idle", StringComparison.OrdinalIgnoreCase) >= 0);+ }++ void RefreshFigures()+ {+ if (visualParent == null) return;+ foreach (var l in live)+ {+ if (l.Go == null) continue;+ var prefab = models.Prefab(l.M.Model);+ if (prefab != l.Prefab) SetModel(l, prefab);+ }+ if (fallbackMaterial != null && live.All(l => l.Go == null || l.Prefab != null))+ {+ streamedAssets?.Release(fallbackMaterial);+ fallbackMaterial = null;}+ Pose(lastDistance, lastMoving);}/// <summary>Total path length in metres.</summary>@@ -148,10 +186,12 @@ namespace Statecraft.HexTilespublic Vector3 Pose(float distance, bool moving){distance = Mathf.Clamp(distance, 0f, length);+ lastDistance = distance; lastMoving = moving;var (centre, heading) = Along(distance);var turn = Quaternion.Euler(0f, heading, 0f);foreach (var l in live){+ if (l.Go == null) continue;var p = centre + turn * new Vector3(l.M.Offset.x * size, 0f, l.M.Offset.y * size);p.y = surface.Height(p);// Board space: the units' parent sits in the board root (or at the origin for a board on its own).@@ -160,7 +200,7 @@ namespace Statecraft.HexTilesif (clip == null) continue;float cycle = l.M.CycleShare * size;float t = moving ? Mathf.Repeat(distance / cycle, 1f) * clip.length : 0f;- clip.SampleAnimation(l.Rig, t); // clips are authored on the Animator's object+ HexStandIns.SampleClip(clip, l.Rig, t); // clips are authored on the Animator's object}return new Vector3(centre.x, surface.Height(centre), centre.z);}diff --git a/unity/Assets/Tests/EditMode/HexCollectionFiguresTests.cs b/unity/Assets/Tests/EditMode/HexCollectionFiguresTests.csnew file mode 100644index 000000000..e44fec7b6--- /dev/null+++ b/unity/Assets/Tests/EditMode/HexCollectionFiguresTests.cs@@ -0,0 +1,189 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game.Map.Collection;+using Statecraft.HexTiles;+using UnityEngine;+using Object = UnityEngine.Object;++public sealed class HexCollectionFiguresTests+{+ const string Scout = "proto:figure-palmach-scout-c12f-1948-v2";+ readonly List<(string id, CollectionDetail detail, Action<GameObject?> done)> pending = new();+ readonly List<GameObject> objects = new();++ [SetUp] public void SetUp()+ {+ HexModels.Clear(); HexModels.DrawCollectionFigures = true;+ HexCollectionFigures.Source = (id, detail, done) => pending.Add((id, detail, done));+ }+ [TearDown] public void TearDown()+ {+ HexCollectionFigures.Source = null;+ foreach (var go in objects) if (go != null) Object.DestroyImmediate(go);+ objects.Clear(); pending.Clear(); HexModels.DrawCollectionFigures = true; HexModels.Clear();+ }+ GameObject Root() { var go = new GameObject("hex test root"); objects.Add(go); return go; }+ GameObject Model()+ {+ var go = GameObject.CreatePrimitive(PrimitiveType.Cube); go.name = "streamed-model";+ Object.DestroyImmediate(go.GetComponent<Collider>()); objects.Add(go); return go;+ }++ [Test] public void EveryAliasUsesTheCatalogDetailAndRequestsOnce()+ {+ int changes = 0;+ using var models = new HexCollectionFigures(() => changes++);+ foreach (var (id, figure, level) in HexModels.FigureAliases)+ {+ Assert.That(models.Prefab(id), Is.EqualTo(Resources.Load<GameObject>(HexModels.PathOf(id))), "fallback while pending");+ models.Prefab(id);+ var request = pending.Last();+ Assert.That(request.id, Is.EqualTo(figure));+ Assert.That(request.detail, Is.EqualTo(level == "far" ? CollectionDetail.Far : CollectionDetail.Near));+ Assert.That(CollectionCatalog.BundleOf(figure), Is.Not.Null);+ }+ Assert.That(pending.Count, Is.EqualTo(HexModels.FigureAliases.Length));+ var prefab = Model(); pending[0].done(prefab);+ Assert.That(models.Prefab(Scout), Is.SameAs(prefab));+ Assert.That(changes, Is.EqualTo(1));+ }++ [Test] public void FailureStaysOnFallbackAndDoesNotRequestEveryFrame()+ {+ using var models = new HexCollectionFigures(() => Assert.Fail("failure does not need a visual rebuild"));+ var before = models.Prefab(Scout); pending[0].done(null);+ for (int i = 0; i < 10; i++) Assert.That(models.Prefab(Scout), Is.EqualTo(before));+ Assert.That(pending.Count, Is.EqualTo(1));+ }++ [Test] public void DisposedAdapterIgnoresLateCallbackAndReloadUsesANewOwner()+ {+ int changes = 0;+ var first = new HexCollectionFigures(() => changes++); first.Prefab(Scout); first.Dispose(); first.Dispose();+ pending[0].done(Model());+ Assert.That(changes, Is.Zero);+ using var second = new HexCollectionFigures(() => changes++); second.Prefab(Scout);+ pending[1].done(Model()); Assert.That(changes, Is.EqualTo(1));+ }++ [Test] public void DisabledAndUnrelatedModelsDoNotStream()+ {+ using var models = new HexCollectionFigures(() => {});+ models.Prefab("missing:unrelated");+ HexModels.DrawCollectionFigures = false; models.Prefab(Scout);+ Assert.That(pending, Is.Empty);+ }++ [Test] public void UnitArrivalReplacesTheCapsulesAtTheLatestPoseWithoutColliders()+ {+ var root = Root(); root.AddComponent<HexBoardAssets>();+ var motion = new HexUnitMotion(HexUnitTypes.Squad("probe", Scout), new[] { (0, 0), (1, 0) }, new FlatSurface(), root.transform);+ motion.ModelYaw = 17f;+ motion.Pose(motion.Length * .7f, true);+ var before = motion.Objects.ToArray(); var positions = before.Select(g => g.transform.localPosition).ToArray();+ Assert.That(pending.Count, Is.EqualTo(1), "eight members share one runtime request");+ Assert.That(before.All(go => go.GetComponentInChildren<SkinnedMeshRenderer>() == null), Is.True, "pending figures use fallback, never Editor aliases");+ var rotations = before.Select(go => go.transform.localRotation).ToArray();+ pending[0].done(Model());+ root.GetComponentInChildren<HexUnitFigureRefresh>().RefreshNow();+ for (int i = 0; i < before.Length; i++)+ {+ Assert.That(motion.Objects[i], Is.Not.SameAs(before[i]));+ Assert.That(motion.Objects[i].transform.localPosition, Is.EqualTo(positions[i]));+ Assert.That(motion.Objects[i].transform.localRotation, Is.EqualTo(rotations[i]));+ Assert.That(motion.Objects[i].transform.localScale.y, Is.EqualTo(HexUnitScale.FigureHeight * HexScale.HexM).Within(.01f));+ }+ var refreshed = motion.Objects.ToArray();+ root.GetComponentInChildren<HexUnitFigureRefresh>().RefreshNow();+ Assert.That(motion.Objects, Is.EqualTo(refreshed), "second refresh is idempotent");+ Assert.That(root.GetComponentsInChildren<Collider>(), Is.Empty);+ }++ [Test] public void BoardRefreshKeepsUnrelatedPiecesAndReleasesOldGeneratedMeshes()+ {+ var root = Root(); var assets = root.AddComponent<HexBoardAssets>();+ HexPlacement Place(string id, StandIn shape, float x) => new(id, shape, Fit.Height, Color.white,+ Matrix4x4.TRS(new Vector3(x,0,0), Quaternion.identity, Vector3.one * 20), 0, 0);+ var layer = HexBoardRenderer.Emit(root.transform, new[] { Place(Scout, StandIn.Figure, 0), Place("", StandIn.Box, 100) }, assets);+ var staticPiece = layer.GetComponentsInChildren<MeshFilter>().First(f => !f.transform.IsChildOf(layer.GetComponentInChildren<HexStreamedPlacements>().transform));+ var refresh = layer.GetComponentInChildren<HexStreamedPlacements>();+ Assert.That(refresh, Is.Not.Null, "aliased placements have a runtime refresh owner");+ var oldMesh = refresh.GetComponentInChildren<MeshFilter>().sharedMesh;+ var oldMaterial = refresh.GetComponentInChildren<Renderer>().sharedMaterial;+ pending[0].done(Model()); refresh.RefreshNow();+ Assert.That(staticPiece != null && staticPiece.sharedMesh != null, Is.True);+ Assert.That(oldMesh == null, Is.True, "generated fallback mesh is released");+ Assert.That(oldMaterial == null, Is.True, "generated fallback material is released");+ Assert.That(refresh.GetComponentsInChildren<Renderer>(), Has.Length.EqualTo(1));+ Assert.That(root.GetComponentsInChildren<Collider>(), Is.Empty);+ }++ [Test] public void BoardTeardownStopsPendingRefreshBeforeDeferredDestruction()+ {+ var root = Root(); var assets = root.AddComponent<HexBoardAssets>();+ var p = new HexPlacement(Scout, StandIn.Figure, Fit.Height, Color.white, Matrix4x4.identity, 0, 0);+ HexBoardRenderer.Emit(root.transform, new[] { p }, assets);+ var refresh = root.GetComponentInChildren<HexStreamedPlacements>();+ assets.Teardown(); pending[0].done(Model()); refresh.RefreshNow();+ Assert.That(root.GetComponentsInChildren<Transform>(true).Any(t => t.name.StartsWith("streamed-model", StringComparison.Ordinal)), Is.False);+ }+ [Test] public void SynchronousArrivalIsAvailableImmediatelyAndDoesNotRequestAgain()+ {+ var prefab = Model(); int requests = 0;+ HexCollectionFigures.Source = (_, _, done) => { requests++; done(prefab); };+ using var models = new HexCollectionFigures(() => {});+ Assert.That(models.Prefab(Scout), Is.SameAs(prefab));+ Assert.That(models.Prefab(Scout), Is.SameAs(prefab));+ Assert.That(requests, Is.EqualTo(1));+ }++ [Test] public void UnitTeardownIgnoresLateArrival()+ {+ var root = Root(); var assets = root.AddComponent<HexBoardAssets>();+ var motion = new HexUnitMotion(HexUnitTypes.Squad("probe", Scout), new[] { (0, 0) }, new FlatSurface(), root.transform);+ var before = motion.Objects.ToArray();+ var owner = root.GetComponentInChildren<HexUnitFigureRefresh>();+ assets.Teardown(); pending[0].done(Model()); owner.RefreshNow();+ Assert.That(motion.Objects, Is.EqualTo(before));+ }++ [Test] public void StandaloneUnitOwnerAlsoCancelsOnTeardown()+ {+ var root = Root();+ var motion = new HexUnitMotion(HexUnitTypes.Squad("probe", Scout), new[] { (0, 0) }, new FlatSurface(), root.transform);+ var before = motion.Objects.ToArray();+ var owner = root.GetComponentInChildren<HexUnitFigureRefresh>();+ var assets = root.GetComponentInChildren<HexBoardAssets>();+ Assert.That(assets, Is.Not.Null);+ assets.Teardown(); pending[0].done(Model()); owner.RefreshNow();+ Assert.That(motion.Objects, Is.EqualTo(before));+ }++ [Test] public void UnitArrivalReleasesFallbackMaterialAndKeepsBorrowedPrefab()+ {+ var root = Root(); root.AddComponent<HexBoardAssets>();+ var motion = new HexUnitMotion(HexUnitTypes.Squad("probe", Scout), new[] { (0, 0) }, new FlatSurface(), root.transform);+ var fallback = motion.Objects[0].GetComponent<Renderer>().sharedMaterial;+ var prefab = Model(); var borrowed = prefab.GetComponent<Renderer>().sharedMaterial;+ pending[0].done(prefab); root.GetComponentInChildren<HexUnitFigureRefresh>().RefreshNow();+ Assert.That(fallback == null, Is.True, "the replaced capsule material is no longer needed");+ Object.DestroyImmediate(root);+ Assert.That(prefab != null && borrowed != null, Is.True, "the Collection owns the source assets");+ }++ [Test] public void RemovingAStreamedUnitReleasesFallbackBeforeTheBoardIsDestroyed()+ {+ var root = Root(); root.AddComponent<HexBoardAssets>();+ var motion = new HexUnitMotion(HexUnitTypes.Squad("probe", Scout), new[] { (0, 0) }, new FlatSurface(), root.transform);+ var fallback = motion.Objects[0].GetComponent<Renderer>().sharedMaterial;+ Object.DestroyImmediate(root.GetComponentInChildren<HexUnitFigureRefresh>().gameObject);+ Assert.That(root != null, Is.True);+ Assert.That(fallback == null, Is.True, "a removed unit cannot retain its fallback until board teardown");+ pending[0].done(Model());+ Assert.That(root!.GetComponentsInChildren<Renderer>(), Is.Empty);+ }++}diff --git a/unity/Assets/Tests/EditMode/HexCollectionFiguresTests.cs.meta b/unity/Assets/Tests/EditMode/HexCollectionFiguresTests.cs.metanew file mode 100644index 000000000..f6beb0bce--- /dev/null+++ b/unity/Assets/Tests/EditMode/HexCollectionFiguresTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 2ebe9cf2be3344a7bfc43f865aa4e34b