A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: ground detail and low 3D scrub between the towns (Refs #2878) (#2890)
Eyal Golan042cc18f81a3
diff --git a/changelog.d/2878.md b/changelog.d/2878.mdnew file mode 100644index 000000000..d4485c228--- /dev/null+++ b/changelog.d/2878.md@@ -0,0 +1,3 @@+- The land between the towns has ground detail at the gameplay zooms: soil grain, painted scrub and stones in a pass of its own over+ the terrain, and low 3D bushes, a few tile draws a frame, that gather on the hills and along the fields' hedges, by the map's+ biomes, the land-use weight, curvature and the towns and routes (#2878).diff --git a/docs/visual-v1.md b/docs/visual-v1.mdindex 0b61a7a42..f628940bd 100644--- a/docs/visual-v1.md+++ b/docs/visual-v1.md@@ -3671,3 +3671,29 @@ later fields' worst frame was 74-127 ms against about 50 ms on the control turn,With #2884 (the border glow) merged locally, the 60 km stills of Beit Kama and Mefalsim show the blue and white stripes whole: the patchstops inside them. It does cover the wash inside the hex where a parcel lies.++## Issue #2878: ground detail and low 3D scrub between the towns++**Survey (main `93cd2f174`).** Between the towns the only ground is `landuse.png`, 79 x 105 m a texel, so it reads as smooth+colour at the 31 km opening and blurs at 12 km. The trees are 1,267 to 2,562 instances in view at 31 km and 779 to 1,464 at 12 km:+large and far apart. Promo 03's land between its towns is covered with small bushes and worn ground.++**Why not in the terrain shader.** That function sits at the cliff recorded under issue #391, and `land_bake.py` is outside this+lane. So the paint is a pass of its own, `GroundDetail.shader`: a `Blend DstColor SrcColor` mesh in the queue right after the+terrain, with one tiling texture (grain, bushes as a height field, their shadows, stones) built at boot.++**Standing scrub.** `GroundScrub.shader`: one mesh of 1,089 bushes covers a 15 km tile and is drawn once for each tile in view,+a few tile instances a frame, not one instance a bush. Its vertex shader stands each bush on a half-float height texture and shrinks to a+point any bush whose rank is over the density. Its bushes stop at 55 m, under the 60 m lip of the smallest unit base (a compact+token's), so a moved token covers them.++**Where it grows (`StatecraftGroundDetail.hlsl`, shared).** By biome (`hexes.json`), the land-use weight (rainfall and slope+from `land_bake.py`), the bake's curvature (thin in gullies) and a broad clump noise; along the land bake's painted hedges;+off the towns, the routes and the units' start clearings (a keep-out texture); off the beaches and dune coasts; off drawn+region borders. Biome scrub shares are design values. It adds no paths: the land round 2 ruling keeps tracks to the+1946 Survey's roads. The shader-side bush shadow assumes `MapLighting.SunAzimuth` 285 degrees: if #2427 turns the sun, the+offset in `GroundDetail.FillTexels` turns with it. A warmer or darker grade changes the multiply's result in proportion and+is not expected to change its balance (hypothesis).++**Tests that now switch the layers off.** `BorderTests.Open` and `TerrainShaderTests.TheBakesCarveTheRelief` measure bare+stripes and bakes, so they switch both new toggles off, as they do the kits and trees. Their thresholds are unchanged.diff --git a/unity/Assets/Resources/Map/GroundDetail.mat b/unity/Assets/Resources/Map/GroundDetail.matnew file mode 100644index 000000000..1e473926d--- /dev/null+++ b/unity/Assets/Resources/Map/GroundDetail.mat@@ -0,0 +1,30 @@+%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: GroundDetail+ m_Shader: {fileID: 4800000, guid: 0864099a0a0c4027a8b5349cc1de5c4b, 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: []+ m_Colors: []+ m_BuildTextureStacks: []+ m_AllowLocking: 1diff --git a/unity/Assets/Resources/Map/GroundDetail.mat.meta b/unity/Assets/Resources/Map/GroundDetail.mat.metanew file mode 100644index 000000000..e8cccdab4--- /dev/null+++ b/unity/Assets/Resources/Map/GroundDetail.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 5a8fb41f197f49ac97b429e2925970a8+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Resources/Map/GroundScrub.mat b/unity/Assets/Resources/Map/GroundScrub.matnew file mode 100644index 000000000..651fc74dc--- /dev/null+++ b/unity/Assets/Resources/Map/GroundScrub.mat@@ -0,0 +1,30 @@+%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: GroundScrub+ m_Shader: {fileID: 4800000, guid: 81ea699129b84f9cbc729ca619cca9aa, type: 3}+ m_Parent: {fileID: 0}+ m_ModifiedSerializedProperties: 0+ m_ValidKeywords: []+ m_InvalidKeywords: []+ m_LightmapFlags: 4+ m_EnableInstancingVariants: 1+ m_DoubleSidedGI: 0+ m_CustomRenderQueue: -1+ stringTagMap: {}+ disabledShaderPasses: []+ m_LockedProperties:+ m_SavedProperties:+ serializedVersion: 3+ m_TexEnvs: []+ m_Ints: []+ m_Floats: []+ m_Colors: []+ m_BuildTextureStacks: []+ m_AllowLocking: 1diff --git a/unity/Assets/Resources/Map/GroundScrub.mat.meta b/unity/Assets/Resources/Map/GroundScrub.mat.metanew file mode 100644index 000000000..483ff0067--- /dev/null+++ b/unity/Assets/Resources/Map/GroundScrub.mat.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: e5295fb007f4468d8571cfad323f6086+NativeFormatImporter:+ externalObjects: {}+ mainObjectFileID: 2100000+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/GroundDetail.cs b/unity/Assets/Scripts/Map/GroundDetail.csnew file mode 100644index 000000000..720241dc7--- /dev/null+++ b/unity/Assets/Scripts/Map/GroundDetail.cs@@ -0,0 +1,432 @@+#nullable enable+using System;+using System.Collections.Generic;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map+{+ /// <summary>The land between the towns (#2878), two layers on one rule for where scrub grows (StatecraftGroundDetail.hlsl).+ /// GroundDetail.shader paints grain, scrub and stones over the terrain, a pass of its own and one draw call+ /// (its header says why). GroundScrub.shader stands low 3D bushes on it: one mesh of a 15 km tile, drawn for the tiles in+ /// view by a few tile instances a frame, not one instance a bush ("the WebGL cost is per instance"), each bush placed on the+ /// ground by the vertex shader. Everything is built at boot, so neither adds a byte to the web download. Neither is drawn+ /// where it could not read: the paint past <see cref="FarM"/>, the bushes past <see cref="ScrubGoneM"/>.</summary>+ [ExecuteAlways]+ public sealed class GroundDetail : MonoBehaviour+ {+ public const string Name = "GroundDetail", MaterialResource = "Map/GroundDetail", ScrubMaterialResource = "Map/GroundScrub",+ Toggle = "grounddetail", ScrubToggle = "groundscrub";+ /// <summary>The queue right after the terrain (Terrain.mat 1998), over its lit colour and under everything else.</summary>+ public const int Queue = (int)RenderQueue.Geometry - 1;+ public const int TextureSize = 1024;+ /// <summary>Design values: the texture's tile on the ground (12 m a texel); the mesh's spacing, fine enough to follow the+ /// hills at these zooms, as this pass needs no more than the terrain's rough height.</summary>+ public const float TileM = 12288f, MeshStepM = 1500f;+ /// <summary>Design values: the detail is full up to a pixel footprint of FadeStartM (m) and gone at FadeEndM, past the+ /// gameplay zoom; the camera distance beyond which the pass is not drawn at all.</summary>+ public const float FadeStartM = 60f, FadeEndM = 130f, FarM = 150000f;++ /// <summary>Design values: the scrub tile's side, its bushes (about 5 a km2 where the density is full), a bush's reach and+ /// height. BushTopM stays under the lip of the smallest unit base (UnitPlinth.LipShare of a compact Army base's radius, as+ /// UnitLayer builds it: about 60 m),+ /// so a bush never stands through a token that moved on top of it; the camera distance over which the bushes shrink away, past the gameplay zoom.</summary>+ public const float ScrubTileM = 15000f, ScrubCellM = 450f, BushMinM = 70f, BushMaxM = 170f, BushHeightShare = 0.62f, BushTopM = 55f, ScrubFadeM = 70000f, ScrubGoneM = 85000f;+ public const int KeepOutWidth = 1024, KeepOutHeight = 2048, HeightStepX = 4, HeightStepY = 2;++ static readonly int TileId = Shader.PropertyToID("_ScDetailTileM"), FadeId = Shader.PropertyToID("_ScDetailFade"),+ DetailId = Shader.PropertyToID("_ScDetailTex"), ClassId = Shader.PropertyToID("_ScDetailClassTex"),+ KeepOutId = Shader.PropertyToID("_ScDetailKeepOutTex"), LandId = Shader.PropertyToID("_ScDetailLandTex"), CoastId = Shader.PropertyToID("_ScDetailCoastTex"),+ BakeId = Shader.PropertyToID("_ScDetailBakeTex"), HeightId = Shader.PropertyToID("_ScDetailHeightTex"), ScrubId = Shader.PropertyToID("_ScDetailScrub");++ /// <summary>One biome's class at a mesh vertex: scrub on land the land use weighs high (the wet unfarmed hills: its weight+ /// falls with rainfall), scrub where it weighs low (the plains' ground between the fields), the soil grain, the stones.+ /// Design values, by biome, tuned on renders.</summary>+ public readonly struct Class+ {+ public readonly float WetScrub, OpenScrub, Grain, Stones;+ public Class(float wetScrub, float openScrub, float grain, float stones) { WetScrub = wetScrub; OpenScrub = openScrub; Grain = grain; Stones = stones; }+ }++ public static Class ClassOf(string biome) => biome switch+ {+ "hills" => new Class(1f, 0.25f, 1f, 0.7f),+ "mountains" => new Class(0.9f, 0.1f, 1f, 1f),+ "lowland" => new Class(0.45f, 0.45f, 0.9f, 0.3f),+ "coastal_plain" => new Class(0.15f, 0.40f, 0.8f, 0f),+ "valley" => new Class(0.2f, 0.35f, 0.8f, 0.2f),+ "desert" => new Class(0f, 0f, 1f, 0.8f),+ _ => new Class(0f, 0f, 0f, 0f), // sea, lake+ };++ MeshRenderer? shown;+ Terrain? ground;+ Mesh? scrubMesh; Material? scrubMaterial;+ bool on = true, scrubOn = true;+ readonly List<Matrix4x4> visible = new List<Matrix4x4>();+ Rect mapRect;+ float reliefM, baseY;+ /// <summary>Scrub tiles submitted for the last camera (a test and profiling aid).</summary>+ public int LastTiles { get; private set; }++ /// <summary>Adds both layers to the map. <paramref name="keepOff"/> are the discs (towns, the units' clearings) and+ /// <paramref name="corridors"/> the routes where no scrub grows, painted or standing. With <paramref name="bushes"/> false+ /// (a map built without its kits and trees) the 3D scrub is left out too: as they do, it casts the map's shadows.</summary>+ public static GroundDetail? Build(Transform parent, Terrain terrain, GeoFrame frame, HexFile hexes, float[,] heights,+ IEnumerable<(Vector2 centre, float radius)> keepOff, IEnumerable<(List<Vector2> line, float halfWidth)> corridors,+ Material terrainMaterial, MapRuntimeAssets assets, bool bushes = true)+ {+ var template = Resources.Load<Material>(MaterialResource); var scrubTemplate = Resources.Load<Material>(ScrubMaterialResource);+ if (template == null || scrubTemplate == null) { Debug.LogWarning($"{MaterialResource} or {ScrubMaterialResource} is missing: no ground detail"); return null; }+ var material = assets.Own(new Material(template) { name = Name, renderQueue = Queue });+ var size = terrain.terrainData.size; var o = terrain.transform.position;+ Shader.SetGlobalTexture(DetailId, assets.Own(BuildTexture()));+ var classes = FillClasses(frame, hexes, out int nx, out int nz);+ Shader.SetGlobalTexture(ClassId, assets.Own(BuildClassTexture(classes, nx, nz)));+ Shader.SetGlobalTexture(KeepOutId, assets.Own(BuildKeepOutTexture(frame, keepOff, corridors)));+ Shader.SetGlobalTexture(HeightId, assets.Own(BuildHeightTexture(heights)));+ Shader.SetGlobalTexture(LandId, terrainMaterial.GetTexture("_ScLandTex"));+ Shader.SetGlobalTexture(CoastId, terrainMaterial.GetTexture("_ScCoastTex"));+ Shader.SetGlobalTexture(BakeId, terrainMaterial.GetTexture("_ScBakeTex"));+ Shader.SetGlobalFloat(TileId, TileM);+ Shader.SetGlobalVector(FadeId, new Vector4(FadeStartM, FadeEndM, 0f, 0f));+ Shader.SetGlobalVector(ScrubId, new Vector4(size.y, o.y, ScrubFadeM, ScrubGoneM));+ var go = new GameObject(Name);+ go.transform.SetParent(parent, true);+ go.AddComponent<MeshFilter>().sharedMesh = assets.Own(BuildMesh(terrain, frame, classes, nx, nz));+ var renderer = go.AddComponent<MeshRenderer>();+ renderer.sharedMaterial = material;+ renderer.shadowCastingMode = ShadowCastingMode.Off; renderer.receiveShadows = false;+ var layer = go.AddComponent<GroundDetail>();+ layer.shown = renderer; layer.ground = terrain;+ if (bushes)+ {+ layer.scrubMesh = assets.Own(BuildScrubMesh());+ layer.scrubMaterial = assets.Own(new Material(scrubTemplate) { name = "GroundScrub", enableInstancing = true });+ }+ layer.mapRect = new Rect(o.x, o.z, size.x, size.z); layer.reliefM = size.y; layer.baseY = o.y;+ assets.OnTeardown(VisualToggles.Register(Toggle, set => layer.on = set));+ assets.OnTeardown(VisualToggles.Register(ScrubToggle, set => layer.scrubOn = set));+ return layer;+ }++ void OnEnable() => RenderPipelineManager.beginCameraRendering += Near;+ void OnDisable() => RenderPipelineManager.beginCameraRendering -= Near;++ /// <summary>Far out the paint has faded: no draw, no fill. Near enough, the scrub's tiles in view go in one instanced+ /// draw; the shadow pass sees casters outside the view too, so the test widens each tile as VegetationLayer's does.</summary>+ void Near(ScriptableRenderContext context, Camera cam)+ {+ if (shown == null || cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;+ float height = cam.transform.position.y;+ bool terrainOn = ground != null && ground.enabled;+ shown.enabled = on && terrainOn && height < FarM;+ LastTiles = 0;+ // The opt-in hex-tile board (HexTilesLook) stands on this ground with its own props.+ if (!scrubOn || !terrainOn || scrubMesh == null || scrubMaterial == null || height > ScrubGoneM || transform.parent.Find(HexTiles.HexTilesLook.RootName) != null) return;+ var planes = GeometryUtility.CalculateFrustumPlanes(cam);+ visible.Clear();+ int nx = Mathf.CeilToInt(mapRect.width / ScrubTileM), nz = Mathf.CeilToInt(mapRect.height / ScrubTileM);+ var eye = cam.transform.position;+ for (int z = 0; z < nz; z++)+ for (int x = 0; x < nx; x++)+ {+ var origin = new Vector3(mapRect.x + x * ScrubTileM, baseY, mapRect.y + z * ScrubTileM);+ var tile = new Bounds(origin + new Vector3(0.5f * ScrubTileM, 0.5f * reliefM, 0.5f * ScrubTileM), new Vector3(ScrubTileM + 3000f, reliefM + 400f, ScrubTileM + 3000f));+ if (tile.SqrDistance(eye) > ScrubGoneM * ScrubGoneM || !GeometryUtility.TestPlanesAABB(planes, tile)) continue;+ visible.Add(Matrix4x4.Translate(origin));+ }+ if (visible.Count == 0) return;+ var rp = new RenderParams(scrubMaterial)+ {+ worldBounds = new Bounds(new Vector3(mapRect.center.x, baseY, mapRect.center.y), new Vector3(mapRect.width + 6000f, 2f * reliefM + 800f, mapRect.height + 6000f)),+ camera = cam, shadowCastingMode = ShadowCastingMode.On, receiveShadows = true, layer = gameObject.layer,+ };+ Graphics.RenderMeshInstanced(rp, scrubMesh, 0, visible);+ LastTiles = visible.Count;+ }++ /// <summary>The land as a coarse grid, every <see cref="MeshStepM"/>, at the terrain's height: a pixel's paint lands+ /// within the terrain's rough relief of where it lies, which grain and bushes cannot show. Quads with no land are left+ /// out (by the hexes' biome class).</summary>+ public static Mesh BuildMesh(Terrain terrain, GeoFrame frame, Color32[] classes, int nx, int nz)+ {+ var data = terrain.terrainData; var o = terrain.transform.position;+ float stepX = frame.WidthM / (nx - 1), stepZ = frame.LengthM / (nz - 1);+ var verts = new Vector3[nx * nz];+ for (int z = 0; z < nz; z++)+ for (int x = 0; x < nx; x++)+ verts[z * nx + x] = new Vector3(x * stepX + o.x, o.y + data.GetInterpolatedHeight((float)x / (nx - 1), (float)z / (nz - 1)), z * stepZ + o.z);+ var tris = new List<int>((nx - 1) * (nz - 1) * 6);+ bool Land(int i) => classes[i].b > 0;+ for (int z = 0; z + 1 < nz; z++)+ for (int x = 0; x + 1 < nx; x++)+ {+ int a = z * nx + x, b = a + 1, c = a + nx, d = c + 1;+ if (!Land(a) && !Land(b) && !Land(c) && !Land(d)) continue;+ tris.Add(a); tris.Add(c); tris.Add(b); tris.Add(b); tris.Add(c); tris.Add(d);+ }+ var mesh = new Mesh { name = Name };+ mesh.vertices = verts; mesh.SetTriangles(tris, 0, true);+ mesh.UploadMeshData(true);+ return mesh;+ }++ /// <summary>The blended class of every mesh step (row 0 = south): r, g, b, a as <see cref="Class"/>'s fields.</summary>+ public static Color32[] FillClasses(GeoFrame frame, HexFile hexes, out int nx, out int nz)+ {+ nx = Mathf.CeilToInt(frame.WidthM / MeshStepM) + 1; nz = Mathf.CeilToInt(frame.LengthM / MeshStepM) + 1;+ float stepX = frame.WidthM / (nx - 1), stepZ = frame.LengthM / (nz - 1);+ var names = new List<string>(MapBuilder.BiomeColours.Keys);+ var classes = new Class[names.Count];+ for (int i = 0; i < classes.Length; i++) classes[i] = ClassOf(names[i]);+ var centres = new List<Vector2>(hexes.hexes.Length); var layers = new List<int>(hexes.hexes.Length);+ foreach (var h in hexes.hexes) { var w = frame.ToWorld(h.lon, h.lat, 0); centres.Add(new Vector2(w.x, w.z)); layers.Add(names.IndexOf(h.biome)); }+ var blender = new BiomeBlender(centres, layers, hexes.hex_size_km * 1000f, names.Count);+ var px = new Color32[nx * nz]; var wts = new float[names.Count];+ for (int z = 0; z < nz; z++)+ for (int x = 0; x < nx; x++)+ {+ blender.Weights(new Vector2(x * stepX, z * stepZ), wts);+ float wet = 0f, dry = 0f, grain = 0f, stones = 0f;+ for (int l = 0; l < wts.Length; l++)+ {+ wet += wts[l] * classes[l].WetScrub; dry += wts[l] * classes[l].OpenScrub;+ grain += wts[l] * classes[l].Grain; stones += wts[l] * classes[l].Stones;+ }+ px[z * nx + x] = new Color32((byte)(255f * wet), (byte)(255f * dry), (byte)(255f * grain), (byte)(255f * stones));+ }+ return px;+ }++ static Texture2D BuildClassTexture(Color32[] px, int nx, int nz)+ {+ var tex = new Texture2D(nx, nz, TextureFormat.RGBA32, false, true) { name = "GroundDetailClass", wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear };+ tex.SetPixels32(px); tex.Apply(false, true);+ return tex;+ }++ /// <summary>Where no scrub grows, one byte a texel (row 0 = south): the discs, and the routes, each corridor's line drawn+ /// as a chain of its half-width's discs. Only the texels they touch are written.</summary>+ public static byte[] FillKeepOut(GeoFrame frame, IEnumerable<(Vector2 centre, float radius)> keepOff, IEnumerable<(List<Vector2> line, float halfWidth)> corridors)+ {+ int w = KeepOutWidth, h = KeepOutHeight;+ var px = new byte[w * h];+ float tx = frame.WidthM / w, tz = frame.LengthM / h;+ void Disc(Vector2 c, float r)+ {+ int x0 = Mathf.Max(0, Mathf.FloorToInt((c.x - r) / tx)), x1 = Mathf.Min(w - 1, Mathf.CeilToInt((c.x + r) / tx));+ int z0 = Mathf.Max(0, Mathf.FloorToInt((c.y - r) / tz)), z1 = Mathf.Min(h - 1, Mathf.CeilToInt((c.y + r) / tz));+ for (int z = z0; z <= z1; z++)+ {+ float dz = (z + 0.5f) * tz - c.y;+ for (int x = x0; x <= x1; x++)+ {+ float dx = (x + 0.5f) * tx - c.x;+ if (dx * dx + dz * dz <= r * r) px[z * w + x] = 255;+ }+ }+ }+ foreach (var (c, r) in keepOff) Disc(c, r);+ foreach (var (line, halfWidth) in corridors)+ for (int i = 0; i + 1 < line.Count; i++)+ {+ Vector2 a = line[i], b = line[i + 1];+ int steps = Mathf.Max(1, Mathf.CeilToInt(Vector2.Distance(a, b) / Mathf.Max(tx, halfWidth)));+ for (int s = 0; s <= steps; s++) Disc(Vector2.Lerp(a, b, (float)s / steps), halfWidth);+ }+ return px;+ }++ static Texture2D BuildKeepOutTexture(GeoFrame frame, IEnumerable<(Vector2 centre, float radius)> keepOff, IEnumerable<(List<Vector2> line, float halfWidth)> corridors)+ {+ var tex = new Texture2D(KeepOutWidth, KeepOutHeight, TextureFormat.R8, false, true) { name = "GroundDetailKeepOut", wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear };+ tex.SetPixelData(FillKeepOut(frame, keepOff, corridors), 0); tex.Apply(false, true);+ return tex;+ }++ /// <summary>The terrain's 0..1 heights for the bushes' vertex shader (Unity's [y, x] as MapBuilder gives them, row 0 =+ /// south, every HeightStep sample): half floats, which WebGL 2 filters, where the terrain's own 16-bit texture may not.</summary>+ static Texture2D BuildHeightTexture(float[,] heights)+ {+ int ny = (heights.GetLength(0) - 1) / HeightStepY + 1, nx = (heights.GetLength(1) - 1) / HeightStepX + 1;+ var px = new ushort[nx * ny];+ for (int y = 0; y < ny; y++)+ for (int x = 0; x < nx; x++)+ px[y * nx + x] = Mathf.FloatToHalf(heights[y * HeightStepY, x * HeightStepX]);+ var tex = new Texture2D(nx, ny, TextureFormat.RHalf, false, true) { name = "GroundDetailHeight", wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear };+ tex.SetPixelData(px, 0); tex.Apply(false, true);+ return tex;+ }++ // A bush's dome from the ground up (the first ring sunk, so it sits in a slope): share of its reach and of its height,+ // the normals' up share, and the shading painted in, darker under the crown.+ static readonly float[] TierRadius = { 0.80f, 1f, 0.55f }, TierHeight = { -0.3f, 0.4f, 0.85f }, TierUp = { 0.1f, 0.55f, 1.6f }, TierShade = { 0.7f, 0.9f, 1.05f };++ /// <summary>One scrub tile: bushes in jittered <see cref="ScrubCellM"/> cells, each a low dome of 3 rings of 6 and an apex+ /// around its pivot (uv0, in the tile), its rank in uv1.x (GroundScrub.shader), its colour a dull olive to grey-brown (design+ /// values, near the hill olives' and the land bake's scrub colours). No geography here: the shader decides which grow.</summary>+ public static Mesh BuildScrubMesh()+ {+ int cells = Mathf.RoundToInt(ScrubTileM / ScrubCellM), n = cells * cells;+ const int Ring = 6, Tiers = 3, Verts = Tiers * Ring + 1;+ var pos = new Vector3[n * Verts]; var nrm = new Vector3[n * Verts]; var col = new Color32[n * Verts];+ var pivot = new Vector2[n * Verts]; var rank = new Vector2[n * Verts];+ var tris = new int[n * 3 * Ring * (2 * (Tiers - 1) + 1)];+ int t = 0;+ for (int cz = 0; cz < cells; cz++)+ for (int cx = 0; cx < cells; cx++)+ {+ int v0 = (cz * cells + cx) * Verts, apex = v0 + Tiers * Ring;+ var p = new Vector2((cx + 0.05f + 0.9f * Hash(cx, cz, 21)) * ScrubCellM, (cz + 0.05f + 0.9f * Hash(cx, cz, 22)) * ScrubCellM);+ float size = Hash(cx, cz, 23), r = Mathf.Lerp(BushMinM, BushMaxM, size * size), yaw = Hash(cx, cz, 24) * Mathf.PI * 2f;+ float top = Mathf.Min(r * BushHeightShare, BushTopM), grow = Hash(cx, cz, 26);+ Color c = Color32.Lerp(new Color32(62, 62, 40, 255), new Color32(92, 80, 58, 255), Hash(cx, cz, 25));+ for (int i = 0; i < Ring; i++)+ {+ float a = yaw + i * Mathf.PI * 2f / Ring, ca = Mathf.Cos(a), sa = Mathf.Sin(a);+ float lobe = r * (0.75f + 0.5f * Hash(i, cx + cz * cells, 27));+ for (int tier = 0; tier < Tiers; tier++)+ {+ float w = TierRadius[tier] * lobe;+ int at = v0 + tier * Ring + i;+ pos[at] = new Vector3(ca * w, TierHeight[tier] * top, sa * w);+ nrm[at] = new Vector3(ca, TierUp[tier], sa).normalized;+ col[at] = c * TierShade[tier];+ }+ int j = (i + 1) % Ring;+ for (int tier = 0; tier + 1 < Tiers; tier++)+ {+ int a0 = v0 + tier * Ring + i, a1 = v0 + tier * Ring + j, b0 = a0 + Ring, b1 = a1 + Ring;+ tris[t++] = a0; tris[t++] = b0; tris[t++] = b1;+ tris[t++] = a0; tris[t++] = b1; tris[t++] = a1;+ }+ tris[t++] = v0 + (Tiers - 1) * Ring + i; tris[t++] = apex; tris[t++] = v0 + (Tiers - 1) * Ring + j;+ }+ pos[apex] = new Vector3(0f, top, 0f); nrm[apex] = Vector3.up; col[apex] = c * 1.15f;+ for (int i = 0; i < Verts; i++) { pivot[v0 + i] = p; rank[v0 + i] = new Vector2(grow, 0f); }+ }+ var mesh = new Mesh { name = "GroundScrub" };+ mesh.vertices = pos; mesh.normals = nrm; mesh.colors32 = col; mesh.SetUVs(0, pivot); mesh.SetUVs(1, rank);+ mesh.triangles = tris;+ mesh.bounds = new Bounds(new Vector3(0.5f * ScrubTileM, 0f, 0.5f * ScrubTileM), new Vector3(ScrubTileM, 2000f, ScrubTileM));+ mesh.UploadMeshData(true);+ return mesh;+ }++ /// <summary>The detail tile (<see cref="TextureSize"/> square, seamless, seeded, data: GroundDetail.shader says its+ /// channels). r is value noise over 3 octaves and a speckle; g and b are dots, one jittered dot per cell, each with its own peak so+ /// a lower threshold shows more of them, its shadow offset away from the sun; a is sparse small dots.</summary>+ public static Texture2D BuildTexture()+ {+ int n = TextureSize;+ var px = FillTexels();+ var tex = new Texture2D(n, n, TextureFormat.RGBA32, true, true) { name = Name, wrapMode = TextureWrapMode.Repeat, filterMode = FilterMode.Trilinear, anisoLevel = 2 };+ tex.SetPixelData(px, 0); tex.Apply(true, true);+ return tex;+ }++ /// <summary>A stable hash in 0..1 of a cell (no Unity random stream moves).</summary>+ static float Hash(int x, int y, int seed)+ {+ unchecked+ {+ uint h = 2166136261u;+ h = (h ^ (uint)x) * 16777619u; h = (h ^ (uint)y) * 16777619u; h = (h ^ (uint)seed) * 16777619u;+ h ^= h >> 13; h *= 1274126177u; h ^= h >> 16;+ return (h & 0xFFFFFF) / 16777216f;+ }+ }++ public static byte[] FillTexels()+ {+ int n = TextureSize;+ var px = new byte[n * n * 4];+ FillGrain(px, n);+ // g and b: the bushes, in cells of 16 texels; a clump noise biases their peaks, so they gather as the promo's do.+ const int Cell = 12; int cells = n / Cell;+ for (int cy = 0; cy < cells; cy++)+ for (int cx = 0; cx < cells; cx++)+ {+ float x = (cx + 0.1f + 0.8f * Hash(cx, cy, 1)) * Cell, y = (cy + 0.1f + 0.8f * Hash(cx, cy, 2)) * Cell;+ float size = Hash(cx, cy, 3), r = 0.9f + 3.6f * size * size; // many small bushes, a few big ones+ float clump = Hash(cx / 6, cy / 6, 4) * 0.6f + Hash(cx / 3, cy / 3, 5) * 0.4f;+ float peak = Mathf.Clamp01(0.25f + 0.40f * Hash(cx, cy, 6) + 0.45f * clump);+ int lobes = 2 + (int)(3f * Hash(cx, cy, 11)); // a bush is a few lobes, never one round dot+ for (int l = 0; l < lobes; l++)+ {+ float bx = x + (Hash(l, cx + cy * cells, 12) - 0.5f) * 2.4f * r, by = y + (Hash(l, cx + cy * cells, 13) - 0.5f) * 2.4f * r;+ float br = r * (0.6f + 0.6f * Hash(l, cx + cy * cells, 14));+ Stamp(px, n, bx, by, br, peak, 1);+ Stamp(px, n, bx + 0.9f * br, by - 0.28f * br, br * 1.05f, peak, 2); // east-south-east: MapLighting.SunAzimuth 285 degrees+ }+ }+ // a: small pale stones, in cells of 9 texels.+ const int StoneCell = 9; int stoneCells = n / StoneCell;+ for (int cy = 0; cy < stoneCells; cy++)+ for (int cx = 0; cx < stoneCells; cx++)+ {+ if (Hash(cx, cy, 7) > 0.4f) continue;+ Stamp(px, n, (cx + Hash(cx, cy, 8)) * StoneCell, (cy + Hash(cx, cy, 9)) * StoneCell, 1.2f + 1.6f * Hash(cx, cy, 10), 1f, 3);+ }+ return px;+ }++ /// <summary>The soil's grain into r: 3 octaves of periodic value noise on a quarter-size tile, spread over the full one+ /// (boot time: the full tile's octaves cost about 140 ms in the editor), plus a fine per-texel speckle.</summary>+ static void FillGrain(byte[] px, int n)+ {+ const int Small = 256;+ var small = new float[Small * Small];+ var periods = new[] { 4, 16, 64 }; var gains = new[] { 0.32f, 0.32f, 0.26f };+ var t = new float[Small]; var cell = new int[Small];+ for (int o = 0; o < periods.Length; o++)+ {+ int p = periods[o]; float k = (float)p / Small;+ var lattice = new float[p * p];+ for (int i = 0; i < lattice.Length; i++) lattice[i] = Hash(i % p, i / p, p);+ for (int i = 0; i < Small; i++) { float f = i * k; cell[i] = (int)f; float u = f - cell[i]; t[i] = u * u * (3f - 2f * u); }+ for (int y = 0; y < Small; y++)+ {+ int y0 = cell[y] % p * p, y1 = (cell[y] + 1) % p * p; float ty = t[y];+ for (int x = 0; x < Small; x++)+ {+ int x0 = cell[x] % p, x1 = (cell[x] + 1) % p; float tx = t[x];+ float v0 = lattice[y0 + x0] + (lattice[y0 + x1] - lattice[y0 + x0]) * tx, v1 = lattice[y1 + x0] + (lattice[y1 + x1] - lattice[y1 + x0]) * tx;+ small[y * Small + x] += (v0 + (v1 - v0) * ty) * gains[o];+ }+ }+ }+ int step = n / Small; float per = 1f / step;+ uint noise = 2463534242u;+ for (int y = 0; y < n; y++)+ {+ int sy = y / step; float ty = (y % step) * per;+ int row0 = sy * Small, row1 = (sy + 1) % Small * Small;+ for (int x = 0; x < n; x++)+ {+ int sx = x / step, sx1 = (sx + 1) % Small; float tx = (x % step) * per;+ float a = small[row0 + sx], b = small[row0 + sx1], c = small[row1 + sx], d = small[row1 + sx1];+ float v = a + (b - a) * tx; v += (c + (d - c) * tx - v) * ty;+ noise ^= noise << 13; noise ^= noise >> 17; noise ^= noise << 5;+ px[(y * n + x) * 4] = (byte)(255f * (v + 0.1f * (noise >> 24) / 255f));+ }+ }+ }++ /// <summary>A soft dot into one channel, wrapping at the tile's edges, keeping the higher value.</summary>+ static void Stamp(byte[] px, int n, float x, float y, float r, float peak, int channel)+ {+ int x0 = Mathf.FloorToInt(x - r), x1 = Mathf.CeilToInt(x + r), y0 = Mathf.FloorToInt(y - r), y1 = Mathf.CeilToInt(y + r);+ for (int v = y0; v <= y1; v++)+ for (int u = x0; u <= x1; u++)+ {+ float dx = (u - x) / r, dy = (v - y) / r, d = dx * dx + dy * dy;+ if (d >= 1f) continue;+ int at = (((v % n + n) % n) * n + (u % n + n) % n) * 4 + channel;+ byte value = (byte)(255f * peak * (1f - d * d));+ if (value > px[at]) px[at] = value;+ }+ }+ }+}diff --git a/unity/Assets/Scripts/Map/GroundDetail.cs.meta b/unity/Assets/Scripts/Map/GroundDetail.cs.metanew file mode 100644index 000000000..de81670ad--- /dev/null+++ b/unity/Assets/Scripts/Map/GroundDetail.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ffe231f02ea0476bbddbd8cb769ae350diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 8cd54daf8..9fd051894 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -863,6 +863,10 @@ namespace Statecraft.Game.MapRoutes.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");diff --git a/unity/Assets/Shaders/GroundDetail.shader b/unity/Assets/Shaders/GroundDetail.shadernew file mode 100644index 000000000..7d28744ef--- /dev/null+++ b/unity/Assets/Shaders/GroundDetail.shader@@ -0,0 +1,90 @@+// Ground detail between the towns (#2878): a multiply pass drawn straight after the terrain, under everything else, so the+// land stops reading as smooth colour at the gameplay zooms. It is a pass of its own, not more code in+// StatecraftTerrain.hlsl, because that function sits at the frame-time cliff docs/visual-v1.md records (#391): a few lines+// added there cost 4-8 ms at gameplay03. The mesh (GroundDetail.BuildMesh) is a coarse copy of the relief. The scrub grows by+// real data: StatecraftGroundDetail.hlsl, which GroundScrub.shader's standing bushes share. What it draws comes from one tiling texture+// (GroundDetail.BuildTexture): r soil grain, g bushes as a height field (a lower threshold shows more of them), b their+// shadows, a pale stones. Blend DstColor SrcColor doubles the source, so 0.5 leaves the ground as it is, and every term+// fades to 0.5 by the pixel's footprint, before a tile could show or a dot could shimmer.+Shader "Statecraft/GroundDetail"+{+ Properties+ {+ _GrainGain ("Soil grain strength", Range(0, 1)) = 0.32+ _BushLight ("A bush's light parts, times the ground", Color) = (0.80, 0.80, 0.68, 1)+ _BushDark ("A bush's dark parts, times the ground", Color) = (0.56, 0.58, 0.47, 1)+ _ShadowDark ("Bush shadow, times the ground", Range(0, 1)) = 0.84+ _StoneGain ("Stones, brighter than the ground", Range(0, 1)) = 0.11+ }+ SubShader+ {+ Tags { "RenderType" = "Opaque" "Queue" = "Geometry-1" "RenderPipeline" = "UniversalPipeline" }+ Pass+ {+ Name "GroundDetail"+ Tags { "LightMode" = "UniversalForward" }+ ZWrite Off+ ZTest Always+ Cull Back+ Blend DstColor SrcColor+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"+ #include "Assets/Shaders/StatecraftMap.hlsl" // the map's globals, ScHexAxial and ScRegionAt; only what is called is compiled+ #include "Assets/Shaders/StatecraftGroundDetail.hlsl"+ CBUFFER_START(UnityPerMaterial)+ float _GrainGain, _ShadowDark, _StoneGain;+ half4 _BushLight, _BushDark;+ CBUFFER_END++ struct Attributes { float4 positionOS : POSITION; };+ struct Varyings+ {+ float4 positionCS : SV_POSITION;+ float2 mapM : TEXCOORD0;+ };++ Varyings Vert(Attributes v)+ {+ Varyings o;+ float3 w = TransformObjectToWorld(v.positionOS.xyz);+ o.positionCS = TransformWorldToHClip(w);+ o.mapM = w.xz - _ScMapOrigin.xz;+ return o;+ }++ half4 Frag(Varyings i) : SV_Target+ {+ float footprint = length(fwidth(i.mapM));+ float fade = 1.0 - smoothstep(_ScDetailFade.x, _ScDetailFade.y, footprint);+ float2 uv = i.mapM / _ScMap.xy;+ float coast = SAMPLE_TEXTURE2D(_ScDetailCoastTex, sampler_ScDetailCoastTex, uv).r;+ fade *= ScOffTheBeach(coast, i.mapM);+ fade *= ScClearOfBorder(i.mapM, footprint);+ clip(fade - 0.001); // not even a rounding step on the sand and the stripes+ float4 land = SAMPLE_TEXTURE2D(_ScDetailLandTex, sampler_ScDetailLandTex, uv);+ half4 cls = SAMPLE_TEXTURE2D(_ScDetailClassTex, sampler_ScDetailClassTex, uv);+ // Two layers of one texture, turned and scaled apart, so no 12 km tile repeats on the screen.+ half4 a = SAMPLE_TEXTURE2D(_ScDetailTex, sampler_ScDetailTex, i.mapM / _ScDetailTileM);+ float2 turned = float2(0.8 * i.mapM.x - 0.6 * i.mapM.y, 0.6 * i.mapM.x + 0.8 * i.mapM.y);+ half4 b = SAMPLE_TEXTURE2D(_ScDetailTex, sampler_ScDetailTex, turned / (0.73 * _ScDetailTileM));+ half scrub = ScScrubDensity(uv, i.mapM, cls, land, coast);+ half threshold = lerp(1.05, 0.38, scrub);+ half ragged = 0.30 * (a.r - b.r); // the grain frays the bushes' round edges+ half height = max(a.g, b.g) + ragged;+ half bush = smoothstep(threshold, threshold + 0.10, height);+ half tone = saturate((height - threshold) / 0.45); // each bush's own peak: tall ones darker, their edges lighter+ half shade = smoothstep(threshold, threshold + 0.16, max(a.b, b.b) + ragged) * (1.0 - bush);+ half stone = smoothstep(0.72, 0.88, a.a) * cls.a;+ half3 c = 1.0 + _GrainGain * cls.b * ((a.r + b.r) - 1.0);+ c *= 1.0 + _StoneGain * stone;+ c *= lerp(1.0, _ShadowDark, shade);+ c *= lerp(half3(1, 1, 1), lerp(_BushLight.rgb, _BushDark.rgb, tone), bush);+ return half4(lerp(half3(0.5, 0.5, 0.5), 0.5 * c, fade), 1.0);+ }+ ENDHLSL+ }+ }+ Fallback Off+}diff --git a/unity/Assets/Shaders/GroundDetail.shader.meta b/unity/Assets/Shaders/GroundDetail.shader.metanew file mode 100644index 000000000..6711a90d8--- /dev/null+++ b/unity/Assets/Shaders/GroundDetail.shader.meta@@ -0,0 +1,9 @@+fileFormatVersion: 2+guid: 0864099a0a0c4027a8b5349cc1de5c4b+ShaderImporter:+ externalObjects: {}+ defaultTextures: []+ nonModifiableTextures: []+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Shaders/GroundScrub.shader b/unity/Assets/Shaders/GroundScrub.shadernew file mode 100644index 000000000..08cf1f864--- /dev/null+++ b/unity/Assets/Shaders/GroundScrub.shader@@ -0,0 +1,112 @@+// The low 3D scrub between the towns (#2878): one small mesh of bushes around the 15 km tile (GroundDetail.BuildScrubMesh),+// drawn at every tile in view, a few tile instances a frame however many bushes they hold, so the WebGL cost stays that of+// a handful of trees. The vertex shader stands each bush on the ground and decides whether it grows, from the same data as+// the painted scrub (StatecraftGroundDetail.hlsl): a bush with a rank (uv1.x) over the density shrinks to a point. The bush's+// pivot in its tile is uv0; the mesh's positions are offsets from that pivot in metres. Lit as Kit.shader lights the trees.+Shader "Statecraft/GroundScrub"+{+ Properties { _Jitter ("Tint jitter", Range(0, 0.5)) = 0.12 }+ SubShader+ {+ Tags { "RenderType" = "Opaque" "Queue" = "Geometry" "RenderPipeline" = "UniversalPipeline" }+ HLSLINCLUDE+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"+ #include "Assets/Shaders/StatecraftMap.hlsl"+ #include "Assets/Shaders/StatecraftGroundDetail.hlsl"+ TEXTURE2D(_ScDetailHeightTex); SAMPLER(sampler_ScDetailHeightTex); // the terrain's 0..1 height, GroundDetail.BuildHeightTexture+ float4 _ScDetailScrub; // x the terrain's height range (m), y terrain origin y, z, w the camera distance (m) where it shrinks away+ static const float ScScrubBorderFootprintM = 60.0; // keeps a bush's reach, not a pixel, off the border's band+ // A bush's pivot stays this far from a hex edge, so no bush stands over the hex lines the terrain draws (#2878: a bush+ // on a line thinned it under a pixel at gameplay03, HexGridTests). A bush reaches up to TierRadius 1 x lobe 1.25 x+ // BushMaxM 170 = 212 m from its pivot (GroundDetail.BuildScrubMesh); the rest covers its top seen from the tilted camera.+ static const float ScScrubGridClearM = 240.0;+ CBUFFER_START(UnityPerMaterial)+ half _Jitter;+ CBUFFER_END++ struct Attributes+ {+ float4 positionOS : POSITION; float3 normalOS : NORMAL; half4 color : COLOR; float2 pivot : TEXCOORD0; float2 rank : TEXCOORD1;+ UNITY_VERTEX_INPUT_INSTANCE_ID+ };++ // The bush's world position: on the ground at its pivot, scaled by its density; a point where it does not grow.+ float3 ScrubPosition(Attributes v)+ {+ float3 tile = TransformObjectToWorld(float3(0, 0, 0));+ float2 mapM = tile.xz + v.pivot - _ScMapOrigin.xz, uv = mapM / _ScMap.xy;+ float scale = 0.0;+ if (uv.x > 0.0 && uv.y > 0.0 && uv.x < 1.0 && uv.y < 1.0)+ {+ float4 land = SAMPLE_TEXTURE2D_LOD(_ScDetailLandTex, sampler_ScDetailLandTex, uv, 0.0);+ float coast = SAMPLE_TEXTURE2D_LOD(_ScDetailCoastTex, sampler_ScDetailCoastTex, uv, 0.0).r;+ half4 cls = SAMPLE_TEXTURE2D_LOD(_ScDetailClassTex, sampler_ScDetailClassTex, uv, 0.0);+ float density = ScScrubDensity(uv, mapM, cls, land, coast);+ density *= ScOffTheBeach(coast, mapM) * ScClearOfBorder(mapM, ScScrubBorderFootprintM);+ density *= step(ScScrubGridClearM, ScHexEdgeDistance(float2(mapM.x, _ScMap.y - mapM.y), _ScMapOrigin.w)); // as ScGridLine reads the grid+ scale = step(v.rank.x * v.rank.x, density) * (0.65 + 0.35 * density); // the rank squared: a thin scrub still shows+ }+ float height = SAMPLE_TEXTURE2D_LOD(_ScDetailHeightTex, sampler_ScDetailHeightTex, uv, 0.0).r * _ScDetailScrub.x + _ScDetailScrub.y;+ float3 pivot = float3(tile.x + v.pivot.x, height, tile.z + v.pivot.y);+ scale *= 1.0 - smoothstep(_ScDetailScrub.z, _ScDetailScrub.w, length(_WorldSpaceCameraPos - pivot));+ return pivot + v.positionOS.xyz * scale;+ }+ ENDHLSL++ Pass+ {+ Name "Scrub"+ Tags { "LightMode" = "UniversalForward" }+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ #pragma multi_compile_instancing+ #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN+ struct Varyings { float4 positionCS : SV_POSITION; float3 positionWS : TEXCOORD0; float3 normalWS : TEXCOORD1; half3 color : TEXCOORD2; };++ Varyings Vert(Attributes v)+ {+ Varyings o;+ UNITY_SETUP_INSTANCE_ID(v);+ o.positionWS = ScrubPosition(v);+ o.positionCS = TransformWorldToHClip(o.positionWS);+ o.normalWS = v.normalOS;+ o.color = v.color.rgb;+ return o;+ }++ half4 Frag(Varyings i) : SV_Target+ {+ float3 n = SafeNormalize(i.normalWS);+ half3 albedo = SRGBToLinear(i.color);+ Light sun = GetMainLight(TransformWorldToShadowCoord(i.positionWS));+ float sunlit = saturate(dot(n, sun.direction)) * sun.shadowAttenuation;+ half3 sh = SampleSH(n);+ half3 bounce = Luminance(sh) * sun.color / max(Luminance(sun.color), 1e-4);+ half3 lit = albedo * (lerp(sh, bounce, 0.6 * (1.0 - sunlit)) + sun.color * sunlit);+ return half4(lerp(lit, _ScHaze.rgb, _ScHaze.a * ScHazeAmount(i.positionWS)), 1.0);+ }+ ENDHLSL+ }+ Pass+ {+ Name "ShadowCaster"+ Tags { "LightMode" = "ShadowCaster" }+ ZWrite On ZTest LEqual ColorMask 0+ Cull Back+ HLSLPROGRAM+ #pragma vertex Vert+ #pragma fragment Frag+ #pragma multi_compile_instancing+ float3 _LightDirection;+ float4 Vert(Attributes v) : SV_POSITION+ {+ UNITY_SETUP_INSTANCE_ID(v);+ return ApplyShadowClamping(TransformWorldToHClip(ApplyShadowBias(ScrubPosition(v), v.normalOS, _LightDirection)));+ }+ half Frag() : SV_Target { return 0; }+ ENDHLSL+ }+ }+ Fallback Off+}diff --git a/unity/Assets/Shaders/GroundScrub.shader.meta b/unity/Assets/Shaders/GroundScrub.shader.metanew file mode 100644index 000000000..c535e8a4f--- /dev/null+++ b/unity/Assets/Shaders/GroundScrub.shader.meta@@ -0,0 +1,9 @@+fileFormatVersion: 2+guid: 81ea699129b84f9cbc729ca619cca9aa+ShaderImporter:+ externalObjects: {}+ defaultTextures: []+ nonModifiableTextures: []+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Shaders/StatecraftGroundDetail.hlsl b/unity/Assets/Shaders/StatecraftGroundDetail.hlslnew file mode 100644index 000000000..e44fffda5--- /dev/null+++ b/unity/Assets/Shaders/StatecraftGroundDetail.hlsl@@ -0,0 +1,65 @@+#ifndef STATECRAFT_GROUND_DETAIL_INCLUDED+#define STATECRAFT_GROUND_DETAIL_INCLUDED+// What GroundDetail.shader (the pass over the terrain) and GroundScrub.shader (the low 3D bushes) share (#2878): where scrub+// grows, one rule, so the painted bushes and the standing ones gather together. Needs StatecraftMap.hlsl first.+TEXTURE2D(_ScDetailTex); SAMPLER(sampler_ScDetailTex); // GroundDetail.BuildTexture+TEXTURE2D(_ScDetailClassTex); SAMPLER(sampler_ScDetailClassTex); // GroundDetail.ClassOf per mesh step: r, g, b, a+TEXTURE2D(_ScDetailKeepOutTex); SAMPLER(sampler_ScDetailKeepOutTex); // 1 on the towns, the routes and the units' clearings+TEXTURE2D(_ScDetailLandTex); SAMPLER(sampler_ScDetailLandTex); // landuse.png+TEXTURE2D(_ScDetailCoastTex); SAMPLER(sampler_ScDetailCoastTex); // coast.png+TEXTURE2D(_ScDetailBakeTex); SAMPLER(sampler_ScDetailBakeTex); // terrain_bake.png+float _ScDetailTileM; // GroundDetail.TileM+float4 _ScDetailFade; // x, y the pixel footprint (m) where the painted detail starts to fade and is gone++// How much of the beach's width (ScShore's strip, up to 1.4 ScBeachM wide) is kept clear of scrub, as a multiple of ScBeachM.+static const float ScScrubOffBeach = 1.5, ScScrubOffDunes = 1.5;+// The land's luma (linear) under which a texel is a hedge, fading to none at y; the scrub density on a hedge.+static const float2 ScHedgeLuma = float2(0.045, 0.09);+static const float ScHedgeScrub = 0.85;++// 0 on the water and the beach, 1 inland (ScShore draws the sand; as the trees do, the owner: "keep them off the sand"). The dune coasts'+// ground stays sand farther in (DuneCoasts: Jaffa south, Haifa Bay).+float ScOffTheBeach(float coast, float2 mapM)+{+ float landM = saturate(coast - 0.5) * 2.0 * ScCoastRangeM;+ float from = (ScScrubOffBeach + ScScrubOffDunes * ScDuneWeight(mapM)) * ScBeachM;+ return smoothstep(from, from + 0.4 * ScBeachM, landM);+}++// Scrub density 0..1 at a point. The class holds the biomes' shares: r where the land use weighs high (the wet hills: its+// weight comes from rainfall and slope, tools/land_bake.py), g where it weighs low (the plains' ground between the fields).+// Maquis gathers: a broad noise (the grain's coarsest octave, about 2.5 km across this far up its mips) leaves thickets and+// bare ground. It thins into the gullies (the bake's curvature: 0.5 flat, lower a hollow). Every read+// is at one LOD, so the vertex shader can call it too.+half ScScrubDensity(float2 uv, float2 mapM, half4 cls, float4 land, float coast)+{+ // The dry south's trace of land use grows nothing: its weight is rainfall's, and the bushes' ranks would show every trace.+ half scrub = saturate(cls.r * smoothstep(0.08, 0.30, land.a) + cls.g * (1.0 - land.a));+ half broad = SAMPLE_TEXTURE2D_LOD(_ScDetailTex, sampler_ScDetailTex, mapM / (3.3 * _ScDetailTileM), 3.0).r;+ scrub *= smoothstep(0.40, 0.58, broad + 0.20 * scrub);+ scrub *= smoothstep(0.36, 0.50, SAMPLE_TEXTURE2D_LOD(_ScDetailBakeTex, sampler_ScDetailBakeTex, uv, 0.0).g);+ // The land bake's hedges and tree lines along the parcels' edges: its darkest colour, so bushes stand on the painted lines.+ half hedge = (1.0 - smoothstep(ScHedgeLuma.x, ScHedgeLuma.y, dot(land.rgb, half3(0.2126, 0.7152, 0.0722)))) * smoothstep(0.4, 0.7, land.a);+ scrub = max(scrub, ScHedgeScrub * hedge * saturate(cls.r + cls.g));+ scrub *= 1.0 - SAMPLE_TEXTURE2D_LOD(_ScDetailKeepOutTex, sampler_ScDetailKeepOutTex, uv, 0.0).r;+ return scrub;+}++// 0 on a drawn region border's band, 1 clear of it: the stripes stay clean (they are the terrain's, so this pass+// would stain them). The terrain's own lookup (ScBorderApply), one texel a pixel, near a hex edge only.+float ScClearOfBorder(float2 mapM, float footprint)+{+ if (_ScBorders.w < 0.5) return 1.0;+ float2 p = float2(mapM.x, _ScMap.y - mapM.y), v;+ float size = max(_ScMapOrigin.w, 1.0), inradius = 0.8660254 * size;+ float2 qr = ScHexAxial(p, size, v);+ float band = max(_ScBorderShape1.x, max(_ScBorderShape2.x, _ScBorderShape3.x)) + 3.0 * footprint;+ float edge = inradius - max(abs(v.x), max(abs(0.5 * v.x + 0.8660254 * v.y), abs(0.5 * v.x - 0.8660254 * v.y)));+ if (edge > band) return 1.0;+ int mask = (int)ScRegionAt(qr).z;+ float nearest = 1e9;+ for (int k = 0; k < 6; k++)+ if ((mask >> k) & 1) nearest = min(nearest, inradius - dot(v, ScHexNormals[k]));+ return smoothstep(band, 1.2 * band, nearest);+}+#endifdiff --git a/unity/Assets/Shaders/StatecraftGroundDetail.hlsl.meta b/unity/Assets/Shaders/StatecraftGroundDetail.hlsl.metanew file mode 100644index 000000000..a90698567--- /dev/null+++ b/unity/Assets/Shaders/StatecraftGroundDetail.hlsl.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: 5a764f40814d4c81a2e6d78c58b0e7d8+ShaderIncludeImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/BorderTests.cs b/unity/Assets/Tests/EditMode/BorderTests.csindex ce2a63456..71283388e 100644--- a/unity/Assets/Tests/EditMode/BorderTests.cs+++ b/unity/Assets/Tests/EditMode/BorderTests.cs@@ -33,7 +33,7 @@ public class BorderTestsMapShaderGlobals.PinWaterTime(100f); // renders compared pixel for pixel: the sea must not move between them// The borders themselves, as SeaTests measures the water: the 1948 villages' houses and trees stand on many edges near// gameplay03, and a roof or crown on a walk is not the border's colour.- foreach (var n in new[] { "kits", "trees" }) if (VisualToggles.Names.Contains(n)) VisualToggles.Set(n, false);+ foreach (var n in new[] { "kits", "trees", GroundDetail.Toggle, GroundDetail.ScrubToggle }) if (VisualToggles.Names.Contains(n)) VisualToggles.Set(n, false);var cam = Camera.main;return (map, cam, cam.GetComponent<CameraRig>());}@@ -319,16 +319,17 @@ public class BorderTests/// measured 2026-10-12 (see the test's log), floor below it as the grid readability test does.</summary>public const float BandLegibleShare = 0.8f;- /// <summary>Review M9 (promo-villages): Open measures the bands with the kits and trees off; this one checks them in the- /// shipped look. Across proof edges by gameplay03 (the coastal plain's villages) and by Tulkarm, with kits and trees on,- /// a walk "reads" when some pixel within 900 m of the edge changes by deltaE76 >= 8 with the borders on against off (a- /// roof or crown may cover part of the band, not all of it). At least BandLegibleShare of the walks read.</summary>+ /// <summary>Review M9 (promo-villages): Open measures the bands with the kits, trees, ground detail and scrub off; this one+ /// checks them in the shipped look, all four on (#2878's painted scrub and standing bushes are kept off the band, so they+ /// must not bury it as a roof or crown could). Across proof edges by gameplay03 (the coastal plain's villages) and by+ /// Tulkarm, a walk "reads" when some pixel within 900 m of the edge changes by deltaE76 >= 8 with the borders on against+ /// off (a roof, crown or bush may cover part of the band, not all of it). At least BandLegibleShare of the walks read.</summary>[UnityTest]public IEnumerator TheBandsStillReadThroughTheVillages(){var (map, cam, rig) = Open();yield return null;- foreach (var n in new[] { "kits", "trees" }) VisualToggles.Set(n, true);+ foreach (var n in new[] { "kits", "trees", GroundDetail.Toggle, GroundDetail.ScrubToggle }) VisualToggles.Set(n, true);RenderSample.TiltShift(false);BorderProof.Show(map);int walks = 0, read = 0;@@ -345,7 +346,7 @@ public class BorderTestsshows = Mathf.Abs(w.SignedM[k]) <= 900f && RenderSample.DeltaE(w.On[k], w.Off[k]) >= 8f;if (shows) { read++; here++; }}- TestContext.WriteLine($"{name}: the band reads on {here} of 9 walks with kits and trees on");+ TestContext.WriteLine($"{name}: the band reads on {here} of 9 walks in the shipped look");}float share = read / (float)walks;TestContext.WriteLine($"bands legible on {read} of {walks} walks ({share:P0})");diff --git a/unity/Assets/Tests/EditMode/GroundDetailShots.cs b/unity/Assets/Tests/EditMode/GroundDetailShots.csnew file mode 100644index 000000000..ce259d548--- /dev/null+++ b/unity/Assets/Tests/EditMode/GroundDetailShots.cs@@ -0,0 +1,122 @@+#nullable enable+using System;+using System.Collections;+using System.Globalization;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Kits;+using Statecraft.Game.UI;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>Writes the before and after stills for issue #2878 (ground detail and scatter between the towns) to+/// `.superpowers/shots-2878/<SHOTS_TAG>/` at the repository root (local, not committed; SHOTS_TAG from the environment,+/// "untagged" when unset). Each still is the map camera's frame with the UI drawn over it (CivMovementShots.Shot), in the+/// game's opening state, so a pair differs only by the change. The poses: the opening itself (the rig as the game leaves+/// it), the same look-at at 12 km, the land between the towns at 31 and 12 km, the hills, the desert, the sea, Jerusalem,+/// and the two promo poses. Each gets a `SHOT` line with the tree instances submitted. Explicit, so it does not run with+/// the checks.</summary>+[Explicit("writes stills for a pull request, not a check")]+public class GroundDetailShots+{+ static readonly (string name, double lon, double lat, float km, float yaw)[] Poses =+ {+ ("between31", 34.93, 32.02, 31f, 0f), ("between12", 34.93, 32.02, 12f, 0f),+ ("citrus12", 34.85, 31.95, 12f, 0f),+ ("hills31", 35.05, 31.85, 31f, 0f), ("hills12", 35.05, 31.76, 12f, 0f),+ ("galilee31", 35.30, 32.85, 31f, 0f),+ ("desert31", 34.85, 30.90, 31f, 0f), ("desert12", 34.90, 30.60, 12f, 0f),+ ("sea31", 34.72, 32.40, 31f, 0f),+ ("jerusalem12", 35.2256, 31.7789, 12f, 0f),+ ("gameplay03", PromoPose.Gameplay03.Lon, PromoPose.Gameplay03.Lat, PromoPose.Gameplay03.Distance / 1000f, PromoPose.Gameplay03.Yaw),+ ("diorama02", PromoPose.Diorama02.Lon, PromoPose.Diorama02.Lat, PromoPose.Diorama02.Distance / 1000f, PromoPose.Diorama02.Yaw),+ };++ string saveDir = "";+ RenderTexture? rt; PanelSettings? ps;++ [SetUp]+ public void Prepare() => saveDir = Path.Combine(Path.GetTempPath(), "statecraft-ground-shots-" + Guid.NewGuid().ToString("N"));++ [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>The map camera's frame at the game's 1920 x 1080, without the UI.</summary>+ static void Shot(string name, string dir)+ {+ var map = Object.FindFirstObjectByType<MapScene>();+ var layer = map.GetComponentInChildren<VegetationLayer>(true);+ var detail = map.GetComponentInChildren<GroundDetail>(true);+ var cam = Camera.main;+ var frame = new RenderTexture(1920, 1080, 24, RenderTextureFormat.ARGB32);+ var before = cam.targetTexture;+ cam.targetTexture = frame; cam.Render(); cam.targetTexture = before;+ var prev = RenderTexture.active; RenderTexture.active = frame;+ var tex = new Texture2D(1920, 1080, TextureFormat.RGB24, false);+ tex.ReadPixels(new Rect(0, 0, 1920, 1080), 0, 0); tex.Apply();+ RenderTexture.active = prev; frame.Release(); Object.DestroyImmediate(frame);+ File.WriteAllBytes(Path.Combine(dir, name + ".png"), tex.EncodeToPNG());+ Object.DestroyImmediate(tex);+ Debug.Log(FormattableString.Invariant($"SHOT {name} trees planted {layer.Count} drawn {layer.LastDrawn} scrub tiles {detail?.LastTiles} aspect {cam.aspect:F3}"));+ }++ /// <summary>The frame with the UI over it, at the UI texture's size (CivMovementShots.Shot).</summary>+ static void UiShot(string name, string dir)+ {+ CivMovementShots.Shot(UiTexture!, name);+ var from = Path.Combine(CivMovementShots.ShotDir, name + ".png");+ File.Copy(from, Path.Combine(dir, name + ".png"), true); File.Delete(from);+ }++ static RenderTexture? UiTexture;++ [UnityTest]+ public IEnumerator WriteStills()+ {+ var tag = Environment.GetEnvironmentVariable("SHOTS_TAG");+ var dir = Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", ".superpowers", "shots-2878", string.IsNullOrEmpty(tag) ? "untagged" : tag));+ Directory.CreateDirectory(dir); Directory.CreateDirectory(CivMovementShots.ShotDir);+ yield return CivMovementShots.Boot(false, saveDir, (t, p, u, g) => { rt = t; ps = p; });+ UiTexture = rt;+ yield return Frames(5);+ // CameraRig.Apply freezes the projection at the camera's own aspect, and a batch run's default is 4:3: every still+ // would come out 1.33 times too wide (as UnitScaleShots). The opening's look-at follows the aspect, so it is set again.+ Camera.main.aspect = 16f / 9f;+ var rig = Camera.main.GetComponent<CameraRig>();+ var opening = Object.FindFirstObjectByType<MapScene>();+ rig.LookAt = CameraRig.OpeningLookAt(opening.Frame, Camera.main.aspect, opening.Settlements.First(s => s.Id == "tel_aviv"), opening.Settlements.First(s => s.Id == "jaffa"));+ rig.Apply();+ var start = rig.LookAt;+ var timer = System.Diagnostics.Stopwatch.StartNew();+ GroundDetail.FillTexels();+ Debug.Log($"SHOT TIME texels {timer.Elapsed.TotalMilliseconds:0.0}");+ Shot("opening31", dir); UiShot("opening31-ui", dir);+ rig.Distance = 12000f; rig.Apply();+ yield return Frames(3);+ Shot("opening12", dir);+ var map = Object.FindFirstObjectByType<MapScene>();+ foreach (var (name, lon, lat, km, yaw) in Poses)+ {+ var at = map.Frame.ToWorld(lon, lat, 0);+ at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;+ rig.LookAt = at; rig.Distance = km * 1000f; rig.Yaw = yaw; rig.Apply();+ yield return Frames(3);+ Shot(name, dir);+ }+ rig.LookAt = start;+ }+}diff --git a/unity/Assets/Tests/EditMode/GroundDetailShots.cs.meta b/unity/Assets/Tests/EditMode/GroundDetailShots.cs.metanew file mode 100644index 000000000..7902990ef--- /dev/null+++ b/unity/Assets/Tests/EditMode/GroundDetailShots.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 6603d0f966bbd4367a8a97c96dbf1c70\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/GroundDetailTests.cs b/unity/Assets/Tests/EditMode/GroundDetailTests.csnew file mode 100644index 000000000..a7c568dd2--- /dev/null+++ b/unity/Assets/Tests/EditMode/GroundDetailTests.cs@@ -0,0 +1,193 @@+#nullable enable+using System.Collections;+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Units;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;++/// <summary>#2878: the ground detail pass over the terrain and the low 3D scrub (GroundDetail, GroundDetail.shader,+/// GroundScrub.shader, StatecraftGroundDetail.hlsl): where they draw, that they follow the map's data, and what they keep off.</summary>+public class GroundDetailTests+{+ [TearDown]+ public void Reset()+ {+ RenderSample.TiltShift(true);+ VisualToggles.SetAll(true);+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); VisualToggles.Clear();+ }++ static MapScene OpenMap()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single); // the scene is not saved+ var map = Object.FindFirstObjectByType<MapScene>();+ map.Build();+ return map;+ }++ static RenderSample At(MapScene map, Camera cam, double lon, double lat, float distance)+ {+ var rig = cam.GetComponent<CameraRig>();+ var at = map.Frame.ToWorld(lon, lat, 0);+ at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;+ rig.LookAt = at; rig.Distance = distance; rig.Apply();+ return RenderSample.Render(cam, 960, 540);+ }++ [Test]+ public void ThePassDrawsRightAfterTheTerrainAndCastsNoShadow()+ {+ var map = OpenMap();+ var detail = map.GetComponentInChildren<GroundDetail>(true);+ Assert.IsNotNull(detail, "the map builds the ground detail");+ var renderer = detail.GetComponent<MeshRenderer>();+ Assert.Greater(renderer.sharedMaterial.renderQueue, map.Terrain.materialTemplate.renderQueue);+ Assert.Less(renderer.sharedMaterial.renderQueue, (int)UnityEngine.Rendering.RenderQueue.Geometry, "before the kits, trees and units");+ Assert.AreEqual(UnityEngine.Rendering.ShadowCastingMode.Off, renderer.shadowCastingMode);+ Assert.Contains(GroundDetail.Toggle, VisualToggles.Names.ToList());+ Assert.Contains(GroundDetail.ScrubToggle, VisualToggles.Names.ToList());+ }++ [Test]+ public void BothShadersCompileForWebGL2()+ {+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(Shader.Find("Statecraft/GroundDetail")));+ CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(Shader.Find("Statecraft/GroundScrub")));+ }++ [UnityTest]+ public IEnumerator TheHillsGainDetailAndTheSeaAndTheOverviewDoNot()+ {+ var map = OpenMap();+ RenderSample.TiltShift(false);+ yield return null;+ var cam = Camera.main;+ foreach (var n in new[] { "kits", "trees" }) if (VisualToggles.Names.Contains(n)) VisualToggles.Set(n, false);+ var hills = At(map, cam, 35.05, 31.85, 31000f);+ var sea = At(map, cam, 34.45, 32.40, 31000f);+ var overview = At(map, cam, PromoPose.Diorama02.Lon, PromoPose.Diorama02.Lat, PromoPose.Diorama02.Distance);+ VisualToggles.Set(GroundDetail.Toggle, false); VisualToggles.Set(GroundDetail.ScrubToggle, false);+ var bareHills = At(map, cam, 35.05, 31.85, 31000f);+ var bareSea = At(map, cam, 34.45, 32.40, 31000f);+ var bareOverview = At(map, cam, PromoPose.Diorama02.Lon, PromoPose.Diorama02.Lat, PromoPose.Diorama02.Distance);+ TestContext.WriteLine($"gradient {bareHills.GradientEnergy(0.25f, 0.75f):0.0000} -> {hills.GradientEnergy(0.25f, 0.75f):0.0000}");+ Assert.Greater(hills.GradientEnergy(0.25f, 0.75f), 1.3f * bareHills.GradientEnergy(0.25f, 0.75f), "the land between the towns gains texture at the opening zoom");+ Assert.AreEqual(bareHills.MeanSaturation(), hills.MeanSaturation(), 0.03f, "detail, not a new colour");+ Assert.AreEqual(bareSea.MeanLuma(0.3f, 0.3f, 0.7f, 0.7f), sea.MeanLuma(0.3f, 0.3f, 0.7f, 0.7f), 0.01f, "not on the open sea");+ Assert.AreEqual(bareOverview.MeanSaturation(), overview.MeanSaturation(), 0.002f, "gone by the overview");+ }++ /// <summary>Scrub draws for the camera at the opening zoom, and not under the opt-in hex-tile board, past the gameplay+ /// zoom, or with the terrain off.</summary>+ [UnityTest]+ public IEnumerator TheScrubDrawsOnlyWhereItCanRead()+ {+ var map = OpenMap();+ yield return null;+ var cam = Camera.main; var detail = map.GetComponentInChildren<GroundDetail>(true);+ At(map, cam, 35.05, 31.85, 31000f);+ Assert.Greater(detail.LastTiles, 0);+ Assert.Less(detail.LastTiles, 40, "a few tile instances, never a bush each");+ At(map, cam, PromoPose.Diorama02.Lon, PromoPose.Diorama02.Lat, PromoPose.Diorama02.Distance);+ Assert.AreEqual(0, detail.LastTiles, "not at the overview");+ var board = new GameObject(Statecraft.HexTiles.HexTilesLook.RootName);+ board.transform.SetParent(map.transform, false);+ At(map, cam, 35.05, 31.85, 31000f);+ Assert.AreEqual(0, detail.LastTiles, "not on the hex-tile board");+ Object.DestroyImmediate(board);+ map.Terrain.enabled = false;+ At(map, cam, 35.05, 31.85, 31000f);+ map.Terrain.enabled = true;+ Assert.AreEqual(0, detail.LastTiles, "not with the terrain off");+ }++ [Test]+ public void TheScrubFollowsTheBiomes()+ {+ Assert.Greater(GroundDetail.ClassOf("hills").WetScrub, GroundDetail.ClassOf("coastal_plain").WetScrub);+ Assert.Greater(GroundDetail.ClassOf("mountains").WetScrub, GroundDetail.ClassOf("valley").WetScrub);+ foreach (var water in new[] { "sea", "lake" })+ {+ var c = GroundDetail.ClassOf(water);+ Assert.AreEqual(0f, c.WetScrub + c.OpenScrub + c.Grain + c.Stones, water);+ }+ var desert = GroundDetail.ClassOf("desert");+ Assert.AreEqual(0f, desert.WetScrub + desert.OpenScrub, "no scrub on the desert");+ Assert.Greater(desert.Grain, 0f);+ var map = OpenMap();+ var px = GroundDetail.FillClasses(map.Frame, map.Hexes, out int nx, out int nz);+ Color32 At2(double lon, double lat)+ {+ var w = map.Frame.ToWorld(lon, lat, 0);+ return px[Mathf.RoundToInt(w.z / map.Frame.LengthM * (nz - 1)) * nx + Mathf.RoundToInt(w.x / map.Frame.WidthM * (nx - 1))];+ }+ Assert.Greater(At2(35.15, 31.80).r, At2(34.80, 32.00).r, "the Judean hills against the coastal plain");+ Assert.AreEqual(0, At2(34.40, 32.60).b, "nothing in the open sea");+ Assert.AreEqual(0, At2(34.90, 30.60).r, "nothing in the Negev");+ }++ [Test]+ public void TheScrubKeepsOffTheDiscsAndCorridors()+ {+ var map = OpenMap();+ var c = new Vector2(40000f, 90000f);+ var line = new List<Vector2> { new Vector2(60000f, 150000f), new Vector2(70000f, 150000f) };+ var px = GroundDetail.FillKeepOut(map.Frame, new[] { (c, 2000f) }, new[] { (line, 400f) });+ byte At(Vector2 p) => px[Mathf.FloorToInt(p.y / map.Frame.LengthM * GroundDetail.KeepOutHeight) * GroundDetail.KeepOutWidth+ + Mathf.FloorToInt(p.x / map.Frame.WidthM * GroundDetail.KeepOutWidth)];+ Assert.AreEqual(255, At(c)); Assert.AreEqual(255, At(c + Vector2.right * 1800f));+ Assert.AreEqual(0, At(c + Vector2.right * 2600f));+ Assert.AreEqual(255, At(new Vector2(65000f, 150000f)), "along a route");+ Assert.AreEqual(0, At(new Vector2(65000f, 151500f)));+ }++ [Test]+ public void ATownAndARouteAreInTheMapsKeepOut()+ {+ var map = OpenMap();+ var s = map.Settlements.First(x => x.Id == "tel_aviv");+ var w = map.Frame.ToWorld(s.Lon, s.Lat, 0);+ var line = map.KitRouteCorridors.First();+ var px = GroundDetail.FillKeepOut(map.Frame, map.SettlementFootprints, map.KitRouteCorridors);+ byte At(Vector2 p) => px[Mathf.FloorToInt(p.y / map.Frame.LengthM * GroundDetail.KeepOutHeight) * GroundDetail.KeepOutWidth+ + Mathf.FloorToInt(p.x / map.Frame.WidthM * GroundDetail.KeepOutWidth)];+ Assert.AreEqual(255, At(new Vector2(w.x, w.z)));+ Assert.AreEqual(255, At(line.line[line.line.Count / 2]));+ }++ /// <summary>The smallest unit base is a compact token's, its radius built as UnitLayer builds every Army base (the full+ /// trio at DrawSpread times the hex, times UnitGround.CompactScale); no bush's top reaches that base's lip.</summary>+ [Test]+ public void NoBushStandsThroughAUnitBase()+ {+ var map = OpenMap();+ float hex = map.Hexes.hex_size_km * 1000f;+ float smallestBase = UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3), UnitShowcase.DrawSpread * hex * UnitGround.CompactScale));+ Assert.Less(GroundDetail.BushTopM, UnitPlinth.LipShare * smallestBase);+ }++ [Test]+ public void TheDetailTileIsSeededAndCarriesEveryChannel()+ {+ var a = GroundDetail.FillTexels(); var b = GroundDetail.FillTexels();+ CollectionAssert.AreEqual(a, b);+ var mean = new float[4];+ for (int i = 0; i < a.Length; i++) mean[i % 4] += a[i];+ for (int k = 0; k < 4; k++) mean[k] /= a.Length / 4f * 255f;+ Assert.AreEqual(0.5f, mean[0], 0.06f, "the grain darkens as much as it lightens");+ for (int k = 1; k < 4; k++) Assert.Greater(mean[k], 0.01f, "channel " + k);+ }++ [Test]+ public void TheScrubTileIsOneSmallMesh()+ {+ var mesh = GroundDetail.BuildScrubMesh();+ Assert.Less(mesh.vertexCount, 30000);+ Object.DestroyImmediate(mesh);+ }+}diff --git a/unity/Assets/Tests/EditMode/GroundDetailTests.cs.meta b/unity/Assets/Tests/EditMode/GroundDetailTests.cs.metanew file mode 100644index 000000000..d25121f3d--- /dev/null+++ b/unity/Assets/Tests/EditMode/GroundDetailTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 5f29db2fc0a424d61b34b8434c5d5f92\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/TerrainShaderTests.cs b/unity/Assets/Tests/EditMode/TerrainShaderTests.csindex df39e5360..4a8ee152c 100644--- a/unity/Assets/Tests/EditMode/TerrainShaderTests.cs+++ b/unity/Assets/Tests/EditMode/TerrainShaderTests.cs@@ -166,6 +166,7 @@ public class TerrainShaderTests{var map = OpenMap();VisualToggles.Set("trees", false);+ VisualToggles.Set(GroundDetail.Toggle, false); VisualToggles.Set(GroundDetail.ScrubToggle, false); // the bakes aloneyield return null;var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();rig.LookAt = map.Frame.ToWorld(35.25, 31.70, 0); rig.Distance = 45000f; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();