A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: a plowed field or drained swamp shows on its hex's ground (Refs #2877) (#2888)
Eyal Golan74cc38590ea0
diff --git a/changelog.d/2877-site-ground.md b/changelog.d/2877-site-ground.mdnew file mode 100644index 000000000..60f70bc8c--- /dev/null+++ b/changelog.d/2877-site-ground.md@@ -0,0 +1,2 @@+- A plowed field now shows on its hex's ground as parcels with pale tracks, and a drained swamp as dark drained ground cut by+ straight canals. Both are redrawn from the game's sites, so a loaded save shows its own (Refs #2877).diff --git a/docs/visual-v1.md b/docs/visual-v1.mdindex 1b9969a47..0b61a7a42 100644--- a/docs/visual-v1.md+++ b/docs/visual-v1.md@@ -3619,3 +3619,55 @@ plaster, ashlar, rubble, roof tile, flat roof, ribbon glass, balcony rail, corru- **Frame time, not measured to this document's standard:** `?vprofile` needs the exclusive lock, which this lane did not take. Arun under the shared lock at load 11-16, main against the branch, read gameplay03 23.53 -> 22.12 ms (spreads 2.93, 3.93) anddiorama02 25.78 -> 28.03 ms (spreads 1.56, 2.98): a noisy reading, not a cost.++## Issue #2877: a plowed field or drained swamp on its hex's ground++The owner's answer on #2812 was "Ground change only", so a built field or a drained swamp has no kit and no pill and the+hex's ground shows it. `SiteGroundLayer` drapes one mesh per site over the terrain (about 2,100 vertices), drawn by+`Statecraft/SiteGround` after the ground and before the roads, in the order of `HulaPapyrusLayer`: `GameRoot` calls it on+every `Changed`, it reads `State.Sites`, and it builds a mesh only for a site that changed, so a loaded save draws its own.+A repaint of `_ScBiomeTex` was rejected: it is one map-wide upload, which would fall on End turn. A zero-area mesh draws from+the first frame, meant to keep the shader's first draw off the End turn that finishes the first site (measured below).+The look is a design value (no field layout or crop is sourced): seeded parcels of ploughed earth, young crop and stubble with+pale tracks; a drained swamp is dark earth with straight canals. The patch keeps off water, off ground that rises over 45 m+(world) round a vertex and off the inner 70% of every locality's footprint, and it fades out short of the hex's edge, so the+grid and the region borders stay on top. A hex with both the swamp and its field shows the field.++Cost, on a WebGL build (`Build.Web -compression disabled`), `?vprofile` under the **shared** machine lock on a busy machine+(load 4-9), so these are not the "How to measure" idle numbers. A throwaway patch, never committed, built seven sites and+limited the run to `all` against `-siteground` at the poses below, 3 interleaved runs of 300 frames each:++| Pose | `all` ms (spread) | `-siteground` ms (spread) | cost ms |+|---|---|---|---|+| Beit Kama, 60 km | 21.94 (3.43) | 21.66 (0.31) | +0.28 |+| Beit Kama, 15 km | 19.89 (0.47) | 20.14 (0.16) | -0.25 |+| Beit Kama, 6 km | 16.14 (0.24) | 16.36 (0.16) | -0.22 |+| Hula, 6 km | 15.27 (0.52) | 15.91 (0.19) | -0.64 |+| gameplay03 | 25.27 (0.20) | 25.41 (0.29) | -0.14 |++All are inside the 2.5 ms budget and within this busy machine's noise, so they say "no measurable cost here", not a number. The+first run at the first pose (24.85 ms, p95 48) is the 3.43 spread; the two runs after it were 21.42 and 21.94 ms.+Not measured: the same run under the exclusive lock.++Time on the main thread, on a WebGL build at `220a7d0a9` with a throwaway timing patch, never committed, under the shared lock+(load about 6-9), six page loads. Each field was left one turn from done in `State.Sites`, and the sim finished it in a real+`SimBridge.EndTurn`, with the camera on the fields at 31 km:++| Step | `ShowAt` ms |+|---|---|+| The first field (one mesh plus `PlacementLayer.CampGround`) | 2.5-5.3 |+| Each later field (one mesh) | 0.9-1.5 |+| `SimBridge.Replace` with seven built fields, four of them new meshes | 3.4-4.3 |++So one mesh is about 1 ms; seven new at once would be about 7 ms by that rate, not measured. The End turn around it took+668-2,253 ms with or without a field (`EndTurn` alone, on controls and on field turns alike), so that freeze is not this layer's.+The load was the `Replace` path with a session whose sites were set by hand, not a save file read from disk.++The warm mesh: three runs with it and three without (`sgnowarm` in the throwaway patch) gave the same frames after the first+field's End turn, the worst of the next 12 being 416-441 ms with it and 417-478 ms without, on this Mac's Chrome (ANGLE over+Metal). Two controls without a field had a 601-621 ms frame in five of the six runs, so that spike is not traced to the field. The+later fields' worst frame was 74-127 ms against about 50 ms on the control turn, with or without the warm mesh and outside+`ShowAt`; the cause is not traced. So the warm mesh shows no gain here; its use on other GPU drivers is not measured.++With #2884 (the border glow) merged locally, the 60 km stills of Beit Kama and Mefalsim show the blue and white stripes whole: the patch+stops inside them. It does cover the wash inside the hex where a parcel lies.diff --git a/unity/Assets/Resources/Map/SiteGround.mat b/unity/Assets/Resources/Map/SiteGround.matnew file mode 100644index 000000000..b24226c77--- /dev/null+++ b/unity/Assets/Resources/Map/SiteGround.mat@@ -0,0 +1,31 @@+%YAML 1.1+%TAG !u! tag:unity3d.com,2011:+--- !u!21 &2100000+Material:+ serializedVersion: 8+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_Name: SiteGround+ m_Shader: {fileID: 4800000, guid: 1ffc93f14926402595c48262fa96d68a, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords: []+ m_InvalidKeywords: []+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 0+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: -1+ stringTagMap: {}+ disabledShaderPasses: []+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs: []+ m_Ints: []+ m_Floats:+ - _Opacity: 0.92+ m_Colors: []+ m_BuildTextureStacks: []+ m_AllowLocking: 1diff --git a/unity/Assets/Resources/Map/SiteGround.mat.meta b/unity/Assets/Resources/Map/SiteGround.mat.metanew file mode 100644index 000000000..9bccdaf18--- /dev/null+++ b/unity/Assets/Resources/Map/SiteGround.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: e010abbddbc040f9909f2d1db4f38616+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/SiteGroundLayer.cs b/unity/Assets/Scripts/Map/SiteGroundLayer.csnew file mode 100644index 000000000..f26dd43f1--- /dev/null+++ b/unity/Assets/Scripts/Map/SiteGroundLayer.cs@@ -0,0 +1,221 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.Game.Map.Kits;+using Statecraft.Game.Map.Routes;+using Statecraft.HexTiles;+using Statecraft.Sim;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map+{+ /// <summary>#2877: a plowed field or a drained swamp shows on its hex's ground (the owner on #2812, "Ground change only": no+ /// kit and no pill, SiteLayer). A patch of parcels draped on the terrain, drawn by Statecraft/SiteGround over the baked ground,+ /// redrawn from State.Sites as <see cref="Collection.HulaPapyrusLayer"/> is, so a loaded save shows its own sites.+ /// Why a layer over the terrain and not a repaint of <c>_ScBiomeTex</c> (MapBuilder.BakeBiomeTexture): that texture is one+ /// map-wide upload, so a repaint would stall End turn; this builds one small mesh, for the site that changed only.+ /// A site's first draw would compile the shader, on the End turn that finishes it, so a zero-area mesh draws from the first+ /// frame (<see cref="WarmName"/>); it costs one draw call and shows nothing.+ /// The look is a design value, no field layout or crop is sourced: the mesh carries the site's own seeded axes, the shader+ /// paints the parcels. A hex with a field and the swamp it was drained from (hula, hula_field) shows the field. The patch+ /// keeps off water, steep ground and the heart of every town's footprint and fades out short of the hex's edge, so the grid and the region borders stay+ /// on top. Presentation only: what is built, and when, is the sim's (R-SITE-001 to R-SITE-003, R-SWAMP-001).</summary>+ public sealed class SiteGroundLayer : MonoBehaviour+ {+ public const string Name = "SiteGround", WarmName = "Warm", ToggleName = "siteground", MaterialResource = "Map/SiteGround";+ /// <summary>The look, in the mesh's vertex colour's red (Statecraft/SiteGround): a plowed field, or the drained swamp.</summary>+ public const int Field = 0, Drained = 1;+ // Design values. StepM: the mesh's spacing, a few of the heightmap's samples, enough to follow the ground and the mask.+ // LiftM: over the highest ground round a vertex, low enough not to bury a house's foot (a road's 20 m would).+ // EdgeInsetM, EdgeFadeM: the patch starts this far inside the hex's edge and is whole this far in, so the parcels+ // the shader drops along the way give it a field's outline, not a hexagon's. ClearShare, ClearFadeM: the same round a+ // town: from this share of its footprint (a footprint's rim is sparse: the whole disc left a round hole in the fields).+ // SteepM: no field on ground that rises this much (world m, exaggerated) round a vertex, about a 28% drawn slope.+ public const float StepM = 160f, LiftM = 6f, EdgeInsetM = 250f, EdgeFadeM = 1500f, ClearShare = 0.7f, ClearFadeM = 1200f, SteepM = 45f;+ const float AxisStepDeg = 15f, OffsetRangeM = 8000f;+ /// <summary>The budget of a site's mesh: a 4.4 km hex at <see cref="StepM"/>, with its rim, comes to about 2,100 vertices.</summary>+ public const int MaxVertices = 2500;++ readonly Dictionary<string, (GameObject Go, Mesh Mesh, int Look)> shown = new Dictionary<string, (GameObject, Mesh, int)>();+ Mesh? warm;+ KitGround? ground;+ MapScene map = null!;++ /// <summary>The site ids drawn now.</summary>+ public IReadOnlyCollection<string> Shown => shown.Keys;+ /// <summary>How many meshes this layer has built (tests: an unchanged turn builds none).</summary>+ public int MeshesBuilt { get; private set; }+ public Mesh? MeshOf(string site) => shown.TryGetValue(site, out var s) ? s.Mesh : null;++ public static Material MaterialFor() => Resources.Load<Material>(MaterialResource);++ /// <summary>The built field and drained swamp sites, one per hex (the field over the swamp it was drained from), in+ /// site-id order.</summary>+ public static List<(Site Site, int Look)> Wanted(Content content, IEnumerable<SiteWork> sites)+ {+ var byHex = new Dictionary<(int, int), (Site Site, int Look)>();+ foreach (var w in sites.Where(w => w.BuiltOn != null).OrderBy(w => w.Site, StringComparer.Ordinal))+ {+ var site = content.Sites.FirstOrDefault(s => s.Id == w.Site);+ if (site == null) continue;+ int look = site.Kinds.Contains(Projects.FieldKind) ? Field : site.Kinds.Contains(Projects.SwampKind) ? Drained : -1;+ if (look < 0) continue;+ var hex = (site.Q, site.R);+ if (!byHex.TryGetValue(hex, out var had) || look == Field) byHex[hex] = (site, look);+ }+ return byHex.Values.OrderBy(v => v.Site.Id, StringComparer.Ordinal).ToList();+ }++ /// <summary>The layer on <paramref name="map"/>, made on the first call with its warm mesh, showing what+ /// <paramref name="sites"/> ask for. Builds only what changed, so it can run on every Changed. Null on the hex-tile map,+ /// whose boards have no such ground to draw on.</summary>+ public static SiteGroundLayer? ShowAt(MapScene map, Content content, IEnumerable<SiteWork> sites)+ {+ if (map == null || map.Terrain == null || map.Hexes == null || content == null || HexTilesLook.Requested()) return null;+ var layer = map.Terrain.transform.Find(Name)?.GetComponent<SiteGroundLayer>();+ if (layer == null)+ {+ var go = new GameObject(Name);+ go.transform.SetParent(map.Terrain.transform, false);+ go.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity); // the meshes' vertices are in world space+ layer = go.AddComponent<SiteGroundLayer>();+ layer.map = map;+ layer.AddWarm();+ var made = layer;+ map.Terrain.GetComponent<MapRuntimeAssets>().OnTeardown(VisualToggles.Register(ToggleName, on => { if (made != null) made.gameObject.SetActive(on); }));+ }+ layer.Show(Wanted(content, sites));+ return layer;+ }++ void AddWarm()+ {+ warm = new Mesh { name = WarmName };+ var centre = new Vector3(0.5f * map.Frame.WidthM, 0f, 0.5f * map.Frame.LengthM);+ warm.vertices = new[] { centre, centre, centre };+ warm.normals = new[] { Vector3.up, Vector3.up, Vector3.up };+ warm.triangles = new[] { 0, 1, 2 };+ warm.bounds = new Bounds(centre, new Vector3(map.Frame.WidthM, 1e6f, map.Frame.LengthM)); // never culled+ Add(WarmName, warm);+ }++ GameObject Add(string name, Mesh mesh)+ {+ var go = new GameObject(name);+ go.transform.SetParent(transform, false);+ go.AddComponent<MeshFilter>().sharedMesh = mesh;+ var r = go.AddComponent<MeshRenderer>();+ r.sharedMaterial = MaterialFor();+ r.shadowCastingMode = ShadowCastingMode.Off;+ r.receiveShadows = true;+ return go;+ }++ void Show(List<(Site Site, int Look)> wanted)+ {+ foreach (var id in shown.Where(s => !wanted.Any(w => w.Site.Id == s.Key && w.Look == s.Value.Look)).Select(s => s.Key).ToList())+ {+ var (go, mesh, _) = shown[id];+ shown.Remove(id);+ Drop(go); Drop(mesh);+ }+ foreach (var (site, look) in wanted)+ {+ if (shown.ContainsKey(site.Id)) continue;+ ground ??= PlacementLayer.CampGround(map);+ var mesh = BuildMesh(map, ground, site, look);+ MeshesBuilt++;+ shown[site.Id] = (Add(site.Id, mesh), mesh, look);+ }+ }++ static void Drop(UnityEngine.Object o) { if (Application.isPlaying) Destroy(o); else DestroyImmediate(o); }++ void OnDestroy()+ {+ foreach (var s in shown.Values) if (s.Mesh != null) Drop(s.Mesh);+ shown.Clear();+ if (warm != null) Drop(warm);+ }++ /// <summary>A stable hash of a site's id (never string.GetHashCode: it differs between runs on some runtimes).</summary>+ internal static uint Hash(string id)+ {+ uint h = 2166136261u;+ foreach (char c in id) h = (h ^ c) * 16777619u;+ return h;+ }++ /// <summary>The distance (m) from <paramref name="p"/>, relative to the hex's centre, to the edge of a pointy-top hex+ /// (HexMath) of corner radius <paramref name="sizeM"/>; negative outside.</summary>+ public static float EdgeDistance(Vector2 p, float sizeM)+ {+ float a = Mathf.Abs(p.x), b = Mathf.Abs(0.5f * p.x + 0.8660254f * p.y), c = Mathf.Abs(0.5f * p.x - 0.8660254f * p.y);+ return 0.8660254f * sizeM - Mathf.Max(a, Mathf.Max(b, c));+ }++ /// <summary>The site's patch: a grid over its hex in world space, each vertex on the ground. Its colour's alpha is the+ /// mask (0 off the hex's inside, on water and on a town), red the look; its uv is the site's own seeded axes, in metres.</summary>+ static Mesh BuildMesh(MapScene map, KitGround ground, Site site, int look)+ {+ var hex = map.Hexes.hexes.First(h => h.q == site.Q && h.r == site.R);+ var c3 = map.Frame.ToWorld(hex.lon, hex.lat, 0f);+ var centre = new Vector2(c3.x, c3.z);+ float sizeM = map.Hexes.hex_size_km * 1000f;+ uint seed = Hash(site.Id);+ float axis = Mathf.Deg2Rad * (seed % 12u) * AxisStepDeg;+ var along = new Vector2(Mathf.Cos(axis), Mathf.Sin(axis));+ var across = new Vector2(-along.y, along.x);+ var offset = new Vector2(((seed >> 8) & 0xffu) / 255f, ((seed >> 16) & 0xffu) / 255f) * OffsetRangeM;+ var terrain = map.Terrain; var data = terrain.terrainData; var origin = terrain.transform.position;+ int n = Mathf.CeilToInt(sizeM / StepM), side = 2 * n + 1;+ var index = new int[side * side];+ var around = new[] { new Vector2(0.5f * StepM, 0f), new Vector2(-0.5f * StepM, 0f), new Vector2(0f, 0.5f * StepM), new Vector2(0f, -0.5f * StepM) };+ // Only the footprints that can reach a vertex: the hex's rim is within two steps of its corner radius.+ float reach = sizeM + 2f * StepM + ClearFadeM;+ var near = map.KitFootprints.Where(f => (f.centre - centre).magnitude - ClearShare * f.radius < reach).ToList();+ var verts = new List<Vector3>(); var normals = new List<Vector3>(); var uvs = new List<Vector2>(); var colours = new List<Color32>();+ for (int j = 0; j < side; j++)+ for (int i = 0; i < side; i++)+ {+ index[j * side + i] = -1;+ var rel = new Vector2((i - n) * StepM, (j - n) * StepM);+ if (EdgeDistance(rel, sizeM) < -StepM) continue;+ var p = centre + rel;+ if (!ground.Inside(p.x, p.y)) continue;+ index[j * side + i] = verts.Count;+ float y = RouteLayer.Ground(data, origin, p), low = y;+ foreach (var d in around)+ {+ float h = RouteLayer.Ground(data, origin, p + d);+ y = Mathf.Max(y, h); low = Mathf.Min(low, h);+ }+ verts.Add(new Vector3(p.x, y + LiftM, p.y));+ normals.Add(data.GetInterpolatedNormal((p.x - origin.x) / data.size.x, (p.y - origin.z) / data.size.z));+ uvs.Add(new Vector2(Vector2.Dot(rel, along), Vector2.Dot(rel, across)) + offset);+ float mask = Mathf.Clamp01((EdgeDistance(rel, sizeM) - EdgeInsetM) / EdgeFadeM);+ if (mask > 0f && (y - low > SteepM || ground.Hex(p.x, p.y) != (site.Q, site.R) || ground.Water(p.x, p.y))) mask = 0f;+ if (mask > 0f)+ foreach (var f in near)+ mask = Mathf.Min(mask, Mathf.Clamp01(((f.centre - p).magnitude - ClearShare * f.radius) / ClearFadeM));+ colours.Add(new Color32((byte)(look == Drained ? 255 : 0), 0, 0, (byte)Mathf.RoundToInt(255f * mask)));+ }+ var tris = new List<int>();+ for (int j = 0; j + 1 < side; j++)+ for (int i = 0; i + 1 < side; i++)+ {+ int a = index[j * side + i], b = index[j * side + i + 1], c = index[(j + 1) * side + i], d = index[(j + 1) * side + i + 1];+ if (a < 0 || b < 0 || c < 0 || d < 0) continue;+ if (colours[a].a == 0 && colours[b].a == 0 && colours[c].a == 0 && colours[d].a == 0) continue;+ tris.AddRange(new[] { a, c, b, b, c, d });+ }+ var mesh = new Mesh { name = Name + " " + site.Id };+ mesh.SetVertices(verts); mesh.SetNormals(normals); mesh.SetUVs(0, uvs); mesh.SetColors(colours);+ mesh.SetTriangles(tris, 0);+ mesh.RecalculateBounds();+ return mesh;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/SiteGroundLayer.cs.meta b/unity/Assets/Scripts/Map/SiteGroundLayer.cs.metanew file mode 100644index 000000000..245ea734d--- /dev/null+++ b/unity/Assets/Scripts/Map/SiteGroundLayer.cs.meta@@ -0,0 +1,11 @@+fileFormatVersion: 2+guid: 78bd9ba6d8bb451ab1316f6d671ae0f2+MonoImporter:+ externalObjects: {}+ serializedVersion: 2+ defaultReferences: []+ executionOrder: 0+ icon: {instanceID: 0}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 11bc0228e..282cc8d15 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -1128,6 +1128,8 @@ namespace Statecraft.Game.UI// once the swamp is drained (#2082; owner, 2 November 2026: "Hula + Arava, map and boards").Statecraft.Game.Map.Collection.HulaPapyrusLayer.ShowAt(map, Bridge.Content,Statecraft.Game.Map.Collection.HulaPapyrusLayer.Drained(Bridge.State));+ // A plowed field's or drained swamp's ground on its hex (#2877): from the sites, so a loaded save shows its own.+ SiteGroundLayer.ShowAt(map, Bridge.Content, Bridge.State.Sites.Values);// Tal Heuberger's civilian figures at towns, villages, transit camps and building sites, ambience only and streamed// after the first frame (#666, #708, #886): the residents follow the settlement state, the builders the projects.Statecraft.Game.Map.Collection.CivilianPeople.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content,diff --git a/unity/Assets/Shaders/SiteGround.shader b/unity/Assets/Shaders/SiteGround.shadernew file mode 100644index 000000000..312c9feab--- /dev/null+++ b/unity/Assets/Shaders/SiteGround.shader@@ -0,0 +1,138 @@+// #2877: the ground of a plowed field or a drained swamp (SiteGroundLayer): one patch draped on the terrain over the baked+// ground, in parcels. The mesh gives the site's own axes in metres (uv: x along the furrows, y across), the look (color.r: 0+// field, 1 drained swamp) and the mask (color.a: 0 at the hex's edge, on water and on a town). Each parcel shows only where the+// mask passes its own hashed threshold, so the patch ends along parcels, not along a hexagon. The furrows and the tracks are+// box-filtered to the pixel (Route.shader's PulseBox), so they fade to their mean instead of shimmering as the camera pulls+// back. Lit like the ground beside it, as Route.shader: the sun with its shadows plus the ambient probe, then the hex grid and+// the land haze of StatecraftMap.hlsl. Drawn before the roads and the railways (the Transparent queue less ten), so they cross+// it on top. All colours and sizes are design values: no field layout or crop is sourced.+Shader "Statecraft/SiteGround"+{+ Properties+ {+ _Opacity ("Opacity", Range(0, 1)) = 1+ }+ SubShader+ {+ Tags { "RenderType" = "Transparent" "Queue" = "Transparent-10" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" }+ Pass+ {+ Name "SiteGround"+ Tags { "LightMode" = "UniversalForward" }+ Blend SrcAlpha OneMinusSrcAlpha+ ZWrite Off+ ZTest LEqual+ Cull Off+ Offset -1, -4+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ // The main light's shadows, as the terrain and Route.shader have them.+ #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN+ #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"+ #include "Assets/Shaders/StatecraftMap.hlsl"++ CBUFFER_START(UnityPerMaterial)+ float _Opacity;+ CBUFFER_END++ // The rows' width and the parcels' mean length along a row (m): about 20 by 40 px at the gameplay zoom.+ static const float RowM = 900.0, ParcelM = 1700.0;+ static const float FurrowM = 130.0; // a furrow pair: three pixels at the gameplay zoom, sharp up close+ static const float TrackDuty = 0.05; // the share of a row or parcel the pale track between them takes+ static const float MaskSoft = 0.06;+ static const float3 PloughedSrgb = float3(0.46, 0.33, 0.22), PloughedDarkSrgb = float3(0.33, 0.23, 0.15);+ static const float3 YoungSrgb = float3(0.42, 0.53, 0.22), YoungDarkSrgb = float3(0.33, 0.45, 0.17);+ static const float3 StubbleSrgb = float3(0.78, 0.65, 0.34), StubbleDarkSrgb = float3(0.69, 0.56, 0.27);+ static const float3 PeatSrgb = float3(0.25, 0.19, 0.14), PeatDarkSrgb = float3(0.18, 0.13, 0.10);+ static const float3 TrackSrgb = float3(0.72, 0.63, 0.47);+ static const float3 CanalSrgb = float3(0.16, 0.24, 0.26);+ static const float CanalM = 2600.0, CanalDuty = 0.05; // the drained swamp's straight canals, about 6 px wide at the gameplay zoom++ struct Attributes { float4 positionOS : POSITION; float3 normalOS : NORMAL; float2 uv : TEXCOORD0; float4 color : COLOR; };+ struct Varyings { float4 positionCS : SV_POSITION; float3 positionWS : TEXCOORD0; float3 normalWS : TEXCOORD1; float2 uv : TEXCOORD2; float2 look : TEXCOORD3; };++ Varyings Vert(Attributes input)+ {+ Varyings o;+ VertexPositionInputs p = GetVertexPositionInputs(input.positionOS.xyz);+ o.positionCS = p.positionCS; o.positionWS = p.positionWS;+ o.normalWS = TransformObjectToWorldNormal(input.normalOS);+ o.uv = input.uv;+ o.look = float2(input.color.r, input.color.a);+ return o;+ }++ float Hash(float2 p)+ {+ float3 q = frac(float3(p.xyx) * 0.1031);+ q += dot(q, q.yzx + 33.33);+ return frac((q.x + q.y) * q.z);+ }++ // Integral of a pulse train (1 for the first `duty` of each `period`, 0 after), for its box filter (Route.shader).+ float PulseIntegral(float x, float period, float duty)+ {+ float k = floor(x / period);+ return k * duty * period + min(x - k * period, duty * period);+ }++ // Share of a pixel `w` wide (same units) centred at x covered by the pulse train.+ float PulseBox(float x, float w, float period, float duty)+ {+ w = max(w, 1e-3);+ return (PulseIntegral(x + 0.5 * w, period, duty) - PulseIntegral(x - 0.5 * w, period, duty)) / w;+ }++ half4 Frag(Varyings input) : SV_Target+ {+ float2 uv = input.uv;+ float wx = max(fwidth(uv.x), 1e-3), wy = max(fwidth(uv.y), 1e-3);+ float2 mapM = input.positionWS.xz - _ScMapOrigin.xz;+ float grid = ScGridAmount(mapM, input.positionWS); // uniform control flow (it takes derivatives)++ float row = floor(uv.y / RowM);+ float x = uv.x + Hash(float2(row, 3.0)) * ParcelM; // each row's parcels break at their own places+ float cell = floor(x / ParcelM);+ float id = Hash(float2(cell, row));+ float show = Hash(float2(row, cell) + 41.0);+ float furrows = PulseBox(uv.y, wy, FurrowM, 0.5);++ bool drained = input.look.x > 0.5;+ float3 lightC, darkC;+ if (drained)+ {+ lightC = SRGBToLinear(id < 0.72 ? PeatSrgb : YoungSrgb);+ darkC = SRGBToLinear(id < 0.72 ? PeatDarkSrgb : YoungDarkSrgb);+ }+ else+ {+ lightC = SRGBToLinear(id < 0.6 ? PloughedSrgb : id < 0.82 ? YoungSrgb : StubbleSrgb);+ darkC = SRGBToLinear(id < 0.6 ? PloughedDarkSrgb : id < 0.82 ? YoungDarkSrgb : StubbleDarkSrgb);+ }+ float3 albedo = lerp(darkC, lightC, furrows);+ // The tracks: the row's and the parcel's first share. A pale line between the parcels.+ float track = saturate(PulseBox(uv.y, wy, RowM, TrackDuty) + PulseBox(x, wx, ParcelM, TrackDuty * 0.6));+ albedo = lerp(albedo, SRGBToLinear(TrackSrgb), track);+ if (drained)+ {+ float canal = saturate(PulseBox(uv.x, wx, CanalM, CanalDuty));+ albedo = lerp(albedo, SRGBToLinear(CanalSrgb), canal);+ }+ albedo = lerp(albedo, SRGBToLinear(ScGridLandSrgb), grid * _ScGrid.x);++ float threshold = 0.15 + 0.7 * show;+ float alpha = smoothstep(threshold - MaskSoft, threshold + MaskSoft, input.look.y);++ float3 n = normalize(input.normalWS);+ Light sun = GetMainLight(TransformWorldToShadowCoord(input.positionWS));+ float3 lit = albedo * (sun.color * saturate(dot(n, sun.direction)) * sun.shadowAttenuation * sun.distanceAttenuation + SampleSH(n));+ float h = _ScHaze.a * ScHazeAmount(input.positionWS);+ return half4(lerp(lit, _ScHaze.rgb, h), alpha * _Opacity);+ }+ ENDHLSL+ }+ }+}diff --git a/unity/Assets/Shaders/SiteGround.shader.meta b/unity/Assets/Shaders/SiteGround.shader.metanew file mode 100644index 000000000..f5c1bd27c--- /dev/null+++ b/unity/Assets/Shaders/SiteGround.shader.meta@@ -0,0 +1,9 @@+fileFormatVersion: 2+guid: 1ffc93f14926402595c48262fa96d68a+ShaderImporter:+ externalObjects: {}+ defaultTextures: []+ nonModifiableTextures: []+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/SiteGroundLayerTests.cs b/unity/Assets/Tests/EditMode/SiteGroundLayerTests.csnew file mode 100644index 000000000..cc275ba09--- /dev/null+++ b/unity/Assets/Tests/EditMode/SiteGroundLayerTests.cs@@ -0,0 +1,283 @@+#nullable enable+using System;+using System.Collections;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Routes;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.Rendering;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>#2877: a plowed field or a drained swamp shows on its hex's ground (the owner on #2812, "Ground change only"), from+/// State.Sites, as HulaPapyrusLayer redraws from it: nothing to bake, built only for a site that just changed (so no hitch at+/// End turn), and right after a save is loaded.</summary>+public class SiteGroundLayerTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static readonly DateTime Date = new DateTime(1949, 6, 30);+ static SiteWork Built(string id) => SiteWork.Built(id, Date);++ [TearDown]+ public void Empty() => EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);++ static MapScene OpenMap()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = Object.FindFirstObjectByType<MapScene>();+ map.Build();+ return map;+ }++ static (int q, int r) HexOf(string id) { var s = C.Sites.Single(x => x.Id == id); return (s.Q, s.R); }++ [Test]+ public void OnlyABuiltFieldOrDrainedSwampWantsGround()+ {+ var wanted = SiteGroundLayer.Wanted(C, new[]+ {+ Built("beit_kama"), Built("tzrifin"), new SiteWork("reim_field", 1, 4, null), Built("gilat_field"), Built("hula"), Built("no_such_site"),+ });+ CollectionAssert.AreEqual(new[] { ("gilat_field", SiteGroundLayer.Field), ("hula", SiteGroundLayer.Drained) }, wanted.Select(w => (w.Site.Id, w.Look)).ToArray());+ }++ [Test]+ public void AHexShowsOneGroundAndTheFieldBeatsTheDrainedSwampItWasBuiltOn()+ {+ // content/sites.yaml: hula_field stands in the swamp's hex and is plowed once the swamp is drained (R-SWAMP-001).+ Assert.AreEqual(HexOf("hula"), HexOf("hula_field"));+ var wanted = SiteGroundLayer.Wanted(C, new[] { Built("hula"), Built("hula_field") });+ CollectionAssert.AreEqual(new[] { ("hula_field", SiteGroundLayer.Field) }, wanted.Select(w => (w.Site.Id, w.Look)).ToArray());+ }++ [Test]+ public void TheGroundStaysOnItsHexAndKeepsOffWaterAndTowns()+ {+ var map = OpenMap();+ var layer = SiteGroundLayer.ShowAt(map, C, new[] { Built("beit_kama_field"), Built("hula"), Built("beit_shemesh_field") })!;+ var ground = PlacementLayer.CampGround(map);+ foreach (var (id, hex) in new[] { "beit_kama_field", "hula", "beit_shemesh_field" }.Select(i => (i, HexOf(i))))+ {+ var mesh = layer.MeshOf(id)!;+ Assert.Greater(mesh.vertexCount, 1000, id + ": the mesh covers the hex");+ Assert.LessOrEqual(mesh.vertexCount, SiteGroundLayer.MaxVertices, id);+ var v = mesh.vertices; var c = mesh.colors32; var n = mesh.normals;+ int shown = 0;+ for (int i = 0; i < v.Length; i++)+ {+ Assert.Greater(n[i].y, 0f, id + ": normals up, as the ground's");+ if (c[i].a == 0) continue;+ shown++;+ Assert.AreEqual(hex, ground.Hex(v[i].x, v[i].z), $"{id} vertex {i}");+ Assert.IsFalse(ground.Water(v[i].x, v[i].z), $"{id} vertex {i} on water");+ foreach (var f in map.KitFootprints)+ Assert.Greater((f.centre - new Vector2(v[i].x, v[i].z)).magnitude, SiteGroundLayer.ClearShare * f.radius, $"{id} vertex {i} inside {f.id}");+ float y = ground.Y(v[i].x, v[i].z);+ Assert.That(v[i].y - y, Is.InRange(0f, 60f), $"{id} vertex {i} lies on the ground");+ }+ Assert.Greater(shown, 300, id + ": most of the hex shows the change");+ }+ }++ /// <summary>No sourced field or swamp site has water under its patch, so the water guard is checked on a made-up field+ /// in the middle of the Sea of Galilee (lake hex 13,9; KitTests.TheLakeIsItsWaterNotItsWholeHex). Only the vertices that+ /// every other guard leaves whole are asked about (well inside the hex, flat, clear of every footprint): water alone must+ /// hide them.</summary>+ [Test]+ public void TheGroundKeepsOffALakesWater()+ {+ var map = OpenMap();+ var lake = new Site { Id = "lake_probe", Q = 13, R = 9, Kinds = new List<string> { Projects.FieldKind } };+ var layer = SiteGroundLayer.ShowAt(map, new Content { Sites = new List<Site> { lake } }, new[] { Built(lake.Id) })!;+ var ground = PlacementLayer.CampGround(map);+ var hex = map.Hexes.hexes.First(h => h.q == lake.Q && h.r == lake.R);+ var c3 = map.Frame.ToWorld(hex.lon, hex.lat, 0f);+ var centre = new Vector2(c3.x, c3.z);+ float sizeM = map.Hexes.hex_size_km * 1000f;+ var data = map.Terrain.terrainData; var origin = map.Terrain.transform.position;+ var around = new[] { new Vector2(0.5f * SiteGroundLayer.StepM, 0f), new Vector2(-0.5f * SiteGroundLayer.StepM, 0f), new Vector2(0f, 0.5f * SiteGroundLayer.StepM), new Vector2(0f, -0.5f * SiteGroundLayer.StepM) };+ var mesh = layer.MeshOf(lake.Id)!;+ var v = mesh.vertices; var c = mesh.colors32;+ int open = 0;+ for (int i = 0; i < v.Length; i++)+ {+ var p = new Vector2(v[i].x, v[i].z);+ if (!ground.Water(p.x, p.y)) continue;+ if (SiteGroundLayer.EdgeDistance(p - centre, sizeM) < SiteGroundLayer.EdgeInsetM + SiteGroundLayer.EdgeFadeM + 1f) continue;+ if (ground.Hex(p.x, p.y) != (lake.Q, lake.R)) continue;+ float low = RouteLayer.Ground(data, origin, p);+ foreach (var d in around) low = Mathf.Min(low, RouteLayer.Ground(data, origin, p + d));+ if (v[i].y - SiteGroundLayer.LiftM - low > SiteGroundLayer.SteepM - 1f) continue;+ if (map.KitFootprints.Any(f => (f.centre - p).magnitude < SiteGroundLayer.ClearShare * f.radius + SiteGroundLayer.ClearFadeM + 1f)) continue;+ open++;+ Assert.AreEqual(0, c[i].a, $"lake vertex {i} at {p}: no field on the water");+ }+ Assert.Greater(open, 100, "the probe's hex holds open, flat lake water that only the water guard keeps clear");+ }++ [Test]+ public void TheGroundIsTheSameEveryTime()+ {+ var map = OpenMap();+ var a = SiteGroundLayer.ShowAt(map, C, new[] { Built("gilat_field") })!.MeshOf("gilat_field")!;+ var (v, uv, c) = (a.vertices, a.uv, a.colors32);+ SiteGroundLayer.ShowAt(map, C, Array.Empty<SiteWork>());+ var b = SiteGroundLayer.ShowAt(map, C, new[] { Built("gilat_field") })!.MeshOf("gilat_field")!;+ Assert.AreNotSame(a, b, "dropped and made again");+ CollectionAssert.AreEqual(v, b.vertices); CollectionAssert.AreEqual(uv, b.uv); CollectionAssert.AreEqual(c, b.colors32);+ }++ [Test]+ public void TheSeedIsFixedAcrossRuns()+ {+ // FNV-1a by hand: string.GetHashCode would give another field layout in each run.+ Assert.AreEqual(3907230421u, SiteGroundLayer.Hash("gilat_field"));+ }++ [Test]+ public void OnlyASiteThatChangedIsBuilt()+ {+ var map = OpenMap();+ var layer = SiteGroundLayer.ShowAt(map, C, new[] { Built("gilat_field") })!;+ var first = layer.MeshOf("gilat_field");+ Assert.NotNull(first);+ int built = layer.MeshesBuilt;+ Assert.AreSame(layer, SiteGroundLayer.ShowAt(map, C, new[] { Built("gilat_field") }), "one layer on the map");+ Assert.AreEqual(built, layer.MeshesBuilt, "nothing changed: the next turn's redraw builds nothing");+ SiteGroundLayer.ShowAt(map, C, new[] { Built("gilat_field"), Built("reim_field") });+ Assert.AreEqual(built + 1, layer.MeshesBuilt, "one more site: one more mesh");+ Assert.AreSame(first, layer.MeshOf("gilat_field"));+ CollectionAssert.AreEquivalent(new[] { "gilat_field", "reim_field" }, layer.Shown);+ }++ [Test]+ public void TheShaderIsWarmBeforeAnySiteIsBuilt()+ {+ // The first draw of a shader compiles it, which must not fall on the End turn that finishes the first site.+ var map = OpenMap();+ var layer = SiteGroundLayer.ShowAt(map, C, Array.Empty<SiteWork>())!;+ CollectionAssert.IsEmpty(layer.Shown);+ var warm = layer.transform.Find(SiteGroundLayer.WarmName).GetComponent<MeshRenderer>();+ Assert.AreEqual(SiteGroundLayer.MaterialFor(), warm.sharedMaterial);+ var mesh = warm.GetComponent<MeshFilter>().sharedMesh;+ Assert.AreEqual(1, mesh.vertices.Distinct().Count(), "no area: nothing shows");+ Assert.AreEqual(ShadowCastingMode.Off, warm.shadowCastingMode);+ Assert.Greater(warm.bounds.size.x, map.Frame.WidthM * 0.9f, "never culled, so the draw happens at any view");+ Assert.Greater(warm.bounds.size.z, map.Frame.LengthM * 0.9f);+ }++ [Test]+ public void TheMaterialDrawsUnderTheRoadsAndCompilesForWebGL2()+ {+ var material = SiteGroundLayer.MaterialFor();+ Assert.NotNull(material, "Resources/" + SiteGroundLayer.MaterialResource);+ Assert.Less(material.renderQueue, Resources.Load<Material>(RouteLayer.RailMaterialResource).renderQueue, "a railway crosses a field on top");+ Assert.Less(material.renderQueue, Resources.Load<Material>(RouteLayer.RoadMaterialResource).renderQueue, "a road crosses a field on top");+ Assert.GreaterOrEqual(material.renderQueue, (int)RenderQueue.GeometryLast + 1, "after the ground and the kits");+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(material.shader));+ }++ [Test]+ public void TheToggleSwitchesTheGroundAndGoesWithTheMap()+ {+ var map = OpenMap();+ var layer = SiteGroundLayer.ShowAt(map, C, new[] { Built("gilat_field") })!;+ CollectionAssert.Contains(VisualToggles.Names, SiteGroundLayer.ToggleName);+ VisualToggles.Set(SiteGroundLayer.ToggleName, false);+ Assert.IsFalse(layer.gameObject.activeSelf);+ Assert.AreSame(layer, SiteGroundLayer.ShowAt(map, C, new[] { Built("gilat_field") }), "still found while switched off");+ VisualToggles.Set(SiteGroundLayer.ToggleName, true);+ Assert.IsTrue(layer.gameObject.activeSelf);+ map.Terrain.GetComponent<MapRuntimeAssets>().RunTeardown();+ CollectionAssert.DoesNotContain(VisualToggles.Names, SiteGroundLayer.ToggleName);+ }++ /// <summary>The camera's frame over the map, as 8-bit pixels (batch runs have a GPU: no -nographics).</summary>+ static Color32[] Frame(Camera cam, int size)+ {+ var rt = new RenderTexture(size, size, 24, RenderTextureFormat.ARGB32);+ var before = cam.targetTexture;+ cam.targetTexture = rt; cam.Render(); cam.targetTexture = before;+ var prev = RenderTexture.active; RenderTexture.active = rt;+ var tex = new Texture2D(size, size, TextureFormat.RGBA32, false);+ tex.ReadPixels(new Rect(0, 0, size, size), 0, 0); tex.Apply();+ RenderTexture.active = prev;+ var px = tex.GetPixels32();+ Object.DestroyImmediate(tex); rt.Release(); Object.DestroyImmediate(rt);+ return px;+ }++ [Test]+ public void TheHexsGroundVisiblyChangesInARealRenderAndTheWarmMeshDrawsNothing()+ {+ var map = OpenMap();+ const int Size = 512;+ var hex = C.HexAt(-9, 32)!;+ var at = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);+ at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;+ var cam = Camera.main;+ ShotCamera.Configure(cam, Size, Size);+ var rig = cam.GetComponent<CameraRig>();+ rig.LookAt = at; rig.Distance = 31000f; rig.Yaw = 0f; rig.Apply();+ // Without a layer, then with the layer and no sites (only the warm mesh), then with the site built.+ var without = Frame(cam, Size);+ SiteGroundLayer.ShowAt(map, C, Array.Empty<SiteWork>());+ var warm = Frame(cam, Size);+ SiteGroundLayer.ShowAt(map, C, new[] { Built("beit_kama_field") });+ var with = Frame(cam, Size);+ int changed = 0, warmChanged = 0, pink = 0;+ for (int i = 0; i < with.Length; i++)+ {+ if (Mathf.Abs(warm[i].r - without[i].r) + Mathf.Abs(warm[i].g - without[i].g) + Mathf.Abs(warm[i].b - without[i].b) > 6) warmChanged++;+ if (Mathf.Abs(with[i].r - without[i].r) + Mathf.Abs(with[i].g - without[i].g) + Mathf.Abs(with[i].b - without[i].b) <= 30) continue;+ changed++;+ if (with[i].r > 200 && with[i].b > 200 && with[i].g < 80) pink++;+ }+ Assert.AreEqual(0, warmChanged, "the warm mesh leaves the frame as it was");+ Assert.Greater(changed, with.Length / 200, "the hex's ground reads as changed at 31 km");+ Assert.Less(changed, with.Length / 4, "only the hex changes");+ Assert.AreEqual(0, pink, "the shader's error colour");+ }++ /// <summary>Through the game itself: GameRoot draws the ground on the bridge's Changed, and a loaded save (SimBridge.Replace,+ /// the load path) draws its own sites and drops what the old game had.</summary>+ [UnityTest]+ public IEnumerator TheGameDrawsTheGroundAndALoadedSaveShowsItsOwn()+ {+ var saves = Path.Combine(Path.GetTempPath(), "statecraft-site-ground-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(saves);+ RenderTexture? rt = null; PanelSettings? ps = null; GameRoot root = null!;+ yield return CivMovementShots.Boot(false, saves, (t, p, u, g) => { rt = t; ps = p; root = g; });+ try+ {+ var map = Object.FindFirstObjectByType<MapScene>();+ var bridge = root.Bridge!;+ var layer = map.Terrain.transform.Find(SiteGroundLayer.Name).GetComponent<SiteGroundLayer>();+ CollectionAssert.IsEmpty(layer.Shown, "a new game has no built field");++ bridge.State.Sites["gilat_field"] = SiteWork.Built("gilat_field", bridge.State.Date);+ bridge.Skip(-2877001);+ CollectionAssert.AreEquivalent(new[] { "gilat_field" }, layer.Shown, "drawn on Changed, as End turn raises it");++ var loaded = GameSession.New(bridge.Session.Content, GoldenRun.Seed, Mode.Historical);+ loaded.State.Sites["reim_field"] = SiteWork.Built("reim_field", loaded.State.Date);+ bridge.Replace(loaded);+ CollectionAssert.AreEquivalent(new[] { "reim_field" }, layer.Shown, "the save's fields, not the old game's");+ }+ finally+ {+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ Directory.Delete(saves, true);+ }+ }+}diff --git a/unity/Assets/Tests/EditMode/SiteGroundLayerTests.cs.meta b/unity/Assets/Tests/EditMode/SiteGroundLayerTests.cs.metanew file mode 100644index 000000000..61f95114e--- /dev/null+++ b/unity/Assets/Tests/EditMode/SiteGroundLayerTests.cs.meta@@ -0,0 +1,11 @@+fileFormatVersion: 2+guid: f281378637ad498cb0529e0353b6abef+MonoImporter:+ externalObjects: {}+ serializedVersion: 2+ defaultReferences: []+ executionOrder: 0+ icon: {instanceID: 0}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/SiteGroundShots.cs b/unity/Assets/Tests/EditMode/SiteGroundShots.csnew file mode 100644index 000000000..fe8a31562--- /dev/null+++ b/unity/Assets/Tests/EditMode/SiteGroundShots.cs@@ -0,0 +1,159 @@+#nullable enable+using System;+using System.Collections;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>Writes the before and after stills for #2877 to `.superpowers/shots-2877/<SHOTS_TAG>/` at the repository root+/// (local, not committed; SHOTS_TAG from the environment, "untagged" when unset). Every field site and the Hula swamp are put in+/// the game's own state (State.Sites, SiteWork.Built) and GameRoot draws them on the bridge's Changed, so each still is the game+/// at 1920x1080: the map camera with the UI drawn over it. Poses: the gameplay pose (60 km, yaw 10) on the promo's own ground and+/// on each kind of site, and closer (31 km, 15 km). It uses only calls main has, so the same file gives both sides. Explicit, so+/// it does not run with the checks. Run (Unity, the unity/ project):+/// <code>SHOTS_TAG=after <Unity> -batchmode -projectPath unity -runTests -testPlatform EditMode -testFilter SiteGroundShots</code></summary>+[Explicit("writes stills for a pull request, not a check")]+public class SiteGroundShots+{+ const int Width = 1920, Height = 1080;+ static string ShotDir+ {+ get+ {+ var tag = Environment.GetEnvironmentVariable("SHOTS_TAG");+ return Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", ".superpowers", "shots-2877", string.IsNullOrEmpty(tag) ? "untagged" : tag));+ }+ }+ static readonly string[] Ours = { "mefalsim_field", "beit_kama_field", "reim_field", "kiryat_shmona_field", "beit_shemesh_field", "gilat_field", "beit_kama", "hula" };+ string saveDir = "";+ RenderTexture? rt; PanelSettings? ps;+ VisualElement ui = null!;+ GameRoot root = null!;++ [SetUp]+ public void Prepare()+ {+ saveDir = Path.Combine(Path.GetTempPath(), "statecraft-site-ground-shots-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(ShotDir);+ }++ [TearDown]+ public void DiscardScene()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);+ }++ static IEnumerator Frames(int n) { for (int i = 0; i < n; i++) yield return null; }++ /// <summary>CivMovementShots.Boot at this rig's size, with the camera's aspect set first (issue #2882).</summary>+ IEnumerator Boot(bool hebrew)+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var doc = Object.FindFirstObjectByType<UIDocument>();+ ShotCamera.Configure(Camera.main, Width, Height);+ rt = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);+ ps = Object.Instantiate(doc.panelSettings);+ ps.targetTexture = rt; ps.clearColor = true; ps.colorClearValue = Color.clear;+ doc.panelSettings = ps;+ Object.FindFirstObjectByType<MapScene>().Build(MapFocusTests.Inputs.Map);+ root = Object.FindFirstObjectByType<GameRoot>();+ root.Store = new SaveStore(saveDir);+ if (hebrew) root.Language = UiLanguage.Hebrew;+ root.Begin(MapFocusTests.Inputs, 0);+ ui = doc.rootVisualElement;+ for (int i = 0; i < 30 && !(ui.Q("top-bar").worldBound.height > 0); i++) yield return null;+ yield return Frames(5);+ GameSceneTests.HideTheOpeningCard(ui);+ if (root.Advisor != null && root.Advisor.IsOpen) UiTestKit.Press(ui.Q<Button>("advisor-close"));+ yield return Frames(3);+ var bridge = root.Bridge!;+ foreach (var id in Ours) bridge.State.Sites[id] = SiteWork.Built(id, bridge.State.Date);+ foreach (var id in Ours) if (!ReferenceEquals(bridge.State, bridge.TurnStart)) bridge.TurnStart.Sites[id] = SiteWork.Built(id, bridge.State.Date);+ bridge.Skip(-2877100);+ yield return Frames(5);+ }++ static Color[] Read(RenderTexture from)+ {+ var prev = RenderTexture.active;+ RenderTexture.active = from;+ var tex = new Texture2D(from.width, from.height, TextureFormat.RGBA32, false);+ tex.ReadPixels(new Rect(0, 0, from.width, from.height), 0, 0);+ tex.Apply();+ RenderTexture.active = prev;+ var px = tex.GetPixels();+ Object.DestroyImmediate(tex);+ return px;+ }++ IEnumerator Shot(string name, double lon, double lat, float distance, float yaw)+ {+ var map = Object.FindFirstObjectByType<MapScene>();+ var at = map.Frame.ToWorld(lon, lat, 0);+ at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ rig.LookAt = at; rig.Distance = distance; rig.Yaw = yaw; rig.Apply();+ for (int i = 0; i < 8; i++) { cam.Render(); yield return null; }+ var frame = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);+ var before = cam.targetTexture;+ cam.targetTexture = frame; cam.Render(); cam.targetTexture = before;+ var mapPx = Read(frame); var over = Read(rt!);+ frame.Release(); Object.DestroyImmediate(frame);+ var outPx = new Color[mapPx.Length];+ for (int i = 0; i < mapPx.Length; i++)+ {+ var u = over[i]; var m = mapPx[i];+ outPx[i] = new Color(u.r + m.r * (1f - u.a), u.g + m.g * (1f - u.a), u.b + m.b * (1f - u.a), 1f);+ }+ var tex = new Texture2D(Width, Height, TextureFormat.RGB24, false);+ tex.SetPixels(outPx); tex.Apply();+ File.WriteAllBytes(Path.Combine(ShotDir, name + ".png"), tex.EncodeToPNG());+ Object.DestroyImmediate(tex);+ Debug.Log(FormattableString.Invariant($"SHOT {name}: rig {rig.Distance:F0} m, aspect {cam.aspect:F3}, m00/m11 {cam.projectionMatrix[0, 0] / cam.projectionMatrix[1, 1]:F3}, frame {Width}x{Height}"));+ }++ IEnumerator OnHex(string name, int q, int r, float distance, float yaw = 10f)+ {+ var hex = MapFocusTests.Inputs.Content.HexAt(q, r)!;+ yield return Shot(name, hex.Lon, hex.Lat, distance, yaw);+ }++ [UnityTest]+ public IEnumerator English()+ {+ yield return Boot(false);+ var p = PromoPose.Gameplay03;+ yield return Shot("gameplay03", p.Lon, p.Lat, p.Distance, p.Yaw);+ yield return OnHex("beitkama-60km-gameplay03", -9, 32, 60000f);+ yield return OnHex("beitkama-31km", -9, 32, 31000f);+ yield return OnHex("beitkama-15km", -9, 32, 15000f);+ yield return OnHex("mefalsim-sea-60km-gameplay03", -11, 31, 60000f);+ yield return OnHex("reim-gilat-desert-31km", -12, 34, 31000f);+ yield return OnHex("beitshemesh-hills-town-31km", -4, 27, 31000f);+ yield return OnHex("beitshemesh-hills-town-15km", -4, 27, 15000f);+ yield return OnHex("hula-60km-gameplay03", 16, 3, 60000f);+ yield return OnHex("hula-31km", 16, 3, 31000f);+ yield return OnHex("hula-15km", 16, 3, 15000f);+ yield return OnHex("kiryatshmona-15km", 16, 2, 15000f);+ }++ [UnityTest]+ public IEnumerator Hebrew()+ {+ yield return Boot(true);+ yield return OnHex("he-beitkama-60km-gameplay03", -9, 32, 60000f);+ }+}diff --git a/unity/Assets/Tests/EditMode/SiteGroundShots.cs.meta b/unity/Assets/Tests/EditMode/SiteGroundShots.cs.metanew file mode 100644index 000000000..6f9a1ad72--- /dev/null+++ b/unity/Assets/Tests/EditMode/SiteGroundShots.cs.meta@@ -0,0 +1,11 @@+fileFormatVersion: 2+guid: d88db3b7de3a4c0187e1fa65e69a0519+MonoImporter:+ externalObjects: {}+ serializedVersion: 2+ defaultReferences: []+ executionOrder: 0+ icon: {instanceID: 0}+ userData:+ assetBundleName:+ assetBundleVariant: