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.

Map: in the GDD loop a corridor's route draws only its built segments (Refs #792, slice 1) (#1312)

Berif321ea2c8346
diff --git a/changelog.d/792.md b/changelog.d/792.md
new file mode 100644
index 000000000..cc8bfae2c
--- /dev/null
+++ b/changelog.d/792.md
@@ -0,0 +1,4 @@
+- GDD Phase 4 PR 8, slice 1: in the GDD loop the map draws a corridor's route by its built segments (refs #792). The
+ Burma Road, the Haifa–Tel Aviv rail link and the Tel Aviv–Netanya road appear one segment at a time as the halutzim
+ build them, at any date; outside the GDD loop they keep their dates. The route index lists each corridor segment's
+ index range (route ribbon bake version 4, runtime route file version 4).
diff --git a/content/map/route_paths_1948.tsv b/content/map/route_paths_1948.tsv
index 8e80ffb27..1c5a33af7 100644
--- a/content/map/route_paths_1948.tsv
+++ b/content/map/route_paths_1948.tsv
@@ -2,7 +2,7 @@
# Do not edit: edit the YAMLs (tools/routes_1948.py writes the first)
# and rerun the tool. The runtime form the map reads at boot (map-only, outside the content hash).
#route id kind status from to length_km on_symbol max_gap_m point_count points
-meta version 3
+meta version 4
meta yaml_check 1351806899
meta routes 21
route jaffa_jerusalem_railway rail draft 1920-10-05 79.4 1.0 65 113 34.76117 32.05894;34.76409 32.05996;34.76949 32.0605;34.77448 32.0603;34.77742 32.05924;34.78086 32.05571;34.78638 32.04568;34.79255 32.03932;34.81436 32.02349;34.83771 32.00775;34.84893 31.99572;34.8713 31.97509;34.88636 31.95755;34.88673 31.95516;34.88565 31.95368;34.87321 31.94354;34.87112 31.94135;34.86992 31.93914;34.8708 31.93573;34.87298 31.93191;34.87781 31.9283;34.88083 31.9234;34.88626 31.91762;34.88954 31.90869;34.88909 31.90734;34.88636 31.90467;34.87678 31.89781;34.87057 31.88903;34.87168 31.87982;34.87147 31.87482;34.86603 31.86169;34.86775 31.85101;34.87009 31.84463;34.87058 31.84073;34.86979 31.82851;34.86722 31.81997;34.86949 31.81555;34.87025 31.8114;34.87181 31.80857;34.87557 31.80583;34.88764 31.79956;34.89363 31.79506;34.90035 31.78828;34.92253 31.76821;34.92847 31.76507;34.93797 31.75898;34.94668 31.759;34.95347 31.75656;34.95884 31.756;34.97276 31.75634;34.98381 31.75799;35.00674 31.75687;35.01071 31.75768;35.01722 31.76211;35.03203 31.76215;35.03544 31.7646;35.03876 31.7659;35.0477 31.76358;35.05046 31.75846;35.05232 31.75727;35.0651 31.76556;35.0675 31.76593;35.06883 31.76475;35.06934 31.76031;35.06539 31.75626;35.06483 31.75461;35.06613 31.75284;35.06934 31.7512;35.0737 31.75011;35.07778 31.75009;35.08386 31.75723;35.08588 31.75852;35.08703 31.7586;35.08797 31.75729;35.08624 31.75413;35.08606 31.7517;35.08691 31.75108;35.09144 31.7511;35.09289 31.75045;35.09369 31.74963;35.09485 31.74558;35.0958 31.7445;35.10339 31.74279;35.11714 31.73811;35.11861 31.7385;35.12205 31.74277;35.12356 31.74337;35.12516 31.74331;35.12622 31.74156;35.1248 31.73751;35.12586 31.73527;35.12727 31.73454;35.12892 31.73445;35.13344 31.73692;35.13546 31.73692;35.13697 31.73577;35.13836 31.73204;35.13999 31.7312;35.14144 31.73175;35.15582 31.74346;35.16043 31.74566;35.16454 31.74553;35.1731 31.74401;35.17851 31.74412;35.18192 31.74515;35.1869 31.74832;35.19691 31.75147;35.19855 31.75147;35.20436 31.74975;35.20594 31.74999;35.21073 31.75343;35.21583 31.75941;35.22466 31.76678
@@ -26,5 +26,8 @@ route gaza_beersheba_road road draft 1946 45.7 0.96 358 55 34.46076 31.50912;34
route beersheba_auja_road road draft 1946 69.9 0.97 261 77 34.78538 31.24664;34.78695 31.24386;34.79402 31.23727;34.79753 31.23201;34.80098 31.22072;34.80203 31.21544;34.80401 31.21001;34.80492 31.20399;34.80684 31.19738;34.80706 31.18043;34.80472 31.164;34.80613 31.15516;34.80491 31.14671;34.80542 31.13519;34.80651 31.1299;34.80798 31.1266;34.81171 31.12141;34.82035 31.11128;34.82177 31.108;34.82207 31.10204;34.82303 31.10092;34.82794 31.09776;34.82993 31.09167;34.83409 31.08549;34.83908 31.07546;34.83842 31.06632;34.83379 31.06149;34.83102 31.0565;34.80519 31.0366;34.79032 31.02098;34.78129 31.01459;34.77774 31.01282;34.77578 31.01246;34.76346 31.01561;34.76158 31.01531;34.7609 31.01406;34.75921 31.00408;34.76199 30.99334;34.76134 30.99179;34.75216 30.98452;34.72421 30.971;34.71105 30.96099;34.70396 30.9572;34.69683 30.95518;34.6775 30.95208;34.67385 30.9485;34.66057 30.94707;34.65502 30.9457;34.65323 30.94433;34.64789 30.93636;34.64092 30.93199;34.6349 30.92653;34.63194 30.92465;34.62888 30.92364;34.62487 30.9232;34.61728 30.92787;34.60679 30.93019;34.60518 30.92916;34.60133 30.92297;34.59443 30.91981;34.58566 30.91813;34.58336 30.91617;34.57899 30.91098;34.57525 30.90814;34.5551 30.90038;34.55032 30.8995;34.54487 30.90086;34.53995 30.90142;34.52619 30.90204;34.52124 30.90158;34.50057 30.89494;34.4856 30.8939;34.48196 30.89325;34.44598 30.88287;34.43721 30.88089;34.43465 30.87916;34.43364 30.8777
route yarkon_rail_link rail draft 1949-09-20 6.1 0.97 65 11 34.88133 32.09675;34.87998 32.09246;34.87867 32.09156;34.87627 32.09107;34.86514 32.09223;34.83516 32.09323;34.83234 32.09435;34.82869 32.09776;34.82921 32.09875;34.82887 32.09903;34.83121 32.10155
route tlv_netanya_road road draft 1950-07-28 27.7 0.0 27694 5 34.78 32.0958;34.8343 32.17;34.8244 32.2006;34.8357 32.2681;34.8567 32.3286
+segments burma_road 34.93444 31.82833;34.95417 31.81278;34.98361 31.80611;35.03472 31.79444;35.07389 31.79806
+segments yarkon_rail_link 34.8813 32.0968;34.831 32.1029
+segments tlv_netanya_road 34.78 32.0958;34.8343 32.17;34.8244 32.2006;34.8357 32.2681;34.8567 32.3286
service jaffa_jerusalem_railway 1950-03-02 34.87556 31.94583 35.22471 31.76685
-meta body_check -49274032
+meta body_check 1329839361
diff --git a/docs/routes.md b/docs/routes.md
index 6e6568473..57a33ce71 100644
--- a/docs/routes.md
+++ b/docs/routes.md
@@ -303,7 +303,11 @@ the YAML (about 125 ms at `--cpu 4`), as the localities do since #291.
- The YAML still ships. When the runtime file is missing, of another version, made from another YAML, cut short (even
inside a number) or edited by hand, the map reads the YAML with a warning (`...; reading the YAML`): the same routes,
only slower.
-- Rerun `uv run tools/route_paths_bake.py` after `tools/routes_1948.py` rewrites the YAML. `test_route_paths_bake.py`
+- A `segments` row per route a corridor follows (`content/corridors.yaml`, #792): the route's first waypoint, then the
+ waypoint each segment ends at, from `routes_1948.yaml` (the map never reads that file). The ribbon bake cuts the
+ route there (Route index, below). Inside `body_check`.
+- Rerun `uv run tools/route_paths_bake.py` after `tools/routes_1948.py` rewrites the YAML, and after a change to a
+ corridor's segments or waypoints (then re-bake the ribbons too). `test_route_paths_bake.py`
fails a stale file and pins a fingerprint of the C# readers; Unity's `RoutePathsRuntimeTests` compares every route
and point with the YAML's.
@@ -317,14 +321,30 @@ does (#320, docs/visual-v1.md).
- When any of them differs from what the map loaded, the bake is refused with a warning (`ROUTES ...: deriving the route
ribbons at load`) and the ribbons are derived as before: the same meshes, only slower.
- **Route index** (for the GDD Phase 4 corridors, #384). Each mesh lists its routes, each with its first vertex, vertex
- count, first index and index count (`RouteSpan`), so a later change can show one route by its construction state.
- Nothing reads it yet; the vertex layout is unchanged.
+ count, first index and index count (`RouteSpan`). Since version 4 (#792), a route a corridor follows also lists where
+ each of its segments starts in the index range, and the range's end (`RouteSpan.Segments`): the first segment starts
+ at the ribbon's start and the last ends at its end, and between them the cut is the cross-section nearest the point of
+ the line nearest the segment's end waypoint (the runtime file's `segments` row), searched in order along the line as
+ `tools/corridor_hexes.py` splits the hexes. The vertex layout is unchanged. The bake's header does not hash the segment ends: CI
+ without Unity checks only their count and alignment, and a moved waypoint or segment end is caught by
+ `RouteTests.TheBakedRibbonsMatchTheRoutes` (a fresh derivation, byte for byte). A map that reads the YAML (no or a
+ stale runtime file, with its warning) has no segment ends, so it derives the ribbons uncut and the corridors draw by
+ date.
+- **Corridors in the GDD loop** (spec §2.6, "Routes"; #792). `RouteLayer.Build` gives each segment of a corridor's route
+ a ribbon of its own (`Corridors/<route> <n>`, outside the dated groups), and marks the route's dated ribbon
+ (`RouteSegment`). In the GDD loop `GameRoot` passes `RouteLayer.BuiltSegments` (the sim's `State.Corridors`) to
+ `ShowAt`: the dated ribbon is hidden and only the built segments are drawn, at any date. Outside the GDD loop the
+ segments are hidden and the route keeps its dates. Every other route keeps its dates in both. Each corridor's route is
+ alone in its mesh (`test_route_ribbon_bake.py` checks it), so hiding its dated ribbon hides no other route. Segments
+ being built are not drawn yet (Q-UI-1's dashed outline is a later slice of #792). Tests:
+ `RouteLayerCorridorTests.OnlyBuiltSegmentsDraw`, `TheLegacyLoopDrawsByDate`.
- **Re-bake** whenever the heightmap, `heightmap.json`, the route file, a constant in the header or the ribbon rule
(`RouteLayer.Geometry`; bump `RouteRibbonFile.Version` with it) changes:
`Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod
Statecraft.Game.EditorTools.RouteRibbonBake.Bake`, under `tools/machine_lock.py` as any Unity run.
- **Checks.** `tools/tests/test_route_ribbon_bake.py` (CI, no Unity) fails on a stale header, reading the constants from
- the C# source, and checks the route index. `RouteTests.TheBakedRibbonsMatchTheRoutes` compares the bake with a fresh
+ the C# source, and checks the route index, its segment cuts and that they are the corridors' segments.
+ `RouteTests.TheBakedRibbonsMatchTheRoutes` compares the bake with a fresh
derivation byte for byte, and with the map's own terrain vertex for vertex; `AStaleRibbonBakeIsDerivedAtLoad` checks
the fallback. A change to `RouteLayer.Geometry` without a version bump is caught only by the Unity test.
- **Boot** (`tools/headed.py boot --runs 3 --cpu 4`, phase `routes built`, three rounds interleaved with main `bc67247`
diff --git a/tools/route_paths_bake.py b/tools/route_paths_bake.py
index 179bb06ea..ed7890d1a 100644
--- a/tools/route_paths_bake.py
+++ b/tools/route_paths_bake.py
@@ -16,6 +16,8 @@ with a warning, when either does not match. Rows, tab-separated:
meta routes <number of route rows>
route id kind status from to length_km on_symbol max_gap_m point_count points
...
+ segments route_id points (one per route a corridor of corridors.yaml follows, GDD Phase 4, #792)
+ ...
service route_id from start end (one per route with a `service` in routes_1948.yaml, issue #668)
...
meta body_check <signed int32> (the last row)
@@ -24,8 +26,13 @@ A service row is a railway's train service: the date regular service resumed (`f
"lon lat" (start, end), read from routes_1948.yaml (the sourced, hand-written file the map never reads), so the train's
date and stretch come from the content. A service changes neither route_paths_1948.yaml nor the ribbon bake.
+A segments row is where a corridor's segments meet on its route (content/corridors.yaml): the route's first waypoint, then
+the waypoint each segment ends at (`to`), as "lon lat" pairs joined by ';', read from routes_1948.yaml. The ribbon bake
+cuts the route's ribbon there, so in the GDD loop the map draws only the built segments (RouteLayer, #792). A change to
+these rows changes the ribbon bake: re-bake it (docs/routes.md).
+
`to` is empty when the route has no end; `points` is "lon lat" pairs joined by ';', each number as Python's shortest
-round-trip form of the YAML's value. `body_check` is FNV-1a over the UTF-8 bytes of every route and service row, each with its
+round-trip form of the YAML's value. `body_check` is FNV-1a over the UTF-8 bytes of every route, segments and service row, each with its
'\n', in order. The reader requires it as the last row and recomputes it, so a file cut anywhere (even inside a
number, review of #547) or edited by hand is refused; the counts give the clearer message for a lost row or point. Lines starting with '#' are comments. No field may hold a tab or a line break.
@@ -44,9 +51,10 @@ import review_record # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "content" / "map" / "route_paths_1948.yaml"
-ROUTES = ROOT / "content" / "map" / "routes_1948.yaml" # the services (issue #668)
+ROUTES = ROOT / "content" / "map" / "routes_1948.yaml" # the services (issue #668) and the waypoints (#792)
+CORRIDORS = ROOT / "content" / "corridors.yaml" # where each corridor's segments end (#792)
RUNTIME = ROOT / "content" / "map" / "route_paths_1948.tsv"
-VERSION = 3 # RoutePaths.RuntimeVersion (2: the body_check row, review of #547; 3: the service rows, #668)
+VERSION = 4 # RoutePaths.RuntimeVersion (2: the body_check row, review of #547; 3: the service rows, #668; 4: segments, #792)
COLUMNS = ["route", "id", "kind", "status", "from", "to", "length_km", "on_symbol", "max_gap_m", "point_count", "points"]
@@ -88,9 +96,9 @@ def running_span(service: dict) -> tuple[dict, dict] | None:
return service["stretches"][first]["start"], service["stretches"][last]["end"]
-def bake(data: bytes, routes: bytes) -> str:
- """The runtime file for the YAML file's bytes and routes_1948.yaml's (the services): deterministic, so a fresh bake
- equals the committed file."""
+def bake(data: bytes, routes: bytes, corridors: bytes) -> str:
+ """The runtime file for the YAML file's bytes, routes_1948.yaml's (the services, the waypoints) and corridors.yaml's
+ (the segments): deterministic, so a fresh bake equals the committed file."""
doc = yaml12.load(data.decode("utf-8"))
sourced = yaml12.load(routes.decode("utf-8"))["routes"]
out = [
@@ -110,6 +118,17 @@ def bake(data: bytes, routes: bytes) -> str:
_number(r["on_symbol"], where), _number(r["max_gap_m"], where), str(len(r["points"]))]
rows.append("\t".join(_field(v, where) for v in row) + "\t" + points)
traced = {r["id"] for r in doc["routes"]}
+ by_id = {r["id"]: r for r in sourced}
+ for c in yaml12.load(corridors.decode("utf-8"))["corridors"]:
+ where = f"corridor '{c.get('id')}'"
+ if c["route"] not in traced or c["route"] not in by_id:
+ raise ValueError(f"{CORRIDORS.name}: {where}: route {c['route']!r} is not in {SOURCE.name} and {ROUTES.name}")
+ via = {w["name"]: w for w in by_id[c["route"]]["via"]}
+ ends = [by_id[c["route"]]["via"][0]["name"]] + [s["to"] for s in c["segments"]]
+ if any(e not in via for e in ends):
+ raise ValueError(f"{CORRIDORS.name}: {where}: a segment ends at a name that is not a waypoint of {c['route']}")
+ points = ";".join(f"{_number(via[e]['lon'], where)} {_number(via[e]['lat'], where)}" for e in ends)
+ rows.append("\t".join(_field(v, where) for v in ["segments", c["route"]]) + "\t" + points)
for r in sourced:
s = r.get("service")
if s is None:
@@ -131,7 +150,7 @@ def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--check", action="store_true", help="fail when the committed runtime file is stale")
args = ap.parse_args()
- fresh = bake(SOURCE.read_bytes(), ROUTES.read_bytes())
+ fresh = bake(SOURCE.read_bytes(), ROUTES.read_bytes(), CORRIDORS.read_bytes())
if args.check:
current = RUNTIME.read_text(encoding="utf-8") if RUNTIME.exists() else ""
if current != fresh:
diff --git a/tools/tests/test_route_paths_bake.py b/tools/tests/test_route_paths_bake.py
index aff0f878a..898b7eb8d 100644
--- a/tools/tests/test_route_paths_bake.py
+++ b/tools/tests/test_route_paths_bake.py
@@ -25,7 +25,7 @@ REBAKE = "run uv run tools/route_paths_bake.py"
# The fingerprint of the readers (code_fingerprint). Re-pin only after RoutePathsRuntimeTests passes in Unity, with
# RoutePaths.RuntimeVersion and route_paths_bake.VERSION bumped together if the runtime layout changed.
-PINNED_CODE = "ea5cd1dccf91f9cc5f5824104546f95e2281925c6b7e6bb6f7bfcbd414e2bf8d"
+PINNED_CODE = "dd12cec870c16d107705d3ff0046f5a71b7ce35d19e3bd8e6d5df45ad084fdc6"
def member(text: str, signature: str) -> str:
@@ -61,7 +61,7 @@ def code_fingerprint() -> str:
def test_the_runtime_file_is_the_bake_of_the_yaml():
- assert bake.RUNTIME.read_text(encoding="utf-8") == bake.bake(bake.SOURCE.read_bytes(), bake.ROUTES.read_bytes()), f"stale: {REBAKE}"
+ assert bake.RUNTIME.read_text(encoding="utf-8") == bake.bake(bake.SOURCE.read_bytes(), bake.ROUTES.read_bytes(), bake.CORRIDORS.read_bytes()), f"stale: {REBAKE}"
def test_the_bake_and_the_reader_share_a_version():
@@ -87,7 +87,7 @@ def test_the_file_ends_with_its_body_check():
lines = bake.RUNTIME.read_text(encoding="utf-8").rstrip("\n").split("\n")
kind, name, value = lines[-1].split("\t")
assert (kind, name) == ("meta", "body_check")
- rows = [line for line in lines if line.startswith(("route\t", "service\t"))]
+ rows = [line for line in lines if line.startswith(("route\t", "segments\t", "service\t"))]
assert int(value) == bake.body_check(rows)
cut = rows[-1][:-1] # the last number a digit short
assert bake.body_check(rows[:-1] + [cut]) != int(value)
@@ -100,13 +100,13 @@ def test_the_runtime_file_carries_the_train_service():
lines = bake.RUNTIME.read_text(encoding="utf-8").rstrip("\n").split("\n")
services = [line.split("\t") for line in lines if line.startswith("service\t")]
assert services == [["service", "jaffa_jerusalem_railway", "1950-03-02", "34.87556 31.94583", "35.22471 31.76685"]]
- rows = [line for line in lines if line.startswith(("route\t", "service\t"))]
+ rows = [line for line in lines if line.startswith(("route\t", "segments\t", "service\t"))]
assert rows[-1].startswith("service\t"), "the service rows follow the route rows"
assert int(lines[-1].split("\t")[2]) == bake.body_check(rows), "the body check covers the service rows too"
def _service_row(routes_text: str) -> list[str] | None:
- tsv = bake.bake(bake.SOURCE.read_bytes(), routes_text.encode("utf-8"))
+ tsv = bake.bake(bake.SOURCE.read_bytes(), routes_text.encode("utf-8"), bake.CORRIDORS.read_bytes())
rows = [line.split("\t") for line in tsv.split("\n") if line.startswith("service\t")]
return rows[0] if rows else None
diff --git a/tools/tests/test_route_ribbon_bake.py b/tools/tests/test_route_ribbon_bake.py
index 69d36d821..44a0cdcec 100644
--- a/tools/tests/test_route_ribbon_bake.py
+++ b/tools/tests/test_route_ribbon_bake.py
@@ -5,7 +5,7 @@ HeightsCheck, FNV-1a checks of heightmap.json and route_paths_1948.yaml, the ter
the bake's version) and then derives the ribbons at boot, which is slower. CI runs no Unity, so this checks the same
header here, with the constants read from the C# source: a change to any of them without a re-bake
(RouteRibbonBake.Bake) fails CI, as the water's bake does. It also walks the meshes and their route index (route id, vertex
-and index range) for the GDD Phase 4 corridors (#384). Unity's RouteTests.TheBakedRibbonsMatchTheRoutes compares the
+and index range, and a corridor route's segment cuts, #792) for the GDD Phase 4 corridors (#384). Unity's RouteTests.TheBakedRibbonsMatchTheRoutes compares the
whole meshes.
The header holds the ribbons' data and constants, not the code that drapes them. A fingerprint of that code (RouteLayer.Plan,
@@ -113,7 +113,7 @@ def test_the_route_ribbon_bake_is_for_the_shipped_map_and_routes():
def test_every_route_is_in_the_index_once_and_its_ranges_tile_its_mesh():
r = Reader(bake_bytes())
head = read_header(r)
- ids = []
+ ids, segmented = [], {}
for _ in range(head["meshes"]):
name = r.text()
nv, ni, nr = r.take("<3i")
@@ -121,8 +121,16 @@ def test_every_route_is_in_the_index_once_and_its_ranges_tile_its_mesh():
for _ in range(nr):
rid = r.text()
first_v, count_v, first_i, count_i = r.take("<4i")
+ cuts = list(r.take(f"<{r.int()}i"))
assert (first_v, first_i) == (vertex, index), f"{name}: {rid} does not follow the route before it"
assert count_i % 3 == 0, f"{name}: {rid}"
+ if cuts:
+ # A corridor's route (#792): its segments tile its range, in order, each cut between two cross-sections.
+ assert (cuts[0], cuts[-1]) == (first_i, first_i + count_i), f"{name}: {rid}'s segments do not tile it"
+ assert cuts == sorted(cuts), f"{name}: {rid}'s segments are out of order"
+ per = 6 * (int(csharp_const("Routes/RouteLayer.cs", "Across")) - 1)
+ assert all((c - first_i) % per == 0 for c in cuts), f"{name}: {rid} is cut inside a cross-section"
+ segmented[rid] = (len(cuts) - 1, nr)
vertex, index = first_v + count_v, first_i + count_i
ids.append(rid)
assert (vertex, index) == (nv, ni), f"{name}: the routes do not cover the mesh"
@@ -132,6 +140,10 @@ def test_every_route_is_in_the_index_once_and_its_ranges_tile_its_mesh():
assert r.at == len(r.data), "longer than its meshes: " + REBAKE
shipped = [route["id"] for route in yaml12.load(ROUTES.read_text(encoding="utf-8"))["routes"]]
assert sorted(ids) == sorted(shipped), "stale (route ids): " + REBAKE
+ # Each corridor's route is cut into its corridor's segments, and is alone in its mesh, so RouteLayer can hide its
+ # dated ribbon in the GDD loop without hiding another route.
+ corridors = yaml12.load((ROOT / "content/corridors.yaml").read_text(encoding="utf-8"))["corridors"]
+ assert segmented == {c["route"]: (len(c["segments"]), 1) for c in corridors}, "stale (corridor segments): " + REBAKE
def test_the_check_is_fnv1a():
@@ -142,7 +154,7 @@ def test_the_check_is_fnv1a():
# The fingerprint of the ribbons' C# code (code_fingerprint), and the RouteRibbonFile.Version it was pinned at. Re-pin both
# together, only after re-baking (RouteRibbonBake.Bake) with Version bumped.
-PINNED_VERSION, PINNED_CODE = 3, "a60ad9441761c59d2dab361e68be89fb710cc59a5edc31e0c051a6ff14367328"
+PINNED_VERSION, PINNED_CODE = 4, "55d8f29f2b769273eba9ea01c328fee536db68b57b5155dd2853345808ceb056"
def code_fingerprint() -> str:
@@ -161,6 +173,8 @@ def code_fingerprint() -> str:
method(layer, "public sealed class RibbonPlan"),
method(layer, "public static List<RibbonPlan> Plan("),
method(layer, "public static RibbonGeometry Derive("),
+ method(layer, "public static int[] SegmentStarts("),
+ method(layer, "static float Project("),
method(layer, "public static List<Vector2> World("),
method(layer, "public static List<Vector2> Drawn("),
method(layer, "public static List<Vector2> TrimEndsInside("),
@@ -207,6 +221,7 @@ def ribbon_vertices_by_route(look: str) -> dict[str, np.ndarray]:
for _ in range(nr):
rid = r.text()
first_v, count_v, _, _ = r.take("<4i")
+ r.take(f"<{r.int()}i") # the segment cuts
spans.append((rid, first_v, count_v))
xyz = np.array(r.take(f"<{3 * nv}f"), dtype=np.float64).reshape(-1, 3) if nv else np.zeros((0, 3))
r.take(f"<{5 * nv}f")
diff --git a/unity/Assets/Resources/Routes/RouteRibbons.bytes b/unity/Assets/Resources/Routes/RouteRibbons.bytes
index b51023d23..f6a64176d 100644
Binary files a/unity/Assets/Resources/Routes/RouteRibbons.bytes and b/unity/Assets/Resources/Routes/RouteRibbons.bytes differ
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 8c84aa435..22b9c774e 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -54,6 +54,9 @@ namespace Statecraft.Game.Map
/// <summary>The game date the routes were last shown at (RouteLayer.ShowAt), so a rebuild draws them as at that date;
/// null before the game has set one (the routes then show as at the game's start).</summary>
public DateTime? RouteDate { get; set; }
+ /// <summary>In the GDD loop, which segments of each corridor route are built (RouteLayer.ShowAt, #792), so a rebuild
+ /// draws them as the game left them; null outside the GDD loop (the routes then show by date).</summary>
+ public IReadOnlyDictionary<string, IReadOnlyList<bool>> RouteSegmentsBuilt { get; set; }
/// <summary>Who held which hex on a date (content/map/control_hexes_1948_49.yaml with the map editor's control
/// overrides), as Build read it, or null without the file: GameRoot draws the borders from it, and the road vehicles
/// (issue #725) stand only on ground Israel held. Display only.</summary>
diff --git a/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs b/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs
index 95b8f702a..5dd04f267 100644
--- a/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs
+++ b/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs
@@ -95,6 +95,7 @@ namespace Statecraft.Game.Map.Routes
readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();
readonly List<Renderer> renderers = new List<Renderer>();
DateTime date;
+ IReadOnlyDictionary<string, IReadOnlyList<bool>>? built;
string? drawnKey;
bool lastClose;
@@ -109,19 +110,21 @@ namespace Statecraft.Game.Map.Routes
layer.map = map; layer.terrain = map.Terrain.terrainData; layer.terrainOrigin = map.Terrain.transform.position;
foreach (var route in routes)
if (Plans.Any(p => p.Route == route.Id)) layer.lines[route.Id] = RouteLayer.Drawn(map.Frame, route);
- layer.ShowAt(date);
+ layer.ShowAt(date, map.RouteSegmentsBuilt);
return layer;
}
/// <summary>Shows the vehicles as at <paramref name="at"/>. The game calls it on every state change, so it lays them
- /// out again only when what it would draw changes: the plans in force, the control period, or a model arriving.</summary>
- public void ShowAt(DateTime at)
+ /// out again only when what it would draw changes: the plans in force, the control period, or a model arriving.
+ /// In the GDD loop (<paramref name="segmentsBuilt"/> given, as RouteLayer.ShowAt has it, #792) a plan on a corridor's
+ /// route is in force only once every segment of that route is built, so no vehicle drives on road not drawn yet.</summary>
+ public void ShowAt(DateTime at, IReadOnlyDictionary<string, IReadOnlyList<bool>>? segmentsBuilt = null)
{
- date = at;
+ date = at; built = segmentsBuilt;
var stream = Stream;
if (stream != null)
foreach (var plan in Plans)
- if (plan.Covers(at) && asked.Add(plan.Model)) { var id = plan.Model; stream(id, CollectionDetail.Near, p => OnModel(id, p)); }
+ if (InForce(plan) && asked.Add(plan.Model)) { var id = plan.Model; stream(id, CollectionDetail.Near, p => OnModel(id, p)); }
Rebuild();
}
@@ -134,13 +137,18 @@ namespace Statecraft.Game.Map.Routes
Rebuild();
}
+ /// <summary>The plan's dates cover the current date and, in the GDD loop, its route is not a corridor's or is built
+ /// end to end.</summary>
+ bool InForce(Plan plan) =>
+ plan.Covers(date) && (built == null || !built.TryGetValue(plan.Route, out var b) || b.All(s => s));
+
/// <summary>What the layer would draw on the current date, as a key: the control period, the plans in force and the
/// models that have arrived.</summary>
string Key()
{
var control = map != null ? map.Control : null;
var period = control?.PeriodOn(date)?.Id ?? "none";
- return period + "|" + string.Concat(Plans.Select(p => p.Covers(date) ? "1" : "0")) + "|"
+ return period + "|" + string.Concat(Plans.Select(p => InForce(p) ? "1" : "0")) + "|"
+ string.Concat(Plans.Select(p => prefabs.TryGetValue(p.Model, out var g) && g != null ? "1" : "0"));
}
@@ -163,7 +171,7 @@ namespace Statecraft.Game.Map.Routes
for (int planIndex = 0; planIndex < Plans.Count; planIndex++)
{
var plan = Plans[planIndex];
- if (!plan.Covers(date) || !lines.TryGetValue(plan.Route, out var line)) continue;
+ if (!InForce(plan) || !lines.TryGetValue(plan.Route, out var line)) continue;
prefabs.TryGetValue(plan.Model, out var prefab);
for (int n = 0; n < plan.Count; n++)
{
diff --git a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs b/unity/Assets/Scripts/Map/Routes/RouteLayer.cs
index e91295b50..09ac89b66 100644
--- a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs
+++ b/unity/Assets/Scripts/Map/Routes/RouteLayer.cs
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using Statecraft.Sim;
using UnityEngine;
namespace Statecraft.Game.Map.Routes
@@ -68,21 +69,41 @@ namespace Statecraft.Game.Map.Routes
/// <summary>Shows the route groups whose window covers <paramref name="date"/> and hides the rest (the game calls it
/// on every state change; cheap: a few SetActive calls), and remembers the date on the map, so a rebuild of the map
- /// (MapScene.Build) draws the routes as at the game's date at once. A map without routes is left alone.</summary>
- public static void ShowAt(MapScene map, DateTime date)
+ /// (MapScene.Build) draws the routes as at the game's date at once. A map without routes is left alone.
+ /// In the GDD loop (<paramref name="built"/> given: route id to each segment built, <see cref="BuiltSegments"/>), a
+ /// route a corridor follows is drawn by its built segments instead, whatever the date (spec §2.6, "Routes"; #792):
+ /// its dated ribbon is hidden and each built segment's own ribbon shown. Every other route keeps its dates.</summary>
+ public static void ShowAt(MapScene map, DateTime date, IReadOnlyDictionary<string, IReadOnlyList<bool>>? built = null)
{
if (map == null) return;
map.RouteDate = date; // a later rebuild of this map starts at the game's date (re-review nit 2)
+ map.RouteSegmentsBuilt = built; // and with the corridors as built
if (map.Terrain == null) return;
var service = map.Terrain.transform.Find($"{RootName}/{ServiceTrain.Name}");
if (service != null) service.GetComponent<ServiceTrain>().ShowAt(date); // from the service date on (issue #668)
var vehicles = map.Terrain.transform.Find($"{RootName}/{RoadVehicles.Name}");
- if (vehicles != null) vehicles.GetComponent<RoadVehicles>().ShowAt(date);
+ if (vehicles != null) vehicles.GetComponent<RoadVehicles>().ShowAt(date, built);
var ribbons = map.Terrain.transform.Find($"{RootName}/{RibbonsName}");
if (ribbons == null) return;
foreach (var g in ribbons.GetComponentsInChildren<RouteGroup>(true)) g.gameObject.SetActive(g.Window.Covers(date));
+ ShowSegments(ribbons, built);
}
+ /// <summary>Outside the GDD loop (<paramref name="built"/> null), each corridor route's dated ribbon and none of its
+ /// segments; in it, only the built segments.</summary>
+ static void ShowSegments(Transform ribbons, IReadOnlyDictionary<string, IReadOnlyList<bool>>? built)
+ {
+ foreach (var s in ribbons.GetComponentsInChildren<RouteSegment>(true))
+ s.gameObject.SetActive(built == null ? s.Index < 0
+ : s.Index >= 0 && built.TryGetValue(s.Route, out var b) && s.Index < b.Count && b[s.Index]);
+ }
+
+ /// <summary>For <see cref="ShowAt"/> in the GDD loop: each corridor's route (corridors.yaml route) and, per segment,
+ /// whether the sim has built it (State.Corridors, R-COR-002). The sim decides what is built; this only reads it.</summary>
+ public static Dictionary<string, IReadOnlyList<bool>> BuiltSegments(Content content, GameState state) =>
+ content.Corridors.ToDictionary(d => d.Route, d => (IReadOnlyList<bool>)Enumerable.Range(0, d.Segments.Count)
+ .Select(i => state.Corridors.TryGetValue(d.Id, out var w) && i < w.Segments.Count && w.Segments[i]?.BuiltOn != null).ToArray());
+
/// <summary>Clearance (m) beyond a ribbon's drawn half-width that kit buildings and trees keep from it, so a lot's or
/// crown's edge never touches the soft edge of the road or the ballast.</summary>
public const float CorridorMarginM = 100f;
@@ -149,8 +170,63 @@ namespace Statecraft.Game.Map.Routes
/// <summary>A plan's ribbon, derived from the terrain (what the bake stores). A change to it or to what it calls
/// (World, Geometry and their helpers) needs a re-bake and a bump of RouteRibbonFile.Version (see Plan).</summary>
- public static RibbonGeometry Derive(RibbonPlan plan, GeoFrame frame, TerrainData data, Vector3 origin) =>
- Geometry(plan.Routes.Select(r => (r.Id, Drawn(frame, r), WidthOf(r.Kind))), data, origin, plan.RailGrade);
+ public static RibbonGeometry Derive(RibbonPlan plan, GeoFrame frame, TerrainData data, Vector3 origin)
+ {
+ var g = Geometry(plan.Routes.Select(r => (r.Id, Drawn(frame, r), WidthOf(r.Kind))), data, origin, plan.RailGrade);
+ for (int k = 0; k < plan.Routes.Count; k++)
+ if (plan.Routes[k].SegmentEnds is { } ends)
+ {
+ var s = g.Routes[k];
+ var at = ends.ConvertAll(p => { var v = frame.ToWorld(p[0], p[1], 0); return new Vector2(v.x, v.z); });
+ g.Routes[k] = new RouteSpan(s.Id, s.FirstVertex, s.VertexCount, s.FirstIndex, s.IndexCount,
+ SegmentStarts(Drawn(frame, plan.Routes[k]), at, s.FirstIndex, s.IndexCount));
+ }
+ return g;
+ }
+
+ /// <summary>The route index's segment cuts (RouteSpan.Segments, #792) for a ribbon drawn along <paramref name="line"/>
+ /// (Geometry's cross-sections, <see cref="Resample"/>), starting at index <paramref name="firstIndex"/>: the first
+ /// segment starts at the ribbon's start and the last ends at its end, so the segments tile the route; between, each
+ /// segment ends at the cross-section nearest the point of the line nearest its end waypoint (<paramref name="ends"/>,
+ /// the route's first waypoint and each segment's end, world x, z), searched from the cut before it on, as
+ /// tools/corridor_hexes.py splits the hexes.</summary>
+ public static int[] SegmentStarts(List<Vector2> line, List<Vector2> ends, int firstIndex, int indexCount)
+ {
+ var cuts = new int[ends.Count];
+ cuts[0] = firstIndex; cuts[ends.Count - 1] = firstIndex + indexCount;
+ if (line.Count < 2) { for (int i = 1; i < ends.Count - 1; i++) cuts[i] = firstIndex; return cuts; }
+ var (_, along) = Resample(line, StepM);
+ const int perSection = (Across - 1) * 6; // Geometry's triangles between two cross-sections
+ float at = Project(line, ends[0], 0f);
+ int section = 0;
+ for (int i = 1; i < ends.Count - 1; i++)
+ {
+ at = Project(line, ends[i], at);
+ int best = section;
+ for (int k = section; k < along.Count; k++)
+ if (Mathf.Abs(along[k] - at) < Mathf.Abs(along[best] - at)) best = k;
+ section = best;
+ cuts[i] = firstIndex + section * perSection;
+ }
+ return cuts;
+ }
+
+ /// <summary>The distance along <paramref name="line"/> of its point nearest <paramref name="p"/>, among the points at
+ /// or past <paramref name="start"/>, so a route that passes near one waypoint twice is cut in order.</summary>
+ static float Project(List<Vector2> line, Vector2 p, float start)
+ {
+ float best = start, bestD = float.PositiveInfinity, s = 0f;
+ for (int i = 1; i < line.Count; i++)
+ {
+ var a = line[i - 1]; var d = line[i] - a; float len = d.magnitude;
+ if (len == 0f) continue;
+ float t = Mathf.Clamp01(Vector2.Dot(p - a, d) / (len * len)), here = s + t * len;
+ float dist = (a + d * t - p).magnitude;
+ if (here >= start && dist < bestD) { best = here; bestD = dist; }
+ s += len;
+ }
+ return best;
+ }
/// <summary>Builds the routes under <paramref name="terrain"/> (so a map rebuild destroys them): one group per display
/// window (its rail and road ribbons), shown as at <paramref name="date"/>, and, when <paramref name="train"/> is not
@@ -182,7 +258,7 @@ namespace Statecraft.Game.Map.Routes
// One group per display window, in the order the windows open (deterministic names and draw order).
var plans = Plan(routes);
var geometry = Geometries(plans, frame, data, origin, baked);
- GameObject? holder = null;
+ GameObject? holder = null, corridors = null;
for (int i = 0; i < plans.Count; i++)
{
var plan = plans[i];
@@ -202,7 +278,32 @@ namespace Statecraft.Game.Map.Routes
r.sharedMaterial = plan.RailGrade ? rail : road;
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
r.receiveShadows = true;
+ // A route a corridor follows (#792; each is alone in its ribbon, tools/tests/test_route_ribbon_bake.py): its
+ // dated ribbon is marked, and each segment gets a ribbon of its own, outside the dated groups, which the GDD
+ // loop shows once the segment is built (ShowAt).
+ for (int k = 0; k < plan.Routes.Count; k++)
+ {
+ var span = geometry[i].Routes[k];
+ if (span.Segments.Length < 2) continue;
+ go.AddComponent<RouteSegment>().Route = span.Id;
+ if (corridors == null) { corridors = new GameObject("Corridors"); corridors.transform.SetParent(ribbons.transform, false); }
+ for (int s = 0; s + 1 < span.Segments.Length; s++)
+ {
+ var part = assets.Own(geometry[i].SegmentMesh(k, s, $"{plan.MeshName} {span.Id} {s + 1}"));
+ part.UploadMeshData(true);
+ var seg = new GameObject($"{span.Id} {s + 1}");
+ seg.transform.SetParent(corridors.transform, false);
+ seg.AddComponent<MeshFilter>().sharedMesh = part;
+ var sr = seg.AddComponent<MeshRenderer>();
+ sr.sharedMaterial = r.sharedMaterial;
+ sr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
+ sr.receiveShadows = true;
+ var mark = seg.AddComponent<RouteSegment>();
+ mark.Route = span.Id; mark.Index = s;
+ }
+ }
}
+ ShowSegments(ribbons.transform, map != null ? map.RouteSegmentsBuilt : null);
assets.OnTeardown(VisualToggles.Register(RoutesToggle, on => { if (ribbons != null) ribbons.SetActive(on); }));
if (map != null) RoadVehicles.Create(root.transform, map, routes, date);
diff --git a/unity/Assets/Scripts/Map/Routes/RoutePaths.cs b/unity/Assets/Scripts/Map/Routes/RoutePaths.cs
index 26223d929..b1a07eb99 100644
--- a/unity/Assets/Scripts/Map/Routes/RoutePaths.cs
+++ b/unity/Assets/Scripts/Map/Routes/RoutePaths.cs
@@ -31,6 +31,11 @@ namespace Statecraft.Game.Map.Routes
/// <summary>The railway's train service in normal play (issue #668), or null: from the runtime file's service row
/// (tools/route_paths_bake.py reads it from routes_1948.yaml); route_paths_1948.yaml never carries one.</summary>
[YamlIgnore] public RouteService? Service { get; set; }
+ /// <summary>Where a corridor's segments meet on this route (GDD Phase 4, #792), or null: the route's first waypoint,
+ /// then the waypoint each segment ends at, as [lon, lat] pairs, from the runtime file's segments row
+ /// (tools/route_paths_bake.py reads them from corridors.yaml and routes_1948.yaml); the YAML never carries them. The
+ /// ribbons are cut there (RouteLayer.Geometry), so the GDD loop draws only the built segments.</summary>
+ [YamlIgnore] public List<List<double>>? SegmentEnds { get; set; }
}
/// <summary>A railway's train service (issue #668; maintainer decision on #35, 16 October 2026): the date regular
@@ -66,7 +71,7 @@ namespace Statecraft.Game.Map.Routes
public const string RuntimeFileName = "route_paths_1948.tsv";
/// <summary>Bump it, with tools/route_paths_bake.py's VERSION, when the runtime file's layout or its reading
/// (ParseRuntime, RuntimeRows) changes; tools/tests/test_route_paths_bake.py pins a fingerprint of that code.</summary>
- public const int RuntimeVersion = 3; // 2: the body_check row (review of #547); 3: the service rows (#668)
+ public const int RuntimeVersion = 4; // 2: the body_check row (review of #547); 3: the service rows (#668); 4: segments (#792)
public const string Rail = "rail", Road = "road", Track = "track";
static readonly HashSet<string> Kinds = new HashSet<string> { Rail, Road, Track };
static readonly Regex IdRule = new Regex(@"^[a-z][a-z0-9_]*\z");
@@ -184,6 +189,22 @@ namespace Statecraft.Game.Map.Routes
var (startLon, startLat) = End(c[3], "start"); var (endLon, endLat) = End(c[4], "end");
route.Service = new RouteService { From = c[2], StartLon = startLon, StartLat = startLat, EndLon = endLon, EndLat = endLat };
}
+ else if (c[0] == "segments")
+ {
+ if (c.Length != 3) throw new InvalidDataException($"{file}:{line}: a segments row has {c.Length} fields, not 3");
+ rows.Add(text);
+ var route = routes.Find(r => r.Id == c[1]) ?? throw new InvalidDataException($"{file}:{line}: segments for '{c[1]}', which no route row before it has");
+ if (route.SegmentEnds != null) throw new InvalidDataException($"{file}:{line}: a second segments row for '{c[1]}'");
+ var ends = new List<List<double>>();
+ foreach (var pair in c[2].Split(';'))
+ {
+ int sp = pair.IndexOf(' ');
+ if (sp < 0 || pair.IndexOf(' ', sp + 1) >= 0) throw new InvalidDataException($"{file}:{line}: segment end '{pair}' is not 'lon lat'");
+ ends.Add(new List<double> { Num(pair.Substring(0, sp), "lon", line), Num(pair.Substring(sp + 1), "lat", line) });
+ }
+ if (ends.Count < 2) throw new InvalidDataException($"{file}:{line}: segments for '{c[1]}' need a start and at least one end");
+ route.SegmentEnds = ends;
+ }
else if (c[0] == "route")
{
if (c.Length != 11) throw new InvalidDataException($"{file}:{line}: a route row has {c.Length} fields, not 11");
diff --git a/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs b/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs
index 8d591f8b0..9247bac65 100644
--- a/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs
+++ b/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs
@@ -9,18 +9,24 @@ using UnityEngine;
namespace Statecraft.Game.Map.Routes
{
/// <summary>One route's share of a ribbon mesh: its first vertex and vertex count, and its first index and index count
- /// (whole triangles). A route whose line is shorter than two points has none.</summary>
+ /// (whole triangles). A route whose line is shorter than two points has none. A route a corridor follows (GDD Phase 4,
+ /// #792) also has its segments' index ranges: <see cref="Segments"/> holds the index each segment starts at, then the
+ /// route's end (FirstIndex + IndexCount), so segment k is [Segments[k], Segments[k + 1]); empty for any other route.</summary>
public readonly struct RouteSpan : IEquatable<RouteSpan>
{
public readonly string Id;
public readonly int FirstVertex, VertexCount, FirstIndex, IndexCount;
- public RouteSpan(string id, int firstVertex, int vertexCount, int firstIndex, int indexCount)
- { Id = id; FirstVertex = firstVertex; VertexCount = vertexCount; FirstIndex = firstIndex; IndexCount = indexCount; }
+ public readonly int[] Segments;
+ public RouteSpan(string id, int firstVertex, int vertexCount, int firstIndex, int indexCount, int[]? segments = null)
+ {
+ Id = id; FirstVertex = firstVertex; VertexCount = vertexCount; FirstIndex = firstIndex; IndexCount = indexCount;
+ Segments = segments ?? Array.Empty<int>();
+ }
public bool Equals(RouteSpan o) => Id == o.Id && FirstVertex == o.FirstVertex && VertexCount == o.VertexCount
- && FirstIndex == o.FirstIndex && IndexCount == o.IndexCount;
+ && FirstIndex == o.FirstIndex && IndexCount == o.IndexCount && (Segments ?? Array.Empty<int>()).AsSpan().SequenceEqual(o.Segments ?? Array.Empty<int>());
public override bool Equals(object? o) => o is RouteSpan s && Equals(s);
public override int GetHashCode() => HashCode.Combine(Id, FirstVertex, VertexCount, FirstIndex, IndexCount);
- public override string ToString() => $"{Id} v{FirstVertex}+{VertexCount} i{FirstIndex}+{IndexCount}";
+ public override string ToString() => $"{Id} v{FirstVertex}+{VertexCount} i{FirstIndex}+{IndexCount}" + (Segments is { Length: > 0 } s ? $" segments {string.Join(",", s)}" : "");
}
/// <summary>A ribbon mesh's arrays (RouteLayer.Geometry), and which routes it holds where (<see cref="Routes"/>), so a
@@ -43,6 +49,23 @@ namespace Statecraft.Game.Map.Routes
mesh.RecalculateBounds();
return mesh;
}
+
+ /// <summary>Segment <paramref name="segment"/> of route <paramref name="route"/> (<see cref="RouteSpan.Segments"/>) as
+ /// a mesh of its own: its triangles and only the vertices they use, so the GDD loop can show each built segment by
+ /// itself (RouteLayer.ShowAt).</summary>
+ public Mesh SegmentMesh(int route, int segment, string name)
+ {
+ var s = Routes[route].Segments;
+ int from = s[segment], count = s[segment + 1] - from;
+ if (count == 0) return new Mesh { name = name }; // two cuts on one cross-section: nothing to draw
+ int low = int.MaxValue, high = -1;
+ for (int i = from; i < from + count; i++) { low = Math.Min(low, Indices[i]); high = Math.Max(high, Indices[i]); }
+ var indices = new int[count];
+ for (int i = 0; i < count; i++) indices[i] = Indices[from + i] - low;
+ int n = high - low + 1;
+ return new RibbonGeometry(Vertices.AsSpan(low, n).ToArray(), Normals.AsSpan(low, n).ToArray(), Uvs.AsSpan(low, n).ToArray(),
+ indices, Array.Empty<RouteSpan>()).ToMesh(name);
+ }
}
/// <summary>The route ribbons, baked (Editor RouteRibbonBake, issue #321), so a player places them instead of deriving
@@ -52,7 +75,7 @@ namespace Statecraft.Game.Map.Routes
/// and route_paths_1948.yaml (<see cref="Check"/>), the terrain's size and origin (6 floats), the geometry constants
/// (<see cref="Floats"/>, then <see cref="Ints"/>), the mesh count;</item>
/// <item>each mesh, in RouteLayer.Plan's order: its name, its vertex, index and route counts, each route's id and
- /// <see cref="RouteSpan"/>, then the vertices, normals and uvs (floats) and the indices (int32).</item>
+ /// <see cref="RouteSpan"/> (its four ints, then the count of its segment starts and the starts), then the vertices, normals and uvs (floats) and the indices (int32).</item>
/// </list>
/// A string is its UTF-8 byte count (int32) and the bytes. tools/tests/test_route_ribbon_bake.py checks the header
/// against the shipped files without Unity.</summary>
@@ -63,7 +86,7 @@ namespace Statecraft.Game.Map.Routes
/// <summary>Bump it when RouteLayer.Geometry's rule changes (the constants are checked on their own), so CI fails a
/// bake made by the old rule. tools/tests/test_route_ribbon_bake.py pins it with a fingerprint of that code
/// (RouteLayer.Plan, Derive and what they call, and Bake below) and fails on an edit until both are re-pinned.</summary>
- public const int Version = 3; // 2: roads cut at the Old City's walls (RouteLayer.Drawn, #319); 3: the railway too
+ public const int Version = 4; // 2: roads cut at the Old City's walls (RouteLayer.Drawn, #319); 3: the railway too; 4: segments (#792)
const int Magic = 0x31524353; // "SCR1"
/// <summary>What the ribbons were made from, as the map read it.</summary>
@@ -105,7 +128,8 @@ namespace Statecraft.Game.Map.Routes
data.size = MapBuilder.TerrainSize(meta);
data.SetHeights(0, 0, heights);
var frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, data.size.x, data.size.z);
- var routes = RoutePaths.ReadOrNone(inputs.RoutesYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), Debug.LogWarning);
+ // As the map reads them (MapScene): the runtime file carries the corridors' segment ends (#792).
+ var routes = RoutePaths.ReadRuntimeOrYaml(inputs.RoutesTsv, inputs.RoutesYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), Debug.LogWarning);
var plans = RouteLayer.Plan(routes);
var ribbons = plans.ConvertAll(p => RouteLayer.Derive(p, frame, data, Vector3.zero));
return Bytes(Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml), data.size, Vector3.zero, plans, ribbons);
@@ -133,6 +157,8 @@ namespace Statecraft.Game.Map.Routes
{
WriteString(w, s.Id);
w.Write(s.FirstVertex); w.Write(s.VertexCount); w.Write(s.FirstIndex); w.Write(s.IndexCount);
+ w.Write(s.Segments.Length);
+ foreach (var start in s.Segments) w.Write(start);
}
var floats = new float[g.Vertices.Length * 8];
for (int i = 0, n = g.Vertices.Length; i < n; i++)
@@ -194,7 +220,17 @@ namespace Statecraft.Game.Map.Routes
{
var id = r.Text();
if (id != plan.Routes[k].Id) { reason = $"'{name}' holds '{id}' where the routes have '{plan.Routes[k].Id}'"; return false; }
- spans[k] = new RouteSpan(id, r.Int(), r.Int(), r.Int(), r.Int());
+ int fv = r.Int(), cv = r.Int(), fi = r.Int(), ci = r.Int();
+ var segments = r.Ints(r.Count());
+ // One start per segment and the route's end: the ends the routes give (RoutePath.SegmentEnds), each
+ // inside the route's range and in order, so a stale bake cannot cut a segment out of another route.
+ int want = plan.Routes[k].SegmentEnds?.Count ?? 0;
+ if (segments.Length != want) { reason = $"'{name}' cuts '{id}' at {segments.Length} points, the routes give {want} (re-bake: RouteRibbonBake.Bake)"; return false; }
+ for (int j = 0; j < segments.Length; j++)
+ if (segments[j] < fi || segments[j] > fi + ci || j > 0 && segments[j] < segments[j - 1]
+ || (j == 0 && segments[j] != fi) || (j == segments.Length - 1 && segments[j] != fi + ci))
+ { reason = $"'{name}' cuts '{id}' outside its range"; return false; }
+ spans[k] = new RouteSpan(id, fv, cv, fi, ci, segments);
}
var floats = r.Floats(8 * nv);
var verts = new Vector3[nv]; var normals = new Vector3[nv]; var uvs = new Vector2[nv];
diff --git a/unity/Assets/Scripts/Map/Routes/RouteSegment.cs b/unity/Assets/Scripts/Map/Routes/RouteSegment.cs
new file mode 100644
index 000000000..1d00656c0
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Routes/RouteSegment.cs
@@ -0,0 +1,14 @@
+#nullable enable
+using UnityEngine;
+
+namespace Statecraft.Game.Map.Routes
+{
+ /// <summary>Marks a ribbon of a route a corridor follows (GDD Phase 4, #792): <see cref="Index"/> -1 for the whole route
+ /// (the dated ribbon, drawn outside the GDD loop), or a segment's 0-based index (drawn in the GDD loop once it is built).
+ /// RouteLayer.ShowAt switches them.</summary>
+ public sealed class RouteSegment : MonoBehaviour
+ {
+ public string Route = "";
+ public int Index = -1;
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Routes/RouteSegment.cs.meta b/unity/Assets/Scripts/Map/Routes/RouteSegment.cs.meta
new file mode 100644
index 000000000..af5f328ac
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Routes/RouteSegment.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: c45b5154825149fa903a21ac4af6bec7
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 6c8eaa67c..7b92e91d3 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -623,7 +623,9 @@ namespace Statecraft.Game.UI
void RenderPlacementsIfChanged()
{
if (Bridge == null) return;
- Statecraft.Game.Map.Routes.RouteLayer.ShowAt(map, Bridge.State.Date); // dated routes (the Burma Road from June 1948)
+ // 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);
// 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/RouteLayerCorridorTests.cs b/unity/Assets/Tests/EditMode/RouteLayerCorridorTests.cs
new file mode 100644
index 000000000..f3025cc25
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RouteLayerCorridorTests.cs
@@ -0,0 +1,148 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Game.Map;
+using Statecraft.Game.Map.Collection;
+using Statecraft.Game.Map.Routes;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+/// <summary>GDD Phase 4 PR 8, item 1 (#792; plan "PR 8: Unity, the pioneers on the map"): in the GDD loop a route a
+/// corridor follows is drawn by its built segments, cut at the route index's segment ranges (RouteSpan.Segments); outside
+/// it every route keeps its dates.</summary>
+public class RouteLayerCorridorTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+
+ static List<RouteSegment> Marks(MapScene map) =>
+ RouteTests.RoutesRoot(map).Find(RouteLayer.RibbonsName).GetComponentsInChildren<RouteSegment>(true).ToList();
+
+ /// <summary>The bake's index entry for <paramref name="route"/>, as the map placed it.</summary>
+ static RouteSpan BakedSpan(string route)
+ {
+ var inputs = Statecraft.Game.Boot.GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap);
+ var (meta, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z);
+ var routes = RoutePaths.ReadRuntimeOrYaml(inputs.RoutesTsv, inputs.RoutesYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), Debug.LogWarning);
+ var plans = RouteLayer.Plan(routes);
+ var baked = AssetDatabase.LoadAssetAtPath<TextAsset>(RouteRibbonFile.AssetPath);
+ var data = new TerrainData { heightmapResolution = meta.width };
+ try
+ {
+ data.size = MapBuilder.TerrainSize(meta);
+ Assert.IsTrue(RouteRibbonFile.TryRead(baked.bytes, RouteRibbonFile.Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml),
+ data.size, Vector3.zero, plans, out var read, out var why), why);
+ return read.SelectMany(g => g.Routes).Single(s => s.Id == route);
+ }
+ finally { Object.DestroyImmediate(data); }
+ }
+
+ /// <summary>Review focus 3: with segment 1 of the Burma Road's 4 built, the map draws that segment's index range and
+ /// nothing else of the route (its dated ribbon hidden, though the date is past 14 June 1948), and nothing of the other
+ /// corridors' routes, none of whose segments is built.</summary>
+ [Test]
+ public void OnlyBuiltSegmentsDraw()
+ {
+ var burma = C.Corridors.Single(d => d.Id == "burma_road");
+ Assert.AreEqual(4, burma.Segments.Count);
+ var state = new GameState();
+ state.Corridors[burma.Id] = new CorridorWork(burma.Id, new SegmentWork[] { new SegmentWork(null, 6, new DateTime(1948, 6, 30)), null, null, null });
+ var span = BakedSpan(burma.Route);
+ Assert.AreEqual(5, span.Segments.Length, "one start per segment and the route's end");
+
+ var map = RouteTests.BuildMap();
+ try
+ {
+ RouteLayer.ShowAt(map, new DateTime(1948, 7, 15), RouteLayer.BuiltSegments(C, state));
+ var shown = Marks(map).Where(m => m.gameObject.activeInHierarchy).ToList();
+ Assert.AreEqual(1, shown.Count, string.Join(", ", shown.Select(m => m.name)));
+ Assert.AreEqual((burma.Route, 0), (shown[0].Route, shown[0].Index));
+ var mesh = shown[0].GetComponent<MeshFilter>().sharedMesh;
+ Assert.AreEqual((uint)(span.Segments[1] - span.Segments[0]), mesh.GetIndexCount(0), "segment 1's index range");
+ Assert.Greater(mesh.GetIndexCount(0), 0u);
+ Assert.Less(mesh.GetIndexCount(0), (uint)span.IndexCount, "not the whole route");
+ // The four segment ribbons tile the route: their triangles add up to the route's, and each holds only the
+ // cross-sections it draws (a section of Across vertices on each cut, shared by the two segments meeting there).
+ var parts = Marks(map).Where(m => m.Route == burma.Route && m.Index >= 0).OrderBy(m => m.Index).ToList();
+ Assert.AreEqual(4, parts.Count);
+ uint sum = 0;
+ foreach (var m in parts)
+ {
+ var part = m.GetComponent<MeshFilter>().sharedMesh;
+ var count = span.Segments[m.Index + 1] - span.Segments[m.Index];
+ Assert.AreEqual((uint)count, part.GetIndexCount(0), m.name);
+ Assert.AreEqual((count / ((RouteLayer.Across - 1) * 6) + 1) * RouteLayer.Across, part.vertexCount, m.name);
+ sum += part.GetIndexCount(0);
+ }
+ Assert.AreEqual((uint)span.IndexCount, sum, "the segments tile the route");
+ // Every corridor route is cut, each into its corridor's segments.
+ foreach (var d in C.Corridors)
+ Assert.AreEqual(d.Segments.Count, Marks(map).Count(m => m.Route == d.Route && m.Index >= 0), d.Id);
+ // A rebuild of the map (MapScene.RouteSegmentsBuilt) draws the corridors as the game left them.
+ map.Build();
+ shown = Marks(map).Where(m => m.gameObject.activeInHierarchy).ToList();
+ Assert.AreEqual(1, shown.Count, "after a rebuild: " + string.Join(", ", shown.Select(m => m.name)));
+ Assert.AreEqual((burma.Route, 0), (shown[0].Route, shown[0].Index), "after a rebuild");
+ }
+ finally { Object.DestroyImmediate(map.gameObject); }
+ }
+
+ /// <summary>The owner's review of #1312: in the GDD loop the Burma Road's convoy truck and lorry (RoadVehicles.Plans) wait
+ /// until every segment of the road is built, so no vehicle drives on road that is not drawn; once it is, both run.</summary>
+ [Test]
+ public void BurmaRoadVehiclesWaitForTheWholeRoad()
+ {
+ var burma = C.Corridors.Single(d => d.Id == "burma_road");
+ var convoy = new[] { RoadVehicles.SandwichConvoy, RoadVehicles.CanvasLorry };
+ var saved = RoadVehicles.Request;
+ var asked = new List<(string id, Action<GameObject> done)>();
+ RoadVehicles.Request = (id, detail, done) => asked.Add((id, done));
+ var map = RouteTests.BuildMap();
+ try
+ {
+ map.Control = Control1948.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", Control1948.FileName)));
+ var vehicles = RouteTests.RoutesRoot(map).Find(RoadVehicles.Name).GetComponent<RoadVehicles>();
+ void Answer() { foreach (var q in asked.ToArray()) q.done(AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(q.id, CollectionDetail.Near))); }
+ var date = new DateTime(1948, 7, 15);
+ var done = new SegmentWork(null, 6, new DateTime(1948, 6, 30));
+ var state = new GameState();
+ state.Corridors[burma.Id] = new CorridorWork(burma.Id, new SegmentWork[] { done, done, done, null });
+ RouteLayer.ShowAt(map, date, RouteLayer.BuiltSegments(C, state));
+ Answer();
+ Assert.IsFalse(asked.Any(q => convoy.Contains(q.id)), "three of four segments built: the convoy models are not asked for");
+ Assert.IsFalse(vehicles.Placed.Any(p => p.Route == burma.Route), "three of four segments built: no vehicle on the road");
+ Assert.IsTrue(vehicles.Placed.Any(), "the other roads' vehicles still run");
+
+ state.Corridors[burma.Id] = new CorridorWork(burma.Id, new SegmentWork[] { done, done, done, done });
+ RouteLayer.ShowAt(map, date, RouteLayer.BuiltSegments(C, state));
+ Answer();
+ CollectionAssert.AreEquivalent(convoy, vehicles.Placed.Where(p => p.Route == burma.Route).Select(p => p.Model),
+ "the whole road built: the convoy truck and the lorry run on it");
+ }
+ finally { RoadVehicles.Request = saved; Object.DestroyImmediate(map.gameObject); }
+ }
+
+ /// <summary>Outside the GDD loop (no built segments given) the corridor routes keep their dates: the Burma Road's
+ /// dated ribbon from 14 June 1948, and no segment ribbon at any date.</summary>
+ [Test]
+ public void TheLegacyLoopDrawsByDate()
+ {
+ var map = RouteTests.BuildMap();
+ try
+ {
+ var dated = Marks(map).Single(m => m.Route == "burma_road" && m.Index < 0);
+ foreach (var (date, drawn) in new[] { (new DateTime(1948, 6, 13), false), (new DateTime(1948, 6, 14), true), (new DateTime(1948, 5, 15), false) })
+ {
+ RouteLayer.ShowAt(map, date);
+ Assert.AreEqual(drawn, dated.gameObject.activeInHierarchy, $"{date:yyyy-MM-dd}");
+ Assert.IsFalse(Marks(map).Any(m => m.Index >= 0 && m.gameObject.activeInHierarchy), "no segment ribbon outside the GDD loop");
+ }
+ }
+ finally { Object.DestroyImmediate(map.gameObject); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/RouteLayerCorridorTests.cs.meta b/unity/Assets/Tests/EditMode/RouteLayerCorridorTests.cs.meta
new file mode 100644
index 000000000..e761fda6e
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RouteLayerCorridorTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 87c96ec6aeb7be0618e4411f370b61ee
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.cs b/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.cs
index 0637d63b1..ef009b501 100644
--- a/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.cs
+++ b/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.cs
@@ -77,7 +77,7 @@ public class RoutePathsRuntimeTests
points[0] = lon.ToString("R", CultureInfo.InvariantCulture) + " " + first[1];
c[10] = string.Join(";", points); lines[at] = string.Join("\t", c);
int end = lines.FindIndex(l => l.StartsWith("meta\tbody_check\t"));
- lines[end] = "meta\tbody_check\t" + RoutePaths.BodyCheck(lines.Where(l => l.StartsWith("route\t") || l.StartsWith("service\t"))).ToString(CultureInfo.InvariantCulture); // #668: the service rows too
+ lines[end] = "meta\tbody_check\t" + RoutePaths.BodyCheck(lines.Where(l => l.StartsWith("route\t") || l.StartsWith("segments\t") || l.StartsWith("service\t"))).ToString(CultureInfo.InvariantCulture); // #668: the service rows too, #792: the segments rows
inputs.RoutesTsv = string.Join("\n", lines);
var fallbacks = new List<string>();
diff --git a/unity/Assets/Tests/EditMode/RouteTests.cs b/unity/Assets/Tests/EditMode/RouteTests.cs
index afa21e2a3..494c65fd4 100644
--- a/unity/Assets/Tests/EditMode/RouteTests.cs
+++ b/unity/Assets/Tests/EditMode/RouteTests.cs
@@ -1024,7 +1024,8 @@ public class RouteTests
CollectionAssert.IsEmpty(derivedAtLoad, "the map places the bake");
var (_, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z);
var source = RouteRibbonFile.Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml);
- var plans = RouteLayer.Plan(RoutePaths.Parse(inputs.RoutesYaml, Bounds));
+ // As the map reads them: the runtime file carries the corridors' segment ends (#792).
+ var plans = RouteLayer.Plan(RoutePaths.ReadRuntimeOrYaml(inputs.RoutesTsv, inputs.RoutesYaml, Bounds, Debug.LogWarning));
var data = map.Terrain.terrainData; var origin = map.Terrain.transform.position;
Assert.IsTrue(RouteRibbonFile.TryRead(baked.bytes, source, data.size, origin, plans, out var read, out var why), why);
var placed = Ribbons(RoutesRoot(map), "Rail").Concat(Ribbons(RoutesRoot(map), "Roads"))
diff --git a/unity/Assets/Tests/EditMode/ServiceTrainTests.cs b/unity/Assets/Tests/EditMode/ServiceTrainTests.cs
index 9557eab06..cbd511e5e 100644
--- a/unity/Assets/Tests/EditMode/ServiceTrainTests.cs
+++ b/unity/Assets/Tests/EditMode/ServiceTrainTests.cs
@@ -116,7 +116,7 @@ public class ServiceTrainTests
static string Rebody(string tsv)
{
var lines = tsv.TrimEnd('\n').Split('\n').ToList();
- var rows = lines.Where(l => l.StartsWith("route\t") || l.StartsWith("service\t")).ToList();
+ var rows = lines.Where(l => l.StartsWith("route\t") || l.StartsWith("segments\t") || l.StartsWith("service\t")).ToList(); // #792: the segments rows too
lines[lines.Count - 1] = $"meta\tbody_check\t{RoutePaths.BodyCheck(rows)}";
return string.Join("\n", lines) + "\n";
}