Skip to content

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

fix(visual): shadows fitted to the view's farthest corner by straight-line distance; lighting restored with the map

eyalgolan7f3e4c3bc117
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 315217a58..2625bc1f5 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -66,19 +66,52 @@ Notes:
`res=1728x860`, with a first-pose spread of 0.68 ms (headless) and one headed run that stalled; do not compare with it.
## Task 2: sun and shadows
-Headless, viewport 1920x1080 at DPR 1 (`res=1920x1080 scale=0.80`), web tier (shadow map 2048, shadow distance fitted to
-1.75 x the rig distance); build from the Task 2 tree on `vis-light`.
+Headless, viewport 1920x1080 at DPR 1 (`res=1920x1080 scale=0.80`), web tier (shadow map 2048, one cascade, cascade
+border 0.1).
+
+**Shadow fit (fix round 1, review I1).** URP fades shadows by straight-line distance from the camera, from
+(1 - cascadeBorder) x shadowDistance out (URP 17.3 `Shadows.hlsl`, `ShadowUtils.GetScaleAndBiasForLinearDistanceFade`).
+The first delivery fitted 1.75 x the rig distance from *view depth*, which left the top corners partly or wholly faded
+(about 76% faded on the web tier at a 0.08 top inset). `ShadowFit` now takes, on every rig `Apply`, the farthest
+straight-line distance from the camera to the ground hits of the four viewport corners (the current aspect and top inset
+included; ground plane y = 0, the terrain's lowest point, so the fit is never short) and divides it by
+(1 - cascadeBorder). It clamps to 3 km .. 1,000 km (the far clip). `LightingTests.TheShadowDistanceCoversTheWholeView`
+checks 6/45/120/250 km x 16:9, 21:9, 4:3 x top insets 0, 0.08, 0.3, 0.5 x borders 0.1 and 0.2.
+
+**Decision: web-tier cascade border 0.2 -> 0.1** (`Mobile_RPAsset` `m_CascadeBorder`). With one cascade, the border is
+the fade band at the edge of the fitted range. A tenth keeps the fade off-screen while spending less of the 2048 map past
+the view (the fitted distance is 1/0.9 rather than 1/0.8 of the farthest corner). PC keeps 0.108 (4 cascades).
| Run | Lines |
|---|---|
-| headless | `PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=2.11 spread_ms=0.10 median_p95_ms=3.00`<br>`PROFILE summary visual=-shadows pose=gameplay03 runs=3 median_avg_ms=2.43 spread_ms=0.11 median_p95_ms=4.00`<br>`PROFILE summary visual=all pose=diorama02 runs=3 median_avg_ms=10.12 spread_ms=0.43 median_p95_ms=11.00`<br>`PROFILE summary visual=-shadows pose=diorama02 runs=3 median_avg_ms=7.39 spread_ms=0.17 median_p95_ms=8.00` |
-
-Budget check (`median(all) - median(-shadows) <= 2.5 ms + the larger spread`):
-- gameplay03: -0.32 ms (within noise; the 6-60 km view casts few shadows) against 2.61 ms: within.
-- diorama02: 2.73 ms against 2.93 ms (2.5 + 0.43): within, with 0.20 ms to spare. The country-wide pose fits the shadow
- map over about 400 km of relief; Task 10 should re-check this pose (cascades or a lower cover factor at the far zoom are
- the levers if the tier review needs headroom).
-- Edit-mode `ReliefCastsShadowsAtMapScale`: shadowed share 3.1 % (floor 2 %) over the Dead Sea escarpment at 60 km.
+| headless, first delivery (`8b20507`, 1.75 x D view-depth fit, border 0.2) | `PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=2.11 spread_ms=0.10 median_p95_ms=3.00`<br>`PROFILE summary visual=-shadows pose=gameplay03 runs=3 median_avg_ms=2.43 spread_ms=0.11 median_p95_ms=4.00`<br>`PROFILE summary visual=all pose=diorama02 runs=3 median_avg_ms=10.12 spread_ms=0.43 median_p95_ms=11.00`<br>`PROFILE summary visual=-shadows pose=diorama02 runs=3 median_avg_ms=7.39 spread_ms=0.17 median_p95_ms=8.00` |
+| headless, fix round 1 (corner fit, border 0.1) | `PROFILE summary visual=all pose=gameplay03 runs=3 median_avg_ms=2.03 spread_ms=0.09 median_p95_ms=3.00`<br>`PROFILE summary visual=-shadows pose=gameplay03 runs=3 median_avg_ms=2.42 spread_ms=0.08 median_p95_ms=4.00`<br>`PROFILE summary visual=all pose=diorama02 runs=3 median_avg_ms=9.87 spread_ms=0.46 median_p95_ms=11.00`<br>`PROFILE summary visual=-shadows pose=diorama02 runs=3 median_avg_ms=7.12 spread_ms=0.11 median_p95_ms=8.00` |
+
+Budget check, fix round 1 (`median(all) - median(-shadows) <= 2.5 ms + the larger spread`):
+- gameplay03: -0.39 ms against 2.59 ms: within.
+- diorama02: 2.75 ms against 2.96 ms (2.5 + 0.46): within, with 0.21 ms to spare.
+
+**For Task 10 (review M5).** At gameplay03, `all` is faster than `-shadows` by more than both spreads, in both deliveries.
+Three runs understate the run-to-run noise, so the 0.2 ms headroom at diorama02 means little. Re-measure diorama02
+shadows with more repeats (at least 7) and headed. If the tier review needs headroom, the levers are:
+- terrain shadow LOD or pixel error (the whole terrain is drawn into the shadow map at about 400 km);
+- a cheaper fit at the far zoom (fit to the map's extent rather than the frustum once the frustum is wider than the map);
+- a web-tier shadow map of 1024 at the far zoom only.
+
+**Rendered coverage (review I2, I3).** `ReliefCastsShadowsAtMapScale` runs at both tiers over the Dead Sea escarpment at
+60 km. Every other registered visual except `water` is off and the settlement markers are hidden, so only relief casts.
+Results: shadowed share **3.06% (web)** and **3.12% (PC)**; the control at the asset's own 50 m is **0.00%** at both.
+Hiding the markers moved the web share from 3.03% to 3.06%, which is noise, so the cubes were never a material part of
+it. The 2% floor stays: it allows a third of the measured share to be lost to the merge (Task 3's tilt-shift softening
+edges, Task 4's grade compressing darks, Track B's haze lifting distant shadow), and the control's 0.00% shows the
+separation is clean. If the merge squeezes it further, switch to a relative test (`lit < flat * 0.9`), not a lower floor.
+
+**Ambient (review M4).** `MapLighting.AmbientProbe` builds the trilight from `AddAmbientLight` plus two
+`AddDirectionalLight` lobes. The lobes add constant and linear terms in every direction, so the probe evaluates darker
+than its constants, which are inputs, not the evaluated colours. Evaluated values, pinned in `LightingTests`: up
+(0.216, 0.255, 0.326), horizon (0.184, 0.179, 0.171), down (0.119, 0.103, 0.080); the constants are sky (0.52, 0.60,
+0.72), equator (0.48, 0.46, 0.42), ground (0.26, 0.22, 0.17). The images were judged on the evaluated values, and Track
+B's thresholds were derived with them, so a least-squares refit would be a look change for Task 4, not a fix here.
## Checkpoints
| Task | Name | Images | Owner verdict |
diff --git a/unity/Assets/Scripts/Map/CameraRig.cs b/unity/Assets/Scripts/Map/CameraRig.cs
index 44aa61e18..28c741c26 100644
--- a/unity/Assets/Scripts/Map/CameraRig.cs
+++ b/unity/Assets/Scripts/Map/CameraRig.cs
@@ -46,8 +46,10 @@ namespace Statecraft.Game.Map
_dof = vol.profile.Add<DepthOfField>(true); _dof.mode.Override(DepthOfFieldMode.Gaussian);
_dof.gaussianMaxRadius.Override(1.5f);
Volume = vol;
- MapLighting.Apply(MapLighting.FindSun());
- TeardownActions.Add(VisualToggles.Register("shadows", on => { var sun = MapLighting.FindSun(); if (sun != null) sun.shadows = on ? LightShadows.Soft : LightShadows.None; }));
+ var sun = MapLighting.FindSun();
+ TeardownActions.Add(MapLighting.Capture(sun)); // first, so it runs last (review M1)
+ MapLighting.Apply(sun);
+ TeardownActions.Add(VisualToggles.Register("shadows", on => { var s = MapLighting.FindSun(); if (s != null) s.shadows = on ? LightShadows.Soft : LightShadows.None; }));
TeardownActions.Add(ShadowFit.Restore);
initialised = true;
Apply();
@@ -58,8 +60,8 @@ namespace Statecraft.Game.Map
transform.rotation = Quaternion.Euler(Pitch, Yaw, 0);
transform.position = LookAt - transform.forward * Distance;
if (_dof != null) { _dof.gaussianStart.Override(Distance * 1.05f); _dof.gaussianEnd.Override(Distance * 1.8f); }
- if (initialised) ShadowFit.Apply(Distance);
ApplyProjection();
+ if (initialised) ShadowFit.Apply(GetComponent<Camera>()); // after the projection: the fit reads the corner rays
}
/// <summary>Sets the camera's projection for <see cref="TopInset"/> only (the transform is left alone). Apply calls it
diff --git a/unity/Assets/Scripts/Map/MapLighting.cs b/unity/Assets/Scripts/Map/MapLighting.cs
index 7eab35f51..9606d246a 100644
--- a/unity/Assets/Scripts/Map/MapLighting.cs
+++ b/unity/Assets/Scripts/Map/MapLighting.cs
@@ -1,6 +1,9 @@
#nullable enable
+using System;
using UnityEngine;
using UnityEngine.Rendering;
+using UnityEngine.SceneManagement;
+using Object = UnityEngine.Object;
namespace Statecraft.Game.Map
{
@@ -17,6 +20,33 @@ namespace Statecraft.Game.Map
public static readonly Color AmbientEquator = new Color(0.48f, 0.46f, 0.42f);
public static readonly Color AmbientGround = new Color(0.26f, 0.22f, 0.17f);
+ /// <summary>Records the sun's transform and light settings and the active scene's ambient, and returns the action that
+ /// puts them back (review M1: CameraRig.Init registers it as its first teardown action, so destroying the map leaves
+ /// the scene's lighting as it was and saving an open Map.unity does not bake the runtime values). The ambient is put
+ /// back only while the same scene is still active, so a map destroyed by loading another scene never writes into it.</summary>
+ public static Action Capture(Light? sun)
+ {
+ var scene = SceneManager.GetActiveScene();
+ var mode = RenderSettings.ambientMode; var sky = RenderSettings.ambientSkyColor;
+ var equator = RenderSettings.ambientEquatorColor; var ground = RenderSettings.ambientGroundColor;
+ var probe = RenderSettings.ambientProbe; var renderSun = RenderSettings.sun;
+ bool hadSun = sun != null;
+ Quaternion rot = default; Color colour = default; float intensity = 0f, strength = 0f; LightShadows shadows = default;
+ if (sun != null) { rot = sun.transform.rotation; colour = sun.color; intensity = sun.intensity; strength = sun.shadowStrength; shadows = sun.shadows; }
+ return () =>
+ {
+ if (hadSun && sun != null)
+ {
+ sun.transform.rotation = rot; sun.color = colour; sun.intensity = intensity;
+ sun.shadowStrength = strength; sun.shadows = shadows;
+ }
+ if (SceneManager.GetActiveScene() != scene) return;
+ RenderSettings.ambientMode = mode; RenderSettings.ambientSkyColor = sky;
+ RenderSettings.ambientEquatorColor = equator; RenderSettings.ambientGroundColor = ground;
+ RenderSettings.ambientProbe = probe; RenderSettings.sun = renderSun;
+ };
+ }
+
/// <summary>The scene's first directional light, or null.</summary>
public static Light? FindSun()
{
@@ -43,7 +73,12 @@ namespace Statecraft.Game.Map
}
/// <summary>The trilight ambient as spherical harmonics (set explicitly: a runtime change of the trilight colours does
- /// not rebuild the probe the shaders read).</summary>
+ /// not rebuild the probe the shaders read). Review M4: this is an approximation, and the three colours are its
+ /// inputs, not what it evaluates to. Each AddDirectionalLight lobe also adds constant and linear terms in every
+ /// direction, and the ground lobe (darker than the equator) pulls the whole probe down. Evaluated, the probe is
+ /// darker than the constants everywhere; LightingTests.TheAmbientFillIsCoolFromTheSkyAndDarkFromTheGround pins the
+ /// evaluated up/horizon/down colours. The look was judged on these evaluated values, and Track B's render thresholds
+ /// were derived with them, so a least-squares refit is a look change for Task 4's grade, not a bug fix here.</summary>
public static SphericalHarmonicsL2 AmbientProbe()
{
var sh = new SphericalHarmonicsL2();
diff --git a/unity/Assets/Scripts/Map/ShadowFit.cs b/unity/Assets/Scripts/Map/ShadowFit.cs
index 041702381..c9e36e1ba 100644
--- a/unity/Assets/Scripts/Map/ShadowFit.cs
+++ b/unity/Assets/Scripts/Map/ShadowFit.cs
@@ -5,25 +5,52 @@ using UnityEngine.Rendering.Universal;
namespace Statecraft.Game.Map
{
/// <summary>Shadows at map scale (research notes §0.2): URP has no per-camera shadow distance, so the active URP asset's
- /// shadowDistance follows the rig's distance, and Restore puts the asset's own value back (the map registers Restore as a
- /// teardown action, so destroying the map, a rebuild or the end of a test leaves the asset as it was).</summary>
+ /// shadowDistance follows the camera, and Restore puts the asset's own value back (the map registers Restore as a
+ /// teardown action, so destroying the map, a rebuild or the end of a test leaves the asset as it was; in the editor,
+ /// leaving play mode and an assembly reload restore it too).
+ /// URP fades shadows by straight-line distance from the camera, starting at (1 - cascadeBorder) of the shadow distance
+ /// (URP 17.3 Shadows.hlsl, ShadowUtils.GetScaleAndBiasForLinearDistanceFade), so the fit is the farthest ground point of
+ /// the view, measured as a straight line, divided by (1 - cascadeBorder): the whole view is inside the unfaded range
+ /// (review I1). It is recomputed on every rig Apply from the camera's own corner rays (top inset and aspect included).</summary>
public static class ShadowFit
{
- /// <summary>View depth of the top screen row is 1.66 x the rig distance at the largest top inset (LightingTests).</summary>
- public const float CoverFactor = 1.75f;
- public const float MinDistanceM = 3000f, MaxDistanceM = 450000f;
+ public const float MinDistanceM = 3000f;
+ /// <summary>The rig's far clip plane: at 250 km, a 21:9 window and the largest top inset the top corners are 550 km away.</summary>
+ public const float MaxDistanceM = 1_000_000f;
+ /// <summary>The ground plane the corner rays are cut with: the terrain's lowest point (its elev_min sits at y = 0), so
+ /// every real ground hit is nearer than the plane's.</summary>
+ public const float GroundY = 0f;
static UniversalRenderPipelineAsset? touched;
static float original;
- public static float Distance(float cameraDistance) => Mathf.Clamp(cameraDistance * CoverFactor, MinDistanceM, MaxDistanceM);
+ static readonly Vector2[] Corners = { new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(0f, 1f), new Vector2(1f, 1f) };
- public static void Apply(float cameraDistance)
+ /// <summary>Straight-line distance from the camera to the farthest of the four viewport corners' ground hits (a corner
+ /// that does not look down counts as MaxDistanceM).</summary>
+ public static float FarthestGroundHit(Camera cam)
+ {
+ float far = 0f;
+ foreach (var v in Corners)
+ {
+ var ray = cam.ViewportPointToRay(new Vector3(v.x, v.y, 0f));
+ if (ray.direction.y > -1e-4f) return MaxDistanceM;
+ var hit = ray.origin + ray.direction * ((GroundY - ray.origin.y) / ray.direction.y);
+ far = Mathf.Max(far, (hit - cam.transform.position).magnitude);
+ }
+ return far;
+ }
+
+ /// <summary>The shadow distance that keeps the whole view of <paramref name="cam"/> unfaded with the given cascade border.</summary>
+ public static float Distance(Camera cam, float cascadeBorder) =>
+ Mathf.Clamp(FarthestGroundHit(cam) / (1f - Mathf.Clamp(cascadeBorder, 0f, 0.9f)), MinDistanceM, MaxDistanceM);
+
+ public static void Apply(Camera cam)
{
var asset = UniversalRenderPipeline.asset;
- if (asset == null) return;
+ if (asset == null || cam == null) return;
if (touched != asset) { Restore(); touched = asset; original = asset.shadowDistance; } // a quality-level switch
- asset.shadowDistance = Distance(cameraDistance);
+ asset.shadowDistance = Distance(cam, asset.cascadeBorder);
}
public static void Restore()
@@ -31,5 +58,23 @@ namespace Statecraft.Game.Map
if (touched != null) touched.shadowDistance = original;
touched = null;
}
+
+#if UNITY_EDITOR
+ /// <summary>Review M2: a domain reload drops the map's teardown list and this class's memory of the original, and leaving
+ /// play mode should not depend on the map's OnDestroy order; both restore here.</summary>
+ [UnityEditor.InitializeOnLoadMethod]
+ static void HookEditor()
+ {
+ UnityEditor.AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
+ UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeChanged;
+ }
+
+ public static void OnBeforeAssemblyReload() => Restore();
+
+ public static void OnPlayModeChanged(UnityEditor.PlayModeStateChange state)
+ {
+ if (state == UnityEditor.PlayModeStateChange.ExitingPlayMode) Restore();
+ }
+#endif
}
}
diff --git a/unity/Assets/Settings/Mobile_RPAsset.asset b/unity/Assets/Settings/Mobile_RPAsset.asset
index b25386f21..2518fb473 100644
--- a/unity/Assets/Settings/Mobile_RPAsset.asset
+++ b/unity/Assets/Settings/Mobile_RPAsset.asset
@@ -59,7 +59,7 @@ MonoBehaviour:
m_Cascade2Split: 0.25
m_Cascade3Split: {x: 0.1, y: 0.3}
m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467}
- m_CascadeBorder: 0.2
+ m_CascadeBorder: 0.1
m_ShadowDepthBias: 1
m_ShadowNormalBias: 1
m_AnyShadowsSupported: 1
diff --git a/unity/Assets/Tests/EditMode/LightingTests.cs b/unity/Assets/Tests/EditMode/LightingTests.cs
index 7f51fa858..3b6e8511e 100644
--- a/unity/Assets/Tests/EditMode/LightingTests.cs
+++ b/unity/Assets/Tests/EditMode/LightingTests.cs
@@ -1,5 +1,6 @@
#nullable enable
using System.Collections;
+using System.Linq;
using NUnit.Framework;
using Statecraft.Game.Map;
using UnityEditor;
@@ -48,29 +49,43 @@ public class LightingTests
Assert.Greater(c[0].b, c[0].r, "sky fill is cool");
Assert.Greater(c[0].grayscale, c[1].grayscale + 0.05f, "brighter from above");
Assert.AreEqual(AmbientMode.Trilight, RenderSettings.ambientMode);
+ // Review M4: the SH lobes leak into every direction, so the trilight constants are inputs, not the evaluated
+ // colours (MapLighting.AmbientProbe); print the evaluated up / horizon / down so the documented values are checked.
+ var e = new Color[3]; RenderSettings.ambientProbe.Evaluate(new[] { Vector3.up, Vector3.right, Vector3.down }, e);
+ TestContext.WriteLine($"ambient evaluated up {e[0]} horizon {e[1]} down {e[2]}");
+ var expected = new[] { new Color(0.216f, 0.255f, 0.326f), new Color(0.184f, 0.179f, 0.171f), new Color(0.119f, 0.103f, 0.080f) };
+ for (int i = 0; i < 3; i++)
+ {
+ Assert.AreEqual(expected[i].r, e[i].r, 0.01f, $"direction {i} r"); Assert.AreEqual(expected[i].g, e[i].g, 0.01f, $"direction {i} g");
+ Assert.AreEqual(expected[i].b, e[i].b, 0.01f, $"direction {i} b");
+ }
}
- [TestCase(6000f)]
- [TestCase(45000f)]
- [TestCase(120000f)]
- [TestCase(250000f)]
- public void TheShadowDistanceCoversTheWholeView(float distance)
+ /// <summary>Review I1: URP fades shadows by straight-line distance from the camera, starting at (1 - cascadeBorder) of
+ /// the shadow distance, so every corner of the view (top corners at 21:9 and the largest top inset included) must lie
+ /// inside the unfaded range.</summary>
+ [Test]
+ public void TheShadowDistanceCoversTheWholeView([Values(6000f, 45000f, 120000f, 250000f)] float distance, [Values(0.1f, 0.2f)] float border)
{
var go = new GameObject("Cam"); var cam = go.AddComponent<Camera>(); var rig = go.AddComponent<CameraRig>();
try
{
cam.fieldOfView = CameraRig.Fov;
- foreach (var aspect in new[] { 16f / 9f, 21f / 9f })
+ foreach (var aspect in new[] { 16f / 9f, 21f / 9f, 4f / 3f })
+ foreach (var inset in new[] { 0f, 0.08f, 0.3f, CameraRig.MaxTopInset })
{
cam.aspect = aspect;
- rig.LookAt = Vector3.zero; rig.Distance = distance; rig.TopInset = CameraRig.MaxTopInset; rig.Apply();
- foreach (var v in new[] { new Vector2(0f, 1f), new Vector2(0.5f, 1f), new Vector2(1f, 1f) })
+ rig.LookAt = Vector3.zero; rig.Distance = distance; rig.TopInset = inset; rig.Apply();
+ float fitted = ShadowFit.Distance(cam, border);
+ foreach (var v in new[] { new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(0f, 1f), new Vector2(0.5f, 1f), new Vector2(1f, 1f) })
{
var ray = cam.ViewportPointToRay(new Vector3(v.x, v.y, 0));
- var hit = ray.origin + ray.direction * (-ray.origin.y / ray.direction.y);
- var depth = Vector3.Dot(hit - cam.transform.position, cam.transform.forward);
- Assert.LessOrEqual(depth, ShadowFit.Distance(distance), $"{distance} m, aspect {aspect:0.00}, viewport {v}");
+ Assert.Less(ray.direction.y, 0f, "the view looks down everywhere");
+ var hit = ray.origin + ray.direction * ((ShadowFit.GroundY - ray.origin.y) / ray.direction.y);
+ var range = (hit - cam.transform.position).magnitude;
+ Assert.LessOrEqual(range, fitted * (1f - border) + 1f, $"{distance} m, aspect {aspect:0.00}, inset {inset}, viewport {v}");
}
+ Assert.LessOrEqual(fitted, ShadowFit.MaxDistanceM);
}
}
finally { Object.DestroyImmediate(go); }
@@ -81,11 +96,39 @@ public class LightingTests
{
var asset = UniversalRenderPipeline.asset; Assert.IsNotNull(asset);
var before = asset!.shadowDistance;
- ShadowFit.Apply(60000f); Assert.AreEqual(ShadowFit.Distance(60000f), asset.shadowDistance, 1e-3f);
- ShadowFit.Apply(10000f); Assert.AreEqual(ShadowFit.Distance(10000f), asset.shadowDistance, 1e-3f);
- Assert.AreEqual(ShadowFit.MinDistanceM, ShadowFit.Distance(100f));
- ShadowFit.Restore(); Assert.AreEqual(before, asset.shadowDistance);
- ShadowFit.Restore(); Assert.AreEqual(before, asset.shadowDistance, "restoring twice is harmless");
+ var go = new GameObject("Cam"); var cam = go.AddComponent<Camera>(); var rig = go.AddComponent<CameraRig>();
+ try
+ {
+ cam.fieldOfView = CameraRig.Fov; cam.aspect = 16f / 9f; rig.LookAt = Vector3.zero;
+ rig.Distance = 60000f; rig.Apply(); ShadowFit.Apply(cam);
+ var far = ShadowFit.Distance(cam, asset.cascadeBorder);
+ Assert.AreEqual(far, asset.shadowDistance, 1e-3f);
+ rig.Distance = 10000f; rig.Apply(); ShadowFit.Apply(cam);
+ Assert.AreEqual(ShadowFit.Distance(cam, asset.cascadeBorder), asset.shadowDistance, 1e-3f);
+ Assert.Less(asset.shadowDistance, far, "follows the zoom");
+ rig.Distance = 100f; rig.Apply();
+ Assert.AreEqual(ShadowFit.MinDistanceM, ShadowFit.Distance(cam, asset.cascadeBorder));
+ ShadowFit.Restore(); Assert.AreEqual(before, asset.shadowDistance);
+ ShadowFit.Restore(); Assert.AreEqual(before, asset.shadowDistance, "restoring twice is harmless");
+ }
+ finally { Object.DestroyImmediate(go); }
+ }
+
+ /// <summary>Review M2: leaving play mode (and an assembly reload, which runs the same Restore) puts the asset back even
+ /// though the map's teardown list is gone.</summary>
+ [Test]
+ public void LeavingPlayModeRestoresTheShadowDistance()
+ {
+ var asset = UniversalRenderPipeline.asset!; var before = asset.shadowDistance;
+ var go = new GameObject("Cam"); var cam = go.AddComponent<Camera>(); go.AddComponent<CameraRig>().Apply();
+ try
+ {
+ ShadowFit.Apply(cam); Assert.AreNotEqual(before, asset.shadowDistance);
+ ShadowFit.OnPlayModeChanged(PlayModeStateChange.EnteredPlayMode); Assert.AreNotEqual(before, asset.shadowDistance);
+ ShadowFit.OnPlayModeChanged(PlayModeStateChange.ExitingPlayMode); Assert.AreEqual(before, asset.shadowDistance);
+ ShadowFit.Apply(cam); ShadowFit.OnBeforeAssemblyReload(); Assert.AreEqual(before, asset.shadowDistance);
+ }
+ finally { Object.DestroyImmediate(go); }
}
[Test]
@@ -100,6 +143,44 @@ public class LightingTests
Assert.AreEqual(before, asset.shadowDistance, "restored with the map");
}
+ /// <summary>Review M1: the sun and the ambient are put back when the map goes, so saving an open Map.unity after a Build
+ /// does not bake the runtime lighting into the scene.</summary>
+ [Test]
+ public void DestroyingTheMapRestoresTheSunAndTheAmbient()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var sun = MapLighting.FindSun()!; Assert.IsNotNull(sun);
+ var rot = sun.transform.rotation; var colour = sun.color; var intensity = sun.intensity; var shadows = sun.shadows;
+ var strength = sun.shadowStrength; var mode = RenderSettings.ambientMode; var sky = RenderSettings.ambientSkyColor;
+ var equator = RenderSettings.ambientEquatorColor; var ground = RenderSettings.ambientGroundColor;
+ var up = new Color[1]; RenderSettings.ambientProbe.Evaluate(new[] { Vector3.up }, up);
+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
+ Assert.AreNotEqual(rot, sun.transform.rotation, "Build points the sun");
+ Object.DestroyImmediate(map.Terrain.gameObject); // its MapRuntimeAssets runs the teardown
+ Assert.AreEqual(0f, Quaternion.Angle(rot, sun.transform.rotation), 1e-3f);
+ Assert.AreEqual(colour, sun.color); Assert.AreEqual(intensity, sun.intensity); Assert.AreEqual(shadows, sun.shadows);
+ Assert.AreEqual(strength, sun.shadowStrength); Assert.AreEqual(mode, RenderSettings.ambientMode);
+ Assert.AreEqual(sky, RenderSettings.ambientSkyColor); Assert.AreEqual(equator, RenderSettings.ambientEquatorColor);
+ Assert.AreEqual(ground, RenderSettings.ambientGroundColor);
+ var upAfter = new Color[1]; RenderSettings.ambientProbe.Evaluate(new[] { Vector3.up }, upAfter);
+ Assert.AreEqual(up[0], upAfter[0]);
+ }
+
+ /// <summary>Review M6 (Review Focus 1): the sun is fixed in the world; orbiting the rig moves the light across the screen.</summary>
+ [Test]
+ public void TheSunStaysFixedInTheWorldWhenTheRigOrbits()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ Object.FindFirstObjectByType<MapScene>().Build();
+ var sun = MapLighting.FindSun()!; var rig = Camera.main.GetComponent<CameraRig>();
+ var forward = sun.transform.forward;
+ foreach (var yaw in new[] { 90f, 180f, 270f })
+ {
+ rig.Yaw = yaw; rig.Apply();
+ Assert.AreEqual(0f, Vector3.Angle(forward, sun.transform.forward), 1e-3f, $"yaw {yaw}");
+ }
+ }
+
[Test]
public void TheHeroZoomComesInToSixKilometres()
{
@@ -114,25 +195,50 @@ public class LightingTests
Assert.AreEqual(2048, web.mainLightShadowmapResolution);
}
- /// <summary>Rendered: over the Dead Sea escarpment (the steepest relief on the map) the sun now casts shadows. Without
- /// the fit (the asset's 50 m) nothing would. Much of the escarpment's shadow at 30 degrees falls east onto the Dead Sea;
- /// in Track A alone that water is URP-lit terrain and darkens; after the merge the water is ScWaterShade, which samples
- /// the main light's shadow attenuation (Task 7, review I6), so the shadow still lands on it and the 2% floor holds.</summary>
+ /// <summary>Review I1: the web tier (one cascade) fades its shadows over the last tenth of the fitted distance, not the
+ /// last fifth, so less of the 2048 map is spent past the view.</summary>
+ [Test]
+ public void TheWebTierFadesShadowsOverTheLastTenth()
+ {
+ var web = AssetDatabase.LoadAssetAtPath<UniversalRenderPipelineAsset>("Assets/Settings/Mobile_RPAsset.asset");
+ Assert.AreEqual(0.1f, web.cascadeBorder, 1e-4f);
+ }
+
+ /// <summary>Rendered, at both tiers (review I2: 0 is the web tier, 1 the PC tier the edit-mode runs default to): over the
+ /// Dead Sea escarpment (the steepest relief on the map) the sun casts shadows. The measurement is isolated (review I3):
+ /// every other registered visual except the water is off and the settlement markers are hidden, so only relief casts;
+ /// and a control at the asset's own 50 m shows that without the fit nothing would. Much of the escarpment's shadow at
+ /// 30 degrees falls east onto the Dead Sea; in Track A alone that water is URP-lit terrain and darkens; after the merge
+ /// the water is ScWaterShade, which samples the main light's shadow attenuation (Task 7, review I6), so the shadow still
+ /// lands on it.</summary>
[UnityTest]
- public IEnumerator ReliefCastsShadowsAtMapScale()
+ public IEnumerator ReliefCastsShadowsAtMapScale([Values(0, 1)] int level)
{
- EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
- var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
- yield return null;
- var cam = Camera.main; var rig = cam.GetComponent<CameraRig>(); var sun = MapLighting.FindSun();
- Assert.IsNotNull(sun, "Map.unity has a directional light");
- rig.LookAt = map.Frame.ToWorld(35.38, 31.45, 0); rig.Distance = 60000f; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();
- var lit = RenderSample.Render(cam, 480, 270);
- VisualToggles.Set("shadows", false);
- var flat = RenderSample.Render(cam, 480, 270);
- VisualToggles.Set("shadows", true);
- float shadowed = RenderSample.FractionDarker(lit, flat, 0.04f);
- TestContext.WriteLine($"shadowed share {shadowed:P1}");
- Assert.Greater(shadowed, 0.02f, "at least 2% of the view is in a cast shadow");
+ int previous = QualitySettings.GetQualityLevel();
+ QualitySettings.SetQualityLevel(level, false);
+ try
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
+ yield return null;
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>(); var sun = MapLighting.FindSun();
+ Assert.IsNotNull(sun, "Map.unity has a directional light");
+ foreach (var n in VisualToggles.Names.Where(n => n != "shadows" && n != "water")) VisualToggles.Set(n, false);
+ map.transform.Find("Settlements").gameObject.SetActive(false);
+ rig.LookAt = map.Frame.ToWorld(35.38, 31.45, 0); rig.Distance = 60000f; rig.Yaw = 0; rig.TopInset = 0; rig.Apply();
+ var lit = RenderSample.Render(cam, 480, 270);
+ VisualToggles.Set("shadows", false);
+ var flat = RenderSample.Render(cam, 480, 270);
+ VisualToggles.Set("shadows", true);
+ float shadowed = RenderSample.FractionDarker(lit, flat, 0.04f);
+
+ ShadowFit.Restore(); // the control: the asset's own shadow distance (50 m)
+ var litUnfitted = RenderSample.Render(cam, 480, 270);
+ float control = RenderSample.FractionDarker(litUnfitted, flat, 0.04f);
+ TestContext.WriteLine($"level {level}: shadowed share {shadowed:P2}, unfitted control {control:P2}");
+ Assert.Less(control, 0.002f, "without the fit the map casts (almost) nothing");
+ Assert.Greater(shadowed, 0.02f, "at least 2% of the view is in a cast shadow");
+ }
+ finally { QualitySettings.SetQualityLevel(previous, false); }
}
}
diff --git a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
index d4566e13e..c0d2406da 100644
--- a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
+++ b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
@@ -177,18 +177,23 @@ public class VisualHarnessTests
var go = new GameObject("cam", typeof(Camera)); var rig = go.AddComponent<CameraRig>();
int ran = 0;
System.Action stale = () => ran++;
- rig.TeardownActions.Add(stale);
+ UnityEngine.Rendering.Volume? first = null;
try
{
+ rig.Init(); first = rig.Volume;
+ int own = rig.TeardownActions.Count; // Init's own undo actions (Task 2: the lighting, the toggle, the shadow fit)
+ rig.TeardownActions.Add(stale);
rig.Init();
Assert.AreEqual(1, ran);
CollectionAssert.DoesNotContain(rig.TeardownActions, stale);
+ Assert.AreEqual(own, rig.TeardownActions.Count, "a second Init does not pile up undo actions (review M3)");
}
finally
{
for (int i = rig.TeardownActions.Count - 1; i >= 0; i--) rig.TeardownActions[i](); // the shadow fit, the toggle
rig.TeardownActions.Clear();
- if (rig.Volume != null) { Object.DestroyImmediate(rig.Volume.profile); Object.DestroyImmediate(rig.Volume.gameObject); }
+ foreach (var vol in new[] { first, rig.Volume })
+ if (vol != null) { Object.DestroyImmediate(vol.profile); Object.DestroyImmediate(vol.gameObject); }
Object.DestroyImmediate(go);
}
}