A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Statecraft.Game.Boot;
using UnityEngine;
namespace Statecraft.Game.Map
{
/// <summary>Builds the whole map: terrain, hexes, 1948 settlements, railways and roads, camera. Materials are editor-made assets
/// (M0 correction 1). Build is idempotent: it destroys what the previous Build made first. In play mode the Boot
/// component calls Build(inputs) once the inputs are loaded (fetched on WebGL); editor tools call Build().</summary>
public sealed class MapScene : MonoBehaviour
{
[SerializeField] Material terrainMaterial, markerMaterial, selectionMaterial, seaMaterial, frameMaterial;
/// <summary>The art spike's procedural settlement kits and trees (Kit.mat, Tree.mat: Statecraft/Kit). Optional: without
/// them the map keeps the placeholder marker boxes.</summary>
[SerializeField] Material kitMaterial, treeMaterial;
/// <summary>Tal Heuberger's building models the towns draw up close (issue #659; Kits.TownModels.SetPath). The map scene
/// leaves it empty (#1273): in a player the 18 originals stream after the first frame (TownModelLayer), so they are not
/// in the first download. In edit mode, where the stream never runs, the editor reads the list from the AssetDatabase
/// (<see cref="TownModelsForBuild"/>). With one missing the towns keep their kits at every zoom.</summary>
[SerializeField] Kits.TownModelSet townModels;
#if UNITY_EDITOR
bool townModelsConfigured;
#endif
/// <summary>The terrain water's mesh, baked (MapTexturePaths.WaterMesh, issue #195). Optional: without it, or when it
/// is for other heights, the map derives the mesh at load (about 90 ms at the boot budget's CPU throttling).</summary>
[SerializeField] TextAsset terrainWaterMesh;
public GeoFrame Frame { get; private set; }
/// <summary>hexes.json as the last Build read it (bounds, hex size, biomes).</summary>
public HexFile Hexes { get; private set; }
public Terrain Terrain { get; private set; }
public Material MarkerMaterial => markerMaterial;
/// <summary>Kit.mat (null without the kits), for the transit camps' kits PlacementLayer builds when a camp is placed.</summary>
public Material KitMaterial => kitMaterial;
/// <summary>The heightmap's lowest elevation (m) as the last Build read it: a KitGround built after the map needs it.</summary>
public float ElevMinM { get; private set; }
/// <summary>The settlements the last Build placed (settlements_1948.yaml), for the UI's map labels and, through
/// SettlementsFor, the info panel's names. Read only: the markers, the kits, the labels and GameRoot share this one
/// list and its objects; nothing may write to them.</summary>
public IReadOnlyList<Settlement> Settlements { get; private set; } = new List<Settlement>();
string settlementsYamlRead; // null before a build
/// <summary>The settlements for <paramref name="yaml"/>: the list the last Build parsed when it read the same text
/// (issue #321: GameRoot parsed the file again at boot only for the names), else a parse of it.</summary>
public IReadOnlyList<Settlement> SettlementsFor(string yaml) =>
settlementsYamlRead != null && string.Equals(yaml, settlementsYamlRead, StringComparison.Ordinal)
? Settlements : SettlementPlacer.Parse(yaml);
/// <summary>The 1948 localities the last Build drew with the kits (content/map/localities_1948.yaml; empty without the
/// kits), for the map labels: 1948 name, today's name. Presentation only, never in the sim.</summary>
public IReadOnlyList<Kits.Localities.Place> Localities { get; private set; } = new List<Kits.Localities.Place>();
/// <summary>Every kit's ground after the last Build (world x, z centre; radius; owner id): the 25 game settlements', the
/// 1948 localities' and the Bedouin camps' footprints (empty without the kits). Anything placed on the map "off the
/// towns" (unit tokens: review I5) keeps clear of these, not of the 25 settlements alone.</summary>
public IReadOnlyList<(Vector2 centre, float radius, string id)> KitFootprints => KitStats?.Footprints ?? (IReadOnlyList<(Vector2, float, string)>)System.Array.Empty<(Vector2, float, string)>();
/// <summary>#2876: the major cities' kit blocks after the last Build (KitLayer.Stats.MajorCityBlocks; empty without the
/// kits): what those cities draw from 40 km out, in place of their building models, which they draw below the close
/// switch (owner, 7 November 2026, "Tal's models close (Recommended)").</summary>
public IReadOnlyList<Kits.SettlementKits.Placed> MajorCityBlocks => KitStats?.MajorCityBlocks ?? (IReadOnlyList<Kits.SettlementKits.Placed>)System.Array.Empty<Kits.SettlementKits.Placed>();
/// <summary>The game date the routes were last shown at (RouteLayer.ShowAt), so a rebuild draws them as at that date;
/// null before the game has set one (the routes then show as at the game's start).</summary>
public DateTime? RouteDate { get; set; }
/// <summary>In the GDD loop, which segments of each corridor route are built (RouteLayer.ShowAt, #792), so a rebuild
/// draws them as the game left them; null outside the GDD loop (the routes then show by date).</summary>
public IReadOnlyDictionary<string, IReadOnlyList<bool>> RouteSegmentsBuilt { get; set; }
/// <summary>Who held which hex on a date (content/map/control_hexes_1948_49.yaml with the map editor's control
/// overrides), as Build read it, or null without the file: GameRoot draws the borders from it, and the road vehicles
/// (issue #725) stand only on ground Israel held. Display only.</summary>
public Control1948 Control { get; set; }
/// <summary>The map editor's overrides as the last Build applied them (content/map/overrides.yaml, #1009).</summary>
public Statecraft.Sim.MapOverrides Overrides { get; private set; } = Statecraft.Sim.MapOverrides.Parse(null);
/// <summary>Where a named location is drawn: its sourced point (<paramref name="lon"/>, <paramref name="lat"/>), or the
/// centre of the hex the map editor moved it to (Overrides), so its label and its logical hex agree.</summary>
public (double lon, double lat) LocationPoint(string id, double lon, double lat)
{
if (Hexes == null || !Overrides.TryLocation(id, out var q, out var r)) return (lon, lat);
foreach (var h in Hexes.hexes) if (h.q == q && h.r == r) return (h.lon, h.lat);
return (lon, lat);
}
/// <summary>The selected hex's outline: a child of the terrain (so a rebuild destroys it).</summary>
public const string SelectionName = "HexSelection";
/// <summary>The frame round the map and the table beyond it (issue #36): a child of the terrain (so a rebuild destroys it).</summary>
public const string FrameName = "MapFrame";
/// <summary>The water inside the map: a mesh over the water and its shore, a child of the terrain (issue #195).</summary>
public const string TerrainWaterName = "TerrainWater";
/// <summary>The terrain water's render queue: after the terrain (Terrain.mat, one queue earlier: MapMaterials) and
/// before every other opaque, so boats, harbours and units drawn on the water cover it despite its depth pull.</summary>
public const int TerrainWaterQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry - 1;
/// <summary>Highlight colour of the selected hex, to read against every biome; MapMaterials bakes it into the
/// editor-made HexSelection.mat. Warm ivory since the visual v1 merge point: the earlier gold (1, 0.84, 0.38) shares
/// the hue of the terrain shader's dry-grass coastal plain (MapPalette), so at gameplay03 it stood out from the land
/// only by lightness (deltaE76 18.2 ungraded, under GradeTests' 20). Ivory differs in chroma too, like the promo's
/// white rings and lines.</summary>
public static readonly Color SelectionColour = new Color(1f, 0.95f, 0.80f);
/// <summary>Width of the outline band, as a fraction of the hex circumradius (about 530 m on a 4.4 km hex).</summary>
public const float SelectionWidth = 0.12f;
/// <summary>Height of the band above the highest ground under it. 30 m since visual v1 Task 8 (it was the line mesh's
/// 120 m plus 20 m, to cover the lines; at the 6 km hero zoom that floated); the material's depth offset keeps it
/// from z-fighting the terrain.</summary>
public const float SelectionClearanceM = 30f;
/// <summary>Hides the selected hex's outline (a selected unit has the ring instead: UnitLayer).</summary>
public void ClearSelection()
{
var found = Terrain != null ? Terrain.transform.Find(SelectionName) : null;
if (found != null) found.GetComponent<MeshRenderer>().enabled = false;
}
/// <summary>Outlines hex (q, r) with a band draped on the terrain (MapBuilder.DrapedRing, HexMath corners) drawn with
/// the editor-made HexSelection.mat, whose depth offset keeps it from z-fighting the ground (no runtime material). The band is sampled at its outer, middle and inner rings and each index
/// takes the highest, so terrain inside the band cannot rise through it. A hex that is not on the map hides it.</summary>
public void Select(int q, int r)
{
if (Terrain == null || Hexes == null) return;
var found = Terrain.transform.Find(SelectionName);
var go = found != null ? found.gameObject : null;
if (go == null)
{
go = new GameObject(SelectionName);
go.transform.SetParent(Terrain.transform, false);
var mesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = SelectionName });
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var renderer = go.AddComponent<MeshRenderer>();
renderer.sharedMaterial = selectionMaterial;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
var mr = go.GetComponent<MeshRenderer>();
HexJson hex = null;
foreach (var h in Hexes.hexes) if (h.q == q && h.r == r) { hex = h; break; }
if (hex == null) { mr.enabled = false; return; }
var c = Frame.ToWorld(hex.lon, hex.lat, 0);
var centre = new Vector2(c.x, c.z);
float size = Hexes.hex_size_km * 1000f, clearance = SelectionClearanceM;
var verts = new List<Vector3>(2 * MapBuilder.RingVertices);
var middle = new List<Vector3>(MapBuilder.RingVertices);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size, clearance, verts);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - SelectionWidth), clearance, verts);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - SelectionWidth / 2), clearance, middle);
int n = MapBuilder.RingVertices;
var tris = new List<int>(6 * n);
for (int j = 0; j < n; j++)
{
// Each index at the highest of the outer, middle and inner ring, so the band clears the ground across it.
float y = Mathf.Max(verts[j].y, Mathf.Max(verts[n + j].y, middle[j].y));
verts[j] = new Vector3(verts[j].x, y, verts[j].z); verts[n + j] = new Vector3(verts[n + j].x, y, verts[n + j].z);
}
for (int j = 0; j < n; j++)
{
int a = j, b = (j + 1) % n, ai = n + j, bi = n + (j + 1) % n;
tris.AddRange(new[] { a, ai, b, b, ai, bi }); // the shader draws both faces (Cull Off)
}
var m = go.GetComponent<MeshFilter>().sharedMesh;
m.Clear();
m.SetVertices(verts); m.SetTriangles(tris, 0);
m.RecalculateBounds();
mr.enabled = true;
}
/// <summary>The hexes a unit's Move can go to, outlined while the player picks one (#754): a child of the terrain.</summary>
public const string ReachableName = "ReachableHexes";
/// <summary>The multi-turn route preview's mesh, beside <see cref="ReachableName"/> under the terrain.</summary>
public const string RouteName = "UnitRoute";
/// <summary>The reachable hexes' band, half the selection's, so the lit hexes read as choices and not as the selection.</summary>
public const float ReachableWidth = SelectionWidth / 2;
/// <summary>The route last passed to <see cref="ShowRoute"/>, for the turn-number labels.</summary>
public IReadOnlyList<(int q, int r, int turn)> ShownRoute { get; private set; } = Array.Empty<(int, int, int)>();
/// <summary>Outlines every hex in <paramref name="hexes"/> (Movement.Reachable's, from InfoPanelPresenter) with a thin
/// band in one mesh, drawn and draped as <see cref="Select"/>'s outline and with its material; nothing to light (none,
/// or only hexes off the map) hides it. Display only: which hexes are lit is the sim's answer, never computed here.
/// A unit has at most 5 movement points (unit_types.yaml), so the mesh stays far under 16-bit indices. Each lit hex also
/// gets a translucent fill over the models (<see cref="ReachableFillName"/>, #2201).</summary>
public void ShowReachable(IEnumerable<(int q, int r)> hexes)
{
if (Terrain == null || Hexes == null) return;
var found = Terrain.transform.Find(ReachableName);
var go = found != null ? found.gameObject : null;
if (go == null)
{
go = new GameObject(ReachableName);
go.transform.SetParent(Terrain.transform, false);
var mesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = ReachableName });
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var renderer = go.AddComponent<MeshRenderer>();
renderer.sharedMaterial = selectionMaterial;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
var byHex = new Dictionary<(int, int), HexJson>();
foreach (var h in Hexes.hexes) byHex[(h.q, h.r)] = h;
float size = Hexes.hex_size_km * 1000f;
int n = MapBuilder.RingVertices;
var verts = new List<Vector3>(); var tris = new List<int>();
var fill = new List<Vector3>(); var fillColours = new List<Color>(); var fillTris = new List<int>(); var inner = new List<Vector3>(n);
var clear = FillColour.linear; clear.a = 0f;
var ring = new List<Vector3>(2 * n); var middle = new List<Vector3>(n);
foreach (var at in hexes)
{
if (!byHex.TryGetValue(at, out var hex)) continue;
var c = Frame.ToWorld(hex.lon, hex.lat, 0);
var centre = new Vector2(c.x, c.z);
ring.Clear(); middle.Clear();
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size, SelectionClearanceM, ring);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - ReachableWidth), SelectionClearanceM, ring);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - ReachableWidth / 2), SelectionClearanceM, middle);
int b0 = verts.Count;
for (int j = 0; j < n; j++) // each index at the highest of its three rings, as Select's band
{
float y = Mathf.Max(ring[j].y, Mathf.Max(ring[n + j].y, middle[j].y));
ring[j] = new Vector3(ring[j].x, y, ring[j].z); ring[n + j] = new Vector3(ring[n + j].x, y, ring[n + j].z);
}
verts.AddRange(ring);
for (int j = 0; j < n; j++)
{
int a = b0 + j, b = b0 + (j + 1) % n, ai = b0 + n + j, bi = b0 + n + (j + 1) % n;
tris.AddRange(new[] { a, ai, b, b, ai, bi }); // the shader draws both faces (Cull Off)
}
// The fill (#2201): a strip from the band's outer ring, in the fill's colour, to a ring FillDepth further in,
// clear, so the tint fades towards the middle of the hex.
inner.Clear();
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - FillDepth), SelectionClearanceM, inner);
int f0 = fill.Count;
for (int j = 0; j < n; j++) { fill.Add(ring[j]); fillColours.Add(FillColour.linear); }
for (int j = 0; j < n; j++) { fill.Add(inner[j]); fillColours.Add(clear); }
for (int j = 0; j < n; j++)
{
int a = f0 + j, b = f0 + (j + 1) % n, ai = f0 + n + j, bi = f0 + n + (j + 1) % n;
fillTris.AddRange(new[] { a, ai, b, b, ai, bi });
}
}
var m = go.GetComponent<MeshFilter>().sharedMesh;
m.Clear();
m.SetVertices(verts); m.SetTriangles(tris, 0);
m.RecalculateBounds();
go.GetComponent<MeshRenderer>().enabled = verts.Count > 0;
SetOverlayMesh(OverlayChild(ReachableFillName), fill, fillColours, fillTris, fadeClose: true);
}
/// <summary>The lit hexes' translucent fill (#2201), beside <see cref="ReachableName"/> under the terrain.</summary>
public const string ReachableFillName = "ReachableFill";
/// <summary>The hover marker on the hex under the pointer while a pick is open (#2201), under the terrain.</summary>
public const string HoverName = "HexHover";
/// <summary>The fill's material (Statecraft/HexOverlay: vertex colours, drawn over the models), in Resources so a player
/// keeps it and its shader.</summary>
public const string OverlayMaterialResource = "Map/HexOverlay";
/// <summary>The hover marker's material: the same shader, queued at Transparent+45, between the fill (+40) and the move
/// arrow (+50, #2184), so the band draws over the fill and under the arrow. A queue, not a sortingOrder: URP sorts by order
/// in layer before the queue, so an order of 1 would draw the band over the arrow's tip on the hovered hex.</summary>
public const string HoverMaterialResource = "Map/HexHover";
/// <summary>The lit hexes' fill at their edge: the selection's ivory at 40%, so a lit hex reads over a town or a wood and the
/// ground still shows through.</summary>
public static readonly Color FillColour = new Color(SelectionColour.r, SelectionColour.g, SelectionColour.b, 0.4f);
/// <summary>How far in from the edge the fill fades to clear, as a fraction of the hex circumradius, so the middle of a lit
/// hex is untinted. The shader also thins the fill as the camera comes close (the closest zoom, 6 km, shows about one
/// hex, and a full tint washed the whole view).</summary>
public const float FillDepth = 0.45f;
/// <summary>The hover band's core and edges: the move arrow's gold and navy ink (#2134), so the band reads on pale
/// towns and dry grass (the navy) and on dark woods (the gold).</summary>
public static readonly Color HoverColour = new Color(1f, 0.82f, 0.25f), HoverInk = new Color(0.06f, 0.08f, 0.14f, 0.9f);
/// <summary>A child of the terrain drawn with the overlay material, made on first use (a rebuild destroys it).</summary>
GameObject OverlayChild(string name, string material = OverlayMaterialResource)
{
var found = Terrain.transform.Find(name);
if (found != null) return found.gameObject;
var go = new GameObject(name);
go.transform.SetParent(Terrain.transform, false);
go.AddComponent<MeshFilter>().sharedMesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = name });
var renderer = go.AddComponent<MeshRenderer>();
renderer.sharedMaterial = Resources.Load<Material>(material);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
return go;
}
/// <summary><paramref name="fadeClose"/>: uv.x 1, so Statecraft/HexOverlay fades the mesh as the camera comes close.</summary>
static void SetOverlayMesh(GameObject go, List<Vector3> verts, List<Color> colours, List<int> tris, bool fadeClose)
{
var m = go.GetComponent<MeshFilter>().sharedMesh;
m.Clear();
var uvs = new List<Vector2>(verts.Count);
for (int i = 0; i < verts.Count; i++) uvs.Add(new Vector2(fadeClose ? 1f : 0f, 0f));
m.SetVertices(verts); m.SetColors(colours); m.SetUVs(0, uvs); m.SetTriangles(tris, 0);
m.RecalculateBounds();
go.GetComponent<MeshRenderer>().enabled = verts.Count > 0;
}
/// <summary>Within this camera distance the hover band thins to the lit-hex outline's <see cref="ReachableWidth"/>: the
/// overlay shader's CloseM (Statecraft/HexOverlay), inside which the fill fades too. At the closest zoom (6 km) one hex
/// fills the view and the selection's 0.12 band hid the buildings on it (owner ruling, #2213).</summary>
public const float HoverCloseM = 8000f;
MeshRenderer hoverRenderer;
(int q, int r)? hovered;
float hoverWidth;
// Kept between calls: the pointer moves to a new hex many times a second, and fresh lists each time made steady garbage.
readonly List<Vector3> hoverVerts = new List<Vector3>();
readonly List<Color> hoverColours = new List<Color>();
readonly List<int> hoverTris = new List<int>();
readonly List<Vector3>[] hoverRings = { new List<Vector3>(), new List<Vector3>(), new List<Vector3>(), new List<Vector3>() };
// The strip edges as shares of the band: a navy edge either side, 0.2 of the band each (about 2 px at the opening zoom,
// not a heavy bar at 6 km), the gold between.
static readonly float[] HoverShares = { 0f, 0.2f, 0.8f, 1f };
/// <summary>Marks hex (q, r) with a band of the selection's width in three strips, navy edge, gold core, navy edge,
/// draped as <see cref="Select"/>'s, thinned to the lit-hex outline's width with the camera within <see cref="HoverCloseM"/>
/// (<paramref name="cameraDistanceM"/>, the camera rig's distance); null or a hex off the map hides it. GameRoot asks every
/// frame: the same hex at the same width again returns at once.</summary>
public void ShowHover((int q, int r)? hex, float cameraDistanceM = float.PositiveInfinity)
{
if (Terrain == null || Hexes == null) return;
float width = cameraDistanceM <= HoverCloseM ? ReachableWidth : SelectionWidth;
if (hoverRenderer != null && hovered == hex && hoverWidth == width) return;
hovered = hex; hoverWidth = width;
var go = OverlayChild(HoverName, HoverMaterialResource);
hoverRenderer = go.GetComponent<MeshRenderer>();
HexJson at = null;
if (hex is (int q, int r)) foreach (var h in Hexes.hexes) if (h.q == q && h.r == r) { at = h; break; }
var verts = hoverVerts; var colours = hoverColours; var tris = hoverTris;
verts.Clear(); colours.Clear(); tris.Clear();
if (at != null)
{
var c = Frame.ToWorld(at.lon, at.lat, 0);
var centre = new Vector2(c.x, c.z);
float size = Hexes.hex_size_km * 1000f;
int n = MapBuilder.RingVertices;
var shares = HoverShares;
var rings = hoverRings;
for (int i = 0; i < shares.Length; i++)
{
rings[i].Clear();
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - width * shares[i]), SelectionClearanceM, rings[i]);
}
for (int j = 0; j < n; j++) // each index at the highest of its rings, as Select's band
{
float y = float.MinValue;
foreach (var ring in rings) y = Mathf.Max(y, ring[j].y);
foreach (var ring in rings) ring[j] = new Vector3(ring[j].x, y, ring[j].z);
}
for (int i = 0; i < 3; i++)
{
var colour = (i == 1 ? HoverColour : HoverInk).linear;
int b0 = verts.Count;
verts.AddRange(rings[i]); verts.AddRange(rings[i + 1]);
for (int j = 0; j < 2 * n; j++) colours.Add(colour);
for (int j = 0; j < n; j++)
{
int a = b0 + j, b = b0 + (j + 1) % n, ai = b0 + n + j, bi = b0 + n + (j + 1) % n;
tris.Add(a); tris.Add(ai); tris.Add(b); tris.Add(b); tris.Add(ai); tris.Add(bi); // the shader draws both faces (Cull Off)
}
}
}
SetOverlayMesh(go, verts, colours, tris, fadeClose: false);
}
/// <summary>Shows the sim's multi-turn route as thin hex bands. Each item carries its arrival turn;
/// <see cref="Statecraft.Game.UI.MapLabelsPresenter"/> labels the last hex of each turn. Empty hides the preview.</summary>
public void ShowRoute(IReadOnlyList<(int q, int r, int turn)> route)
{
ShownRoute = route?.ToList() ?? new List<(int, int, int)>();
if (Terrain == null || Hexes == null) return;
var found = Terrain.transform.Find(RouteName);
var go = found != null ? found.gameObject : null;
if (go == null)
{
go = new GameObject(RouteName);
go.transform.SetParent(Terrain.transform, false);
var mesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = RouteName });
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var renderer = go.AddComponent<MeshRenderer>();
renderer.sharedMaterial = selectionMaterial;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
var byHex = new Dictionary<(int, int), HexJson>();
foreach (var h in Hexes.hexes) byHex[(h.q, h.r)] = h;
float size = Hexes.hex_size_km * 1000f;
int n = MapBuilder.RingVertices;
var verts = new List<Vector3>(); var tris = new List<int>();
var ring = new List<Vector3>(2 * n); var middle = new List<Vector3>(n);
foreach (var at in ShownRoute)
{
if (!byHex.TryGetValue((at.q, at.r), out var hex)) continue;
var c = Frame.ToWorld(hex.lon, hex.lat, 0);
var centre = new Vector2(c.x, c.z);
ring.Clear(); middle.Clear();
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size, SelectionClearanceM, ring);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - ReachableWidth), SelectionClearanceM, ring);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - ReachableWidth / 2), SelectionClearanceM, middle);
int b0 = verts.Count;
for (int j = 0; j < n; j++)
{
float y = Mathf.Max(ring[j].y, Mathf.Max(ring[n + j].y, middle[j].y));
ring[j] = new Vector3(ring[j].x, y, ring[j].z);
ring[n + j] = new Vector3(ring[n + j].x, y, ring[n + j].z);
}
verts.AddRange(ring);
for (int j = 0; j < n; j++)
{
int a = b0 + j, b = b0 + (j + 1) % n, ai = b0 + n + j, bi = b0 + n + (j + 1) % n;
tris.AddRange(new[] { a, ai, b, b, ai, bi });
}
}
var m = go.GetComponent<MeshFilter>().sharedMesh;
m.Clear(); m.SetVertices(verts); m.SetTriangles(tris, 0); m.RecalculateBounds();
go.GetComponent<MeshRenderer>().enabled = verts.Count > 0;
}
/// <summary>The move arrow's mesh (#2134), beside <see cref="RouteName"/> under the terrain.</summary>
public const string MoveArrowName = "MoveArrow";
/// <summary>The arrow's material (Statecraft/MoveArrow), in Resources so a player keeps it and its shader.</summary>
public const string MoveArrowMaterialResource = "Map/MoveArrow";
/// <summary>The arrow's full width (its head's base) per metre of camera distance, as MoveArrow.mat gives the shader:
/// about 27 px at 1080 px at every zoom (CameraRig.Fov 35 degrees), the shaft about a third of that.</summary>
public const float MoveArrowWidthPerDistance = 0.016f;
/// <summary>The arrow leaves the unit's hex this share of the hex size from its centre, clear of the unit's token.</summary>
public const float MoveArrowStartShare = 0.35f;
/// <summary>Spacing (m) of the arrow's cross-sections along a hex-to-hex leg, each on the ground under it: about the
/// heightmap's spacing, so the arrow keeps to the relief as the camera's tilt sees it.</summary>
public const float MoveArrowStepM = 250f;
/// <summary>The widest half-width (m) the shader gives the arrow: at CameraController.MaxDistance, with half again for
/// the vertices of a tilted view that lie farther from the camera than its look-at point. The cross-sections next to
/// a bend stay beyond the reach of a band this wide (review of #2134, C1), and the bounds hold it (C4).</summary>
public const float MoveArrowWidestHalfM = 0.5f * MoveArrowWidthPerDistance * CameraController.MaxDistance * 1.5f;
/// <summary>The hexes last passed to <see cref="ShowMoveArrow"/>: the unit's hex, then the path's.</summary>
public IReadOnlyList<(int q, int r)> ShownArrow => shownArrow;
readonly List<(int q, int r)> shownArrow = new List<(int q, int r)>();
/// <summary>The map's hexes by (q, r), for the arrow; made once per hex file (a Build loads a new one).</summary>
Dictionary<(int, int), HexJson> arrowHexes;
HexFile arrowHexesOf;
readonly List<Vector2> arrowLine = new List<Vector2>();
readonly List<Vector3> arrowVerts = new List<Vector3>();
readonly List<Vector2> arrowUv = new List<Vector2>();
readonly List<Vector4> arrowSide = new List<Vector4>();
readonly List<int> arrowTris = new List<int>();
/// <summary>Draws the move arrow (#2134) from the first hex's centre through every later hex's centre, in order, with
/// its head on the last: <paramref name="hexes"/> is the unit's hex and the sim's path (InfoPanelPresenter.ArrowHexes:
/// Movement.Path or Movement.Route, never computed here). Fewer than two hexes on the map hides it. Built once per call;
/// the chevrons move in the shader (Statecraft/MoveArrow), so nothing runs per frame.</summary>
public void ShowMoveArrow(IReadOnlyList<(int q, int r)> hexes)
{
shownArrow.Clear();
if (hexes != null) shownArrow.AddRange(hexes);
if (Terrain == null || Hexes == null) return;
if (arrowHexes == null || arrowHexesOf != Hexes)
{
arrowHexes = new Dictionary<(int, int), HexJson>();
foreach (var h in Hexes.hexes) arrowHexes[(h.q, h.r)] = h;
arrowHexesOf = Hexes;
}
var found = Terrain.transform.Find(MoveArrowName);
var go = found != null ? found.gameObject : null;
if (go == null)
{
go = new GameObject(MoveArrowName);
go.transform.SetParent(Terrain.transform, false);
var mesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = MoveArrowName });
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var renderer = go.AddComponent<MeshRenderer>();
renderer.sharedMaterial = Resources.Load<Material>(MoveArrowMaterialResource)
?? throw new InvalidOperationException($"Resources/{MoveArrowMaterialResource}.mat is missing");
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
arrowLine.Clear(); arrowVerts.Clear(); arrowUv.Clear(); arrowSide.Clear(); arrowTris.Clear();
foreach (var at in shownArrow)
{
if (!arrowHexes.TryGetValue((at.q, at.r), out var hex)) continue;
var c = Frame.ToWorld(hex.lon, hex.lat, 0);
var point = new Vector2(c.x, c.z);
if (arrowLine.Count == 0 || (point - arrowLine[arrowLine.Count - 1]).sqrMagnitude > 1f) arrowLine.Add(point);
}
if (arrowLine.Count >= 2)
{
arrowLine[0] += (arrowLine[1] - arrowLine[0]).normalized * (MoveArrowStartShare * Hexes.hex_size_km * 1000f);
float total = 0f;
for (int i = 1; i < arrowLine.Count; i++) total += (arrowLine[i] - arrowLine[i - 1]).magnitude;
var data = Terrain.terrainData;
float along = 0f;
for (int i = 0; i + 1 < arrowLine.Count; i++)
{
Vector2 a = arrowLine[i], b = arrowLine[i + 1];
float len = (b - a).magnitude;
int steps = Mathf.Max(1, Mathf.CeilToInt(len / MoveArrowStepM));
var dir = (b - a) / len;
// Near a bend the widest band's inner edge reaches back along the leg (the mitre's setback): no cross-section
// there, or the band would fold back over itself and blend twice (review of #2134, C1).
float back = i > 0 ? MoveArrowWidestHalfM * MitreSetback((a - arrowLine[i - 1]).normalized, dir) : 0f;
float front = i + 2 < arrowLine.Count ? MoveArrowWidestHalfM * MitreSetback(dir, (arrowLine[i + 2] - b).normalized) : 0f;
for (int k = i == 0 ? 0 : 1; k <= steps; k++)
{
if (k > 0 && k < steps && (len * k / steps <= back || len * k / steps >= len - front)) continue;
var p = Vector2.Lerp(a, b, (float)k / steps);
var side = new Vector2(dir.y, -dir.x);
// A bend (a later leg's first point): the mitre of the two legs, so the band keeps its width round it.
if (k == steps && i + 2 < arrowLine.Count)
{
var next = (arrowLine[i + 2] - b).normalized;
var mitre = (side + new Vector2(next.y, -next.x)).normalized;
side = mitre / Mathf.Max(0.5f, Vector2.Dot(mitre, side));
}
float y = data.GetInterpolatedHeight(Mathf.Clamp01(p.x / Frame.WidthM), Mathf.Clamp01(p.y / Frame.LengthM)) + SelectionClearanceM;
float s = along + len * k / steps;
int v = arrowVerts.Count;
for (int u = 0; u <= 1; u++)
{
arrowVerts.Add(new Vector3(p.x, y, p.y));
arrowUv.Add(new Vector2(u, s));
arrowSide.Add(new Vector4(side.x, side.y, total, 0f));
}
if (v > 0) { arrowTris.Add(v - 2); arrowTris.Add(v); arrowTris.Add(v - 1); arrowTris.Add(v - 1); arrowTris.Add(v); arrowTris.Add(v + 1); }
}
along += len;
}
}
var m = go.GetComponent<MeshFilter>().sharedMesh;
m.Clear();
m.SetVertices(arrowVerts); m.SetUVs(0, arrowUv); m.SetUVs(1, arrowSide); m.SetTriangles(arrowTris, 0);
// The vertices lie on the centre line and the shader widens the band: grow the bounds by the widest it is drawn, a
// mitre's twice the half-width included (Expand grows the size, so each side by half), so culling never drops a
// band whose centre line is just off screen (review of #2134, C4).
var bounds = m.bounds; bounds.Expand(4f * MoveArrowWidestHalfM);
m.bounds = bounds;
go.GetComponent<MeshRenderer>().enabled = arrowVerts.Count > 0;
}
/// <summary>How far back along a leg, per metre of half-width, a band's inner edge reaches at a bend from direction
/// <paramref name="into"/> to <paramref name="outOf"/> (unit vectors): tan of half the turn. Capped near a U-turn.</summary>
static float MitreSetback(Vector2 into, Vector2 outOf)
{
float cos = Mathf.Max(-0.9f, Vector2.Dot(into, outOf));
return Mathf.Sqrt((1f - cos) / (1f + cos));
}
public void Configure(Material terrain, Material marker, Material selection, Material sea, Material frame)
{
terrainMaterial = terrain; markerMaterial = marker; selectionMaterial = selection;
seaMaterial = sea; frameMaterial = frame;
}
/// <summary>The settlement kits' and trees' materials (null, null: placeholder markers only).</summary>
public void ConfigureKits(Material kit, Material tree) { kitMaterial = kit; treeMaterial = tree; }
/// <summary>Sets the town models (issue #659): the editor bake saves them in the scene; tests set a broken list.</summary>
public void ConfigureTownModels(Kits.TownModelSet set)
{
townModels = set;
#if UNITY_EDITOR
townModelsConfigured = true;
#endif
}
/// <summary>The list KitLayer gets: the configured one; else, in edit mode only (tests, MapCapture), the editor's list
/// at Kits.TownModels.SetPath; else null, which in play mode streams the originals (#1273). A missing asset reference
/// is Unity's fake null: this returns a real null.</summary>
Kits.TownModelSet TownModelsForBuild()
{
if (townModels != null) return townModels;
#if UNITY_EDITOR
if (!townModelsConfigured && !Application.isPlaying)
return UnityEditor.AssetDatabase.LoadAssetAtPath<Kits.TownModelSet>(Kits.TownModels.SetPath);
#endif
return null;
}
/// <summary>Each settlement's footprint on the ground plane (centre x, z; radius m): the kits' discs
/// (SettlementKits.FootprintRadiusM) of the game settlements and, with the kits, of the 1948 localities, so the units
/// keep their tokens off the buildings (UnitLayer). The Bedouin camps are not here: they are placed after the units and
/// keep off them (KitGround.Tokens). Empty before Build.</summary>
public IReadOnlyList<(Vector2 centre, float radius)> SettlementFootprints { get; private set; } = new List<(Vector2, float)>();
/// <summary>Whether the next Build keeps a kit clearing for the units' showcase trio (Units.UnitShowcase.Clearing), as
/// for a unit in a town: null means only when the run asks for the showcase (?units, -units), so a plain screenshot
/// keeps every kit (review of #559).</summary>
public bool? ShowcaseClearing { get; set; }
/// <summary>The railways' and roads' corridors (RouteLayer.Corridors) of every route drawn while a unit token stands
/// (RouteLayer.UnitRoutes, #786), so the units keep their figures off them. Empty before Build.</summary>
public IReadOnlyList<(List<Vector2> line, float halfWidth)> RouteCorridors { get; private set; } = new List<(List<Vector2>, float)>();
/// <summary>Every route of content/map/routes_1948.yaml as the last Build read them, with its id (empty before Build, or
/// when the file is missing or malformed): SpecialBuildingModels stands the low wall beside one road by id.</summary>
public IReadOnlyList<Routes.RoutePath> RouteList { get; private set; } = new List<Routes.RoutePath>();
/// <summary>The corridors the kits keep off: those of the routes drawn at the game's start (RouteLayer.KitRoutes, #786).
/// Empty before Build.</summary>
public IReadOnlyList<(List<Vector2> line, float halfWidth)> KitRouteCorridors { get; private set; } = new List<(List<Vector2>, float)>();
/// <summary>The units of content/map/units_1948.yaml as the last Build read them (empty before a build, or when the
/// file is missing or malformed). Read only: the units layer draws from this same list (UnitEntriesFor).</summary>
public IReadOnlyList<Units.UnitEntry> UnitEntries { get; private set; } = Array.Empty<Units.UnitEntry>();
string unitsYamlRead; // null before a build
/// <summary>The 1948 sub-districts as the last Build read them for the Bedouin camps' hexes (null when it did not:
/// no kits, or no sub-district file). Read only: GameRoot's region layers draw from this same object.</summary>
public Subdistricts1948 Subdistricts { get; private set; }
string regionsYamlRead; // null before a build, or when Build did not read the file
/// <summary>The sub-districts for <paramref name="yaml"/>: the object the last Build read when it read the same text
/// (issue #321: the file was read twice at boot), else read from <paramref name="tsv"/> or the YAML
/// (Subdistricts1948.ReadRuntimeOrYaml, warning through <paramref name="warn"/>).</summary>
public Subdistricts1948 SubdistrictsFor(string tsv, string yaml, Action<string> warn) =>
regionsYamlRead != null && Subdistricts != null && string.Equals(yaml, regionsYamlRead, StringComparison.Ordinal)
? Subdistricts : Subdistricts1948.ReadRuntimeOrYaml(tsv, yaml, warn);
/// <summary>The unit spots the last Build placed (UnitGround.Place over <see cref="UnitEntries"/>, keyed by their
/// anchors; an anchor it could not place has none) and the hexes it placed them on. The units layer takes them instead
/// of placing again when it draws the same units on the same hexes (issue #321; UnitSpotsFor).</summary>
public IReadOnlyDictionary<Units.UnitAnchor, Units.AnchorSpot> UnitSpots { get; private set; } = new Dictionary<Units.UnitAnchor, Units.AnchorSpot>();
/// <remarks>Kept for the map's life, not released once a layer has taken the spots: GameRoot.Begin may run again on
/// the same map (it shuts the old layer down and makes a new one; the editor tests do), and each layer checks its
/// hexes against these. 1,102 small objects; nothing writes to them after Build.</remarks>
public IReadOnlyList<Statecraft.Sim.MapHex> UnitHexes { get; private set; } = Array.Empty<Statecraft.Sim.MapHex>();
/// <summary>The map's unit spots when <paramref name="units"/> is the list the map
/// placed and <paramref name="hexes"/> match the hexes it placed them on (q, r, lon, lat and land, in order): the same
/// ground, so the same spots. Null otherwise: the caller places them itself.</summary>
public IReadOnlyDictionary<Units.UnitAnchor, Units.AnchorSpot> UnitSpotsFor(
IReadOnlyList<Units.UnitEntry> units, IReadOnlyList<Statecraft.Sim.MapHex> hexes)
{
if (unitsYamlRead == null || !ReferenceEquals(units, UnitEntries) || hexes == null || hexes.Count != UnitHexes.Count) return null;
for (int i = 0; i < hexes.Count; i++)
{
var (a, b) = (hexes[i], UnitHexes[i]);
if (a.Q != b.Q || a.R != b.R || a.Land != b.Land
|| BitConverter.DoubleToInt64Bits(a.Lon) != BitConverter.DoubleToInt64Bits(b.Lon)
|| BitConverter.DoubleToInt64Bits(a.Lat) != BitConverter.DoubleToInt64Bits(b.Lat)) return null;
}
return UnitSpots;
}
/// <summary>The units for <paramref name="yaml"/>: the list the last Build parsed when it read the same text (issue
/// #321: the file was parsed twice at boot, here and for the units layer), else a parse of it (UnitData.ReadOrNone,
/// warning through <paramref name="warn"/>).</summary>
public IReadOnlyList<Units.UnitEntry> UnitEntriesFor(string yaml, Action<string> warn) =>
unitsYamlRead != null && string.Equals(yaml, unitsYamlRead, StringComparison.Ordinal)
? UnitEntries : Units.UnitData.ReadOrNone(yaml, warn);
/// <summary>Where the kits keep their buildings and trees off the units (centre x, z; radius m): the spot of a unit that
/// stands in a town (UnitPlacer's last round, UnitGround.ClearingRadius), so no token stands in a building. An air
/// anchor uses the parked fighter's footprint; every other service keeps the compact ring. Empty before
/// Build or without the unit file.</summary>
public IReadOnlyList<(Vector2 centre, float radius)> UnitClearings { get; private set; } = new List<(Vector2, float)>();
/// <summary>The unit tokens that stand outside the towns (centre x, z; footprint radius m), as the kits get them
/// (KitGround.Tokens), with the day the token's window ends (its anchor's `to`, exclusive): the transit camps
/// PlacementLayer builds later keep off those still present on the camp's date (KitGround.DatedTokens). Empty before
/// Build.</summary>
public IReadOnlyList<(Vector2 centre, float radius, DateTime until)> UnitTokens { get; private set; } = new List<(Vector2, float, DateTime)>();
/// <summary>The last Build's kit numbers (buildings, vertices, trees, build time), or null without kits.</summary>
public Kits.KitLayer.Stats KitStats { get; private set; }
readonly Dictionary<string, Bounds[]> kitColumns = new Dictionary<string, Bounds[]>();
/// <summary>A settlement's kit (its buildings' merged mesh, as the last Build made it) as a few world boxes that hold
/// all of it: the occupied cells of a KitMesh.ColumnGrid-square grid over its footprint, each from the ground
/// under the kit to its tallest vertex in the cell. Much tighter on screen than the kit's one bounding box under a
/// tilted camera (a water tower at the back no longer lifts the whole box). False without kits or for a kit with no
/// buildings. The map labels keep clear of it (issue #214).</summary>
public bool TryKitColumns(string id, out Bounds[] columns) => kitColumns.TryGetValue(id, out columns);
MeshRenderer kitProbe; // one kit's renderer: the "kits" toggle enables or disables them all together
/// <summary>Whether the kits are drawn (built, and the "kits" toggle on); when not, the marker boxes are, and the map
/// labels keep clear of those instead.</summary>
public bool KitsShown => kitProbe != null && kitProbe.enabled;
/// <summary>Builds from the repository files with System.IO (editor and desktop only).</summary>
public void Build() => Build(GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap));
internal Collection.ProductionResidency Residency { get; } = Collection.ProductionResidency.Approved();
public void Build(MapInputs inputs)
{
if (inputs == null) throw new ArgumentNullException(nameof(inputs));
if (terrainMaterial == null) throw new InvalidOperationException("MapScene: terrainMaterial is not assigned");
if (markerMaterial == null) throw new InvalidOperationException("MapScene: markerMaterial is not assigned");
if (selectionMaterial == null) throw new InvalidOperationException("MapScene: selectionMaterial is not assigned");
if (seaMaterial == null) throw new InvalidOperationException("MapScene: seaMaterial is not assigned");
if (frameMaterial == null) throw new InvalidOperationException("MapScene: frameMaterial is not assigned");
var cam = Camera.main;
if (cam == null) throw new InvalidOperationException("MapScene needs a camera tagged MainCamera");
Clear();
kitColumns.Clear(); kitProbe = null;
var (meta, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z, MetaPath);
ElevMinM = meta.elev_min_m;
DiagLog.BootPhase("heightmap decoded");
Hexes = MapBuilder.LoadHexes(inputs.HexesJson, HexesPath);
DiagLog.BootPhase("hexes parsed");
var list = SettlementPlacer.Parse(inputs.SettlementsYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), SettlementsPath);
Settlements = list; settlementsYamlRead = inputs.SettlementsYaml;
// The map editor's overrides (content/map/overrides.yaml, #1009) go on last, over the generated hexes, settlements
// and control, so a rerun of a generator keeps them; everything drawn below reads the result. The sim applies the
// same terrain and location overrides to its content (ContentLoader), which also checks the location ids.
Overrides = Statecraft.Sim.MapOverrides.Parse(inputs.OverridesYaml);
Overrides.ValidateMap(Hexes.hexes.Select(h => new Statecraft.Sim.MapHex { Q = h.q, R = h.r, Land = h.land, Biome = h.biome }).ToList(), null);
var hexAt = Hexes.hexes.ToDictionary(h => (h.q, h.r));
foreach (var terrain in Overrides.Terrain) hexAt[(terrain.Hex.Q, terrain.Hex.R)].biome = terrain.Value;
foreach (var moved in list)
if (Overrides.TryLocation(moved.Id, out var hq, out var hr)) { moved.Lon = hexAt[(hq, hr)].lon; moved.Lat = hexAt[(hq, hr)].lat; }
Control = string.IsNullOrWhiteSpace(inputs.ControlYaml) ? null
: Control1948.ReadRuntimeOrYaml(inputs.ControlTsv, inputs.ControlYaml, Debug.LogWarning);
if (Control != null) Control.ApplyOverrides(Overrides);
else Overrides.ValidateControl(Array.Empty<(int, int)>(), Array.Empty<string>(), Array.Empty<string>()); // no control file: any control override is an error
bool kitsOn = kitMaterial != null && treeMaterial != null;
var localities = new Kits.Localities.Doc();
if (kitsOn)
{
if (string.IsNullOrWhiteSpace(inputs.PopulationYaml))
{
// Review N1: without the file every town would quietly take the smallest footprint. The editor (and its
// tests) refuses; a player warns and builds the small towns rather than no map.
var missing = $"map/{Kits.KitPopulation.FileName} is missing or empty: the settlement kits need it to size the towns";
if (Application.isEditor) throw new InvalidDataException(missing);
Debug.LogWarning("KITS " + missing + "; every town takes the smallest footprint");
}
var table = string.IsNullOrWhiteSpace(inputs.PopulationYaml)
? new Dictionary<string, int>() : Kits.KitPopulation.Parse(inputs.PopulationYaml, "map/" + Kits.KitPopulation.FileName);
if (string.IsNullOrWhiteSpace(inputs.LocalitiesTsv))
{
// As the population file: the editor refuses, a player warns and draws the 25 game settlements only.
var missing = $"map/{Kits.Localities.RuntimeFileName} is missing or empty: the kits draw the 1948 localities from it (tools/localities_bake.py)";
if (Application.isEditor) throw new InvalidDataException(missing);
Debug.LogWarning("KITS " + missing);
localities = new Kits.Localities.Doc();
}
else
{
var reserved = new HashSet<string>(); foreach (var s in list) reserved.Add(s.Id);
// The baked runtime form, not the 176k-character YAML (boot budget; pytest fails a stale bake).
localities = Kits.Localities.ParseRuntime(inputs.LocalitiesTsv, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), reserved,
"map/" + Kits.Localities.RuntimeFileName);
}
foreach (var p in localities.Places) table[p.Settlement.Id] = p.Population;
Kits.KitPopulation.Use(table);
// The camps' areas are the sub-districts as the region layer draws them (review I4: no copy in the
// localities file).
if (string.IsNullOrWhiteSpace(inputs.RegionsYaml)) { localities.Encampments.Clear(); Debug.LogWarning($"KITS map/{Subdistricts1948.FileName} is missing: no Bedouin camps"); }
else
{
// The camps' hexes from the sub-districts, read once from their runtime form (issue #321) and handed on
// to GameRoot's region layers (SubdistrictsFor).
Subdistricts = Subdistricts1948.ReadRuntimeOrYaml(inputs.RegionsTsv, inputs.RegionsYaml, Debug.LogWarning);
regionsYamlRead = inputs.RegionsYaml;
Kits.Localities.FillHexes(localities, Subdistricts, Hexes, "map/" + Kits.Localities.FileName);
}
}
Kits.Localities.Use(localities.Places); // on every build, so a map without the kits inherits nothing (review M13)
if (kitsOn) DiagLog.BootPhase("localities parsed");
Localities = localities.Places;
var localitySettlements = localities.Places.ConvertAll(p => p.Settlement);
var painted = new List<Settlement>(list); painted.AddRange(localitySettlements);
float hexSizeM = Hexes.hex_size_km * 1000f;
var terrainGo = MapBuilder.Build(meta, heights, Hexes, terrainMaterial,
kitsOn ? (px, res, frame) =>
{
// The ground tint under every town and locality (review I6: timed, as the boot budget is tight).
var tint = System.Diagnostics.Stopwatch.StartNew();
Kits.SettlementKits.PaintGround(px, res, frame, painted, hexSizeM);
Debug.Log(FormattableString.Invariant($"KITS ground_tint_ms={tint.Elapsed.TotalMilliseconds:0.0} places={painted.Count}"));
} : null, bakedBiome: true); // the biome colours from their bake (issue #321: boot time)
terrainGo.transform.SetParent(transform, true);
Terrain = terrainGo.GetComponent<Terrain>();
var size = Terrain.terrainData.size;
AddFrame(terrainGo, meta.elev_min_m);
DiagLog.BootPhase("frame");
AddTerrainWater(terrainGo, heights, meta.elev_min_m);
DiagLog.BootPhase("terrain water");
Frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, size.x, size.z);
var markers = SettlementPlacer.Place(list, Frame, Terrain, markerMaterial);
markers.transform.SetParent(transform, true);
DiagLog.BootPhase("settlements placed");
KitStats = null;
// The 1948 railways and roads (issue #35), read before the kits so buildings and trees keep off them.
// From the baked runtime form when it matches the YAML (issue #321: boot time), else from the YAML with a warning.
var routes = Routes.RoutePaths.ReadRuntimeOrYaml(inputs.RoutesTsv, inputs.RoutesYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), Debug.LogWarning);
RouteList = routes;
DiagLog.BootPhase("route paths read"); // issue #321: the splits of the units' phase
// Only the routes drawn at the start keep the kits off (#786); the units keep off those drawn while they stand.
KitRouteCorridors = Routes.RouteLayer.Corridors(Frame, Routes.RouteLayer.KitRoutes(routes));
DiagLog.BootPhase("route corridors");
// The game settlements' and the 1948 localities' discs, as the kits will claim them (review I5: a token placed "off
// the towns" keeps off the villages too). The camps are placed after the units and keep off them instead.
SettlementFootprints = painted.Select(s => { var w = Frame.ToWorld(s.Lon, s.Lat, 0); return (new Vector2(w.x, w.z), Kits.SettlementKits.FootprintRadiusM(s, hexSizeM)); }).ToList();
// The units' spots depend only on the footprints, the routes and the land, so they are known before the kits:
// a unit placed in a town gets a clearing the kits keep free (UnitLayer places it the same way).
DiagLog.BootPhase("footprints");
var unitData = Units.UnitData.ReadOrNone(inputs.UnitsYaml, Debug.LogWarning);
UnitEntries = unitData; unitsYamlRead = inputs.UnitsYaml ?? "";
DiagLog.BootPhase("unit data read");
// The end of the last token's window (anchors always have one): a route opened later takes no token's spot (#786).
var unitsUntil = unitData.SelectMany(u => u.Anchors).Select(a => Units.UnitData.Day(a.To)).DefaultIfEmpty(DateTime.MaxValue).Max();
RouteCorridors = Routes.RouteLayer.Corridors(Frame, Routes.RouteLayer.UnitRoutes(routes, unitsUntil));
var unitHexes = Hexes.hexes.Select(h => new Statecraft.Sim.MapHex { Q = h.q, R = h.r, Lon = h.lon, Lat = h.lat, ElevM = h.elev_m, Land = h.land, Biome = h.biome }).ToList();
UnitHexes = unitHexes;
var unitGround = new Units.UnitGround(SettlementFootprints, RouteCorridors, unitHexes,
(lon, lat) => { var w = Frame.ToWorld(lon, lat, 0); return new Vector2(w.x, w.z); }, hexSizeM, Units.UnitLayer.Water(this));
var clearings = new List<(Vector2 centre, float radius)>();
var unitRings = new List<(Vector2 centre, float radius)>();
var datedRings = new List<(Vector2 centre, float radius, DateTime until)>();
// The units' showcase trio gets the same clearing at its spot, off the railways and roads, so its base stands
// clear of the kits (review of #559).
if (ShowcaseClearing ?? Units.UnitShowcase.Requested()) clearings.Add(Units.UnitShowcase.Clearing(this));
if (unitData.Count > 0)
{
var spots = unitGround.Place(unitData, (lon, lat) => { var w = Frame.ToWorld(lon, lat, 0); return new Vector2(w.x, w.z); }, null, control: Control);
UnitSpots = spots;
foreach (var kv in spots.OrderBy(k => k.Value.X).ThenBy(k => k.Value.Z))
{
var c = new Vector2((float)kv.Value.X, (float)kv.Value.Z);
var service = unitData.First(u => u.Anchors.Contains(kv.Key)).Service;
if (kv.Value.InTown && !clearings.Exists(x => x.centre == c))
{
// Only an air anchor gets the parked fighter's span; army census clearings keep their compact radius.
clearings.Add((c, unitGround.ClearingRadius(service)));
}
else if (!kv.Value.InTown)
{
float radius = unitGround.ClearanceRadius(service, kv.Value.Compact);
unitRings.Add((c, radius));
datedRings.Add((c, radius, Units.UnitData.Day(kv.Key.To)));
}
}
}
UnitClearings = clearings;
DiagLog.BootPhase("units placed"); // issue #321: the routes' corridors, the footprints and the unit spots
UnitTokens = datedRings;
if (kitsOn)
{
// ?kitscale=, ?housescale=, ?treescale= in the WebGL player: the same layout at another symbolic scale (city
// blocks, houses, trees), clamped to KitScale.Min..Max; docs/dev-setup.md lists the flags.
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
var url = Application.absoluteURL;
int ks = UrlFlags.Int(url, "kitscale"), hs = UrlFlags.Int(url, "housescale"), ts = UrlFlags.Int(url, "treescale");
if (ks > 0) Kits.KitScale.CityBlocks = Kits.KitScale.Clamp(ks);
if (hs > 0) Kits.KitScale.Houses = Kits.KitScale.Clamp(hs);
if (ts > 0) Kits.KitScale.Trees = Kits.KitScale.Clamp(ts);
}
// The kits replace the marker boxes; the boxes stay as the labels' and tests' anchors, and come back when the
// "kits" toggle turns the kits off (so settlements are never left undrawn).
// The units' clearings go in as corridors (village houses and tents keep off them too); the tokens outside
// the towns are kept off by the Bedouin camps, the one kit placed where no footprint is (review I5).
var kits = Kits.KitLayer.Build(list, localitySettlements, localities.Encampments, Terrain, Frame, Hexes, meta.elev_min_m, kitMaterial, treeMaterial,
TownModelsForBuild(),
terrainGo.GetComponent<MapRuntimeAssets>(), markers, out var stats,
KitRouteCorridors.Concat(UnitClearings.Select(c => (new List<Vector2> { c.centre, c.centre + Vector2.right }, c.radius))).ToList(), kitColumns,
unitRings, Residency);
kits.transform.SetParent(transform, true);
kitProbe = kits.GetComponentInChildren<MeshRenderer>(true);
KitStats = stats;
DiagLog.BootPhase("kits built");
Debug.Log(stats.ToString());
}
// The routes are drawn map-only, as at the game's date (the start until the game sets one); a missing or malformed
// file means no routes and a warning; the promo's train in screenshots, editor renders and ?train, and in normal play
// the service train from its sourced date (issue #668), streamed then, never at boot. The ribbons are
// placed from their bake when it was made from these inputs (issue #321), else derived.
Routes.RouteLayer.Build(Terrain, Frame, routes, Routes.RouteLayer.ModeForThisRun(), RouteDate ?? Routes.RouteLayer.DefaultDate,
Routes.RouteRibbonFile.Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml), this);
DiagLog.BootPhase("routes built");
// The ground between the towns (#2878): grain, scrub and stones, a pass over the terrain.
GroundDetail.Build(transform, Terrain, Frame, Hexes, heights, SettlementFootprints.Concat(UnitClearings).Concat(UnitTokens.Select(t => (t.centre, t.radius))),
KitRouteCorridors, terrainMaterial, terrainGo.GetComponent<MapRuntimeAssets>(), bushes: kitsOn);
DiagLog.BootPhase("ground detail");
// The 1949 armistice lines as their true polylines (#237), unless the run turns them off with the
// "noarmisticelines" flag; a missing or malformed file means no overlay and a warning. Display only.
if (ArmisticeLines.Wanted() && inputs.ArmisticeLinesGeojson == "") Debug.LogWarning($"ARMISTICE LINES: {ArmisticeLines.FileName} is missing; no overlay");
else if (ArmisticeLines.Wanted())
{
try
{
var lines = ArmisticeLines.ForBuild(ArmisticeLines.Parse(inputs.ArmisticeLinesGeojson), Application.isEditor || Debug.isDebugBuild);
ArmisticeLines.Build(Terrain, Frame, lines, selectionMaterial, RouteDate ?? Routes.RouteLayer.DefaultDate);
}
catch (InvalidDataException e) { Debug.LogWarning($"ARMISTICE LINES: {e.Message}; no overlay"); }
}
if (!cam.TryGetComponent(out CameraRig rig)) rig = cam.gameObject.AddComponent<CameraRig>();
// The opening: Tel Aviv and Jaffa both in frame at CameraRig.StartDistance, including on a phone held upright
// (owner, 3 November 2026: "Open at ~30 km, like the promo").
var telAviv = list.Single(s => s.Id == "tel_aviv"); var jaffa = list.Single(s => s.Id == "jaffa");
rig.LookAt = CameraRig.OpeningLookAt(Frame, cam.aspect, telAviv, jaffa); rig.Init();
rig.Volume.transform.SetParent(transform, true);
// VolumeProfile's own teardown only releases its components, it does not destroy them (Core RP 17.3), so own both.
var assets = terrainGo.GetComponent<MapRuntimeAssets>();
foreach (var c in rig.Volume.profile.components) assets.Own(c);
assets.Own(rig.Volume.profile);
foreach (var undo in rig.TeardownActions) assets.OnTeardown(undo);
rig.TeardownActions.Clear();
}
/// <summary>The frame round the map and the table beyond it (MapBuilder.BuildFrame), drawn with the editor-made
/// MapFrame.mat; no collider, so clicks still pick only the terrain, and no shadow. It lies outside the terrain's
/// footprint only.</summary>
void AddFrame(GameObject terrainGo, float elevMinM)
{
var frame = new GameObject(FrameName);
frame.transform.SetParent(terrainGo.transform, false);
frame.AddComponent<MeshFilter>().sharedMesh =
MapBuilder.BuildFrame(Terrain.terrainData, elevMinM, terrainGo.GetComponent<MapRuntimeAssets>());
var renderer = frame.AddComponent<MeshRenderer>();
renderer.sharedMaterial = frameMaterial;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
/// <summary>The water inside the map (issue #195): MapBuilder.BuildWaterMesh's copy of the terrain's surface over the
/// water and its shore, drawn with a copy of Sea.mat in its terrain-water mode (Sea.shader _ScTerrainWater), which
/// adds the water's colour times its coverage on top of the terrain graph (black there); the land adds 0 (no discard: whole quads, #306). Drawn
/// right after the terrain, before the other opaques (TerrainWaterQueue); no depth write, no shadow, no collider
/// (clicks still pick only the terrain). The water's shading thus stays out of the terrain's fragment shader, whose
/// size it had pushed past a WebGL cost cliff (about 3 ms a frame at gameplay03, even with the water toggled
/// off).</summary>
void AddTerrainWater(GameObject terrainGo, float[,] heights, float elevMinM)
{
var assets = terrainGo.GetComponent<MapRuntimeAssets>();
var material = assets.Own(new Material(seaMaterial) { name = TerrainWaterName });
material.SetFloat("_ScTerrainWater", 1f);
material.SetFloat("_ScSrcBlend", (float)UnityEngine.Rendering.BlendMode.One);
material.SetFloat("_ScDstBlend", (float)UnityEngine.Rendering.BlendMode.One);
material.SetFloat("_ScZWrite", 0f);
material.SetShaderPassEnabled("DepthOnly", false);
material.SetShaderPassEnabled("DepthNormals", false);
material.renderQueue = TerrainWaterQueue;
var go = new GameObject(TerrainWaterName);
go.transform.SetParent(terrainGo.transform, false);
go.AddComponent<MeshFilter>().sharedMesh = WaterMesh(heights, elevMinM, assets);
var renderer = go.AddComponent<MeshRenderer>();
renderer.sharedMaterial = material;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
/// <summary>The baked water mesh when it matches these heights, else the one derived from them.</summary>
Mesh WaterMesh(float[,] heights, float elevMinM, MapRuntimeAssets assets)
{
var data = Terrain.terrainData;
if (terrainWaterMesh != null)
{
if (MapBuilder.TryReadWaterMesh(terrainWaterMesh.bytes, data.heightmapResolution, heights, out var grid, out var indices, out var why))
return assets.Own(MapBuilder.WaterMesh(data.heightmapResolution, data.size, heights, grid, indices));
Debug.LogWarning($"MAP {MapTexturePaths.WaterMesh}: {why}; deriving the water mesh at load");
}
return MapBuilder.BuildWaterMesh(data, heights, elevMinM, assets);
}
/// <summary>Test and editor seam: the baked water mesh (null: derived at load).</summary>
public void ConfigureWater(TextAsset baked) => terrainWaterMesh = baked;
static string MetaPath => "heightmap.json";
static string HexesPath => "hexes.json";
static string SettlementsPath => SettlementPlacer.DefaultFileName;
/// <summary>Destroys every child: all of them are things Build made (terrain, Settlements, PostFX). Walking the
/// hierarchy rather than remembered fields keeps Build idempotent after a domain reload (R2). The VolumeProfile is
/// owned by the terrain's MapRuntimeAssets, so destroying the terrain destroys it.</summary>
void Clear()
{
if (Application.isPlaying) Clear(go => { go.transform.SetParent(null); Destroy(go); });
else Clear(go => DestroyImmediate(go));
}
/// <summary>Clear with the destroy step given (test seam for the play-mode path, whose Destroy is deferred): each
/// child's MapRuntimeAssets teardown runs first, so it has run by the time Clear returns (review I1).</summary>
internal void Clear(Action<GameObject> destroy)
{
for (int i = transform.childCount - 1; i >= 0; i--)
{
var go = transform.GetChild(i).gameObject;
foreach (var assets in go.GetComponentsInChildren<MapRuntimeAssets>(true)) assets.RunTeardown();
destroy(go);
}
Terrain = null;
Hexes = null;
settlementsYamlRead = null;
UnitEntries = Array.Empty<Units.UnitEntry>(); unitsYamlRead = null;
Subdistricts = null; regionsYamlRead = null;
UnitSpots = new Dictionary<Units.UnitAnchor, Units.AnchorSpot>(); UnitHexes = Array.Empty<Statecraft.Sim.MapHex>();
RouteList = new List<Routes.RoutePath>();
}
}
}