A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: draw the 1949 armistice lines as true polylines (display only) (Refs #237) (#2012)
Beri124f59552f6e
diff --git a/changelog.d/237-armistice-polylines.md b/changelog.d/237-armistice-polylines.mdnew file mode 100644index 000000000..86efd2c0d--- /dev/null+++ b/changelog.d/237-armistice-polylines.md@@ -0,0 +1,8 @@+- A map mode draws the 1949 armistice lines as their true polylines over the hex-snapped bands (#237; owner's ruling of+ 30 October 2026): `?armisticelines` in the web page's URL, `-armisticelines` on desktop. Each line shows from its own+ date. The Jordan lines, traced from a low-resolution scan, are dashed, wider and a step lighter, so they read as low+ accuracy, and the two Syrian Demilitarized Zone parts too narrow to hold a hex centre are drawn as outlines. Zoomed out+ past the gameplay zoom the lines widen with the distance, so they stay readable at the full-map zoom. A release build+ draws and ships only the features the owner has signed off (11 of 16): the five draft ones are cut from its copy of the+ file. Display only: the sim never reads the lines, the bands are unchanged, and without the flag nothing is built.+ Goldens did not move.diff --git a/docs/dev-setup.md b/docs/dev-setup.mdindex e1b01db37..63bddac9f 100644--- a/docs/dev-setup.md+++ b/docs/dev-setup.md@@ -57,8 +57,8 @@ Not possible without Unity and not in CI: the Unity EditMode tests, player build- Page flags: `?golden` (golden check), `?smoke=N` (play N turns through the UI; bare `?smoke` = 5, `?smoke=0` = off),`?profile` (terrain profile), `?camlog` (log the camera distance), `?bootlog` (each boot phase's timing) and `?navlog`(every UI pointer and submit event, screen toggle and map click, with its frame), `?vprofile` (the visual frame-time- profile per feature), `?shot` (screenshots at the promo poses as `SHOT` console lines) and `?kitscale=N`, `?housescale=N`, `?treescale=N` (the settlement kits' symbolic scale for city blocks, houses and trees, clamped to 5–200; defaults 60, 100, 100). In the editor, `MapCapture.Kits` takes `-kitScale`, `-houseScale` and `-treeScale`. Desktop players take `-golden`,- `-smoke N`, `-profile`, `-camlog`, `-bootlog`, `-navlog`, `-vprofile` and `-shot`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.+ profile per feature), `?shot` (screenshots at the promo poses as `SHOT` console lines) and `?kitscale=N`, `?housescale=N`, `?treescale=N` (the settlement kits' symbolic scale for city blocks, houses and trees, clamped to 5–200; defaults 60, 100, 100), `?armisticelines` (the 1949 armistice lines as true polylines over the hex bands, #237; a release build draws and ships only the signed-off features). In the editor, `MapCapture.Kits` takes `-kitScale`, `-houseScale` and `-treeScale`. Desktop players take `-golden`,+ `-smoke N`, `-profile`, `-camlog`, `-bootlog`, `-navlog`, `-vprofile`, `-shot` and `-armisticelines`. The console also shows `GAME OK <date> turn <n> hash <h>` at start and `TURN <n> <date> hash <h>` per turn.- First card in normal mode (#909): `?firstcard` keeps the start screen and decision video on, presses New Game at onceand logs `FIRST CARD OK event=<id> media=<photo|portrait fallback> wait=<ms> ms budget=<ms> ms`, or `FIRST CARD FAIL`after the budget (10 s, proposed). Run it with `uv run tools/machine_lock.py --shared -- uv run tools/web_check.py <build>diff --git a/unity/Assets/Editor/ContentSync.cs b/unity/Assets/Editor/ContentSync.csindex 65fd70dae..14e717268 100644--- a/unity/Assets/Editor/ContentSync.cs+++ b/unity/Assets/Editor/ContentSync.cs@@ -9,7 +9,8 @@ namespace Statecraft.Game.EditorTools/// <summary>Copies the repository's content/ into Assets/StreamingAssets/content with a manifest.json and a bundle.json/// (every text in one file, which the web boot fetches: #1054) before every player build (git-ignored output), so/// players read the same content the editor reads from the repo.- /// Run alone: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.ContentSync.Sync</summary>+ /// Run alone: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.ContentSync.Sync+ /// (copies as for a release player: the armistice lines' draft features left out).</summary>public sealed class ContentSync : IPreprocessBuildWithReport{public static string Target => Path.Combine(UnityEngine.Application.dataPath, "StreamingAssets", "content");@@ -17,12 +18,17 @@ namespace Statecraft.Game.EditorToolspublic int callbackOrder => 0;- public void OnPreprocessBuild(BuildReport report) => Sync();+ /// <summary>A release player (no Development option) ships only the armistice lines the owner has signed off+ /// (ContentManifest.Copy; owner review of #2012); a development build ships them all, as it draws them all.</summary>+ public void OnPreprocessBuild(BuildReport report) => SyncTo((report.summary.options & BuildOptions.Development) == 0);- public static void Sync()+ // Not an overload of Sync: -executeMethod finds its method by name alone.+ public static void Sync() => SyncTo(release: true);++ static void SyncTo(bool release){- var files = ContentManifest.Copy(Paths.Content, Target);- try { ContentManifest.Verify(Paths.Content, Target); }+ var files = ContentManifest.Copy(Paths.Content, Target, release);+ try { ContentManifest.Verify(Paths.Content, Target, release); }catch (InvalidDataException e) { throw new BuildFailedException("ContentSync: " + e.Message); }UnityEngine.Debug.Log($"ContentSync: {files.Count} files to {Target}");var source = Path.Combine(Paths.RepoRoot, "sim", "Statecraft.Sim.Tests");diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs b/unity/Assets/Scripts/Boot/ContentManifest.csindex 49a22e884..1b2ab02f7 100644--- a/unity/Assets/Scripts/Boot/ContentManifest.cs+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs@@ -3,6 +3,7 @@ using System;using System.Collections.Generic;using System.IO;using System.Linq;+using Statecraft.Game.Map;using UnityEngine;namespace Statecraft.Game.Boot@@ -28,9 +29,9 @@ namespace Statecraft.Game.Boot/// <summary>Baked map files that are not YAML, listed when present: the runtime forms of the 1948 localities and of the/// route paths and the region files (boot budget, issue #321). Their YAML still ships: each runtime file is checked- /// against it.</summary>+ /// against it. Also the true armistice lines, which the "armisticelines" map mode draws as they are (#237).</summary>public static readonly IReadOnlyList<string> RuntimeData = new[] { "map/localities_1948.tsv", "map/route_paths_1948.tsv",- "map/subdistrict_hexes_1948.tsv", "map/armistice_hexes_1949.tsv", "map/control_hexes_1948_49.tsv" };+ "map/subdistrict_hexes_1948.tsv", "map/armistice_hexes_1949.tsv", "map/control_hexes_1948_49.tsv", "map/armistice_lines_1949.geojson" };[Serializable] sealed class ManifestJson { public string[] files = new string[0]; }[Serializable] sealed class BundleJson { public string[] files = new string[0]; public string[] texts = new string[0]; }@@ -60,13 +61,23 @@ namespace Statecraft.Game.Boot}/// <summary>bundle.json for <paramref name="files"/> (paths relative to <paramref name="contentDir"/>), each text- /// read as the disk path reads it (File.ReadAllText), so the content hash is the disk's.</summary>- public static string WriteBundle(string contentDir, IReadOnlyList<string> files) => JsonUtility.ToJson(new BundleJson+ /// read as the disk path reads it (File.ReadAllText), so the content hash is the disk's; a <paramref name="release"/>+ /// build's as <see cref="Shipped"/> gives it.</summary>+ public static string WriteBundle(string contentDir, IReadOnlyList<string> files, bool release = false) => JsonUtility.ToJson(new BundleJson{files = files.ToArray(),- texts = files.Select(f => File.ReadAllText(Path.Combine(contentDir, f))).ToArray(),+ texts = files.Select(f => Shipped(contentDir, f, release)).ToArray(),});+ /// <summary>A file's text as a build ships it: the source's, but a <paramref name="release"/> build's true armistice+ /// lines hold only the features the owner has signed off (ArmisticeLines.ReleaseText; owner review of #2012). The+ /// sim never reads that file, so the content hash is the same either way.</summary>+ static string Shipped(string contentDir, string file, bool release)+ {+ var text = File.ReadAllText(Path.Combine(contentDir, file));+ return release && file == "map/" + ArmisticeLines.FileName ? ArmisticeLines.ReleaseText(text) : text;+ }+/// <summary>Parses bundle.json into the file list (as manifest.json lists it) and each file's text; throws/// InvalidDataException when it is not a bundle.</summary>public static (List<string> Files, Dictionary<string, string> Texts) ParseBundle(string json)@@ -84,9 +95,9 @@ namespace Statecraft.Game.Boot}/// <summary>Checks a copy made by Copy: manifest.json equals Collect(contentDir) and every listed file exists, and- /// bundle.json lists the same files with each one's text as the source has it. Throws InvalidDataException naming- /// the problem.</summary>- public static void Verify(string contentDir, string targetDir)+ /// bundle.json lists the same files with each one's text as the source has it (as a <paramref name="release"/> build+ /// ships it). Throws InvalidDataException naming the problem.</summary>+ public static void Verify(string contentDir, string targetDir, bool release = false){var expected = Collect(contentDir);var written = Parse(File.ReadAllText(Path.Combine(targetDir, FileName)));@@ -100,11 +111,12 @@ namespace Statecraft.Game.Bootif (!expected.SequenceEqual(files))throw new InvalidDataException($"{BundleFileName} in {targetDir} does not match the content files ({files.Count} listed, {expected.Count} expected)");foreach (var f in files)- if (texts[f] != File.ReadAllText(Path.Combine(contentDir, f))) throw new InvalidDataException($"{f}: its text in {BundleFileName} differs from the source");+ if (texts[f] != Shipped(contentDir, f, release)) throw new InvalidDataException($"{f}: its text in {BundleFileName} differs from the source");}- /// <summary>Replaces <paramref name="targetDir"/> with a copy of the collected files plus manifest.json and bundle.json.</summary>- public static List<string> Copy(string contentDir, string targetDir)+ /// <summary>Replaces <paramref name="targetDir"/> with a copy of the collected files plus manifest.json and bundle.json;+ /// for a <paramref name="release"/> build, the files as <see cref="Shipped"/> gives them.</summary>+ public static List<string> Copy(string contentDir, string targetDir, bool release = false){var files = Collect(contentDir);if (Directory.Exists(targetDir)) Directory.Delete(targetDir, true);@@ -112,10 +124,11 @@ namespace Statecraft.Game.Boot{var to = Path.Combine(targetDir, f);Directory.CreateDirectory(Path.GetDirectoryName(to)!);- File.Copy(Path.Combine(contentDir, f), to);+ if (release && f == "map/" + ArmisticeLines.FileName) File.WriteAllText(to, Shipped(contentDir, f, release));+ else File.Copy(Path.Combine(contentDir, f), to);}File.WriteAllText(Path.Combine(targetDir, FileName), Write(files));- File.WriteAllText(Path.Combine(targetDir, BundleFileName), WriteBundle(contentDir, files));+ File.WriteAllText(Path.Combine(targetDir, BundleFileName), WriteBundle(contentDir, files, release));return files;}}diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.csindex 84665058a..627c11a65 100644--- a/unity/Assets/Scripts/Boot/GameInputs.cs+++ b/unity/Assets/Scripts/Boot/GameInputs.cs@@ -42,6 +42,9 @@ namespace Statecraft.Game.Boot/// <summary>content/map/control_hexes_1948_49.yaml: who held which areas, 1948-49, by period (display only; "" when/// absent: the older drawing, sub-districts with the armistice zones over them).</summary>public string ControlYaml = "";+ /// <summary>content/map/armistice_lines_1949.geojson: the true armistice lines, drawn as polylines in the+ /// "armisticelines" map mode (ArmisticeLines, #237; display only; "" when absent: no overlay).</summary>+ public string ArmisticeLinesGeojson = "";/// <summary>heightmap.r16z as read: packed (HeightmapCodec); HeightmapLoader decodes it when the map is built.</summary>public byte[] HeightmapR16z = new byte[0];}@@ -75,6 +78,7 @@ namespace Statecraft.Game.BootArmisticeTsv = ReadIfExists(Path.Combine(contentDir, "map", Armistice1949.RuntimeFileName)),ControlTsv = ReadIfExists(Path.Combine(contentDir, "map", Control1948.RuntimeFileName)),ControlYaml = ReadIfExists(Path.Combine(contentDir, "map", Control1948.FileName)),+ ArmisticeLinesGeojson = ReadIfExists(Path.Combine(contentDir, "map", ArmisticeLines.FileName)),};/// <summary>A map-only, cosmetic input: "" when the file is missing (the map then skips that layer with a warning).</summary>@@ -117,6 +121,7 @@ namespace Statecraft.Game.BootArmisticeTsv = texts.TryGetValue("map/" + Armistice1949.RuntimeFileName, out var armisticeTsv) ? armisticeTsv : "",ControlTsv = texts.TryGetValue("map/" + Control1948.RuntimeFileName, out var controlTsv) ? controlTsv : "",ControlYaml = texts.TryGetValue("map/" + Control1948.FileName, out var control) ? control : "",+ ArmisticeLinesGeojson = texts.TryGetValue("map/" + ArmisticeLines.FileName, out var lines) ? lines : "",},};}diff --git a/unity/Assets/Scripts/Map/ArmisticeLine.cs b/unity/Assets/Scripts/Map/ArmisticeLine.csnew file mode 100644index 000000000..2c3a726ab--- /dev/null+++ b/unity/Assets/Scripts/Map/ArmisticeLine.cs@@ -0,0 +1,39 @@+#nullable enable+using System;+using System.Collections.Generic;+using Statecraft.Game.Map.Kits;+using UnityEngine;++namespace Statecraft.Game.Map+{+ /// <summary>Marks one feature's line in the true-polyline overlay (<see cref="ArmisticeLines"/>, #237): its id, the date+ /// it is shown from (ArmisticeLines.ShowAt) and whether it is drawn in the low-accuracy style. It follows the zoom: far+ /// out it is drawn wider (ArmisticeLines.WidthScale).</summary>+ public sealed class ArmisticeLine : MonoBehaviour+ {+ public string Id = ""; public DateTime ShownFrom; public bool LowAccuracy;+ /// <summary>The width scale the line is drawn at now (ArmisticeLines.WidthScale).</summary>+ public float Scale { get; private set; }+ /// <summary>Makes the line's mesh at a width scale (owned by the overlay's MapRuntimeAssets); set by ArmisticeLines.Build.</summary>+ internal Func<float, Mesh>? MeshAt;+ readonly Dictionary<float, Mesh> meshes = new Dictionary<float, Mesh>();++ void LateUpdate() { var cam = Camera.main; if (cam != null) ShowFor(TownModelLayer.ViewDistance(cam)); }++ /// <summary>Draws the line at the width for a camera <paramref name="distanceM"/> away.</summary>+ public void ShowFor(float distanceM)+ {+ float scale = ArmisticeLines.WidthScale(distanceM);+ if (scale != Scale) DrawAt(scale);+ }++ /// <summary>Draws the line at a width scale; each scale's mesh is made once, on first use. At most three steps past the+ /// gameplay zoom, so the first zoom-out past each costs one rebuild of the lines (a one-off hitch, in an opt-in mode).</summary>+ internal void DrawAt(float scale)+ {+ if (MeshAt == null) return;+ if (!meshes.TryGetValue(scale, out var mesh)) meshes[scale] = mesh = MeshAt(scale);+ GetComponent<MeshFilter>().sharedMesh = mesh; Scale = scale;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/ArmisticeLine.cs.meta b/unity/Assets/Scripts/Map/ArmisticeLine.cs.metanew file mode 100644index 000000000..0f9f3e3e2--- /dev/null+++ b/unity/Assets/Scripts/Map/ArmisticeLine.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 2c3ef5455be5806a0ad5ccc4bba50036\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/ArmisticeLines.cs b/unity/Assets/Scripts/Map/ArmisticeLines.csnew file mode 100644index 000000000..d2b5bb9f1--- /dev/null+++ b/unity/Assets/Scripts/Map/ArmisticeLines.cs@@ -0,0 +1,269 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Linq;+using Statecraft.Game.Boot;+using Statecraft.Game.Map.Routes;+using UnityEngine;+using YamlDotNet.Core;+using YamlDotNet.Serialization;++namespace Statecraft.Game.Map+{+ /// <summary>The 1949 armistice lines as their true polylines (#237; option 3 of docs/visual-v1.md, "Region borders"):+ /// every feature of content/map/armistice_lines_1949.geojson drawn as a thin dark line draped on the ground, over the+ /// hex-snapped bands (<see cref="Armistice1949"/>), which stay as they are. A map mode, off unless asked for+ /// ("armisticelines" in the WebGL page URL, -armisticelines on desktop and in the editor): with the flag the map builds+ /// it, without it nothing is built. A release build draws only the features the owner has signed off+ /// (<see cref="ForBuild"/>) and ships only those (<see cref="ReleaseText"/>). Zoomed out past the gameplay zoom the lines+ /// widen with the distance (<see cref="WidthScale"/>). Each feature shows from its own shown_from date, as the bands do. Features traced+ /// from the low-resolution scan (source_quality: low_res_scan, the Jordan lines) are drawn dashed and a step lighter, so+ /// they read as low accuracy without a legend and without colour alone. Zones (the Demilitarized Zones, including the+ /// two Syrian parts too narrow to hold a hex centre) are drawn as their closed outlines. Reuses the route ribbons'+ /// draping (<see cref="RouteLayer.Geometry"/>) and the selected hex's unlit material (HexSelection.mat, copied per+ /// style). Display only: the sim never reads the file, and this changes no sim state and no other map layer.</summary>+ public static class ArmisticeLines+ {+ public const string FileName = "armistice_lines_1949.geojson", RootName = "ArmisticeLines", ToggleName = "armisticelines",+ Flag = "armisticelines";+ /// <summary>The line's width on the ground: about 4 px at the gameplay zoom (52 m a pixel), a third of a road's, so+ /// it reads as a drawn line, not as a band or a route.</summary>+ public const float WidthM = 200f;+ /// <summary>The low-accuracy lines' width: half as wide again, so the dashes hold their own between the hill+ /// villages' trees and houses, and the wider line hints at the wider error (about +-1-3 km).</summary>+ public const float LowAccuracyWidthM = 300f;+ /// <summary>The camera distance the widths above are set for: the opening and gameplay zoom (CameraRig.Distance;+ /// about 52 m a pixel at 1080 px). Farther out the lines widen with the distance (<see cref="WidthScale"/>), since a+ /// fixed ground width thins to about a pixel at the full-map zoom (owner review of #2012).</summary>+ public const float WidthsSetAtM = 90000f;+ /// <summary>The low-accuracy dashes: a DashM period, DashOn of it drawn (1 km dashes, 0.6 km gaps; about 19 and 12 px+ /// at the gameplay zoom).</summary>+ public const float DashM = 1600f, DashOn = 0.625f;+ /// <summary>sRGB. Firm: a near-black ink that stands out on the gold and olive ground and on both sides' bands.+ /// Low accuracy: a dark grey, a step lighter, so the dashes read as the weaker line (a mid grey was lost on the hills'+ /// ground in the captures).</summary>+ public static readonly Color FirmColour = new Color(0.10f, 0.09f, 0.08f), LowAccuracyColour = new Color(0.24f, 0.23f, 0.21f);++ public sealed class Feature+ {+ public string Id = ""; public DateTime ShownFrom; public bool LowAccuracy;+ /// <summary>The owner's sensitivity review is recorded (status: sensitivity-reviewed; docs/m3-release.md, "Map lines").</summary>+ public bool Reviewed;+ /// <summary>The lines in lon/lat: one per LineString, per MultiLineString member, or per polygon ring (closed).</summary>+ public List<List<(double lon, double lat)>> Parts = new List<List<(double lon, double lat)>>();+ }++ /// <summary>Whether this run draws the overlay (MapScene.Build asks). A seam: a test turns the mode on to build the map+ /// with it.</summary>+ internal static Func<bool> Wanted = Requested;++ public static bool Requested() =>+ Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);++ public static bool Requested(string? url, string[] args, bool webgl) =>+ webgl ? UrlFlags.Has(url, Flag) : args.Contains("-" + Flag);++ /// <summary>Parses the GeoJSON (JSON is YAML, so the YAML reader the content already uses reads it). Every malformed+ /// input throws InvalidDataException naming the file and the feature.</summary>+ public static List<Feature> Parse(string geojson)+ {+ Dictionary<object, object>? doc;+ try { doc = new DeserializerBuilder().Build().Deserialize<Dictionary<object, object>>(geojson); }+ catch (YamlException e) { throw new InvalidDataException($"{FileName}: line {e.Start.Line}: {e.InnerException?.Message ?? e.Message}", e); }+ if (doc == null || !doc.TryGetValue("features", out var fs) || !(fs is List<object> list) || list.Count == 0)+ throw new InvalidDataException($"{FileName}: no features");+ var features = new List<Feature>();+ foreach (var item in list)+ {+ var f = item as Dictionary<object, object> ?? throw new InvalidDataException($"{FileName}: a feature is not an object");+ var props = Map(f, "properties", "?");+ var id = Str(props, "id") ?? throw new InvalidDataException($"{FileName}: a feature has no id");+ if (features.Any(x => x.Id == id)) throw new InvalidDataException($"{FileName}: {id}: twice");+ if (!DateTime.TryParseExact(Str(props, "shown_from"), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var from))+ throw new InvalidDataException($"{FileName}: {id}: shown_from is not a yyyy-MM-dd date");+ var geometry = Map(f, "geometry", id);+ var type = Str(geometry, "type");+ var coords = geometry.TryGetValue("coordinates", out var c) ? c as List<object> : null;+ if (coords == null) throw new InvalidDataException($"{FileName}: {id}: no coordinates");+ var feature = new Feature { Id = id, ShownFrom = from, LowAccuracy = Str(props, "source_quality") == "low_res_scan",+ Reviewed = Str(props, "status") == "sensitivity-reviewed" };+ switch (type)+ {+ case "LineString": feature.Parts.Add(Line(coords, id)); break;+ case "MultiLineString": case "Polygon": foreach (var l in coords) feature.Parts.Add(Line(l, id)); break;+ case "MultiPolygon": foreach (var p in coords) foreach (var l in p as List<object> ?? new List<object>()) feature.Parts.Add(Line(l, id)); break;+ default: throw new InvalidDataException($"{FileName}: {id}: geometry '{type}' is not a line or a polygon");+ }+ if (feature.Parts.Count == 0) throw new InvalidDataException($"{FileName}: {id}: no coordinates");+ features.Add(feature);+ }+ return features;+ }++ /// <summary>The features a build draws: every one in the editor and development builds; in a release (shareable)+ /// build only those the owner has signed off, since the lines "need the same review before a shared build shows+ /// them" (docs/m3-release.md, "Map lines"; the five flagged on 23 October 2026 stay draft, #196).</summary>+ public static List<Feature> ForBuild(IEnumerable<Feature> features, bool devBuild) =>+ features.Where(f => devBuild || f.Reviewed).ToList();++ /// <summary>The file as a release build ships it (ContentManifest.Copy for a release player): only the features+ /// <see cref="ForBuild"/> draws in a release build, cut out of the text so the header and every kept feature stay as+ /// written. A release build must not ship the draft lines it does not draw (owner review of #2012).</summary>+ public static string ReleaseText(string geojson)+ {+ var signedOff = new HashSet<string>(ForBuild(Parse(geojson), devBuild: false).Select(f => f.Id));+ // The "features" array's items, split at its top-level commas (brackets and braces counted outside strings). The+ // header holds no "features" key or text (tools/armistice_digitise.py writes it), so the first one is the array's.+ int open = geojson.IndexOf('[', geojson.IndexOf("\"features\"", StringComparison.Ordinal)), from = open + 1, depth = 0, i = from;+ var kept = new List<string>();+ for (bool quoted = false; ; i++)+ {+ char c = geojson[i];+ if (quoted) { if (c == '\\') i++; else if (c == '"') quoted = false; }+ else if (c == '"') quoted = true;+ else if (depth == 0 && (c == ',' || c == ']'))+ {+ var item = geojson.Substring(from, i - from);+ if (signedOff.Contains(Parse("{\"features\": [" + item + "]}")[0].Id)) kept.Add(item);+ from = i + 1;+ if (c == ']') break;+ }+ else if (c == '{' || c == '[') depth++;+ else if (c == '}' || c == ']') depth--;+ }+ return geojson.Substring(0, open + 1) + string.Join(",", kept) + geojson.Substring(i);+ }++ /// <summary>How much wider than WidthM / LowAccuracyWidthM, and how much longer the dashes, a line is drawn seen from+ /// <paramref name="distanceM"/>: 1 up to <see cref="WidthsSetAtM"/>, then in proportion to the distance (so about the+ /// gameplay width on screen), in steps of a factor of the square root of 2 so each step's mesh is made once, up to+ /// the farthest zoom (CameraController.MaxDistance: about 2.8).</summary>+ public static float WidthScale(float distanceM)+ {+ float d = Mathf.Min(distanceM, CameraController.MaxDistance);+ return d <= WidthsSetAtM ? 1f : Mathf.Pow(2f, Mathf.Round(2f * Mathf.Log(d / WidthsSetAtM, 2f)) / 2f);+ }++ static Dictionary<object, object> Map(Dictionary<object, object> o, string key, string id) =>+ o.TryGetValue(key, out var v) && v is Dictionary<object, object> d ? d : throw new InvalidDataException($"{FileName}: {id}: no {key}");++ static string? Str(Dictionary<object, object> o, string key) => o.TryGetValue(key, out var v) ? v as string : null;++ static List<(double lon, double lat)> Line(object o, string id)+ {+ var points = o as List<object> ?? throw new InvalidDataException($"{FileName}: {id}: a line is not a list of points");+ var line = new List<(double lon, double lat)>(points.Count);+ foreach (var p in points)+ {+ if (!(p is List<object> xy) || xy.Count < 2+ || !double.TryParse(xy[0] as string, NumberStyles.Float, CultureInfo.InvariantCulture, out var lon)+ || !double.TryParse(xy[1] as string, NumberStyles.Float, CultureInfo.InvariantCulture, out var lat)+ || double.IsNaN(lon) || double.IsInfinity(lon) || double.IsNaN(lat) || double.IsInfinity(lat))+ throw new InvalidDataException($"{FileName}: {id}: a point is not [lon, lat]");+ line.Add((lon, lat));+ }+ if (line.Count < 2) throw new InvalidDataException($"{FileName}: {id}: a line needs two points");+ return line;+ }++ /// <summary>The drawn pieces of a dashed <paramref name="line"/> (world x, z): from its start, DashOn of every DashM+ /// period (times <paramref name="scale"/>, the <see cref="WidthScale"/> it is drawn at), each piece following the+ /// line's bends.</summary>+ public static List<List<Vector2>> Dashes(List<Vector2> line, float scale = 1f)+ {+ var dashes = new List<List<Vector2>>();+ List<Vector2>? dash = null;+ float s = 0f, period = DashM * scale, on = period * DashOn;+ for (int i = 1; i < line.Count; i++)+ {+ var a = line[i - 1]; var b = line[i]; float len = (b - a).magnitude;+ float t = 0f;+ while (t < len)+ {+ float phase = (s + t) % period;+ bool drawn = phase < on;+ float step = Mathf.Min(len - t, drawn ? on - phase : period - phase);+ if (drawn)+ {+ if (dash == null) { dash = new List<Vector2> { Vector2.Lerp(a, b, t / len) }; dashes.Add(dash); }+ dash.Add(Vector2.Lerp(a, b, (t + step) / len));+ }+ else dash = null;+ t += Mathf.Max(step, 1e-3f);+ }+ s += len;+ }+ dashes.RemoveAll(d => d.Count < 2);+ return dashes;+ }++ /// <summary>Builds the overlay under <paramref name="terrain"/> (a map rebuild destroys it): one child per feature,+ /// shown as at <paramref name="date"/>, each a ribbon mesh in a copy of <paramref name="lineMaterial"/> (the selected+ /// hex's unlit material) per style, at the gameplay width until the camera says otherwise+ /// (ArmisticeLine.ShowFor). Meshes and materials are owned by the root's MapRuntimeAssets, which also+ /// unregisters the "armisticelines" toggle. Returns the root.</summary>+ public static GameObject Build(Terrain terrain, GeoFrame frame, IReadOnlyList<Feature> features, Material lineMaterial, DateTime date)+ {+ if (terrain == null) throw new ArgumentNullException(nameof(terrain));+ if (lineMaterial == null) throw new ArgumentNullException(nameof(lineMaterial));+ var root = new GameObject(RootName);+ root.transform.SetParent(terrain.transform, false);+ root.transform.position = Vector3.zero; // children are in world space+ var assets = root.AddComponent<MapRuntimeAssets>();+ var lines = new GameObject("Lines");+ lines.transform.SetParent(root.transform, false);+ Material Copy(string name, Color c)+ {+ var m = assets.Own(new Material(lineMaterial) { name = name });+ m.SetColor("_BaseColor", c);+ return m;+ }+ var firm = Copy("ArmisticeLine", FirmColour); var low = Copy("ArmisticeLineLowAccuracy", LowAccuracyColour);+ var data = terrain.terrainData; var origin = terrain.transform.position;+ foreach (var f in features)+ {+ var world = f.Parts.Select(part => part.Select(p => { var v = frame.ToWorld(p.lon, p.lat, 0); return new Vector2(v.x, v.z); }).ToList()).ToList();+ // The line's mesh at a width scale: widths and dashes scaled together, so the dashed lines keep their look.+ Mesh MeshAt(float scale)+ {+ var pieces = new List<(string id, List<Vector2> line, float width)>();+ foreach (var line in world)+ if (f.LowAccuracy) pieces.AddRange(Dashes(line, scale).Select(d => (f.Id, d, LowAccuracyWidthM * scale)));+ else pieces.Add((f.Id, line, WidthM * scale));+ var mesh = assets.Own(RouteLayer.Geometry(pieces, data, origin).ToMesh($"{RootName} {f.Id}"));+ mesh.UploadMeshData(true);+ return mesh;+ }+ var go = new GameObject(f.Id);+ go.transform.SetParent(lines.transform, false);+ go.AddComponent<MeshFilter>();+ var r = go.AddComponent<MeshRenderer>();+ r.sharedMaterial = f.LowAccuracy ? low : firm;+ r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;+ r.receiveShadows = false;+ var mark = go.AddComponent<ArmisticeLine>();+ mark.Id = f.Id; mark.ShownFrom = f.ShownFrom; mark.LowAccuracy = f.LowAccuracy;+ mark.MeshAt = MeshAt; mark.DrawAt(1f);+ }+ ShowAt(root, date);+ assets.OnTeardown(VisualToggles.Register(ToggleName, on => { if (lines != null) lines.SetActive(on); }));+ return root;+ }++ /// <summary>Shows each line of the map's overlay from its date (the game calls it on every state change, beside+ /// RouteLayer.ShowAt). A map without the overlay is left alone.</summary>+ public static void ShowAt(MapScene map, DateTime date)+ {+ if (map == null || map.Terrain == null) return;+ var root = map.Terrain.transform.Find(RootName);+ if (root != null) ShowAt(root.gameObject, date);+ }++ public static void ShowAt(GameObject root, DateTime date)+ {+ foreach (var l in root.GetComponentsInChildren<ArmisticeLine>(true)) l.gameObject.SetActive(date >= l.ShownFrom);+ }+ }+}diff --git a/unity/Assets/Scripts/Map/ArmisticeLines.cs.meta b/unity/Assets/Scripts/Map/ArmisticeLines.cs.metanew file mode 100644index 000000000..2d25e0e3b--- /dev/null+++ b/unity/Assets/Scripts/Map/ArmisticeLines.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ae4eae8c4b6f3fc279f8cf201b8d8436\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex f2fcf311c..3c9da8767 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -588,6 +588,18 @@ 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 1949 armistice lines as their true polylines (#237), only in the map mode asked for with the+ // "armisticelines" flag; a missing or malformed file means no overlay and a warning. Display only.+ if (ArmisticeLines.Wanted() && inputs.ArmisticeLinesGeojson == "") Debug.LogWarning($"ARMISTICE LINES: {ArmisticeLines.FileName} is missing; no overlay");+ else if (ArmisticeLines.Wanted())+ {+ try+ {+ var lines = ArmisticeLines.ForBuild(ArmisticeLines.Parse(inputs.ArmisticeLinesGeojson), Application.isEditor || Debug.isDebugBuild);+ ArmisticeLines.Build(Terrain, Frame, lines, selectionMaterial, RouteDate ?? Routes.RouteLayer.DefaultDate);+ }+ catch (InvalidDataException e) { Debug.LogWarning($"ARMISTICE LINES: {e.Message}; no overlay"); }+ }if (!cam.TryGetComponent(out CameraRig rig)) rig = cam.gameObject.AddComponent<CameraRig>();rig.LookAt = Frame.ToWorld(34.95, 31.95, 0); rig.Init(); // central Israel: Tel Aviv–Jerusalem corridordiff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex a03d17b8c..81433fc63 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -834,6 +834,8 @@ namespace Statecraft.Game.UI// Dated routes (the Burma Road from June 1948); in the GDD loop the corridors by their built segments (#792).Statecraft.Game.Map.Routes.RouteLayer.ShowAt(map, Bridge.State.Date,Bridge.Content.IsGdd ? Statecraft.Game.Map.Routes.RouteLayer.BuiltSegments(Bridge.Content, Bridge.State) : null);+ // The true armistice lines (#237, the "armisticelines" map mode), each from its own date; nothing without the mode.+ ArmisticeLines.ShowAt(map, Bridge.State.Date);// Tal Heuberger's whole-town models on their towns far off (#663, "Whole model far, buildings near"), streamed after the first frame; the ma'abara from its date.// The camps and housing built as city projects bring theirs too, as the placement layer draws them (#1275).Statecraft.Game.Map.Collection.TownLandmarks.ShowAt(map, Bridge.State.Date,diff --git a/unity/Assets/Tests/EditMode/ArmisticeLinesTests.cs b/unity/Assets/Tests/EditMode/ArmisticeLinesTests.csnew file mode 100644index 000000000..09ecd3974--- /dev/null+++ b/unity/Assets/Tests/EditMode/ArmisticeLinesTests.cs@@ -0,0 +1,291 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using System.Text.RegularExpressions;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Boot;+using Statecraft.Game.Map;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using Object = UnityEngine.Object;++/// <summary>#237: the 1949 armistice lines drawn as their true polylines (content/map/armistice_lines_1949.geojson), a map+/// mode beside the hex-snapped bands. Owner ruling of 30 October 2026: display only, no sim change, the Jordan lines styled+/// as low accuracy, the two Syrian DMZ parts that hold no hex centre included.</summary>+public class ArmisticeLinesTests+{+ static string GeoText => File.ReadAllText(Path.Combine(Paths.Content, "map", ArmisticeLines.FileName));+ /// <summary>The feature ids, read off the file with a pattern rather than the parser under test.</summary>+ static List<string> FileIds => Regex.Matches(GeoText, "\"properties\":\\s*\\{\\s*\"id\":\\s*\"([a-z0-9_]+)\"").Select(m => m.Groups[1].Value).ToList();+ static readonly DateTime After = new DateTime(1951, 1, 1);++ static MapScene? map;+ static MapScene Map => map != null ? map : map = RouteTests.BuildMap();++ [OneTimeTearDown]+ public void DiscardScene()+ {+ map = null;+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); VisualToggles.Clear();+ }++ static Material Selection => AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexSelection.mat");+ static GameObject Overlay(DateTime date) =>+ ArmisticeLines.Build(Map.Terrain, Map.Frame, ArmisticeLines.Parse(GeoText), Selection, date);++ static Dictionary<string, ArmisticeLine> Drawn(GameObject root) =>+ root.GetComponentsInChildren<ArmisticeLine>(true).ToDictionary(l => l.Id);++ [Test]+ public void EveryFeatureOfTheTrueLinesIsDrawnAsAPolyline()+ {+ var ids = FileIds;+ Assert.AreEqual(16, ids.Count, "the committed file's features");+ CollectionAssert.IsSubsetOf(new[] { "syria_dmz_north", "syria_dmz_south" }, ids, "the two DMZ parts with no hex centre");+ var root = Overlay(After);+ try+ {+ var drawn = Drawn(root);+ var features = ArmisticeLines.Parse(GeoText);+ CollectionAssert.AreEquivalent(ids, drawn.Keys, "one drawn polyline per feature");+ foreach (var (id, line) in drawn)+ {+ Assert.IsTrue(line.gameObject.activeInHierarchy, $"{id} is shown in 1951");+ var mesh = line.GetComponent<MeshFilter>().sharedMesh;+ Assert.Greater(mesh.vertexCount, 0, $"{id} has geometry");+ // On the ground where the line is: the mesh's footprint holds the feature's own points.+ var b = mesh.bounds;+ var feature = features.First(f => f.Id == id);+ foreach (var part in feature.Parts)+ {+ var p = Map.Frame.ToWorld(part[0].lon, part[0].lat, 0); float w = ArmisticeLines.LowAccuracyWidthM;+ Assert.IsTrue(p.x >= b.min.x - w && p.x <= b.max.x + w && p.z >= b.min.z - w && p.z <= b.max.z + w, $"{id} is drawn where its points are");+ }+ }+ // The two narrow Syrian DMZ parts are closed outlines, so they read as areas, not as lines.+ foreach (var id in new[] { "syria_dmz_north", "syria_dmz_south" })+ {+ var part = features.First(f => f.Id == id).Parts.Single();+ Assert.AreEqual(part[0], part[part.Count - 1], $"{id}'s ring is closed");+ }+ }+ finally { Object.DestroyImmediate(root); }+ }++ [Test]+ public void TheJordanLinesAreDrawnInTheLowAccuracyStyleAndNoOtherIs()+ {+ var features = ArmisticeLines.Parse(GeoText);+ var low = features.Where(f => f.LowAccuracy).Select(f => f.Id).ToList();+ CollectionAssert.AreEquivalent(FileIds.Where(id => id.StartsWith("jordan_")).ToList(), low,+ "exactly the features traced from the low-resolution scan (source_quality: low_res_scan)");+ Assert.AreEqual(7, low.Count, "the seven Jordan features");+ var root = Overlay(After);+ try+ {+ var drawn = Drawn(root);+ var lowColour = drawn[low[0]].GetComponent<MeshRenderer>().sharedMaterial.GetColor("_BaseColor");+ var firmColour = drawn["lebanon_adl"].GetComponent<MeshRenderer>().sharedMaterial.GetColor("_BaseColor");+ Assert.AreNotEqual(firmColour, lowColour, "the low-accuracy style has its own colour");+ foreach (var (id, line) in drawn)+ {+ Assert.AreEqual(low.Contains(id), line.LowAccuracy, id);+ Assert.AreEqual(low.Contains(id) ? lowColour : firmColour, line.GetComponent<MeshRenderer>().sharedMaterial.GetColor("_BaseColor"), id);+ }+ }+ finally { Object.DestroyImmediate(root); }+ // ...and is dashed, a cue that is not colour: the dashes cover DashOn of the line, in pieces of the dash's length.+ var straight = new List<Vector2> { Vector2.zero, new Vector2(10000f, 0f) };+ var dashes = ArmisticeLines.Dashes(straight);+ Assert.Greater(dashes.Count, 4);+ float covered = dashes.Sum(d => (d[d.Count - 1] - d[0]).magnitude);+ Assert.AreEqual(10000f * ArmisticeLines.DashOn, covered, ArmisticeLines.DashM * ArmisticeLines.DashOn);+ Assert.IsTrue(dashes.All(d => (d[d.Count - 1] - d[0]).magnitude <= ArmisticeLines.DashM * ArmisticeLines.DashOn + 1f));+ // A dash runs on round a bend: on an L with an 800 m first leg the first dash keeps the corner and its full length.+ var bent = ArmisticeLines.Dashes(new List<Vector2> { Vector2.zero, new Vector2(800f, 0f), new Vector2(800f, 2000f) });+ CollectionAssert.Contains(bent[0], new Vector2(800f, 0f), "the dash over the corner keeps the corner");+ float first = 0f; for (int i = 1; i < bent[0].Count; i++) first += (bent[0][i] - bent[0][i - 1]).magnitude;+ Assert.AreEqual(ArmisticeLines.DashM * ArmisticeLines.DashOn, first, 1f, "a full dash, measured along the bend");+ }++ [Test]+ public void EachLineIsShownFromItsOwnDate()+ {+ var root = Overlay(new DateTime(1949, 3, 1));+ try+ {+ var drawn = Drawn(root);+ // From the Egypt agreement (24 Feb 1949) only its 1949 features; the 1950 modus vivendi lines and the later fronts wait.+ CollectionAssert.AreEquivalent(new[] { "egypt_adl_gaza", "egypt_el_auja_dmz" },+ drawn.Values.Where(l => l.gameObject.activeSelf).Select(l => l.Id).ToArray());+ ArmisticeLines.ShowAt(root, new DateTime(1949, 7, 20));+ Assert.IsTrue(drawn["syria_dmz_north"].gameObject.activeSelf && drawn["syria_dmz_south"].gameObject.activeSelf);+ Assert.IsFalse(drawn["egypt_mv1950_demarcation"].gameObject.activeSelf);+ ArmisticeLines.ShowAt(root, After);+ Assert.IsTrue(drawn.Values.All(l => l.gameObject.activeSelf));+ }+ finally { Object.DestroyImmediate(root); }+ }++ /// <summary>Display only: off unless asked for (the map builds no overlay without the flag), nothing in the sim reads the+ /// file (the content hash), and drawing it leaves the hex-snapped layer and its baked data as they were.</summary>+ [Test]+ public void TheOverlayIsDisplayOnlyAndOffUnlessAsked()+ {+ Assert.IsNull(Map.Terrain.transform.Find(ArmisticeLines.RootName), "no overlay without the flag");+ Assert.IsFalse(ArmisticeLines.Requested("https://x/index.html", new string[0], true));+ Assert.IsTrue(ArmisticeLines.Requested("https://x/index.html?armisticelines", new string[0], true));+ Assert.IsTrue(ArmisticeLines.Requested(null, new[] { "game", "-armisticelines" }, false));+ Assert.IsFalse(ArmisticeLines.Requested(null, new[] { "game" }, false));++ // The hex bands are drawn from the RegionHexes texture (MapBorders); drawing the overlay leaves every texel as it was+ // (a layer is drawn first, so the texels are not all empty).+ BorderProof.Show(Map);+ var regionTex = (Texture2D)Shader.GetGlobalTexture("_ScRegionTex");+ var texels = regionTex.GetPixels32();+ var root = Overlay(After);+ try+ {+ Assert.AreSame(regionTex, Shader.GetGlobalTexture("_ScRegionTex"));+ CollectionAssert.AreEqual(texels, regionTex.GetPixels32(), "the hex bands are untouched");+ CollectionAssert.Contains(VisualToggles.Names, ArmisticeLines.ToggleName);+ VisualToggles.Set(ArmisticeLines.ToggleName, false);+ Assert.IsFalse(root.transform.GetChild(0).gameObject.activeInHierarchy, "the toggle hides it");+ VisualToggles.Set(ArmisticeLines.ToggleName, true);+ }+ finally { Object.DestroyImmediate(root); MapBorders.Use(null); }++ var copy = Path.Combine(Path.GetTempPath(), "statecraft-armlines-" + Guid.NewGuid().ToString("N"));+ try+ {+ ContentManifest.Copy(Paths.Content, copy);+ File.WriteAllText(Path.Combine(copy, "map", ArmisticeLines.FileName), "{}");+ Assert.AreEqual(ContentLoader.Load(Paths.Content).Hash, ContentLoader.Load(copy).Hash, "the sim never reads the true lines");+ }+ finally { if (Directory.Exists(copy)) Directory.Delete(copy, true); }+ }++ /// <summary>A release build draws only the features the owner has signed off (docs/m3-release.md, "Map lines"); both+ /// Syrian DMZ parts are among them. The editor and development builds draw every feature.</summary>+ [Test]+ public void AReleaseBuildDrawsOnlyTheReviewedFeatures()+ {+ var all = ArmisticeLines.Parse(GeoText);+ Assert.AreEqual(16, ArmisticeLines.ForBuild(all, devBuild: true).Count);+ var release = ArmisticeLines.ForBuild(all, devBuild: false).Select(f => f.Id).ToList();+ int reviewed = Regex.Matches(GeoText, "\"status\":\\s*\"sensitivity-reviewed\"").Count;+ Assert.AreEqual(11, reviewed, "the committed file: 11 of 16 signed off (#1444)");+ Assert.AreEqual(reviewed, release.Count);+ CollectionAssert.IsSubsetOf(new[] { "syria_dmz_north", "syria_dmz_south" }, release);+ CollectionAssert.IsNotSubsetOf(new[] { "syria_adl" }, release, "a draft feature waits for the owner's review");+ }++ /// <summary>Owner review of #2012: a release build's data holds no draft feature, in the copied file and in the bundle+ /// the web boot fetches (ContentSync copies with release for a player without the Development option); a development+ /// copy ships the file as it is.</summary>+ [Test]+ public void AReleaseBuildShipsNoDraftFeature()+ {+ var drafts = ArmisticeLines.Parse(GeoText).Where(f => !f.Reviewed).Select(f => f.Id).ToList();+ Assert.AreEqual(5, drafts.Count, "the five flagged on 23 October 2026");+ var target = Path.Combine(Path.GetTempPath(), "statecraft-armlines-release-" + Guid.NewGuid().ToString("N"));+ try+ {+ ContentManifest.Copy(Paths.Content, target, release: true);+ ContentManifest.Verify(Paths.Content, target, release: true);+ var (_, texts) = ContentManifest.ParseBundle(File.ReadAllText(Path.Combine(target, ContentManifest.BundleFileName)));+ foreach (var shipped in new[] { File.ReadAllText(Path.Combine(target, "map", ArmisticeLines.FileName)), texts["map/" + ArmisticeLines.FileName] })+ {+ foreach (var id in drafts) StringAssert.DoesNotContain($"\"id\":\"{id}\"", shipped, $"{id} is not shipped");+ var kept = ArmisticeLines.Parse(shipped);+ Assert.AreEqual(11, kept.Count, "the signed-off features are all shipped");+ Assert.IsTrue(kept.All(f => f.Reviewed));+ }+ ContentManifest.Copy(Paths.Content, target);+ Assert.AreEqual(GeoText, File.ReadAllText(Path.Combine(target, "map", ArmisticeLines.FileName)), "a development copy is the file as it is");+ }+ finally { if (Directory.Exists(target)) Directory.Delete(target, true); }+ }++ /// <summary>Owner review of #2012: a fixed ground width thins to about a pixel at the full-map zoom, so farther out than+ /// the gameplay zoom the lines are drawn wider, the low-accuracy ones still wider (and still dashed); closer in they+ /// keep their ground width.</summary>+ [Test]+ public void FarOutTheLinesAreDrawnWiderAndCloseInAsBefore()+ {+ Assert.AreEqual(1f, ArmisticeLines.WidthScale(30000f), "close in: the ground width");+ Assert.AreEqual(1f, ArmisticeLines.WidthScale(ArmisticeLines.WidthsSetAtM), "the gameplay zoom: the ground width");+ float far = ArmisticeLines.WidthScale(CameraController.MaxDistance);+ Assert.That(far, Is.InRange(2.5f, 3.2f), "the full-map zoom: about as much wider as the camera is farther (250 / 90 km)");+ Assert.AreEqual(far, ArmisticeLines.WidthScale(float.PositiveInfinity));+ // The dashes lengthen with the width, so the dashed lines keep their look.+ var straight = new List<Vector2> { Vector2.zero, new Vector2(20000f, 0f) };+ var firstDash = ArmisticeLines.Dashes(straight, far)[0];+ Assert.AreEqual(ArmisticeLines.DashM * ArmisticeLines.DashOn * far, firstDash[firstDash.Count - 1].x, 1f);++ var root = Overlay(After);+ try+ {+ var drawn = Drawn(root);+ foreach (var id in new[] { "egypt_el_auja_dmz", "jordan_adl_d_arava" })+ {+ var line = drawn[id];+ var filter = line.GetComponent<MeshFilter>();+ line.ShowFor(30000f);+ var close = filter.sharedMesh; var closeSize = close.bounds.size;+ Assert.AreEqual(1f, line.Scale, id);+ line.ShowFor(CameraController.MaxDistance);+ Assert.AreEqual(far, line.Scale, id);+ var farSize = filter.sharedMesh.bounds.size;+ // A wider ribbon: its footprint grows by about the extra width (at least half of it on the wider side).+ float extra = ((line.LowAccuracy ? ArmisticeLines.LowAccuracyWidthM : ArmisticeLines.WidthM) * (far - 1f)) / 2f;+ Assert.Greater(Mathf.Max(farSize.x - closeSize.x, farSize.z - closeSize.z), extra, $"{id} is wider far out");+ line.ShowFor(30000f);+ Assert.AreSame(close, filter.sharedMesh, $"{id}: back in, the same ground-width mesh");+ }+ }+ finally { Object.DestroyImmediate(root); }+ }++ /// <summary>The wiring (review of #2012, optional): with the mode asked for, building the map builds the overlay under the+ /// terrain; the other cases call ArmisticeLines.Build directly.</summary>+ [Test]+ public void TheMapBuildsTheOverlayWhenTheModeIsAsked()+ {+ var was = ArmisticeLines.Wanted;+ ArmisticeLines.Wanted = () => true;+ try+ {+ var built = RouteTests.BuildMap();+ var root = built.Terrain.transform.Find(ArmisticeLines.RootName);+ Assert.IsNotNull(root, "Terrain/ArmisticeLines");+ Assert.AreEqual(16, root.GetComponentsInChildren<ArmisticeLine>(true).Length, "the editor draws every feature");+ }+ finally { ArmisticeLines.Wanted = was; map = null; }+ }++ [Test]+ public void TheWebGLBuildShipsTheTrueLinesAndTheMapReadsThem()+ {+ CollectionAssert.Contains(ContentManifest.Collect(Paths.Content), "map/" + ArmisticeLines.FileName);+ Assert.AreEqual(GeoText, GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap).ArmisticeLinesGeojson);+ }++ [TestCase("{\"type\": \"FeatureCollection\", \"features\": []}", "no features")]+ [TestCase("{\"features\": [{\"properties\": {\"id\": \"a\", \"shown_from\": \"1949-01-01\"}, \"geometry\": {\"type\": \"Point\", \"coordinates\": [34.5, 31.5]}}]}", "a: geometry 'Point'")]+ [TestCase("{\"features\": [{\"properties\": {\"id\": \"a\"}, \"geometry\": {\"type\": \"LineString\", \"coordinates\": [[34.5, 31.5], [34.6, 31.6]]}}]}", "a: shown_from")]+ [TestCase("{\"features\": [{\"properties\": {\"id\": \"a\", \"shown_from\": \"1949-01-01\"}, \"geometry\": {\"type\": \"LineString\", \"coordinates\": [[34.5, 31.5]]}}]}", "a: a line needs two points")]+ [TestCase("{\"features\": [{\"properties\": {\"id\": \"a\", \"shown_from\": \"1949-01-01\"}, \"geometry\": {\"type\": \"LineString\", \"coordinates\": [[34.5, 31.5], [34.6]]}}]}", "a: a point is not [lon, lat]")]+ [TestCase("not: [json", "armistice_lines_1949.geojson")]+ public void BadFilesNameTheFileAndTheProblem(string text, string expected)+ {+ var e = Assert.Throws<InvalidDataException>(() => ArmisticeLines.Parse(text));+ StringAssert.StartsWith(ArmisticeLines.FileName + ":", e.Message);+ StringAssert.Contains(expected, e.Message);+ }+}diff --git a/unity/Assets/Tests/EditMode/ArmisticeLinesTests.cs.meta b/unity/Assets/Tests/EditMode/ArmisticeLinesTests.cs.metanew file mode 100644index 000000000..cda807e29--- /dev/null+++ b/unity/Assets/Tests/EditMode/ArmisticeLinesTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 68daa1cf7e2afef4abe1b89aa26d32c8\ No newline at end of file