Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

fix(map): the selection band has a depth offset and clears the ground across its width (fix round 1, M2)

eyalgolanf0f9e4468497
diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.cs
index c4b47f43f..41bc64b0c 100644
--- a/unity/Assets/Editor/MapCapture.cs
+++ b/unity/Assets/Editor/MapCapture.cs
@@ -29,7 +29,7 @@ public static class MapCapture
var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
var controller = Camera.main.gameObject.AddComponent<CameraController>(); // adds the CameraRig it requires
var map = new GameObject("MapScene").AddComponent<MapScene>();
- map.Configure(Load(MapMaterials.TerrainPath), Load(MapMaterials.OverlayPath), Load(MapMaterials.MarkerPath));
+ map.Configure(Load(MapMaterials.TerrainPath), Load(MapMaterials.OverlayPath), Load(MapMaterials.MarkerPath), Load(MapMaterials.SelectionPath));
var boot = new GameObject("Boot").AddComponent<GameBoot>();
boot.Configure(map);
var placements = new GameObject("Placements").AddComponent<PlacementLayer>();
diff --git a/unity/Assets/Editor/MapMaterials.cs b/unity/Assets/Editor/MapMaterials.cs
index 89ff6b03e..91967e890 100644
--- a/unity/Assets/Editor/MapMaterials.cs
+++ b/unity/Assets/Editor/MapMaterials.cs
@@ -12,6 +12,7 @@ namespace Statecraft.Game.EditorTools
public const string TerrainPath = Folder + "/Terrain.mat";
public const string OverlayPath = Folder + "/HexOverlay.mat";
public const string MarkerPath = Folder + "/SettlementMarker.mat";
+ public const string SelectionPath = Folder + "/HexSelection.mat";
public static void Create()
{
@@ -26,6 +27,8 @@ namespace Statecraft.Game.EditorTools
var marker = Make(MarkerPath, "Universal Render Pipeline/Lit", Color.white);
marker.SetFloat("_Smoothness", 0f); marker.SetFloat("_Metallic", 0f);
EditorUtility.SetDirty(marker);
+ // The selected hex's outline: its own shader (Assets/Shaders/HexSelection.shader) with a depth offset (fix round 1, M2).
+ Make(SelectionPath, "Statecraft/HexSelection", Statecraft.Game.Map.MapScene.SelectionColour);
AssetDatabase.SaveAssets();
}
diff --git a/unity/Assets/Map.unity b/unity/Assets/Map.unity
index d62ebe13f..a2895b2ba 100644
--- a/unity/Assets/Map.unity
+++ b/unity/Assets/Map.unity
@@ -382,6 +382,7 @@ MonoBehaviour:
terrainMaterial: {fileID: 2100000, guid: fc63b910005e64adaaa42ba488bcc248, type: 2}
overlayMaterial: {fileID: 2100000, guid: 29dd83b7b3b1f4a4aa5a710be0078164, type: 2}
markerMaterial: {fileID: 2100000, guid: 7c65bbd4355344f1990495c458323a4e, type: 2}
+ selectionMaterial: {fileID: 2100000, guid: 6116b1f8c72b244e0a9556c2cdb6b1c5, type: 2}
--- !u!4 &1195372453
Transform:
m_ObjectHideFlags: 0
diff --git a/unity/Assets/Materials/HexSelection.mat b/unity/Assets/Materials/HexSelection.mat
new file mode 100644
index 000000000..f2fd0c48a
--- /dev/null
+++ b/unity/Assets/Materials/HexSelection.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: HexSelection
+ m_Shader: {fileID: 4800000, guid: 6e20d5043e2fd4f698101a4fd55cefaf, 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:
+ - _BaseColor: {r: 1, g: 0.84, b: 0.38, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/unity/Assets/Materials/HexSelection.mat.meta b/unity/Assets/Materials/HexSelection.mat.meta
new file mode 100644
index 000000000..92cded632
--- /dev/null
+++ b/unity/Assets/Materials/HexSelection.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 6116b1f8c72b244e0a9556c2cdb6b1c5
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 79bfc4f51..c17baef11 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -11,7 +11,7 @@ namespace Statecraft.Game.Map
/// component calls Build(inputs) once the inputs are loaded (fetched on WebGL); editor tools call Build().</summary>
public sealed class MapScene : MonoBehaviour
{
- [SerializeField] Material terrainMaterial, overlayMaterial, markerMaterial;
+ [SerializeField] Material terrainMaterial, overlayMaterial, markerMaterial, selectionMaterial;
public GeoFrame Frame { get; private set; }
/// <summary>hexes.json as the last Build read it (bounds, hex size, biomes).</summary>
@@ -21,17 +21,18 @@ namespace Statecraft.Game.Map
/// <summary>The selected hex's outline: a child of the terrain (so a rebuild destroys it).</summary>
public const string SelectionName = "HexSelection";
- /// <summary>Highlight colour of the selected hex (the UI's gold, brighter, to read against every biome).</summary>
+ /// <summary>Highlight colour of the selected hex (the UI's gold, brighter, to read against every biome); MapMaterials
+ /// bakes it into the editor-made HexSelection.mat.</summary>
public static readonly Color SelectionColour = new Color(1f, 0.84f, 0.38f);
/// <summary>Width of the outline band, as a fraction of the hex circumradius (about 600 m on a 5 km hex).</summary>
public const float SelectionWidth = 0.12f;
- /// <summary>Height of the band above the hex overlay's lines, which it covers.</summary>
+ /// <summary>Height of the band above the hex overlay's lines, which it covers (its material also has a depth offset).</summary>
public const float SelectionLiftM = 20f;
- static readonly int BaseColor = Shader.PropertyToID("_BaseColor");
- /// <summary>Outlines hex (q, r) with a band draped on the terrain in <see cref="SelectionColour"/>: the hex overlay's
- /// geometry (MapBuilder.DrapedRing, HexMath corners) and its editor-made material, coloured through a
- /// MaterialPropertyBlock (no runtime material). A hex that is not on the map hides the outline.</summary>
+ /// <summary>Outlines hex (q, r) with a band draped on the terrain: the hex overlay's geometry (MapBuilder.DrapedRing,
+ /// HexMath corners) drawn with the editor-made HexSelection.mat, whose depth offset keeps the overlay lines under it
+ /// from z-fighting (no runtime material). The band is sampled at its outer, middle and inner rings and each index
+ /// takes the highest, so terrain inside the band cannot rise through it. A hex that is not on the map hides it.</summary>
public void Select(int q, int r)
{
if (Terrain == null || Hexes == null) return;
@@ -44,11 +45,8 @@ namespace Statecraft.Game.Map
var mesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = SelectionName });
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var renderer = go.AddComponent<MeshRenderer>();
- renderer.sharedMaterial = overlayMaterial;
+ renderer.sharedMaterial = selectionMaterial;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
- var block = new MaterialPropertyBlock();
- block.SetColor(BaseColor, SelectionColour);
- renderer.SetPropertyBlock(block);
}
var mr = go.GetComponent<MeshRenderer>();
HexJson hex = null;
@@ -58,20 +56,22 @@ namespace Statecraft.Game.Map
var centre = new Vector2(c.x, c.z);
float size = Hexes.hex_size_km * 1000f, clearance = MapBuilder.OverlayClearanceM + SelectionLiftM;
var verts = new List<Vector3>(2 * MapBuilder.RingVertices);
+ var middle = new List<Vector3>(MapBuilder.RingVertices);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size, clearance, verts);
MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - SelectionWidth), clearance, verts);
+ MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - SelectionWidth / 2), clearance, middle);
int n = MapBuilder.RingVertices;
- var tris = new List<int>(12 * n);
+ var tris = new List<int>(6 * n);
for (int j = 0; j < n; j++)
{
- // Both rings at the higher of the two, so the band clears the ground between them too.
- float y = Mathf.Max(verts[j].y, verts[n + j].y);
+ // Each index at the highest of the outer, middle and inner ring, so the band clears the ground across it.
+ float y = Mathf.Max(verts[j].y, Mathf.Max(verts[n + j].y, middle[j].y));
verts[j] = new Vector3(verts[j].x, y, verts[j].z); verts[n + j] = new Vector3(verts[n + j].x, y, verts[n + j].z);
}
for (int j = 0; j < n; j++)
{
int a = j, b = (j + 1) % n, ai = n + j, bi = n + (j + 1) % n;
- tris.AddRange(new[] { a, ai, b, b, ai, bi, a, b, ai, b, bi, ai }); // both windings: seen from any yaw
+ tris.AddRange(new[] { a, ai, b, b, ai, bi }); // the shader draws both faces (Cull Off)
}
var m = go.GetComponent<MeshFilter>().sharedMesh;
m.Clear();
@@ -80,8 +80,8 @@ namespace Statecraft.Game.Map
mr.enabled = true;
}
- public void Configure(Material terrain, Material overlay, Material marker)
- { terrainMaterial = terrain; overlayMaterial = overlay; markerMaterial = marker; }
+ public void Configure(Material terrain, Material overlay, Material marker, Material selection)
+ { terrainMaterial = terrain; overlayMaterial = overlay; markerMaterial = marker; selectionMaterial = selection; }
/// <summary>Builds from the repository files with System.IO (editor and desktop only).</summary>
public void Build() => Build(GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap));
@@ -92,6 +92,7 @@ namespace Statecraft.Game.Map
if (terrainMaterial == null) throw new InvalidOperationException("MapScene: terrainMaterial is not assigned");
if (overlayMaterial == null) throw new InvalidOperationException("MapScene: overlayMaterial is not assigned");
if (markerMaterial == null) throw new InvalidOperationException("MapScene: markerMaterial is not assigned");
+ if (selectionMaterial == null) throw new InvalidOperationException("MapScene: selectionMaterial is not assigned");
var cam = Camera.main;
if (cam == null) throw new InvalidOperationException("MapScene needs a camera tagged MainCamera");
diff --git a/unity/Assets/Shaders.meta b/unity/Assets/Shaders.meta
new file mode 100644
index 000000000..1cfa7ab1f
--- /dev/null
+++ b/unity/Assets/Shaders.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: aff381a4fe47d490ebc15dabe1b556d3
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Shaders/HexSelection.shader b/unity/Assets/Shaders/HexSelection.shader
new file mode 100644
index 000000000..b53d214c5
--- /dev/null
+++ b/unity/Assets/Shaders/HexSelection.shader
@@ -0,0 +1,40 @@
+// The selected hex's outline band (MapScene.Select). Unlit, one colour, drawn after the hex overlay with a depth offset
+// towards the camera, so the overlay's lines under the band's edge never z-fight with it, even at the camera's maximum
+// distance where a 24-bit depth step is tens of metres (fix round 1, M2). Both faces: the band is seen from every yaw.
+Shader "Statecraft/HexSelection"
+{
+ Properties
+ {
+ [MainColor] _BaseColor("Color", Color) = (1, 0.84, 0.38, 1)
+ }
+ SubShader
+ {
+ Tags { "RenderType" = "Opaque" "Queue" = "Geometry+10" "RenderPipeline" = "UniversalPipeline" }
+ Pass
+ {
+ Name "Unlit"
+ Tags { "LightMode" = "UniversalForward" }
+ Cull Off
+ ZWrite On
+ ZTest LEqual
+ Offset -1, -4
+ HLSLPROGRAM
+ #pragma vertex Vert
+ #pragma fragment Frag
+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+ CBUFFER_START(UnityPerMaterial)
+ half4 _BaseColor;
+ CBUFFER_END
+ struct Attributes { float4 positionOS : POSITION; };
+ struct Varyings { float4 positionCS : SV_POSITION; };
+ Varyings Vert(Attributes input)
+ {
+ Varyings o;
+ o.positionCS = TransformObjectToHClip(input.positionOS.xyz);
+ return o;
+ }
+ half4 Frag(Varyings input) : SV_Target { return _BaseColor; }
+ ENDHLSL
+ }
+ }
+}
diff --git a/unity/Assets/Shaders/HexSelection.shader.meta b/unity/Assets/Shaders/HexSelection.shader.meta
new file mode 100644
index 000000000..3f1e8525b
--- /dev/null
+++ b/unity/Assets/Shaders/HexSelection.shader.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 6e20d5043e2fd4f698101a4fd55cefaf
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Tests/EditMode/MapActionUiTests.cs b/unity/Assets/Tests/EditMode/MapActionUiTests.cs
index 0a344bbb4..7448b2a41 100644
--- a/unity/Assets/Tests/EditMode/MapActionUiTests.cs
+++ b/unity/Assets/Tests/EditMode/MapActionUiTests.cs
@@ -112,7 +112,8 @@ public class MapActionUiTests
var map = new GameObject("MapScene").AddComponent<MapScene>();
map.Configure(AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Terrain.mat"),
AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexOverlay.mat"),
- AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat"));
+ AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat"),
+ AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexSelection.mat"));
map.Build();
var layer = new GameObject("Placements").AddComponent<PlacementLayer>();
var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
@@ -238,7 +239,8 @@ public class MapActionUiTests
var map = new GameObject("MapScene").AddComponent<MapScene>();
map.Configure(AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Terrain.mat"),
AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexOverlay.mat"),
- AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat"));
+ AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat"),
+ AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexSelection.mat"));
map.Build();
Physics.SyncTransforms();
return map;
diff --git a/unity/Assets/Tests/EditMode/SettlementTests.cs b/unity/Assets/Tests/EditMode/SettlementTests.cs
index abbb1c73a..0dc414c4b 100644
--- a/unity/Assets/Tests/EditMode/SettlementTests.cs
+++ b/unity/Assets/Tests/EditMode/SettlementTests.cs
@@ -129,7 +129,7 @@ public class MapSceneTests
static string RealYamlPath => Path.Combine(Paths.Content, "map", "settlements_1948.yaml");
const string TerrainMatPath = "Assets/Materials/Terrain.mat", OverlayMatPath = "Assets/Materials/HexOverlay.mat",
- MarkerMatPath = "Assets/Materials/SettlementMarker.mat";
+ MarkerMatPath = "Assets/Materials/SettlementMarker.mat", SelectionMatPath = "Assets/Materials/HexSelection.mat";
[SetUp] public void FreshScene() => EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
@@ -142,7 +142,7 @@ public class MapSceneTests
{
if (withCamera) new GameObject("TestMainCamera") { tag = "MainCamera" }.AddComponent<Camera>();
var map = new GameObject("MapScene").AddComponent<MapScene>();
- map.Configure(Load(TerrainMatPath), Load(OverlayMatPath), Load(MarkerMatPath));
+ map.Configure(Load(TerrainMatPath), Load(OverlayMatPath), Load(MarkerMatPath), Load(SelectionMatPath));
return map;
}
@@ -196,28 +196,32 @@ public class MapSceneTests
public void SelectingAHexOutlinesItOnTheTerrain()
{
var map = NewMap(); map.Build();
- var overlay = Load(OverlayMatPath);
+ var selection = Load(SelectionMatPath);
+ // Fix round 1, M2: its own editor-made material, whose shader pulls the band towards the camera in depth (Offset), so
+ // the overlay lines under its edge cannot z-fight with it at long range.
+ Assert.AreEqual("Statecraft/HexSelection", selection.shader.name);
+ StringAssert.IsMatch(@"(?m)^\s*Offset\s+-\d+\s*,\s*-\d+", File.ReadAllText(AssetDatabase.GetAssetPath(selection.shader)));
+ Assert.Greater(selection.renderQueue, Load(OverlayMatPath).renderQueue, "drawn after the overlay lines");
float size = map.Hexes.hex_size_km * 1000f;
bool Inland(HexJson h) // whole hex on the terrain, so no corner is clamped to the map's edge
{
var w = map.Frame.ToWorld(h.lon, h.lat, 0);
return w.x > size && w.x < map.Frame.WidthM - size && w.z > size && w.z < map.Frame.LengthM - size;
}
- var land = System.Array.FindAll(map.Hexes.hexes, h => h.land && h.biome == "hills" && Inland(h));
+ // The roughest inland hexes: the band must clear the ground across its whole width there, not just at its edges.
+ var land = System.Array.FindAll(map.Hexes.hexes, h => h.land && (h.biome == "mountains" || h.biome == "hills") && Inland(h));
Assert.Greater(land.Length, 2);
- foreach (var h in new[] { land[0], land[land.Length / 2] })
+ foreach (var h in land)
{
map.Select(h.q, h.r);
var sel = map.Terrain.transform.Find(MapScene.SelectionName);
Assert.IsNotNull(sel, "the selection outline exists");
var mr = sel.GetComponent<MeshRenderer>();
Assert.IsTrue(mr.enabled, "the outline is shown");
- Assert.AreSame(overlay, mr.sharedMaterial, "the editor-made overlay material, not an instance");
- var block = new MaterialPropertyBlock(); mr.GetPropertyBlock(block);
- var colour = block.GetColor(Shader.PropertyToID("_BaseColor"));
- Assert.Less(Mathf.Abs(colour.r - MapScene.SelectionColour.r) + Mathf.Abs(colour.g - MapScene.SelectionColour.g)
- + Mathf.Abs(colour.b - MapScene.SelectionColour.b), 1e-3f, $"highlight colour, got {colour}");
+ Assert.AreSame(selection, mr.sharedMaterial, "the editor-made selection material, not an instance");
var verts = sel.GetComponent<MeshFilter>().sharedMesh.vertices;
+ int n = MapBuilder.RingVertices;
+ Assert.AreEqual(2 * n, verts.Length);
var centre = map.Frame.ToWorld(h.lon, h.lat, 0);
var c2 = new Vector2(centre.x, centre.z);
for (int i = 0; i < 6; i++)
@@ -225,10 +229,12 @@ public class MapSceneTests
var corner = HexMath.Corner(c2, size, i);
Assert.IsTrue(System.Array.Exists(verts, v => (new Vector2(v.x, v.z) - corner).magnitude < 1f), $"corner {i} of ({h.q}, {h.r})");
}
- foreach (var v in verts)
+ for (int j = 0; j < n; j++)
{
- Assert.LessOrEqual((new Vector2(v.x, v.z) - c2).magnitude, size + 1f, "inside the hex");
- Assert.Greater(v.y, map.Terrain.SampleHeight(v) + MapBuilder.OverlayClearanceM - 1f, "draped above the terrain");
+ Assert.LessOrEqual((new Vector2(verts[j].x, verts[j].z) - c2).magnitude, size + 1f, "inside the hex");
+ var mid = (verts[j] + verts[n + j]) / 2; // the middle of the band, between its outer and inner edge
+ Assert.Greater(mid.y, map.Terrain.SampleHeight(mid) + MapBuilder.OverlayClearanceM - 1f,
+ $"({h.q}, {h.r}) vertex {j}: the band clears the ground across its width");
}
}
map.Select(-9999, -9999);
@@ -239,9 +245,12 @@ public class MapSceneTests
public void BuildWithoutMaterialsNamesTheMissingField()
{
var map = new GameObject("MapScene").AddComponent<MapScene>();
- map.Configure(Load(TerrainMatPath), Load(OverlayMatPath), null);
+ map.Configure(Load(TerrainMatPath), Load(OverlayMatPath), null, Load(SelectionMatPath));
var ex = Assert.Throws<System.InvalidOperationException>(() => map.Build());
StringAssert.Contains("markerMaterial", ex.Message);
+ map.Configure(Load(TerrainMatPath), Load(OverlayMatPath), Load(MarkerMatPath), null);
+ ex = Assert.Throws<System.InvalidOperationException>(() => map.Build());
+ StringAssert.Contains("selectionMaterial", ex.Message);
}
[Test]
@@ -268,7 +277,7 @@ public class MapSceneTests
var map = NewMap(); map.Build();
var go = map.gameObject; Object.DestroyImmediate(map);
var fresh = go.AddComponent<MapScene>();
- fresh.Configure(Load(TerrainMatPath), Load(OverlayMatPath), Load(MarkerMatPath));
+ fresh.Configure(Load(TerrainMatPath), Load(OverlayMatPath), Load(MarkerMatPath), Load(SelectionMatPath));
fresh.Build();
AssertOneOfEach();
}