A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: a wide beach on the dune coasts, baked into coast.png, and trees kept off it (refs #388) (#685)
Eyal Golana288b626ed4b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 232075c8f..d01dbb0f2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -535,6 +535,16 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBmuch of the hills, with fewer instances. The olive clumps now keep off the hex-edge midpoints as the scatter does(owner: "Yes, add the guard now"). The scrub, the plain's and the valleys' olives, the mesh, the colours and thecypress rows are unchanged.+- Sea round 3, a wide beach on the dune coasts (refs #388; owner, 15 October 2026: geographic, through the coast map,+ about 2.5-3 km, trees kept off the sand): from Jaffa south and along Haifa Bay the sand reaches about 2.7 km inland, as+ promo 03 draws it south of Jaffa; from Tel Aviv north, under the kurkar, it stays 900 m. `tools/terrain_bake.py` bakes+ the extra width into `coast.png`'s land side past the wet sand, so no shader changes; the water side is unchanged. Citrus+ groves and olives keep their crowns off the beach's full sand (`BeachBands`, the bake's C# twin). Each settlement's own+ lots and fields stay off the sand (owner, 16 October 2026, option (c)): the extra width yields to every game settlement's+ and 1948 locality's plot reach, where the beach stays 900 m, and comes back over 1 km beyond it. Haifa Bay's band ends+ at the Na'aman's mouth, so Acre, a cape of the bay and not dune country, keeps the 900 m beach. Bedouin camp tents+ keep off the dune coasts' extra sand, so one encampment in the Jaffa subdistrict is no longer placed: the map draws 64+ camps and 174 tents, against 65 and 176 before.- The map's region files (the 1948 sub-districts, the 1949 armistice lines, the 1948-49 control areas) are readfrom baked runtime forms at boot instead of being parsed as YAML (`tools/regions_bake.py`, refs #321), as thelocalities and the route paths are. The sub-districts are read once, for the camps and the region layers. A stale,diff --git a/tools/README.md b/tools/README.mdindex bb636e3b4..12a790151 100644--- a/tools/README.md+++ b/tools/README.md@@ -56,8 +56,11 @@ Offline data tools (uv inline-script Python). Run from the repo root.- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.- `terrain_bake.py` writes `unity/Assets/Textures/Map/terrain_bake.png` (AO, curvature, sky-view), `ao.png` (the AOalone, imported uncompressed) and `coast.png`- (exact signed Euclidean distance to the shoreline; lakes under 1 km2 count as land) from the committed heightmap (no- network). Re-run it whenever the heightmap changes; its PNG bytes are reproducible only on the same toolchain.+ (exact signed Euclidean distance to the shoreline; lakes under 1 km2 count as land; on the dune coasts its land side is+ beach-scaled for the wider beach, #388, except over each settlement's own ground) from the committed heightmap and+ the settlement, locality and population files in `content/map/` (no network). Re-run it whenever any of them changes+ (`test_the_committed_coast_is_the_bake_of_todays_settlements` fails on a stale `coast.png`); its PNG bytes are+ reproducible only on the same toolchain.- `land_bake.py` writes `unity/Assets/Textures/Map/landuse.png` (the land-use colour and weight: field parcels withfarm tracks, garrigue, terraces and scrub, placed by slope, rainfall and towns) from the heightmap, the CHELSA rainfall,the hex biomes and the 1948 settlements (no network); `StatecraftLand.hlsl` lays it over the biome ground. Re-run itdiff --git a/tools/terrain_bake.py b/tools/terrain_bake.pyindex e96463c9e..e47f37082 100644--- a/tools/terrain_bake.py+++ b/tools/terrain_bake.py@@ -1,6 +1,6 @@# /// script# requires-python = ">=3.11"-# dependencies = ["numpy==2.5.3", "pillow==12.3.0"]+# dependencies = ["numpy==2.5.3", "pillow==12.3.0", "pyyaml==6.0.3"]# ///"""Heightmap -> the baked shading textures of the terrain and sea shaders (no network: reads only the committed heightmap).@@ -13,7 +13,11 @@ Reads unity/Assets/StreamingAssets/map/heightmap.r16z (heightmap_codec) + heightunity/Assets/Textures/Map/coast.png L8: 0.5 + d / (2 COAST_RANGE_M), clamped; d = signed distance (m) to thenearest shoreline, < 0 in water (open sea: |elevation| < SEA_EPS_M and connected to the map's border; lakes: flatwater below LAKE_BELOW_M covering at least MIN_LAKE_AREA_KM2), the rules tools/hexgrid.py uses for its sea and lake- biomes; the area floor drops the Karameh reservoir (0.3 km2, built in the 1990s) and dike slivers between the pans+ biomes; the area floor drops the Karameh reservoir (0.3 km2, built in the 1990s) and dike slivers between the pans.+ The land side is beach-scaled, not metres, on the dune coasts (BEACH_BANDS): beach_widened takes BEACH_EXTRA_M out+ of the distance past the wet sand, so the shader's beach (ScShore) reaches that much further inland there, except+ over a settlement's own ground (beach_keep: its plots' reach, from content/map/settlements_1948.yaml,+ localities_1948.yaml and settlement_population_1945.yaml), where the beach stays ScShore's ownHeights are multiplied by VERTICAL_EXAGGERATION (MapBuilder.VerticalExaggeration) so the shading matches the relief thegame draws. Texel (j, i) is the mean of heightmap samples j..j+1, i..i+1, so its centre sits at terrain UV (j + 0.5) / 2048.Distances are exact Euclidean (a Felzenszwalb-Huttenlocher two-pass transform) with each axis' own sample spacing (about@@ -27,10 +31,12 @@ import numpy as npfrom PIL import Imageimport heightmap_codec+import yaml12ROOT = Path(__file__).resolve().parents[1]MAP_DIR = ROOT / "unity" / "Assets" / "StreamingAssets" / "map"OUT_DIR = ROOT / "unity" / "Assets" / "Textures" / "Map"+CONTENT_MAP = ROOT / "content" / "map"VERTICAL_EXAGGERATION = 3.0AO_RADIUS_M = 2000.0SKY_RADIUS_M = 12000.0@@ -43,6 +49,30 @@ LAKE_BELOW_M = -150.0LAKE_FLAT_M = 0.25 # largest height range in a 3x3 window that is still a water surfaceMIN_LAKE_AREA_KM2 = 1.0 # smaller flat pools are land (Karameh 0.30 km2; the smallest kept pan is 1.05 km2)COAST_RANGE_M = 12000.0 # StatecraftMap.hlsl ScCoastRangeM+# Sea round 3 (#388): a wider beach on the dune coasts, as promo 03 draws south of Jaffa (owner, 15 October 2026: geographic,+# through the coast map, about 2.5-3 km). The sands lie from Tel Aviv southwards and line Haifa Bay; the kurkar ridges hold+# the coast from Tel Aviv northwards (Wikipedia: "Kurkar", "Haifa Bay", "Holon", "Nitzanim", retrieved 2026-10-15). The+# widths are art direction, and the cut-off at Jaffa is interpolated between Jaffa (32.05 N) and Tel Aviv, not a sourced+# line. Each band is (lon west, lon east, lat south, lat north, ramp in degrees): the extra width is full inside it and+# falls to 0 over the ramp at each edge. Unity's tree keep-out reads a twin (Kits/BeachBands.cs, pinned by a test).+BEACH_EXTRA_M = 1800.0 # ScShore's 900 m beach becomes about 2.7 km+BEACH_BANDS = ((34.0, 34.86, 31.0, 32.07, 0.04), # Jaffa south to the map's southern coast (full south of 32.03 N)+ (35.02, 35.2, 32.77, 32.91, 0.02)) # Haifa Bay, from the Kishon's mouth to the Na'aman's (32.91 N)+# Acre was not dune country (owner, 16 October 2026): Haifa and Acre are the bay's capes and its centre is lined with dunes+# (Wikipedia, "Haifa Bay"); the Na'aman empties into the bay south of Acre (Wikipedia, "Na'aman River" and "Acre, Israel"),+# at 32.909 N 35.081 E (he.wikipedia, "נחל נעמן"; all retrieved 2026-10-16). So the bay's band ends at the Na'aman's mouth,+# full sand to 32.89 N, and Acre (32.928 N) keeps ScShore's own beach.+# Option (c) (owner, 16 October 2026): each settlement's own lots and fields stay off the sand. The extra width yields to+# every game settlement's and 1948 locality's plot reach, as SettlementKits sizes it (FootprintRadiusM x PlotReach: the disc+# its plots fill and PaintGround tints; its fields are the land use under it), and comes back over BEACH_YIELD_RAMP_M beyond.+# Inside the reach the beach is ScShore's own 900 m, behind which the towns keep their 700 m setback, as before the round.+PEOPLE_PER_HEX, MIN_HEXES, PLOT_REACH = 60000.0, 0.08, 1.1 # SettlementKits.PeoplePerHex, MinHexes, PlotReach (pinned)+BEACH_YIELD_RAMP_M = 1000.0+BEACH_KNEE_M = (230.0, 280.0) # metres past the wet sand (ScShore: 60-160 m) and past a shore texel's diagonal sample+ # (hypot(79, 211) m), so every texel the waterline crosses keeps its metric value; the extra+ # is gone by 280 m, which encodes as level 130 (235 m) at most, inside ScShore's narrowest+ # full sand (0.55 x 0.6 x 900 = 297 m): the squeezed stretch is all full sand, so its 8-bit+ # steps never showdef load_heightmap(map_dir: Path) -> tuple[np.ndarray, dict]:@@ -227,29 +257,97 @@ def to_u8(a: np.ndarray) -> np.ndarray:return np.clip(np.round(a * 255), 0, 255).astype(np.uint8)+def smoothstep01(t: np.ndarray) -> np.ndarray:+ t = np.clip(t, 0.0, 1.0)+ return t * t * (3 - 2 * t)+++def beach_extra_m(lon: np.ndarray, lat: np.ndarray) -> np.ndarray:+ """The extra beach width (m) at each point: BEACH_EXTRA_M inside a band of BEACH_BANDS, ramped to 0 at its edges."""+ w = np.zeros(np.broadcast(lon, lat).shape)+ for lon0, lon1, lat0, lat1, ramp in BEACH_BANDS:+ w = np.maximum(w, smoothstep01((lon - lon0) / ramp) * smoothstep01((lon1 - lon) / ramp)+ * smoothstep01((lat - lat0) / ramp) * smoothstep01((lat1 - lat) / ramp))+ return w * BEACH_EXTRA_M+++def beach_widened(d: np.ndarray, extra: np.ndarray) -> np.ndarray:+ """The land side's beach-scaled distance: metres to BEACH_KNEE_M[0] (the waterline's ramps and the wet sand), then+ squeezed so that BEACH_KNEE_M[1] + extra lands on BEACH_KNEE_M[1], then metres less the extra. Water (d < 0) and+ extra 0 pass through unchanged."""+ a, b = BEACH_KNEE_M+ squeezed = a + (d - a) * (b - a) / (b - a + extra)+ return np.where((d <= a) | (extra <= 0), d, np.where(d >= b + extra, d - extra, squeezed))+++def plot_reaches(meta: dict, content: Path = CONTENT_MAP) -> list[tuple[float, float, float]]:+ """(x, z, reach) in world metres (GeoFrame.ToWorld: x east of lon0, z north of lat0) of every game settlement and 1948+ locality: SettlementKits.FootprintRadiusM (a disc of max(MIN_HEXES, population / PEOPLE_PER_HEX) hexes) x PLOT_REACH,+ the population as KitPopulation reads it (settlement_population_1945.yaml; a locality's own row; none: the smallest)."""+ pop = {r["id"]: r.get("population") for r in yaml12.load((content / "settlement_population_1945.yaml").read_text())["settlements"]}+ towns = yaml12.load((content / "settlements_1948.yaml").read_text())["settlements"]+ places = yaml12.load((content / "localities_1948.yaml").read_text())["places"]+ hex_m = json.loads((content / "hexes.json").read_text())["hex_size_km"] * 1000+ hex_area = 1.5 * math.sqrt(3) * hex_m * hex_m+ w_m, l_m = meta["width_km"] * 1000, meta["length_km"] * 1000+ out = []+ for s, n in [(t, pop.get(t["id"]) or 0) for t in towns] + [(p, p["population"]) for p in places]:+ r = math.sqrt(max(MIN_HEXES, n / PEOPLE_PER_HEX) * hex_area / math.pi)+ out.append(((s["lon"] - meta["lon0"]) / (meta["lon1"] - meta["lon0"]) * w_m,+ (s["lat"] - meta["lat0"]) / (meta["lat1"] - meta["lat0"]) * l_m, r * PLOT_REACH))+ return out+++def beach_keep(x: np.ndarray, z: np.ndarray, reaches: list[tuple[float, float, float]]) -> np.ndarray:+ """How much of the extra width stands on the grid of world x (columns, east) by z (rows): 0 inside a settlement's plot+ reach, rising (smoothstep) to 1 at BEACH_YIELD_RAMP_M beyond it. Each disc is evaluated only in its own window."""+ keep = np.ones((len(z), len(x)))+ for cx, cz, reach in reaches:+ out = reach + BEACH_YIELD_RAMP_M+ cols, rows = np.nonzero(np.abs(x - cx) < out)[0], np.nonzero(np.abs(z - cz) < out)[0]+ if len(cols) == 0 or len(rows) == 0:+ continue+ win = np.s_[rows[0]:rows[-1] + 1, cols[0]:cols[-1] + 1]+ d = np.hypot(x[None, cols[0]:cols[-1] + 1] - cx, z[rows[0]:rows[-1] + 1, None] - cz)+ keep[win] = np.minimum(keep[win], smoothstep01((d - reach) / BEACH_YIELD_RAMP_M))+ return keep++def encode_coast(signed_m: np.ndarray, range_m: float = COAST_RANGE_M) -> np.ndarray:return to_u8(0.5 + signed_m / (2 * range_m))-def bake(elev: np.ndarray, meta: dict) -> tuple[np.ndarray, np.ndarray]:+def coast(elev: np.ndarray, meta: dict, reaches: list[tuple[float, float, float]] = ()) -> np.ndarray:+ """coast.png's levels (L8, 2048 x 2048, row 0 = north); the beach's extra width yields to <reaches> (plot_reaches;+ main() passes the map's)."""+ dx, dy = spacing_m(meta)+ water = water_mask(elev, dx, dy)+ h, w = elev.shape+ lon = meta["lon0"] + np.arange(w)[None, :] / (w - 1) * (meta["lon1"] - meta["lon0"])+ lat = meta["lat1"] - np.arange(h)[:, None] / (h - 1) * (meta["lat1"] - meta["lat0"]) # row 0 = north+ extra = beach_extra_m(lon, lat) * beach_keep(np.arange(w) * dx, (h - 1 - np.arange(h)) * dy, reaches)+ land_m = beach_widened(distance_to(water, dx, dy, COAST_RANGE_M), extra)+ signed = np.where(water, -distance_to(~water, dx, dy, COAST_RANGE_M), land_m)+ return encode_coast(to_texels(signed.astype(np.float32)))+++def bake(elev: np.ndarray, meta: dict, reaches: list[tuple[float, float, float]] = ()) -> tuple[np.ndarray, np.ndarray]:dx, dy = spacing_m(meta)z = elev * np.float32(VERTICAL_EXAGGERATION)ao, sky, curv = openness(z, dx, dy, AO_RADIUS_M), openness(z, dx, dy, SKY_RADIUS_M), curvature(z, dx, dy)- water = water_mask(elev, dx, dy)- signed = np.where(water, -distance_to(~water, dx, dy, COAST_RANGE_M), distance_to(water, dx, dy, COAST_RANGE_M))rgb = np.stack([to_u8(to_texels(ao)), to_u8(to_texels(curv)), to_u8(to_texels(sky))], axis=-1)- return rgb, encode_coast(to_texels(signed.astype(np.float32)))+ return rgb, coast(elev, meta, reaches)def main(map_dir: Path = MAP_DIR, out_dir: Path = OUT_DIR) -> None:elev, meta = load_heightmap(map_dir)- rgb, coast = bake(elev, meta)+ rgb, levels = bake(elev, meta, plot_reaches(meta))out_dir.mkdir(parents=True, exist_ok=True)Image.fromarray(rgb, "RGB").save(out_dir / "terrain_bake.png")- Image.fromarray(coast, "L").save(out_dir / "coast.png")+ Image.fromarray(levels, "L").save(out_dir / "coast.png")Image.fromarray(np.ascontiguousarray(rgb[..., 0]), "L").save(out_dir / "ao.png")- print(f"wrote {out_dir / 'terrain_bake.png'}, {out_dir / 'ao.png'} and {out_dir / 'coast.png'} ({coast.shape[1]} x {coast.shape[0]}): "- f"water {np.mean(coast < 128):.1%} of texels; AO mean {rgb[..., 0].mean() / 255:.3f}, sky-view mean {rgb[..., 2].mean() / 255:.3f}")+ print(f"wrote {out_dir / 'terrain_bake.png'}, {out_dir / 'ao.png'} and {out_dir / 'coast.png'} ({levels.shape[1]} x {levels.shape[0]}): "+ f"water {np.mean(levels < 128):.1%} of texels; AO mean {rgb[..., 0].mean() / 255:.3f}, sky-view mean {rgb[..., 2].mean() / 255:.3f}")if __name__ == "__main__":diff --git a/tools/tests/test_terrain_bake.py b/tools/tests/test_terrain_bake.pyindex 7022dbf97..8f161e381 100644--- a/tools/tests/test_terrain_bake.py+++ b/tools/tests/test_terrain_bake.py@@ -243,3 +243,174 @@ def test_constants_duplicated_in_csharp_and_hlsl_match_the_bake():cr = float(re.search(r"static const float ScCoastRangeM\s*=\s*([0-9.]+)", hlsl).group(1))assert tb.VERTICAL_EXAGGERATION == veassert tb.COAST_RANGE_M == cr+++# Sea round 3 (#388): a wider beach on the dune coasts, baked into coast.png's land side (no shader change).++def test_the_beach_widening_keeps_the_waterline_metric_and_takes_the_extra_out_beyond_the_full_sand():+ d = np.linspace(0, 12000, 24001)+ assert np.array_equal(tb.beach_widened(d, np.zeros_like(d)), d), "no extra: metres"+ e = np.full_like(d, 1800.0)+ w = tb.beach_widened(d, e)+ a, b = tb.BEACH_KNEE_M+ assert np.array_equal(w[d <= a], d[d <= a]), "the waterline, the land use's fade and the wet sand stay in metres"+ assert np.allclose(w[d >= b + 1800], d[d >= b + 1800] - 1800), "beyond the full sand: the extra taken out, metric again"+ assert (np.diff(w) > 0).all(), "monotone, so the shore's ramps keep their order"+ assert np.abs(np.diff(w)).max() <= np.diff(d).max() + 1e-9, "continuous: no step"+ assert tb.encode_coast(np.array([b]))[0] / 255 * 2 * tb.COAST_RANGE_M - tb.COAST_RANGE_M < 0.55 * 0.6 * 900, (+ "the squeezed stretch, as 8-bit levels, reads as full sand at ScShore's narrowest width")+ assert np.array_equal(tb.beach_widened(-d, e), -d), "the water side is untouched"+++def test_the_extra_width_is_south_of_jaffa_and_in_haifa_bay_only():+ lon = np.array([34.72, 34.55, 34.42, 35.06, 35.05, 34.78, 34.89, 34.96, 35.08, 34.95, 35.60])+ lat = np.array([31.95, 31.70, 31.50, 32.88, 32.84, 32.15, 32.50, 32.70, 33.00, 29.50, 32.80])+ extra = tb.beach_extra_m(lon, lat)+ assert np.allclose(extra[:5], tb.BEACH_EXTRA_M), "Rishon, Ashdod, Gaza's coast, Haifa Bay's dunes"+ assert np.allclose(extra[5:], 0), "Herzliya, Netanya, the Carmel coast, north of Acre, Eilat, the Sea of Galilee"+ ramp = tb.beach_extra_m(np.full(81, 34.75), np.linspace(32.00, 32.10, 81))+ assert (np.diff(ramp) <= 0).all() and ramp[0] == tb.BEACH_EXTRA_M and ramp[-1] == 0, "a smooth ramp at Jaffa"+ assert np.abs(np.diff(ramp)).max() < 0.06 * tb.BEACH_EXTRA_M+++def test_the_bake_widens_only_the_land_side_inside_a_band(tmp_path, monkeypatch):+ n = 41+ y, x = np.mgrid[0:n, 0:n]+ elev = np.where(x < 15, 0.0, 5.0 + 0.5 * x).astype(np.float32)+ meta = {**meta_for(n, n, 79.0, 211.0), "lon0": 34.55, "lon1": 34.59, "lat0": 31.80, "lat1": 31.88} # off Ashdod+ _, wide = tb.bake(elev, meta)+ monkeypatch.setattr(tb, "BEACH_EXTRA_M", 0.0)+ _, metric = tb.bake(elev, meta)+ wet = metric < 128+ assert wet[:, :10].all() and np.array_equal(wide[wet], metric[wet]), "the water texels are the metric encoding"+ assert (wide[:, 25:] < metric[:, 25:]).all(), "the land beyond the full sand reads nearer the sea"+ assert (wide <= metric).all()+++def lonlat(row: int, col: int) -> tuple[float, float]:+ return 34.2 + (col + 0.5) / 2048 * 1.7, 33.35 - (row + 0.5) / 2048 * 3.9+++def land_m_inland(lat: float, km: float) -> float:+ """coast.png's land-side metres (as ScShore decodes them) km east of the Mediterranean shore on lat's row."""+ c = np.asarray(png(ROOT / "unity/Assets/Textures/Map/coast.png")).astype(np.float64) / 255+ row, _ = texel(34.2, lat)+ line = c[row, :texel(35.1, lat)[1]]+ shore = int(np.argmax(line >= 0.5))+ col = shore + round(km * 1000 / (161529.4 / 2048))+ return (line[col] - 0.5) * 2 * tb.COAST_RANGE_M+++def test_the_committed_coast_draws_a_wide_beach_south_of_jaffa_and_a_narrow_one_under_the_kurkar():+ # ScShore (StatecraftMap.hlsl): full sand to 0.55 W and none beyond W, W = ScBeachM (900 m) x 0.6..1.4.+ # 31.90 N (off Yavne's dunes): 31.95 N, by Rishon LeZion, is now 2.3 km from Nabi Rubin, whose own ground the beach+ # yields to (option (c)).+ assert land_m_inland(31.90, 2.0) < 0.55 * 0.6 * 900, "2 km inland south of Jaffa: full sand at any width"+ assert land_m_inland(32.15, 2.0) > 1.4 * 900, "2 km inland at Herzliya: no sand at any width"+++def test_the_csharp_twin_of_the_beach_bands_matches_the_bake():+ import re+ cs = (ROOT / "unity/Assets/Scripts/Map/Kits/BeachBands.cs").read_text()+ hlsl = (ROOT / "unity/Assets/Shaders/StatecraftMap.hlsl").read_text()+ assert float(re.search(r"const float ExtraM = ([0-9.]+)f", cs).group(1)) == tb.BEACH_EXTRA_M+ bands = [tuple(float(v) for v in m) for m in re.findall(+ r"\(([0-9.]+), ([0-9.]+), ([0-9.]+), ([0-9.]+), ([0-9.]+)\)", cs.split("Bands =", 1)[1].split(";", 1)[0])]+ assert bands == [tuple(b) for b in tb.BEACH_BANDS]+ beach = float(re.search(r"static const float ScBeachM = ([0-9.]+);", hlsl).group(1))+ full = float(re.search(r"const float FullSandM = ([0-9.]+)f", cs).group(1))+ assert full == pytest.approx(0.55 * 1.4 * beach, abs=0.5), "ScShore's widest full sand"+++# Option (c) (#685; owner, 16 October 2026): "Keep each settlement's own lots and fields off the sand, and narrow the beach+# ramp at Acre, which was not dune country."++def test_acre_and_the_naaman_mouth_get_no_extra_width_and_the_bays_dunes_keep_it():+ lon = np.array([35.082, 35.081, 35.07, 35.06])+ lat = np.array([32.928, 32.909, 32.885, 32.86])+ extra = tb.beach_extra_m(lon, lat)+ assert extra[0] == 0, "Acre's walled town (Wikipedia: 32.928 N 35.082 E), a cape of the bay, not dune country"+ assert extra[1] < 0.01 * tb.BEACH_EXTRA_M, "the Na'aman's mouth (he.wikipedia: 32.909 N 35.081 E), where the bay's dunes end"+ assert np.allclose(extra[2:], tb.BEACH_EXTRA_M), "the bay's dunes south of the Na'aman keep the wide beach"+++def test_the_beach_yields_to_a_settlements_plot_reach_and_comes_back_beyond_it():+ x = np.linspace(0, 6000, 61)+ keep = tb.beach_keep(x, np.array([0.0]), [(0.0, 0.0, 2000.0)])[0]+ assert (keep[x <= 2000] == 0).all(), "no extra width over the settlement's own ground"+ assert (keep[x >= 2000 + tb.BEACH_YIELD_RAMP_M] == 1).all(), "the full extra width beyond the ramp"+ assert (np.diff(keep) >= 0).all() and np.abs(np.diff(keep)).max() < 0.2, "a smooth ramp"+ two = tb.beach_keep(x, np.array([0.0]), [(0.0, 0.0, 2000.0), (6000.0, 0.0, 1000.0)])[0]+ assert np.array_equal(two, np.minimum(keep, tb.beach_keep(x, np.array([0.0]), [(6000.0, 0.0, 1000.0)])[0]))+++def test_the_plot_reaches_are_the_kits_footprints():+ meta = json.loads((ROOT / "unity/Assets/StreamingAssets/map/heightmap.json").read_text())+ reaches = tb.plot_reaches(meta)+ towns = len(tb.yaml12.load((ROOT / "content/map/settlements_1948.yaml").read_text())["settlements"])+ places = len(tb.yaml12.load((ROOT / "content/map/localities_1948.yaml").read_text())["places"])+ assert len(reaches) == towns + places, "every game settlement and every 1948 locality"+ hex_area = 1.5 * np.sqrt(3) * 5000.0 ** 2+ w_m, l_m = meta["width_km"] * 1000, meta["length_km"] * 1000+ def reach_at(lon: float, lat: float) -> float:+ x, z = (lon - meta["lon0"]) / (meta["lon1"] - meta["lon0"]) * w_m, (lat - meta["lat0"]) / (meta["lat1"] - meta["lat0"]) * l_m+ return next(r for cx, cz, r in reaches if abs(cx - x) < 1 and abs(cz - z) < 1)+ smallest = np.sqrt(tb.MIN_HEXES * hex_area / np.pi) * tb.PLOT_REACH+ assert reach_at(34.7503, 32.0231) == pytest.approx(smallest), "Bat Yam (2,000 people, a locality): the smallest footprint"+ assert reach_at(34.7531, 32.0522) == pytest.approx(np.sqrt(94310 / 60000 * hex_area / np.pi) * 1.1), "Jaffa: 94,310 people"+++def test_the_kits_constants_and_the_yield_ramp_match_the_csharp():+ import re+ kits = (ROOT / "unity/Assets/Scripts/Map/Kits/SettlementKits.cs").read_text()+ cs = (ROOT / "unity/Assets/Scripts/Map/Kits/BeachBands.cs").read_text()+ assert float(re.search(r"const float PeoplePerHex = ([0-9.]+)f", kits).group(1)) == tb.PEOPLE_PER_HEX+ assert float(re.search(r"const float MinHexes = ([0-9.]+)f", kits).group(1)) == tb.MIN_HEXES+ assert float(re.search(r"const float PlotReach = ([0-9.]+)f", kits).group(1)) == tb.PLOT_REACH+ assert float(re.search(r"const float YieldRampM = ([0-9.]+)f", cs).group(1)) == tb.BEACH_YIELD_RAMP_M+++def committed_and_metric_coast():+ elev, meta = tb.load_heightmap(tb.MAP_DIR)+ return elev, meta, np.asarray(png(ROOT / "unity/Assets/Textures/Map/coast.png")).astype(int)+++def test_the_committed_coast_is_the_bake_of_todays_settlements(monkeypatch):+ # A locality added or resized on the dune coast without a re-bake would leave its ground under the extra sand.+ elev, meta, committed = committed_and_metric_coast()+ fresh = tb.coast(elev, meta, tb.plot_reaches(meta)).astype(int)+ diff = np.abs(fresh - committed)+ assert diff.max() <= 1 and (diff > 0).mean() < 1e-4, (+ "unity/Assets/Textures/Map/coast.png is stale against content/map/settlements_1948.yaml, localities_1948.yaml or "+ "settlement_population_1945.yaml (the dune beach yields to each place's plot reach, set by its coordinates and "+ "population): run `uv run tools/terrain_bake.py` from the repo root and commit unity/Assets/Textures/Map/coast.png")+++def test_the_committed_coast_keeps_every_settlements_own_ground_at_scshores_beach(monkeypatch):+ elev, meta, committed = committed_and_metric_coast()+ monkeypatch.setattr(tb, "BEACH_EXTRA_M", 0.0)+ metric = tb.coast(elev, meta).astype(int)+ h, w = elev.shape+ dx, dy = tb.spacing_m(meta)+ x = (np.arange(w - 1) + 0.5) * dx # texel centres (to_texels: the mean of 2 x 2 samples)+ z = (h - 1 - (np.arange(h - 1) + 0.5)) * dy+ own = np.zeros((h - 1, w - 1), bool)+ for cx, cz, reach in tb.plot_reaches(meta):+ own |= (x[None, :] - cx) ** 2 + (z[:, None] - cz) ** 2 < reach ** 2+ assert own.sum() > 0+ worst = np.abs(committed - metric)[own].max()+ assert worst <= 1, f"a settlement's plot reach has extra sand (coast.png reads up to {worst} levels short)"+ assert (committed < metric - 1).sum() > 100_000, "the open dune coast keeps its wide beach"+++def test_the_committed_coast_draws_acre_at_scshores_beach_and_the_bays_dunes_wide(monkeypatch):+ elev, meta, committed = committed_and_metric_coast()+ monkeypatch.setattr(tb, "BEACH_EXTRA_M", 0.0)+ metric = tb.coast(elev, meta).astype(int)+ r0, c0 = texel(35.05, 32.95)+ r1, c1 = texel(35.12, 32.912)+ acre = np.s_[r0:r1, c0:c1] # Acre's walled town, its peninsula and its shore to just north of the Na'aman's mouth+ assert (committed[acre] >= 128).sum() > 50 and np.abs(committed[acre] - metric[acre]).max() <= 1, (+ "Acre has ScShore's own beach, no extra width")+ # ScShore (StatecraftMap.hlsl): full sand at any width under 0.55 x 0.6 x 900 m.+ assert land_m_inland(32.87, 2.0) < 0.55 * 0.6 * 900, "2 km inland on the bay's dunes south of the Na'aman: full sand"diff --git a/unity/Assets/Scripts/Map/Kits/BeachBands.cs b/unity/Assets/Scripts/Map/Kits/BeachBands.csnew file mode 100644index 000000000..573788dc0--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/BeachBands.cs@@ -0,0 +1,77 @@+#nullable enable+using System.Collections.Generic;+using UnityEngine;++namespace Statecraft.Game.Map.Kits+{+ /// <summary>Sea round 3 (#388): the dune coasts' wider beach, for the kits. The terrain draws it from coast.png, whose+ /// land side tools/terrain_bake.py bakes beach-scaled there (BEACH_EXTRA_M, BEACH_BANDS, beach_keep); KitGround does not+ /// read coast.png, so this is its C# twin, pinned to the bake by tools/tests/test_terrain_bake.py.</summary>+ public static class BeachBands+ {+ /// <summary>The extra beach width (m) inside a band: ScShore's 900 m beach becomes about 2.7 km.</summary>+ public const float ExtraM = 1800f;+ /// <summary>(lon west, lon east, lat south, lat north, ramp in degrees): Jaffa south to the map's southern coast, and+ /// Haifa Bay from the Kishon's mouth to the Na'aman's, south of Acre (owner, 16 October 2026: Acre was not dune+ /// country). The extra width falls to 0 over the ramp at each edge.</summary>+ static readonly (double lon0, double lon1, double lat0, double lat1, double ramp)[] Bands =+ {+ (34.0, 34.86, 31.0, 32.07, 0.04),+ (35.02, 35.2, 32.77, 32.91, 0.02),+ };+ /// <summary>Option (c) (owner, 16 October 2026: each settlement's own lots and fields stay off the sand): the extra+ /// width is 0 inside a settlement's plot reach (SettlementKits.FootprintRadiusM x PlotReach) and comes back over this+ /// many metres beyond it.</summary>+ public const float YieldRampM = 1000f;+ /// <summary>How far (m) from the sea ScShore (StatecraftMap.hlsl) paints full sand at its widest: 0.55 of a width+ /// that reaches 1.4 x ScBeachM (900 m).</summary>+ public const float FullSandM = 693f;+ /// <summary>The farthest any full sand reaches from the sea (m).</summary>+ public const float MaxFullSandM = FullSandM + ExtraM;++ static double Smooth(double t) { t = t < 0 ? 0 : t > 1 ? 1 : t; return t * t * (3 - 2 * t); }++ /// <summary>The band's extra beach width (m) at (lon, lat): ExtraM inside a band, ramped to 0 at its edges, before+ /// the settlements' yield.</summary>+ public static float ExtraAt(double lon, double lat)+ {+ double w = 0;+ foreach (var (lon0, lon1, lat0, lat1, ramp) in Bands)+ w = System.Math.Max(w, Smooth((lon - lon0) / ramp) * Smooth((lon1 - lon) / ramp) * Smooth((lat - lat0) / ramp) * Smooth((lat1 - lat) / ramp));+ return (float)(w * ExtraM);+ }++ /// <summary>The plot reaches (world centre, m) of <paramref name="places"/> that the extra width yields to, as the+ /// bake's plot_reaches: only those whose yield (reach plus YieldRampM) can reach a band.</summary>+ public static List<(Vector2 centre, float reach)> Reaches(IReadOnlyList<Settlement> places, KitGround ground)+ {+ var list = new List<(Vector2, float)>();+ foreach (var s in places)+ {+ var w = ground.Frame.ToWorld(s.Lon, s.Lat, 0);+ float reach = SettlementKits.FootprintRadiusM(s, ground.HexSizeM) * SettlementKits.PlotReach, rim = reach + YieldRampM;+ var (lonW, latS) = ground.Frame.ToLonLat(new Vector3(w.x - rim, 0f, w.z - rim));+ var (lonE, latN) = ground.Frame.ToLonLat(new Vector3(w.x + rim, 0f, w.z + rim));+ foreach (var (lon0, lon1, lat0, lat1, _) in Bands)+ if (lonE > lon0 && lonW < lon1 && latN > lat0 && latS < lat1) { list.Add((new Vector2(w.x, w.z), reach)); break; }+ }+ return list;+ }++ /// <summary>How far (m) from the sea the full sand reaches at world (x, z): the extra width yields to+ /// <paramref name="reaches"/> (<see cref="Reaches"/>).</summary>+ public static float FullSandAt(GeoFrame frame, float x, float z, List<(Vector2 centre, float reach)> reaches)+ {+ var (lon, lat) = frame.ToLonLat(new Vector3(x, 0f, z));+ float extra = ExtraAt(lon, lat);+ if (extra <= 0f) return FullSandM;+ double keep = 1; var p = new Vector2(x, z);+ foreach (var (c, reach) in reaches)+ {+ keep = System.Math.Min(keep, Smooth(((p - c).magnitude - reach) / YieldRampM));+ if (keep <= 0) break;+ }+ return FullSandM + (float)(extra * keep);+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Kits/BeachBands.cs.meta b/unity/Assets/Scripts/Map/Kits/BeachBands.cs.metanew file mode 100644index 000000000..7da4e25c2--- /dev/null+++ b/unity/Assets/Scripts/Map/Kits/BeachBands.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: c3cc42bf24a014d3794d5101cd61e5a3\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs b/unity/Assets/Scripts/Map/Kits/SettlementKits.csindex 8d3a48dc3..02c2807ee 100644--- a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.cs@@ -198,9 +198,12 @@ namespace Statecraft.Game.Map.Kitsint n = landmarks[s.Id] + PlaceHouses(s, centres[s.Id], ground, km, lots, ref rnd, merged, out var scatter, out var palms); // towns round 2: plot latticesgameTowns.Add((s, km, n, scatter, palms));}+ // The dune coasts' extra sand yields to the places' own ground (BeachBands, option (c)); a camp is not a place, so+ // its tents keep off that sand instead.+ var reaches = camps.Count > 0 ? BeachBands.Reaches(order, ground) : new List<(Vector2, float)>();foreach (var area in camps){- var (c, t) = Encampments(area, ground, lots, Tile);+ var (c, t) = Encampments(area, ground, lots, Tile, reaches);result.Camps += c; result.Tents += t;}// Last, the small towns' fallback houses (#317), largest place first: after every place's own houses and the camps,@@ -660,8 +663,9 @@ namespace Statecraft.Game.Map.Kitsk >= 1f ? b : new Spec { w = b.w * k, d = b.d * k, h = b.h, storeys = b.storeys, lotR = b.lotR * k };- /// <summary>How far (m) a new town's buildings keep back from the sea: the beach strip (promo-sea's ScBeachM, 650 m on- /// average) stays sand, with its palms, as in promo 03's Tel Aviv. The old towns (Jaffa, Acre, Gaza, Haifa's lower+ /// <summary>How far (m) a new town's buildings keep back from the sea: the beach strip (ScShore's ScBeachM, 900 m on+ /// average; on the dune coasts the extra width yields to a town's own ground, terrain_bake.py's beach_keep) stays+ /// sand, with its palms, as in promo 03's Tel Aviv. The old towns (Jaffa, Acre, Gaza, Haifa's lower/// town by the port) meet the water.</summary>const float BeachSetbackM = 700f;@@ -1286,7 +1290,8 @@ namespace Statecraft.Game.Map.Kits/// this clear of every unit token (KitGround.Tokens).</summary>public const float CampReach = 64f;- static (int camps, int tents) Encampments(Localities.Area area, KitGround ground, Lots lots, System.Func<Vector2, KitMesh> tile)+ static (int camps, int tents) Encampments(Localities.Area area, KitGround ground, Lots lots, System.Func<Vector2, KitMesh> tile,+ List<(Vector2 centre, float reach)> reaches){if (area.Hexes.Count == 0) return (0, 0);float m = KitScale.Houses, hex = ground.HexSizeM;@@ -1317,6 +1322,9 @@ namespace Statecraft.Game.Map.Kitsfloat tyaw = yaw + rnd.Range(-20f, 20f);float lotR = 0.55f * Mathf.Sqrt(tw * tw + td * td);if (ground.Water(p.x, p.y) || !FreeAt(lots, p, lotR) || ground.OnRoute(p, lotR) || ground.OnGridMark(p, lotR)) continue;+ // Nor on the dune coasts' extra sand (option (c), #685), which yields to the places but not to a camp.+ float sand = BeachBands.FullSandAt(ground.Frame, p.x, p.y, reaches);+ if (sand > BeachBands.FullSandM && ground.SeaDistance(p.x, p.y, sand + lotR) != float.MaxValue) continue;lots.Add(new Lot { c = p, r = lotR, id = "camp:" + area.Subdistrict });var (bottom, top) = GroundSpan(p, tyaw, tw, td, ground, m);// Goat-hair cloth, a warm dark brown rather than black: at the overview a black row read as a scratch.diff --git a/unity/Assets/Scripts/Map/Kits/Vegetation.cs b/unity/Assets/Scripts/Map/Kits/Vegetation.csindex f2ebc631c..d3528ffe8 100644--- a/unity/Assets/Scripts/Map/Kits/Vegetation.cs+++ b/unity/Assets/Scripts/Map/Kits/Vegetation.cs@@ -116,6 +116,24 @@ namespace Statecraft.Game.Map.Kits// Counts fall with the square of the tree scale (k = 1 at the default), so a larger tree covers the same ground// with fewer instances instead of burying the towns.float ks = s / KitScale.CountReference;+ // Sea round 3 (#388): no citrus or olive crown on the beach's full sand (BeachBands; owner: "keep them off the+ // sand"). Set only round the groves and olive cells near the sea: SeaDistance costs up to 48 height samples.+ bool nearSand = false;+ // The sand yields to every settlement's plot reach (option (c), owner 16 October 2026), as the bake's beach_keep.+ var reaches = BeachBands.Reaches(settlements, ground);+ // Sea within r (m) of (x, z): SeaDistance's sea test on its outer ring of 12 directions only (a quarter of its+ // samples; the boot's trees phase rose 37 ms with all four rings), which finds a straight shore r away by+ // r / cos 15 degrees.+ bool SeaWithin(float x, float z, float r)+ {+ r *= 1.035f;+ for (int i = 0; i < 12; i++)+ {+ float px = x + Mathf.Cos(i * Mathf.PI / 6f) * r, pz = z + Mathf.Sin(i * Mathf.PI / 6f) * r;+ if (ground.Inside(px, pz) && Mathf.Abs(ground.ElevM(px, pz)) <= MapBuilder.SeaToleranceM + 0.5f) return true;+ }+ return false;+ }void Add(TreeKind k, float x, float z, ref KitRandom rnd, float size = 1f, float yawDeg = float.NaN, float squash = 1f){// The tree's own numbers first, whether it stands or not: a tree left out for a lot or a route then never@@ -126,7 +144,7 @@ namespace Statecraft.Game.Map.Kits// grove rows through blocks).// Nor into a railway's or road's corridor (the routes run through the groves otherwise).float crown = CrownRadiusM(k) * s * size * 1.15f;- if (ground.OnLot(x, z, crown) || ground.OnRoute(new Vector2(x, z), crown)) return;+ if (ground.OnLot(x, z, crown) || ground.OnRoute(new Vector2(x, z), crown) || nearSand && SeaWithin(x, z, BeachBands.FullSandAt(ground.Frame, x, z, reaches) + crown)) return;float y = ground.Y(x, z);float yaw = float.IsNaN(yawDeg) ? spin : yawDeg;trees.Add((k, Matrix4x4.TRS(new Vector3(x, y, z), Quaternion.Euler(0, yaw, 0), new Vector3(scale, scale * stretch * squash, scale))));@@ -156,7 +174,9 @@ namespace Statecraft.Game.Map.Kits// Grove sizes grow with the square root of the tree scale, so a bigger tree means fewer, not only larger, rows.float grow = Mathf.Sqrt(s / KitScale.CountReference);float w = rnd.Range(1300f, 3000f) * grow, d = rnd.Range(900f, 2000f) * grow, step = 2f * GroveStepM * s; // one 2 x 2 patch per step- groveDiscs.Add((gc, 0.5f * Mathf.Sqrt(w * w + d * d) + CrownRadiusM(TreeKind.CitrusPatch) * s * 1.15f)); // to its edge rows' crowns+ float disc = 0.5f * Mathf.Sqrt(w * w + d * d) + CrownRadiusM(TreeKind.CitrusPatch) * s * 1.15f; // to its edge rows' crowns+ groveDiscs.Add((gc, disc));+ nearSand = SeaWithin(gc.x, gc.y, BeachBands.MaxFullSandM + disc);// A ragged block: each row stops at its own length, and some groves lose a corner (an L shape).bool notch = rnd.Chance(0.3f); float nu = rnd.Range(0.1f, 0.3f) * w, nv = rnd.Range(0.1f, 0.3f) * d;for (float v = -d / 2; v <= d / 2; v += step)@@ -210,6 +230,7 @@ namespace Statecraft.Game.Map.Kitsfloat e = ground.ElevM(px, pz);if (e < (plain ? 5f : 40f) || e > 950f || ground.Water(px, pz) || ground.InTown(px, pz, 0.9f) || ground.Slope(px, pz, 600f) > 0.35f) continue;int n = rnd.Range(1, 4);+ nearSand = SeaWithin(px, pz, BeachBands.MaxFullSandM + 0.71f * cell + CrownRadiusM(TreeKind.Olive) * s * size * 1.15f);for (int i = 0; i < n; i++){float tx = px + rnd.Range(-0.5f, 0.5f) * cell, tz = pz + rnd.Range(-0.5f, 0.5f) * cell;@@ -219,6 +240,7 @@ namespace Statecraft.Game.Map.Kitsif (!ground.Water(tx, tz) && !ground.InTown(tx, tz, 0.85f)) Add(TreeKind.Olive, tx, tz, ref rnd, size);}}+ nearSand = false;}// The hills' loose scatter between the olive clumps (promo 03's hills, and the demo video at 23 s): single olivesdiff --git a/unity/Assets/Tests/EditMode/KitTests.cs b/unity/Assets/Tests/EditMode/KitTests.csindex 6512572b6..7bb801966 100644--- a/unity/Assets/Tests/EditMode/KitTests.cs+++ b/unity/Assets/Tests/EditMode/KitTests.cs@@ -338,6 +338,104 @@ public class KitTestsAssert.IsTrue(g.Water(lake.x, lake.z), "the Sea of Galilee is water");}+ /// <summary>Sea round 3 (#388, owner 15 October 2026: "keep them off the sand"): no citrus or olive crown reaches the+ /// beach's full sand. Read from coast.png itself (the file the terrain's ScShore draws the beach from, beach-scaled on the+ /// dune coasts): ScShore paints full sand where the land-side distance is under 0.55 of a width that reaches 1.4 x+ /// ScBeachM (693 m), and the distance field is 1-Lipschitz there, so a trunk at that distance plus its crown's radius+ /// keeps the whole crown off it. One 8-bit level of coast.png (94 m) is the tolerance. ScShore draws sand only by+ /// sea-level water (above -100 m), and coast.png also measures the distance to the rift lakes (the Sea of Galilee at+ /// -210 m, the Dead Sea): a crown that reads near water is counted only when KitGround.SeaDistance, the sea-level test+ /// the keep-out itself uses, finds the sea within that reach (plus the dune coasts' extra width, which coast.png takes+ /// out of its land side), so a tree by a lake, where no sand is drawn, is not counted.</summary>+ [Test]+ public void NoGroveOrOliveCrownStandsOnTheBeach()+ {+ var map = OpenMap();+ var coast = new Texture2D(2, 2);+ try+ {+ Assert.IsTrue(coast.LoadImage(System.IO.File.ReadAllBytes(System.IO.Path.Combine(Application.dataPath, "Textures/Map/coast.png"))));+ var g = Ground(map);+ // The game's list (towns and 1948 localities), so the keep-out's sand yields to every place's own ground as the+ // bake's does (option (c)).+ var trees = Vegetation.Plant(map.Settlements.Concat(LoadLocalities(map).Places.Select(p => p.Settlement)).ToList(), g);+ float LandM(float x, float z) => (coast.GetPixelBilinear(x / g.Width, z / g.Length).r - 0.5f) * 2f * 12000f; // ScCoastRangeM+ const float FullSandM = 0.55f * 1.4f * 900f, LevelM = 2f * 12000f / 255f;+ var bad = new List<string>();+ int citrus = 0, olives = 0, byLake = 0;+ foreach (var (kind, m) in trees)+ {+ if (kind != TreeKind.Citrus && kind != TreeKind.CitrusPatch && kind != TreeKind.Olive) continue;+ if (kind == TreeKind.Olive) olives++; else citrus++;+ Vector3 p = m.GetColumn(3); float crown = Vegetation.CrownRadiusM(kind) * ((Vector3)m.GetColumn(0)).magnitude;+ float d = LandM(p.x, p.z) - crown;+ if (d >= FullSandM - LevelM) continue;+ // The water coast.png sees, in metres: on the dune coasts its land side reads up to BeachBands.ExtraM short.+ float reach = LandM(p.x, p.z) + BeachBands.ExtraM + 2f * LevelM;+ if (g.SeaDistance(p.x, p.z, reach) == float.MaxValue) // that water is a lake+ {+ // A crown SeaDistance misses would land here and pass silently, so it must stand in the rift: the+ // Mediterranean's shore is at sea level, the Sea of Galilee's at -210 m (today 6 crowns, -70 to -214 m,+ // on its western shore by Tiberias).+ byLake++;+ if (g.ElevM(p.x, p.z) >= -50f) bad.Add($"{kind} at ({p.x:0}, {p.z:0}): near water SeaDistance misses, but not in the rift ({g.ElevM(p.x, p.z):0} m)");+ continue;+ }+ bad.Add($"{kind} at ({p.x:0}, {p.z:0}): crown {d:0} m from the sea's edge in coast.png");+ }+ TestContext.WriteLine($"{citrus} citrus and {olives} olive instances; {bad.Count} crowns on the full sand; {byLake} near a rift lake only");+ CollectionAssert.IsEmpty(bad.Take(20), $"{bad.Count} crowns on the beach's full sand");+ Assert.Greater(citrus, 500, "the groves keep their trees");+ }+ finally { Object.DestroyImmediate(coast); }+ }++ /// <summary>Option (c) (#685; owner, 16 October 2026: "Keep each settlement's own lots and fields off the sand"): the+ /// lots the map builds (every building's, landmark's and tent's, over the 296 places, the camps and the routes), each+ /// centre read against coast.png's full sand: ScShore paints full sand under 0.55 of a width of 0.6-1.4 x ScBeachM+ /// (900 m), so under 297 m at any noise width and under 693 m at the widest. A lot by a lake only is not counted (no sand+ /// is drawn there; KitGround.SeaDistance, as NoGroveOrOliveCrownStandsOnTheBeach). Main before the wide beach (adf102c9)+ /// has 9 and 30 such lots (the old towns' waterfronts, al-Jura, Deir al-Balah and the like, which met the shore); the+ /// wide beach before option (c) had 83 and 119, over 17 places.</summary>+ [Test]+ public void TheSettlementsOwnLotsStayOffTheDuneSand()+ {+ var (any, widest, places) = LotsOnTheSand(System.IO.Path.Combine(Application.dataPath, "Textures/Map/coast.png"));+ TestContext.WriteLine($"lot centres on the full sand: {any} at any noise, {widest} at the widest; places: {string.Join(", ", places)}");+ Assert.LessOrEqual(any, 9, "lots on the full sand at any noise width: main's 9");+ Assert.LessOrEqual(widest, 30, "lots on the full sand at the widest noise: main's 30");+ }++ /// <summary>The map's lots (TheSettlementsOwnLotsStayOffTheDuneSand) whose centre is on the full sand of the coast.png at+ /// <paramref name="coastPath"/>: at any noise width, at the widest, and the places they belong to (sorted).</summary>+ internal static (int any, int widest, List<string> places) LotsOnTheSand(string coastPath)+ {+ var map = OpenMap();+ var g = Ground(map);+ foreach (var (line, half) in Corridors(map)) g.AddCorridor(line, half);+ var doc = LoadLocalities(map);+ var built = SettlementKits.Build(map.Settlements, doc.Places.Select(p => p.Settlement).ToList(), doc.Encampments, g);+ foreach (var k in built.Towns) Object.DestroyImmediate(k.mesh);+ foreach (var t in built.Tiles) Object.DestroyImmediate(t.mesh);+ Assert.Greater(built.Claimed.Count, 3000, "the whole map's lots");+ var coast = new Texture2D(2, 2);+ try+ {+ Assert.IsTrue(coast.LoadImage(System.IO.File.ReadAllBytes(coastPath)));+ int any = 0, widest = 0; var places = new SortedSet<string>(System.StringComparer.Ordinal);+ foreach (var (c, _, id) in built.Claimed)+ {+ float d = (coast.GetPixelBilinear(c.x / g.Width, c.y / g.Length).r - 0.5f) * 2f * 12000f; // ScCoastRangeM+ if (d <= 0f || d >= 0.55f * 1.4f * 900f) continue;+ if (g.SeaDistance(c.x, c.y, 3000f) == float.MaxValue) continue; // a lake: no sand drawn+ widest++; if (d < 0.55f * 0.6f * 900f) any++;+ places.Add(id);+ }+ return (any, widest, places.ToList());+ }+ finally { Object.DestroyImmediate(coast); }+ }+/// <summary>#317: nothing stands in a lake's drawn water. Read from coast.png itself (the file the water shader samples,/// decoded here because the import is not CPU-readable): no tree trunk and no building's or landmark's lot centre in the/// rift (a lake hex, or ground below MapBuilder.LakeBelowM) lies where the drawn water covers the ground (coast belowdiff --git a/unity/Assets/Tests/EditMode/SeaTests.cs b/unity/Assets/Tests/EditMode/SeaTests.csindex da77c25f1..a766a2f5e 100644--- a/unity/Assets/Tests/EditMode/SeaTests.cs+++ b/unity/Assets/Tests/EditMode/SeaTests.cs@@ -279,6 +279,39 @@ public class SeaTestsAssert.Greater(b.b / b.g, 0.62f, "sand, not the plain's yellow-green");}+ /// <summary>Sea round 3 (#388, owner 15 October 2026: geographic, about 2.5-3 km, as promo 03 draws south of Jaffa): the+ /// beach is wide on the dune coast and stays narrow under the kurkar. Rendered 2 km inland of the shore (25 texels east of+ /// the first land texel, about 1.85 km across the coast), without the kits: at 31.90 N (south of Jaffa, off Yavne's+ /// dunes; 31.95 N, by Rishon LeZion, is 2.3 km from Nabi Rubin, whose own ground the beach yields to under option (c))+ /// the sample is pale sand by ASandStripLinesTheMediterraneanShore's own floors (luma over 0.72, b/g over 0.62);+ /// at 32.15 N (Herzliya) it is not, as on main, whose 900 m beach is gone by 1.26 km at its widest. That test's third+ /// floor (0.32 over a plain 5 km inland) is not used: 5 km inland south of Jaffa is the pale dune belt's land use, not+ /// Tel Aviv's darker plain.</summary>+ [UnityTest]+ public IEnumerator TheBeachIsWideOnTheDuneCoastAndNarrowUnderTheKurkar()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ Object.FindFirstObjectByType<MapScene>().ConfigureKits(null, null); // the scene is not saved+ var map = OpenMap(reopen: false);+ yield return null;+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();+ Color At(float lat)+ {+ var (col, row) = ShoreTexel(lat);+ Vector3 b = TexelWorld(map, col + 1 + 25, row);+ rig.LookAt = b; rig.Distance = 30000f; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();+ var px = new Vector2[1];+ var r = RenderSample.Render(cam, 960, 540, new[] { b }, px);+ return r.Mean((int)px[0].x, (int)px[0].y, 1);+ }+ bool Sand(Color b) => Luma(b) > 0.72f && b.b / b.g > 0.62f;+ Color south = At(31.90f), north = At(32.15f);+ TestContext.WriteLine($"2 km inland: 31.90 N {south} (luma {Luma(south):0.000}, b/g {south.b / south.g:0.00}); " ++ $"32.15 N {north} (luma {Luma(north):0.000}, b/g {north.b / north.g:0.00})");+ Assert.IsTrue(Sand(south), "the dune coast south of Jaffa: sand 2 km inland");+ Assert.IsFalse(Sand(north), "the kurkar coast at Herzliya: no sand 2 km inland");+ }+/// <summary>The coast.png column of the first water texel west of (34.95 E, lat) and its row; row 0 = south.</summary>static (int col, int row) ShoreTexel(float lat){diff --git a/unity/Assets/Textures/Map/coast.png b/unity/Assets/Textures/Map/coast.pngindex 1bc717461..517745909 100644Binary files a/unity/Assets/Textures/Map/coast.png and b/unity/Assets/Textures/Map/coast.png differ