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.

Camera: keep the view on the map and out of the hills (fixes #174) (#244)

Eyal Golan0a5156da2ee5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index faf519352..745618820 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -147,3 +147,6 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
- "International Standing" keeps to one line on a full-width bar.
- The open sea no longer shows a blocky checker up close (about 6-20 km): its waves now come from smooth gradient noise
on rotated lattices instead of value noise differenced along the map's axes. Presentation only.
+- Panning past the map's edge no longer fills the view with flat land and a hard seam: the camera stops where the view
+ meets the edge of the map, and at close zoom over high ground (the Golan, the Galilee hills) it no longer sinks into
+ the hills. At the overview, where the view is wider than the map, it is centred east to west (#174).
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 05ff6ab2e..bff4508d3 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -2,7 +2,10 @@
Plan: `docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md`. Promo targets: `promo/final/03-gameplay-1936.png`,
`promo/final/02-map-diorama.png`. Poses: `PromoPose.Gameplay03` (34.86 E, 32.00 N, 60 km, yaw 10) and
-`PromoPose.Diorama02` (35.05 E, 31.55 N, 250 km, yaw 0).
+`PromoPose.Diorama02` (35.05 E, 31.55 N, 250 km, yaw 0). Since #174 the camera keeps its view on the map, and centres
+it east to west wherever the view is wider than the map. In the player, which runs that fit every frame, diorama02 can
+shift by up to a few hundred metres from its pose. The controller accepted this (owner-delegated). The other poses do
+not move.
## How to measure
- Frame time: `?vprofile` (WebGL) or `-vprofile` (desktop player, quits when done), always under
diff --git a/unity/Assets/Scripts/Map/CameraController.cs b/unity/Assets/Scripts/Map/CameraController.cs
index 185ab3006..974a46def 100644
--- a/unity/Assets/Scripts/Map/CameraController.cs
+++ b/unity/Assets/Scripts/Map/CameraController.cs
@@ -19,7 +19,10 @@ namespace Statecraft.Game.Map
/// <summary>Pans, zooms and orbits the diorama camera from the project-wide "Camera" action map (Input System only).
/// While the pointer is over the UI (IsOverUi, wired by the scene) the wheel and the drag belong to the UI; keyboard pan
/// and orbit still move the camera (plan amendment A4). Pan speed scales with
- /// distance, zoom is clamped to [MinDistance, MaxDistance], and the look-at point stays on the map.</summary>
+ /// distance, zoom is clamped to [MinDistance, MaxDistance], and the view stays on the map (issue #174): the look-at
+ /// point is held far enough inside the map that the visible ground does not leave it, so the border skirt never fills
+ /// the view at gameplay zoom. Where the view is wider than the map (the overview), it is centred on the map instead.
+ /// Given the ground's height (Ground), the camera also never sinks into the terrain (MinClearanceShare).</summary>
[RequireComponent(typeof(CameraRig))]
public sealed class CameraController : MonoBehaviour
{
@@ -31,11 +34,22 @@ namespace Statecraft.Game.Map
public const float ZoomPerStep = 0.1f; // fraction of the distance per wheel notch
public const float OrbitDegreesPerSecond = 60f;
public const float MaxFrameSeconds = 0.1f; // a stalled frame (tab in the background) must not fling the camera
+ /// <summary>The least height above the ground beneath it the camera keeps, as a share of its height above the
+ /// look-at plane (y = 0). Issue #174: the look-at point lies on y = 0, the terrain's lowest point, but high ground is
+ /// several km above it at 3x relief (the Golan edge about 6 km), so at the hero zoom (camera 4.6 km up) the camera
+ /// sat inside the hills and showed only haze. Below this share the look-at point is lifted just enough; above it
+ /// nothing changes. The promo and close-check poses all keep more (hero06judea, the least, 24%).</summary>
+ public const float MinClearanceShare = 0.2f;
/// <summary>Answers "is the pointer over the UI?" for a screen position (y up). Null = never.</summary>
public Func<Vector2, bool>? IsOverUi;
- /// <summary>The map rectangle on the ground (x, z), in world metres; the look-at point is clamped to it.</summary>
+ /// <summary>The map rectangle on the ground (x, z), in world metres; the view is kept inside it (Step).</summary>
public Rect Bounds = new Rect(0, 0, float.MaxValue, float.MaxValue);
+ /// <summary>The ground's world height at a point (x, z), or null for none (the camera then keeps to y = 0).</summary>
+ public Func<Vector2, float>? Ground;
+ /// <summary>The highest the ground (and the border skirt, which holds the edge's height) reaches in world y: with it,
+ /// ViewFootprint bounds the near side of the view tightly. ShadowFit.GroundY (the default) means flat ground.</summary>
+ public float GroundTop = ShadowFit.GroundY;
CameraRig rig = null!;
InputAction? pan, dragPan, zoom, orbit;
@@ -61,9 +75,13 @@ namespace Statecraft.Game.Map
Vector2? pointer = Pointer.current != null ? Pointer.current.position.ReadValue() : (Vector2?)null;
var down = Mouse.current != null && Mouse.current.rightButton.isPressed;
Step(rig, Gather(pan.ReadValue<Vector2>(), dragPan.ReadValue<Vector2>(), zoom.ReadValue<float>(),
- orbit.ReadValue<float>(), down, pointer), ClampDt(Time.unscaledDeltaTime), Bounds);
+ orbit.ReadValue<float>(), down, pointer), ClampDt(Time.unscaledDeltaTime), Bounds, Ground, GroundTop);
}
+ /// <summary>Fits the rig's current pose with no input (review B-m3: a minimap jump goes through the same view fit and
+ /// ground clearance as panning, so no frame shows the skirt or the inside of a hill).</summary>
+ public void Settle() => Step(GetComponent<CameraRig>(), default, 0f, Bounds, Ground, GroundTop);
+
public static float ClampDt(float dt) => Mathf.Min(dt, MaxFrameSeconds);
/// <summary>Builds one frame of input from raw action values. The wheel is checked against the UI at the pointer every frame;
@@ -84,8 +102,10 @@ namespace Statecraft.Game.Map
};
}
- /// <summary>Applies one frame of input to the rig and calls rig.Apply(). Pure apart from the rig, so it is testable.</summary>
- public static void Step(CameraRig rig, CameraInput input, float dt, Rect bounds)
+ /// <summary>Applies one frame of input to the rig and calls rig.Apply(). Pure apart from the rig (and the ground's
+ /// height, when given), so it is testable. <paramref name="groundTop"/>: see GroundTop.</summary>
+ public static void Step(CameraRig rig, CameraInput input, float dt, Rect bounds, Func<Vector2, float>? ground = null,
+ float groundTop = ShadowFit.GroundY)
{
var zoom = input.OverUi ? 0f : input.Zoom;
var drag = input.DragFromUi ? Vector2.zero : input.DragPan;
@@ -96,8 +116,100 @@ namespace Statecraft.Game.Map
var move = input.Pan * (PanPerSecond * dt) - drag * DragPanPerPixel;
var delta = yaw * new Vector3(move.x, 0, move.y) * rig.Distance;
var p = rig.LookAt + delta;
- rig.LookAt = new Vector3(Mathf.Clamp(p.x, bounds.xMin, bounds.xMax), p.y, Mathf.Clamp(p.z, bounds.yMin, bounds.yMax));
+ // Issue #174: clamping only the look-at point let up to three quarters of the view (at a corner) show the border
+ // skirt, whose land is a flat slab with a hard seam against the terrain. The view's ground footprint around the
+ // look-at point depends on the distance, yaw, aspect and top inset, not on where the point is, so it is measured
+ // once at this frame's pose and the point is held where the whole footprint stays on the map.
+ // With the ground given, the look-at point's height is the lift (Lift) over y = 0, measured afresh each frame; the
+ // footprint is measured at the lifted pose (a higher camera sees farther on y = 0), so the fit runs twice. Both
+ // passes are pose maths on the projection alone; the transform, tilt-shift and shadow fit are applied once.
+ float y = ground == null ? p.y : 0f;
+ rig.ApplyProjection();
+ for (int pass = 0; pass < (ground == null ? 1 : 2); pass++)
+ {
+ rig.LookAt = new Vector3(p.x, y, p.z);
+ var view = ViewFootprint(rig, groundTop);
+ var fitted = new Vector3(Fit(p.x, bounds.xMin, bounds.xMax, view.xMin, view.xMax), 0f,
+ Fit(p.z, bounds.yMin, bounds.yMax, view.yMin, view.yMax));
+ if (ground != null) y = Lift(rig, fitted, ground);
+ rig.LookAt = new Vector3(fitted.x, y, fitted.z);
+ }
rig.Apply();
}
+
+ /// <summary>The terrain's world height at (x, z), clamped to its edge outside it (the border skirt holds the edge's
+ /// height near the map, so the camera keeps clear of it too).</summary>
+ public static Func<Vector2, float> GroundOf(Terrain terrain)
+ {
+ var origin = terrain.transform.position; var size = terrain.terrainData.size;
+ return p => origin.y + terrain.SampleHeight(new Vector3(Mathf.Clamp(p.x, origin.x, origin.x + size.x), 0f,
+ Mathf.Clamp(p.y, origin.z, origin.z + size.z)));
+ }
+
+ /// <summary>How far to lift a look-at point on y = 0 so the camera keeps MinClearanceShare of its height above the
+ /// ground beneath it (0 where it already does).</summary>
+ public static float Lift(CameraRig rig, Vector3 lookAt, Func<Vector2, float> ground)
+ {
+ var rot = Quaternion.Euler(CameraRig.Pitch, rig.Yaw, 0);
+ var cam = new Vector3(lookAt.x, 0f, lookAt.z) - rot * Vector3.forward * rig.Distance;
+ float height = cam.y, below = ground(new Vector2(cam.x, cam.z));
+ return Mathf.Max(0f, below + MinClearanceShare * height - height);
+ }
+
+ /// <summary>Corners of the visible map area in viewport units: the top inset's band is covered by the UI.</summary>
+ static readonly Vector2[] FootprintCorners = { new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(0f, 1f), new Vector2(1f, 1f) };
+
+ /// <summary>The terrain's highest world y (TerrainData.bounds holds the heightmap's actual range); the border skirt
+ /// never rises above its edge, so this bounds it too.</summary>
+ public static float GroundTopOf(Terrain terrain) => terrain.transform.position.y + terrain.terrainData.bounds.max.y;
+
+ /// <summary>The ground the rig's camera shows, as offsets (x, z) from the look-at point. Every ground point the view
+ /// shows lies between y = ShadowFit.GroundY (the terrain's lowest point) and y = <paramref name="groundTop"/> (its
+ /// highest), so each corner ray of the visible area (below the top inset) meets it on the segment between its hits on
+ /// those two planes (from the camera itself where the camera is below the top plane); seen from above, everything
+ /// visible lies in the bounding box of those eight points (the frustum meets each plane in a convex quad). Bounding
+ /// only by the y = 0 hits missed high ground on the near side (just behind the south edge the whole 6 km view was
+ /// skirt); bounding by the point below the camera instead hid the map's southern 19-20 km at 60 km (review B-I1).
+ /// A rig without a camera shows a point (Rect.zero); a corner that does not look down gives an infinite box. Worked
+ /// from the rig's pose relative to the look-at point and the camera's projection matrix (aspect, FOV, the inset's
+ /// shift; set by ApplyProjection), not Camera.ViewportPointToRay: that unprojects through the 1000 km far plane in
+ /// world coordinates, and its rays strayed by up to kilometres (measured: 0.25-4 km).</summary>
+ public static Rect ViewFootprint(CameraRig rig, float groundTop = ShadowFit.GroundY)
+ {
+ var cam = rig.GetComponent<Camera>();
+ if (cam == null) return Rect.zero;
+ var rot = Quaternion.Euler(CameraRig.Pitch, rig.Yaw, 0);
+ var eye = -(rot * Vector3.forward) * rig.Distance; // the camera, relative to the look-at point
+ float camY = rig.LookAt.y + eye.y;
+ // NDC x = m00 x / -z - m02, NDC y = m11 y / -z - m12 (CameraRig.ApplyProjection): one unit ahead, the ray through (x, y).
+ var m = cam.projectionMatrix;
+ float top = 1f - Mathf.Clamp(rig.TopInset, 0f, CameraRig.MaxTopInset);
+ float x0 = float.PositiveInfinity, x1 = float.NegativeInfinity, z0 = float.PositiveInfinity, z1 = float.NegativeInfinity;
+ foreach (var c in FootprintCorners)
+ {
+ float nx = 2f * c.x - 1f, ny = 2f * c.y * top - 1f;
+ var dir = rot * new Vector3((nx + m[0, 2]) / m[0, 0], (ny + m[1, 2]) / m[1, 1], 1f);
+ if (dir.y > -1e-4f)
+ return Rect.MinMaxRect(float.NegativeInfinity, float.NegativeInfinity, float.PositiveInfinity, float.PositiveInfinity);
+ Add(ShadowFit.GroundY); Add(Mathf.Max(groundTop, ShadowFit.GroundY));
+
+ void Add(float planeY)
+ {
+ var hit = eye + dir * Mathf.Max(0f, (planeY - camY) / dir.y);
+ x0 = Mathf.Min(x0, hit.x); x1 = Mathf.Max(x1, hit.x); z0 = Mathf.Min(z0, hit.z); z1 = Mathf.Max(z1, hit.z);
+ }
+ }
+ return Rect.MinMaxRect(x0, z0, x1, z1);
+ }
+
+ /// <summary>One axis of the look-at point: within [lo, hi] such that [v + viewMin, v + viewMax] stays in it. A view
+ /// wider than the map is centred on it (continuous as the view grows, so zooming out never jumps); an unbounded
+ /// view falls back to keeping the point itself on the map.</summary>
+ static float Fit(float v, float lo, float hi, float viewMin, float viewMax)
+ {
+ float a = lo - viewMin, b = hi - viewMax;
+ if (a <= b) return Mathf.Clamp(v, a, b);
+ return float.IsInfinity(a) || float.IsInfinity(b) || float.IsNaN(a) || float.IsNaN(b) ? Mathf.Clamp(v, lo, hi) : 0.5f * (a + b);
+ }
}
}
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 501b6df3d..31f676004 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -169,8 +169,11 @@ namespace Statecraft.Game.UI
var terrain = map.Terrain;
var size = terrain.terrainData.size;
var oldBounds = cameraController.Bounds;
+ var oldGround = cameraController.Ground; var oldTop = cameraController.GroundTop;
cameraController.IsOverUi = overUi;
cameraController.Bounds = new Rect(terrain.transform.position.x, terrain.transform.position.z, size.x, size.z);
+ cameraController.Ground = CameraController.GroundOf(terrain);
+ cameraController.GroundTop = CameraController.GroundTopOf(terrain);
pointer.Map = map;
pointer.IsOverUi = overUi;
Action<int, int> onHex = info.Show;
@@ -179,7 +182,7 @@ namespace Statecraft.Game.UI
Own(new TopBarInset(root, camRig)); // the map is framed below the top bar
var mini = minimap = Own(new MinimapPresenter(root, map.Hexes));
labels = Own(new MapLabelsPresenter(root, map, cameraController.GetComponent<Camera>()));
- mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); camRig.Apply(); SyncMinimap(); labels?.Refresh(); }; // the click may come after LateUpdate (review M6)
+ mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); cameraController.Settle(); SyncMinimap(); labels?.Refresh(); }; // the click may come after LateUpdate (review M6)
Action onChanged = RenderPlacementsIfChanged;
bridge.Changed += onChanged;
// One console line per turn, so a browser run (reload, Continue) can be checked against the hash.
@@ -197,6 +200,7 @@ namespace Statecraft.Game.UI
if (cameraController.IsOverUi == overUi) cameraController.IsOverUi = null;
if (pointer.Map == map) pointer.Map = null;
cameraController.Bounds = oldBounds;
+ cameraController.Ground = oldGround; cameraController.GroundTop = oldTop;
}));
drawn = null;
RenderPlacementsIfChanged();
diff --git a/unity/Assets/Tests/EditMode/CameraInputTests.cs b/unity/Assets/Tests/EditMode/CameraInputTests.cs
index 1951307aa..01a88f86c 100644
--- a/unity/Assets/Tests/EditMode/CameraInputTests.cs
+++ b/unity/Assets/Tests/EditMode/CameraInputTests.cs
@@ -11,11 +11,15 @@ public class CameraInputTests
{
var go = new GameObject("RigTest", typeof(Camera));
var rig = go.AddComponent<CameraRig>();
- rig.LookAt = new Vector3(50000, 0, 50000); rig.Distance = 100000f;
+ rig.LookAt = new Vector3(500000, 0, 500000); rig.Distance = 100000f;
return rig;
}
- static readonly Rect Map = new Rect(0, 0, 160000, 430000);
+ /// <summary>A map far larger than the view, so the input tests below never meet the view clamp (issue #174), which
+ /// the edge tests further down check on a map the size of the real one.</summary>
+ static readonly Rect Map = new Rect(0, 0, 1000000, 1000000);
+ /// <summary>The real terrain's size (heightmap.json: 161.5 x 431.2 km).</summary>
+ static readonly Rect RealMap = new Rect(0, 0, 161529f, 431223f);
[Test]
public void TheCameraActionMapIsInTheProjectWideAsset()
@@ -50,8 +54,8 @@ public class CameraInputTests
try
{
CameraController.Step(rig, new CameraInput { Pan = Vector2.up }, 0.5f, Map);
- Assert.AreEqual(50000f, rig.LookAt.x, 1e-2);
- Assert.AreEqual(50000f + 0.4f * 100000f, rig.LookAt.z, 1e-1); // 0.8 distances per second for half a second
+ Assert.AreEqual(500000f, rig.LookAt.x, 1e-2);
+ Assert.AreEqual(500000f + 0.4f * 100000f, rig.LookAt.z, 1e-1); // 0.8 distances per second for half a second
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
@@ -67,8 +71,9 @@ public class CameraInputTests
CameraController.Step(rig, new CameraInput { Orbit = 1 }, 0.5f, Map);
Assert.AreEqual(30f, rig.Yaw, 1e-3);
Assert.AreEqual(30f, rig.transform.eulerAngles.y, 1e-3);
- CameraController.Step(rig, new CameraInput { Pan = Vector2.left }, 100f, Map);
- Assert.AreEqual(0f, rig.LookAt.x, 1e-3); // clamped to the map edge
+ CameraController.Step(rig, new CameraInput { Pan = Vector2.left }, 1000f, Map);
+ // Clamped so the view's west edge is the map's (issue #174), not the look-at point.
+ Assert.AreEqual(Map.xMin, rig.LookAt.x + CameraController.ViewFootprint(rig).xMin, 1f);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
@@ -98,7 +103,7 @@ public class CameraInputTests
CameraController.Step(rig, new CameraInput { Pan = Vector2.up, Orbit = 1, Zoom = 1, OverUi = true }, 0.5f, Map);
Assert.AreEqual(100000f, rig.Distance, 1e-3); // the wheel was over the UI
Assert.AreEqual(30f, rig.Yaw, 1e-3);
- Assert.Greater(rig.LookAt.z, 50000f);
+ Assert.Greater(rig.LookAt.z, 500000f);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
@@ -126,8 +131,8 @@ public class CameraInputTests
{
rig.Yaw = 90f; // looking east: forward is +x
CameraController.Step(rig, new CameraInput { Pan = Vector2.up }, 0.5f, Map);
- Assert.AreEqual(50000f + 0.4f * 100000f, rig.LookAt.x, 1f);
- Assert.AreEqual(50000f, rig.LookAt.z, 1f);
+ Assert.AreEqual(500000f + 0.4f * 100000f, rig.LookAt.x, 1f);
+ Assert.AreEqual(500000f, rig.LookAt.z, 1f);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
@@ -180,6 +185,141 @@ public class CameraInputTests
finally { Object.DestroyImmediate(a.gameObject); Object.DestroyImmediate(b.gameObject); }
}
+ /// <summary>The view's ground on the map at the rig's current pose: [look-at + footprint] inside the map, within tol.</summary>
+ static void AssertViewOnMap(CameraRig rig, Rect map, string what, float tol = 1f)
+ {
+ var f = CameraController.ViewFootprint(rig);
+ Assert.GreaterOrEqual(rig.LookAt.x + f.xMin, map.xMin - tol, what + ": west");
+ Assert.LessOrEqual(rig.LookAt.x + f.xMax, map.xMax + tol, what + ": east");
+ Assert.GreaterOrEqual(rig.LookAt.z + f.yMin, map.yMin - tol, what + ": south");
+ Assert.LessOrEqual(rig.LookAt.z + f.yMax, map.yMax + tol, what + ": north");
+ }
+
+ /// <summary>Issue #174: panning past a corner at gameplay zoom stops where the view's edges meet the map's, at every
+ /// yaw and with the top bar's inset, so the border skirt never shows. (The look-at clamp alone left 3/4 of the view on it.)</summary>
+ [Test]
+ public void PanningPastACornerKeepsTheViewOnTheMap()
+ {
+ var rig = NewRig();
+ try
+ {
+ var cam = rig.GetComponent<Camera>(); cam.aspect = 16f / 9f; cam.fieldOfView = CameraRig.Fov; // the game's view (Init is not run here)
+ foreach (var d in new[] { CameraController.MinDistance, 30000f, 60000f })
+ foreach (var yaw in new[] { 0f, 45f, 90f, 200f })
+ foreach (var inset in new[] { 0f, 0.1f })
+ foreach (var dir in new[] { new Vector2(1, 1), new Vector2(-1, 1), new Vector2(1, -1), new Vector2(-1, -1) })
+ {
+ rig.LookAt = new Vector3(RealMap.center.x, 0, RealMap.center.y); rig.Distance = d; rig.Yaw = yaw; rig.TopInset = inset;
+ var what = $"{d / 1000f} km, yaw {yaw}, inset {inset}, pan {dir}";
+ for (int i = 0; i < 120; i++) CameraController.Step(rig, new CameraInput { Pan = dir }, 0.5f, RealMap);
+ AssertViewOnMap(rig, RealMap, what);
+ // and it got there: the view touches the map's edge on at least one side
+ var f = CameraController.ViewFootprint(rig);
+ float gap = Mathf.Min(Mathf.Abs(rig.LookAt.x + f.xMin - RealMap.xMin), Mathf.Abs(rig.LookAt.x + f.xMax - RealMap.xMax),
+ Mathf.Abs(rig.LookAt.z + f.yMin - RealMap.yMin), Mathf.Abs(rig.LookAt.z + f.yMax - RealMap.yMax));
+ Assert.Less(gap, 1f, what + ": the pan reached the edge");
+ }
+ }
+ finally { Object.DestroyImmediate(rig.gameObject); }
+ }
+
+ /// <summary>Issue #174: where the view is wider than the map (the overview), it is centred on the map on that axis, and
+ /// zooming out at the edge moves the view smoothly rather than jumping (the clamp narrows to the centre continuously).</summary>
+ [Test]
+ public void AViewWiderThanTheMapIsCentredAndZoomingOutNeverJumps()
+ {
+ var rig = NewRig();
+ try
+ {
+ var cam = rig.GetComponent<Camera>(); cam.aspect = 16f / 9f; cam.fieldOfView = CameraRig.Fov; // the game's view (Init is not run here)
+ rig.LookAt = new Vector3(RealMap.xMax, 0, RealMap.center.y); rig.Distance = CameraController.MinDistance; rig.Yaw = 0;
+ CameraController.Step(rig, new CameraInput { Pan = Vector2.right }, 10f, RealMap);
+ float worst = 0f;
+ while (rig.Distance < CameraController.MaxDistance - 1f)
+ {
+ var before = rig.LookAt;
+ CameraController.Step(rig, new CameraInput { Zoom = -0.2f, Pan = Vector2.right }, 0.016f, RealMap);
+ // a frame's pan alone moves 0.8 * 0.016 distances; the clamp may add the view's growth, a few % of it
+ worst = Mathf.Max(worst, (rig.LookAt - before).magnitude / rig.Distance);
+ if (CameraController.ViewFootprint(rig).width <= RealMap.width)
+ AssertViewOnMap(rig, RealMap, $"{rig.Distance / 1000f:0} km");
+ }
+ Assert.Less(worst, 0.05f, "no jump while zooming out at the edge");
+ var f = CameraController.ViewFootprint(rig);
+ Assert.Greater(f.width, RealMap.width, "at the overview the view is wider than the map");
+ Assert.AreEqual(RealMap.center.x, rig.LookAt.x + f.center.x, 1f, "so it is centred on the map");
+ }
+ finally { Object.DestroyImmediate(rig.gameObject); }
+ }
+
+ /// <summary>Issue #174: over low ground the look-at point stays on y = 0 (the approved framing); over ground high enough
+ /// to come within MinClearanceShare of the camera, it is lifted just enough, and dropped again on the way back down.</summary>
+ [Test]
+ public void TheCameraIsLiftedOnlyOverHighGround()
+ {
+ var rig = NewRig();
+ try
+ {
+ rig.Distance = CameraController.MinDistance;
+ float height = rig.Distance * Mathf.Sin(CameraRig.Pitch * Mathf.Deg2Rad);
+ float groundY = 0f;
+ System.Func<Vector2, float> ground = _ => groundY;
+ foreach (var g in new[] { 0f, 0.5f, 0.79f, 0.9f, 1.3f, 0.3f })
+ {
+ groundY = g * height;
+ CameraController.Step(rig, new CameraInput(), 0f, Map, ground);
+ float clearance = rig.transform.position.y - groundY;
+ if (g <= 1f - CameraController.MinClearanceShare)
+ Assert.AreEqual(0f, rig.LookAt.y, 1e-3, $"ground at {g} of the camera's height: no lift");
+ else
+ Assert.AreEqual(CameraController.MinClearanceShare * height, clearance, 1f, $"ground at {g}: lifted to the least clearance");
+ }
+ }
+ finally { Object.DestroyImmediate(rig.gameObject); }
+ }
+
+ /// <summary>Review B-I1: with the ground's top given, the near side of the view is bounded by the corner rays' hits on
+ /// that plane, not by the point below the camera: at 60 km, pushed to the south edge, the camera may stand behind the
+ /// edge, and the strip kept off screen is a few km (it was 19-20 km). With the camera below the top plane (the hero
+ /// zoom over high ground) the point below the camera is the bound.</summary>
+ [Test]
+ public void TheNearSideIsBoundedByTheGroundsTopNotTheCamera()
+ {
+ var rig = NewRig();
+ try
+ {
+ var cam = rig.GetComponent<Camera>(); cam.aspect = 16f / 9f; cam.fieldOfView = CameraRig.Fov;
+ const float top = 8400f; // about the real terrain's highest point (2367 m + 427 m, at 3x)
+ float back = Mathf.Cos(CameraRig.Pitch * Mathf.Deg2Rad); // the camera is this many distances behind the look-at point
+ rig.LookAt = new Vector3(RealMap.center.x, 0, RealMap.center.y); rig.Distance = 60000f; rig.Yaw = 0; rig.TopInset = 0;
+ for (int i = 0; i < 60; i++) CameraController.Step(rig, new CameraInput { Pan = Vector2.down }, 0.5f, RealMap, _ => 0f, top);
+ var f = CameraController.ViewFootprint(rig, top);
+ Assert.AreEqual(RealMap.yMin, rig.LookAt.z + f.yMin, 1f, "the view's near side at the south edge");
+ Assert.Less(rig.LookAt.z, back * rig.Distance - 10000f, "the camera stands behind the edge: the edge rows stay reachable");
+ var flat = CameraController.ViewFootprint(rig);
+ Assert.Less(flat.yMin - f.yMin, 5000f, "the high-ground margin at 60 km is a few km");
+ Assert.Greater(flat.yMin - f.yMin, 1000f, "and it is there");
+ rig.Distance = CameraController.MinDistance; rig.ApplyProjection(); // camera 4.6 km up, below the 8.4 km plane
+ Assert.AreEqual(-back * rig.Distance, CameraController.ViewFootprint(rig, top).yMin, 1f, "the point below the camera bounds it");
+ }
+ finally { Object.DestroyImmediate(rig.gameObject); }
+ }
+
+ /// <summary>A rig without a camera keeps the old rule: the look-at point itself stays on the map.</summary>
+ [Test]
+ public void ARigWithoutACameraClampsTheLookAtPoint()
+ {
+ var go = new GameObject("BareRig");
+ try
+ {
+ var rig = go.AddComponent<CameraRig>(); rig.LookAt = new Vector3(100, 0, 100); rig.Distance = 6000f;
+ Assert.AreEqual(Rect.zero, CameraController.ViewFootprint(rig));
+ CameraController.Step(rig, new CameraInput { Pan = Vector2.left }, 10f, RealMap);
+ Assert.AreEqual(0f, rig.LookAt.x, 1e-3);
+ }
+ finally { Object.DestroyImmediate(go); }
+ }
+
static CameraController NewController(out GameObject go)
{
go = new GameObject("CtlTest", typeof(Camera));
diff --git a/unity/Assets/Tests/EditMode/MapEdgeTests.cs b/unity/Assets/Tests/EditMode/MapEdgeTests.cs
new file mode 100644
index 000000000..a144f944a
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MapEdgeTests.cs
@@ -0,0 +1,196 @@
+using System.Collections;
+using System.IO;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.TestTools;
+
+/// <summary>Issue #174 (integration bug B11): panning past the terrain's edge filled the view with flat fills and a hard
+/// seam. Two causes: the look-at clamp let the view run off the map onto the border skirt (a flat slab), and at the high
+/// north-east corner (the ground about 6 km up at 3x relief) the hero-zoom camera, 4.6 km above the look-at plane y = 0,
+/// sat inside the hills and showed only haze. Rendered at the worst pan pose: the hero zoom pushed into each corner of the
+/// map, through the same CameraController.Step the game runs every frame, with the bounds and ground GameRoot gives it.</summary>
+public class MapEdgeTests
+{
+ const int W = 1600, H = 900;
+
+ [SetUp] public void FreshScene() => EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ [TearDown] public void DiscardScene() => EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+
+ /// <summary>The camera bounds as GameRoot sets them: the terrain's footprint (and CameraController.GroundOf and
+ /// GroundTopOf its ground).</summary>
+ static Rect Bounds(MapScene map)
+ {
+ var t = map.Terrain; var size = t.terrainData.size;
+ return new Rect(t.transform.position.x, t.transform.position.z, size.x, size.z);
+ }
+
+ /// <summary>Where the renders are written (the before/after images for the issue): the project's Logs folder (git-ignored;
+ /// Unity empties Temp when it quits).</summary>
+ static string ShotDir => Path.Combine(Path.GetDirectoryName(Application.dataPath), "Logs", "map-edge");
+
+ [UnityTest]
+ public IEnumerator PanningIntoACornerShowsNoSkirtSeamOrFlatFill()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build();
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();
+ var skirt = map.Terrain.transform.Find(MapScene.BorderSkirtName).GetComponent<MeshRenderer>();
+ var bounds = Bounds(map); var ground = CameraController.GroundOf(map.Terrain); var top = CameraController.GroundTopOf(map.Terrain);
+ var rt = new RenderTexture(W, H, 24);
+ Directory.CreateDirectory(ShotDir);
+ RenderSample.TiltShift(false); // a colour test: the blur spreads pixels across the frame
+ try
+ {
+ cam.targetTexture = rt; // the clamp measures the view at the render's aspect
+ yield return null;
+ var failures = new System.Collections.Generic.List<string>();
+ foreach (var (name, corner, push) in new[]
+ {
+ ("ne", new Vector2(bounds.xMax, bounds.yMax), new Vector2(1, 1)), ("nw", new Vector2(bounds.xMin, bounds.yMax), new Vector2(-1, 1)),
+ ("se", new Vector2(bounds.xMax, bounds.yMin), new Vector2(1, -1)), ("sw", new Vector2(bounds.xMin, bounds.yMin), new Vector2(-1, -1)),
+ })
+ {
+ rig.LookAt = new Vector3(corner.x, 0, corner.y); rig.Distance = CameraController.MinDistance; rig.Yaw = 0; rig.TopInset = 0;
+ for (int i = 0; i < 20; i++) CameraController.Step(rig, new CameraInput { Pan = push }, CameraController.MaxFrameSeconds, bounds, ground, top);
+ var with = RenderSample.Render(cam, W, H);
+ skirt.enabled = false;
+ var without = RenderSample.Render(cam, W, H);
+ skirt.enabled = true;
+ map.Terrain.enabled = false;
+ var noTerrain = RenderSample.Render(cam, W, H);
+ map.Terrain.enabled = true;
+ File.WriteAllBytes(Path.Combine(ShotDir, $"edge-{name}.png"), Png(with));
+
+ // 1. The skirt draws no pixel of the view: hiding it changes nothing.
+ // 2. No flat fill: the terrain draws (nearly) every pixel, so hiding it changes them. Before the fix, at the
+ // north-east corner the camera sat inside the hills and nothing drew: 0% (haze over the clear colour). Kits
+ // and trees standing in front of the ground are the only pixels allowed to stay.
+ int skirtPixels = 0, terrainPixels = 0;
+ for (int i = 0; i < with.Pixels.Length; i++)
+ {
+ if (Differs(with.Pixels[i], without.Pixels[i])) skirtPixels++;
+ if (Differs(with.Pixels[i], noTerrain.Pixels[i])) terrainPixels++;
+ }
+ float terrainShare = (float)terrainPixels / with.Pixels.Length;
+ TestContext.WriteLine($"{name}: look-at ({rig.LookAt.x:0}, {rig.LookAt.y:0}, {rig.LookAt.z:0}) of ({bounds.xMax:0}, {bounds.yMax:0}); " +
+ $"camera {rig.transform.position.y:0} over ground {ground(new Vector2(rig.transform.position.x, rig.transform.position.z)):0}; " +
+ $"skirt pixels {skirtPixels}; terrain {100f * terrainShare:0.00}% of the view");
+ if (skirtPixels > 0) failures.Add($"{name} corner: the border skirt shows in {skirtPixels} pixels");
+ if (terrainShare <= MinTerrainShare) failures.Add($"{name} corner: the terrain draws only {100f * terrainShare:0.0}% of the view (a flat fill)");
+ }
+ Assert.IsEmpty(failures, string.Join("; ", failures)); // every corner checked and written before failing
+ }
+ finally
+ {
+ RenderSample.TiltShift(true);
+ skirt.enabled = true; map.Terrain.enabled = true;
+ cam.targetTexture = null; rt.Release(); Object.DestroyImmediate(rt);
+ }
+ }
+
+ /// <summary>The least share of the view the terrain must draw at the corner poses (kits and trees may cover the rest).</summary>
+ const float MinTerrainShare = 0.95f;
+
+ static bool Differs(Color a, Color b) => Mathf.Max(Mathf.Abs(a.r - b.r), Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b)) > 2.5f / 255f;
+
+ static byte[] Png(RenderSample s)
+ {
+ var tex = new Texture2D(s.Width, s.Height, TextureFormat.RGB24, false);
+ try { tex.SetPixels(s.Pixels); tex.Apply(); return tex.EncodeToPNG(); }
+ finally { Object.DestroyImmediate(tex); }
+ }
+
+ /// <summary>The promo and close-check poses already frame only the map where the view fits it, so the clamp leaves
+ /// them where they are (the shots in the WebGL player run through Step every frame); diorama02, wider than the map,
+ /// is centred on it east to west, at most a few hundred metres from its pose (accepted: controller ruling, owner-delegated).</summary>
+ [Test]
+ public void ThePromoPosesStayPut()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build();
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();
+ cam.aspect = 16f / 9f;
+ try
+ {
+ foreach (var pose in new System.Collections.Generic.List<PromoPose>(PromoPose.All) { PromoPose.CloseChecks[0], PromoPose.CloseChecks[1] })
+ {
+ pose.Apply(rig, map.Frame); rig.TopInset = 0;
+ var before = rig.LookAt;
+ CameraController.Step(rig, new CameraInput(), 0f, Bounds(map), CameraController.GroundOf(map.Terrain), CameraController.GroundTopOf(map.Terrain));
+ float moved = (rig.LookAt - before).magnitude;
+ TestContext.WriteLine($"{pose.Name}: moved {moved:0} m");
+ Assert.Less(moved, pose.Distance > 100000f ? 1000f : 1f, pose.Name);
+ }
+ }
+ finally { cam.ResetAspect(); }
+ }
+
+ /// <summary>Issue #174: at the hero zoom, anywhere on the map and at any yaw, the camera keeps MinClearanceShare of its
+ /// height above the ground beneath it, so it never sits inside the hills (before, about 6% of the map put it underground).</summary>
+ [Test]
+ public void TheCameraNeverSinksIntoTheGround()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build();
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();
+ cam.aspect = 16f / 9f;
+ var bounds = Bounds(map); var ground = CameraController.GroundOf(map.Terrain); var top = CameraController.GroundTopOf(map.Terrain);
+ try
+ {
+ int lifted = 0, n = 0; float least = float.MaxValue;
+ for (int i = 0; i <= 40; i++)
+ for (int j = 0; j <= 40; j++)
+ foreach (var yaw in new[] { 0f, 120f, 240f })
+ {
+ rig.LookAt = new Vector3(bounds.xMin + bounds.width * i / 40f, 0, bounds.yMin + bounds.height * j / 40f);
+ rig.Distance = CameraController.MinDistance; rig.Yaw = yaw; rig.TopInset = 0;
+ CameraController.Step(rig, new CameraInput(), 0f, bounds, ground, top);
+ var c = rig.transform.position;
+ Assert.LessOrEqual(ground(new Vector2(rig.LookAt.x, rig.LookAt.z)), top + 1f, "GroundTopOf bounds the ground");
+ float height = rig.Distance * Mathf.Sin(CameraRig.Pitch * Mathf.Deg2Rad);
+ float share = (c.y - ground(new Vector2(c.x, c.z))) / height;
+ least = Mathf.Min(least, share); n++;
+ if (rig.LookAt.y > 0f) lifted++;
+ }
+ TestContext.WriteLine($"{n} poses, {lifted} lifted, least clearance {least:0.000} of the camera's height");
+ Assert.GreaterOrEqual(least, CameraController.MinClearanceShare - 1e-3f);
+ Assert.Greater(lifted, 0, "the rule took effect somewhere (the Golan, the Galilee, the Jordanian plateau)");
+ }
+ finally { cam.ResetAspect(); }
+ }
+
+ /// <summary>Review B-I1: the clamp must not hide the map's own edge rows at gameplay zoom. Bounding the near side by the
+ /// point below the camera kept the southern 19-20 km (Umm Rashrash/Eilat, the last four hex rows) off screen at 60 km;
+ /// panning to the edge must bring Eilat on screen looking north, and Metula looking south.</summary>
+ [TestCase("Eilat", 34.95, 29.55, 0f)]
+ [TestCase("Metula", 35.578, 33.28, 180f)]
+ public void PanningToAnEdgeBringsItsTownsOnScreen(string town, double lon, double lat, float yaw)
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build();
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();
+ cam.aspect = 16f / 9f;
+ var bounds = Bounds(map); var ground = CameraController.GroundOf(map.Terrain); var top = CameraController.GroundTopOf(map.Terrain);
+ try
+ {
+ var at = map.Frame.ToWorld(lon, lat, 0); at.y = ground(new Vector2(at.x, at.z));
+ foreach (var inset in new[] { 0f, 0.09f })
+ {
+ rig.LookAt = new Vector3(at.x, 0, bounds.center.y); rig.Distance = PromoPose.Gameplay03.Distance; rig.Yaw = yaw; rig.TopInset = inset;
+ for (int i = 0; i < 100; i++) CameraController.Step(rig, new CameraInput { Pan = Vector2.down }, CameraController.MaxFrameSeconds, bounds, ground, top);
+ var v = cam.WorldToViewportPoint(at);
+ TestContext.WriteLine($"{town}, yaw {yaw}, inset {inset}: look-at {map.Frame.ToLonLat(rig.LookAt)}, viewport {v}");
+ Assert.Greater(v.z, 0f, town);
+ Assert.That(v.x, Is.InRange(0f, 1f), $"{town} across the view (inset {inset})");
+ Assert.That(v.y, Is.InRange(0f, 1f - inset), $"{town} on screen below the bar (inset {inset})");
+ }
+ }
+ finally { cam.ResetAspect(); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/MapEdgeTests.cs.meta b/unity/Assets/Tests/EditMode/MapEdgeTests.cs.meta
new file mode 100644
index 000000000..1e12d87e4
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MapEdgeTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 37adb4bda108044479335350bcb9d3ea
\ No newline at end of file