Inventory grid harness: judged against the golden of the shader's own output, not the sprite sheets

One bound, GoldenBound, replaces AtlasBound, ThermalBound and ThermalHullBound: the atlas, thermal and alpha/clip sections and the overlay capture compare the grid's render with the PNGs of tests/fixtures/inventory-grid (largest RGBA channel difference over the whole crop). The sprite oracle goes: Oracle, the sheet pixels-per-unit check, the mask 33/289 and 136/392 slip exclusions, the thermal least-squares fit, the hull states' whole-panel pixel parity (the atlas golden covers records to pixels, the records golden panel to records and rects), the tie-pixel exclusion and the thermal background check. The ghost is judged against the panel's own pixels: the panel's grid drawn before the drag, then the ghost alone with the panel shrunk to nothing; rgb halves in linear light (the target is sRGB), alpha in stored value.

Bounds by lodur:ruling:deterministic-bound-margin, readings in the comments: golden 12 (shipped 0 taken as 1, least mutant pipe-width-minus 153), overlay 7 (shipped 0 as 1, least mutant 43), ghost 11 (shipped 1, ghost-full-alpha 115). cargo-thermal-kept was killed by hull pixel parity; a direct check that the grid's Thermal flag follows the state replaces it. flip-ignored moves to the switch run (records golden). The ghost check picks an item inside the panel's viewport.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 08:54:53 +01:00
commit 40c16c4727
3 changed files with 309 additions and 629 deletions

View file

@ -6,13 +6,14 @@ using UnityEngine;
using UnityEngine.UI;
using int2 = CultMath.int2;
// Parity of the inventory grid on a ScreenSpaceOverlay canvas, the kind the game's canvases are, which the camera rig of
// The inventory grid on a ScreenSpaceOverlay canvas, the kind the game's canvases are, which the camera rig of
// InventoryGridParityCapture cannot draw. An overlay canvas draws to the Game view's back buffer, so this enters play mode and
// reads the screen at the end of a frame: once with the sprite cells, once with the grid over the same canvas rects.
// reads the screen at the end of a frame, and compares the grid's crop with its golden PNG (tests/fixtures/inventory-grid/overlay-*.png).
//
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridOverlayCapture.Run [-pngOut <dir>] [-goldenOut [<dir>]] -logFile <log>
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridOverlayCapture.Run [-pngOut <dir>] [-goldenIn <dir>] [-goldenOut [<dir>]] -logFile <log>
//
// -goldenOut also writes the grid's crop of each capture as overlay-<name>.png into <dir> (default tests/fixtures/inventory-grid/).
// -goldenIn is where the goldens are read from and -goldenOut writes the grid's crop of each capture as overlay-<name>.png instead (both
// default to tests/fixtures/inventory-grid/); a run with -goldenOut compares nothing.
//
// Needs a GPU device; do not pass -nographics or -quit. Logs "[InventoryGridOverlay]" lines and exits 0 or 1.
public static class InventoryGridOverlayCapture
@ -20,8 +21,11 @@ public static class InventoryGridOverlayCapture
private const string Pending = "InventoryGridOverlayCapture.pending";
private const string PngKey = "InventoryGridOverlayCapture.png";
private const string GoldenKey = "InventoryGridOverlayCapture.golden";
// The parity harness's atlas bound (InventoryGridParityCapture.AtlasBound): sqrt(4 x 66).
private const int Bound = 16;
private const string GoldenInKey = "InventoryGridOverlayCapture.goldenIn";
// The bound on the largest 8-bit channel difference of the grid's crop against its golden. lodur:ruling:deterministic-bound-margin: the
// shipped reading is 0 in both of two fresh runs, taken as 1 (the 8-bit quantum); the least claimed mutant is alpha-multiply-dropped at 43
// (concave-bracket-dropped reads 138); sqrt(1 x 43) = 6.6, bound 7, a separation of 7 below and 6.1 above.
private const int Bound = 7;
public static void Run()
{
@ -31,6 +35,9 @@ public static class InventoryGridOverlayCapture
var golden = Array.IndexOf(args, "-goldenOut");
SessionState.SetString(GoldenKey, golden < 0 ? "" : golden + 1 < args.Length && !args[golden + 1].StartsWith("-") ? args[golden + 1]
: Path.Combine(Directory.GetParent(Application.dataPath)!.FullName, "tests", "fixtures", "inventory-grid"));
var goldenIn = Array.IndexOf(args, "-goldenIn");
SessionState.SetString(GoldenInKey, goldenIn >= 0 && goldenIn + 1 < args.Length ? args[goldenIn + 1]
: Path.Combine(Directory.GetParent(Application.dataPath)!.FullName, "tests", "fixtures", "inventory-grid"));
SessionState.SetBool(Pending, true);
EditorApplication.EnterPlaymode();
}
@ -76,8 +83,7 @@ public static class InventoryGridOverlayCapture
var overallWorst = 0;
var png = SessionState.GetString(PngKey, "");
var goldenOut = SessionState.GetString(GoldenKey, "");
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/UI/Inventory.prefab");
var panel = prefab.GetComponentInChildren<InventoryPanel>(true);
var goldenIn = SessionState.GetString(GoldenInKey, "");
var shader = AssetDatabase.LoadAssetAtPath<Shader>("Assets/Shaders/InventoryGrid.shader");
// An overlay canvas draws to the Game view's back buffer, which batch mode does not create on its own.
Log("Game view menu item: " + EditorApplication.ExecuteMenuItem("Window/General/Game"));
@ -122,31 +128,6 @@ public static class InventoryGridOverlayCapture
var bgColor = new Color(.6f, .2f, .1f, .8f);
Vector2 At(int k) => new Vector2(8 + k % 8 * stride, 8 + k / 8 * stride);
for (var k = 0; k < masks.Count; k++)
{
var cell = Instantiate(panel.NodePrototype.gameObject, canvasObject.transform, false);
// The prototype deactivates itself in Start unless it is an instance it handed out; a plain clone is not one.
Destroy(cell.GetComponent<Prototype>());
cell.SetActive(true);
var rect = (RectTransform) cell.transform;
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.anchoredPosition = At(k);
rect.sizeDelta = new Vector2(size, size);
var node = cell.GetComponent<InventoryCell>();
node.Background.sprite = panel.NodeBackgroundTextures[masks[k] & 255];
node.Background.color = new Color(bgColor.r, bgColor.g, bgColor.b, bgColor.a * alpha);
node.Icon.sprite = panel.NodeTextures[masks[k]];
node.Icon.pixelsPerUnitMultiplier = multiplier;
node.Icon.color = new Color(iconColor.r, iconColor.g, iconColor.b, iconColor.a * alpha);
}
yield return null;
watchdog.Arm("end of frame, sprite cells");
yield return new WaitForEndOfFrame();
watchdog.Disarm();
var old = ScreenCapture.CaptureScreenshotAsTexture();
for (var c = canvasObject.transform.childCount - 1; c >= 1; c--) Destroy(canvasObject.transform.GetChild(c).gameObject);
yield return null;
for (var k = 0; k < masks.Count; k++)
{
var go = new GameObject("Grid", typeof(RectTransform), typeof(CanvasRenderer)) { layer = canvasObject.layer };
@ -172,45 +153,53 @@ public static class InventoryGridOverlayCapture
watchdog.Disarm();
var fresh = ScreenCapture.CaptureScreenshotAsTexture();
var scale = 1f;
var worst = 0;
var lit = 0;
var a = old.GetPixels32();
var cropW = Mathf.Min(fresh.width, Mathf.CeilToInt(8 + 8 * stride));
var cropH = Mathf.Min(fresh.height, Mathf.CeilToInt(8 + 12 * stride));
var b = fresh.GetPixels32();
for (var k = 0; k < masks.Count; k++)
var crop = new Color32[cropW * cropH];
var lit = 0;
for (var y = 0; y < cropH; y++)
for (var x = 0; x < cropW; x++)
{
var origin = At(k) * scale;
for (var y = Mathf.Max(0, Mathf.FloorToInt(origin.y) - 1); y < Mathf.Min(old.height, Mathf.CeilToInt(origin.y + size * scale) + 1); y++)
for (var x = Mathf.Max(0, Mathf.FloorToInt(origin.x) - 1); x < Mathf.Min(old.width, Mathf.CeilToInt(origin.x + size * scale) + 1); x++)
crop[y * cropW + x] = b[y * fresh.width + x];
if (crop[y * cropW + x].r + crop[y * cropW + x].g + crop[y * cropW + x].b > 30) lit++;
}
var worst = 0;
Color32[] a = null;
if (goldenOut != "")
{
Directory.CreateDirectory(goldenOut);
var written = new Texture2D(cropW, cropH, TextureFormat.RGBA32, false, true);
written.SetPixels32(crop);
File.WriteAllBytes(Path.Combine(goldenOut, $"overlay-{name}.png"), written.EncodeToPNG());
Destroy(written);
Log($"golden written: overlay-{name}.png {cropW}x{cropH}");
}
else
{
var path = Path.Combine(goldenIn, $"overlay-{name}.png");
var golden = new Texture2D(2, 2, TextureFormat.RGBA32, false, true);
if (!File.Exists(path) || !golden.LoadImage(File.ReadAllBytes(path)) || golden.width != cropW || golden.height != cropH)
{
var i = y * old.width + x;
worst = Mathf.Max(worst, Mathf.Abs(a[i].r - b[i].r), Mathf.Abs(a[i].g - b[i].g), Mathf.Abs(a[i].b - b[i].b));
if (a[i].r + a[i].g + a[i].b > 30) lit++;
failed = true;
Log($"BOUND BREACHED overlay {name}: no golden {path} of {cropW}x{cropH}");
}
else
{
a = golden.GetPixels32();
for (var i = 0; i < a.Length; i++)
worst = Mathf.Max(worst, Mathf.Abs(a[i].r - crop[i].r), Mathf.Abs(a[i].g - crop[i].g), Mathf.Abs(a[i].b - crop[i].b), Mathf.Abs(a[i].a - crop[i].a));
}
Destroy(golden);
}
overallWorst = Mathf.Max(overallWorst, worst);
Log($"overlay {name}: {masks.Count} masks, scale {scale:F3}, max8bitDiff={worst}, {lit} lit pixels in the sprite render");
Log($"overlay {name}: {masks.Count} masks, max8bitDiff against the golden={worst}, {lit} lit pixels");
if (lit == 0 || worst > Bound)
{
failed = true;
Log($"BOUND BREACHED overlay {name}: worst {worst} (bound {Bound}), lit {lit}");
}
var cropW = Mathf.Min(old.width, Mathf.CeilToInt((8 + 8 * stride) * scale));
var cropH = Mathf.Min(old.height, Mathf.CeilToInt((8 + 12 * stride) * scale));
if (goldenOut != "")
{
Directory.CreateDirectory(goldenOut);
var crop = new Texture2D(cropW, cropH, TextureFormat.RGBA32, false, true);
var cropPixels = new Color32[cropW * cropH];
for (var y = 0; y < cropH; y++)
for (var x = 0; x < cropW; x++)
cropPixels[y * cropW + x] = b[y * old.width + x];
crop.SetPixels32(cropPixels);
File.WriteAllBytes(Path.Combine(goldenOut, $"overlay-{name}.png"), crop.EncodeToPNG());
Destroy(crop);
Log($"golden written: overlay-{name}.png {cropW}x{cropH}");
}
if (png != "")
if (png != "" && a != null)
{
Directory.CreateDirectory(png);
var sheet = new Texture2D(cropW * 3, cropH, TextureFormat.RGBA32, false);
@ -218,12 +207,12 @@ public static class InventoryGridOverlayCapture
for (var y = 0; y < cropH; y++)
for (var x = 0; x < cropW; x++)
{
var i = y * old.width + x;
var i = y * cropW + x;
pixels[y * cropW * 3 + x] = new Color32(a[i].r, a[i].g, a[i].b, 255);
pixels[y * cropW * 3 + cropW + x] = new Color32(b[i].r, b[i].g, b[i].b, 255);
pixels[y * cropW * 3 + cropW + x] = new Color32(crop[i].r, crop[i].g, crop[i].b, 255);
pixels[y * cropW * 3 + 2 * cropW + x] = new Color32(
(byte) Mathf.Min(255, 8 * Mathf.Abs(a[i].r - b[i].r)), (byte) Mathf.Min(255, 8 * Mathf.Abs(a[i].g - b[i].g)),
(byte) Mathf.Min(255, 8 * Mathf.Abs(a[i].b - b[i].b)), 255);
(byte) Mathf.Min(255, 8 * Mathf.Abs(a[i].r - crop[i].r)), (byte) Mathf.Min(255, 8 * Mathf.Abs(a[i].g - crop[i].g)),
(byte) Mathf.Min(255, 8 * Mathf.Abs(a[i].b - crop[i].b)), 255);
}
sheet.SetPixels32(pixels);
File.WriteAllBytes(Path.Combine(png, $"overlay-{name}.png"), sheet.EncodeToPNG());

View file

@ -13,18 +13,19 @@ using UniRx.Triggers;
using GameCult.Caching;
using int2 = CultMath.int2;
// The parity harness of the inventory grid (map IG): the sheet sprites are the oracle and InventoryGrid is judged against them.
// Every check logs one "[InventoryGridParity]" line, and the run exits 0 when every bound holds, 1 otherwise.
// The parity harness of the inventory grid (map IG): InventoryGrid is judged against a golden of its own output (tests/fixtures/inventory-grid,
// written by -goldenOut at the last commit where the sprite sheets still judged it), against the golden records of the hull states, and by
// its own checks. Every check logs one "[InventoryGridParity]" line, and the run exits 0 when every bound holds, 1 otherwise.
//
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridParityCapture.Run [-pngOut <dir>] [-mutant <name>] [-hullOnly] [-recordsIn <golden>] [-goldenOut [<dir>]] -logFile <log>
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridParityCapture.Run [-pngOut <dir>] [-mutant <name>] [-hullOnly] [-recordsIn <records>] [-goldenIn <dir>] [-goldenOut [<dir>]] -logFile <log>
//
// -goldenOut writes the grid renders of the synthetic sections (the atlas, the thermal pipes, vertex alpha and clip) as PNGs into <dir>
// (default tests/fixtures/inventory-grid/), cropped to the judged region. A run that writes them must pass every sprite bound, so the golden is
// the shader's output at a commit where the sheets judged it.
// The grid renders of the synthetic sections (the atlas, the thermal pipes, vertex alpha and clip) are compared with the PNGs of -goldenIn
// (default tests/fixtures/inventory-grid/), cropped to the judged region. -goldenOut writes them instead (a deliberate look change: show the
// operator the old and new crops side by side before committing them); a run with -goldenOut compares nothing against them.
//
// -recordsIn is the golden of the real-hull states (every cell's record and rect in page canvas units, and the temperature display's
// rect) that the first commit of the switch cut wrote from the sprite panels (`-recordsOut`, which exists only at that commit); the live
// panels must equal it. The golden is a run output, kept outside git; Soul regenerates it from that commit.
// panels must equal it. It is a run output, kept outside git; regenerate it from that commit.
//
// Needs a GPU device; do not pass -nographics or -quit. A mutant is one named perturbation of the new path (see Mutants); the
// run must then fail a bound.
@ -33,22 +34,18 @@ public static class InventoryGridParityCapture
private const string PrefabPath = "Assets/Prefabs/UI/Inventory.prefab";
private const string ShaderPath = "Assets/Shaders/InventoryGrid.shader";
// The bound on the largest 8-bit channel difference of any pixel of the atlas, the real hull, vertex alpha and RectMask2D, outside the
// footprints of the oracle's own slips. lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped worst reading (4) and the
// least claimed mutant's reading (66, alpha-multiply-dropped), sqrt(4 x 66) = 16.2, a separation of about 4 on each side. The other
// mutants read 122 to 255.
private static int AtlasBound = 16;
// The bound on a thermal mask's rms difference, 0..1 channel units, in the atlas (the sprites at 1:1 and 2:1): the geometric mean of the
// shipped worst reading (0.0430, S32 mask 0) and the pipe-width-minus mutant's (0.1306), a separation of 1.74 on each side. The real hull's
// thermal cells have their own bound, ThermalHullBound, because they sit at half-pixel offsets the sprites blur across: shipped 0.1007,
// mutant 0.1731, geometric mean 0.132, a separation of 1.31.
private static double ThermalBound = 0.075;
private static double ThermalHullBound = 0.132;
private static int _atlasWorst, _hullWorst, _maskedWorst, _alphaClipWorst;
private static double _thermalWorst, _thermalHullWorst;
// The bound on the largest 8-bit channel difference (RGBA) of any pixel of a synthetic section against its golden PNG.
// lodur:ruling:deterministic-bound-margin: the shipped reading is 0 in both of two fresh runs, taken as 1 (the 8-bit quantum); the least
// claimed mutant is pipe-width-minus at 153 (the others read 170 to 255); sqrt(1 x 153) = 12.4, bound 12, a separation of 12 below and
// 12.8 above. The golden is GPU-specific (GTX 1070, D3D11, Starfire): a reading from another GPU is reported, not absorbed by loosening.
private static int GoldenBound = 12;
// The bound on the drag ghost's pixels against half the panel's own over the item's cell interiors, in 8-bit levels: the shipped reading is
// 1 (rounding), the least claimed mutant ghost-full-alpha reads 115; sqrt(1 x 115) = 10.7, bound 11, a separation of 11 and 10.5.
private static int GhostBound = 11;
private static int _goldenWorst, _maskedWorst, _ghostWorst;
private static string _mutant = "";
private static string _pngOut, _recordsIn, _goldenOut;
private static string _pngOut, _recordsIn, _goldenOut, _goldenIn;
private static readonly List<string> Breaches = new List<string>();
public static readonly string[] Mutants =
@ -61,9 +58,8 @@ public static class InventoryGridParityCapture
// The golden of the shader's own output: one RGBA PNG per synthetic case, cropped to the judged region.
private static string GoldenDefault => Path.Combine(Directory.GetParent(Application.dataPath)!.FullName, "tests", "fixtures", "inventory-grid");
private static void WriteGolden(string name, Rig rig, Color32[] pixels, RectInt region)
private static Color32[] Crop(Rig rig, Color32[] pixels, ref RectInt region)
{
if (_goldenOut == null) return;
var x1 = Mathf.Min(rig.Width, region.x + region.width);
var y1 = Mathf.Min(rig.Height, region.y + region.height);
region = new RectInt(Mathf.Max(0, region.x), Mathf.Max(0, region.y), x1 - Mathf.Max(0, region.x), y1 - Mathf.Max(0, region.y));
@ -71,11 +67,49 @@ public static class InventoryGridParityCapture
for (var y = 0; y < region.height; y++)
for (var x = 0; x < region.width; x++)
crop[y * region.width + x] = pixels[(region.y + y) * rig.Width + region.x + x];
var texture = new Texture2D(region.width, region.height, TextureFormat.RGBA32, false, true);
texture.SetPixels32(crop);
File.WriteAllBytes(Path.Combine(_goldenOut, name + ".png"), texture.EncodeToPNG());
UnityEngine.Object.DestroyImmediate(texture);
Log($"golden written: {name}.png {region.width}x{region.height}");
return crop;
}
// One synthetic case against its golden: written with -goldenOut (nothing is compared then), otherwise the largest RGBA channel difference
// over the whole crop, which breaches GoldenBound. The returned frame is the golden pasted at the region, for the side-by-side PNG.
private static int CompareToGolden(string name, Rig rig, Color32[] fresh, RectInt region, out Color32[] reference)
{
reference = fresh;
var crop = Crop(rig, fresh, ref region);
if (_goldenOut != null)
{
var texture = new Texture2D(region.width, region.height, TextureFormat.RGBA32, false, true);
texture.SetPixels32(crop);
File.WriteAllBytes(Path.Combine(_goldenOut, name + ".png"), texture.EncodeToPNG());
UnityEngine.Object.DestroyImmediate(texture);
Log($"golden written: {name}.png {region.width}x{region.height}");
return 0;
}
var path = Path.Combine(_goldenIn, name + ".png");
if (!File.Exists(path)) { Breaches.Add($"{name}: no golden {path}"); return 0; }
var golden = new Texture2D(2, 2, TextureFormat.RGBA32, false, true);
golden.LoadImage(File.ReadAllBytes(path));
if (golden.width != region.width || golden.height != region.height)
{
Breaches.Add($"{name}: the golden is {golden.width}x{golden.height}, the render {region.width}x{region.height}");
UnityEngine.Object.DestroyImmediate(golden);
return 0;
}
var expected = golden.GetPixels32();
UnityEngine.Object.DestroyImmediate(golden);
var worst = 0;
reference = new Color32[fresh.Length];
for (var y = 0; y < region.height; y++)
for (var x = 0; x < region.width; x++)
{
var a = expected[y * region.width + x];
var b = crop[y * region.width + x];
reference[(region.y + y) * rig.Width + region.x + x] = a;
worst = Mathf.Max(worst, Mathf.Abs(a.r - b.r), Mathf.Abs(a.g - b.g), Mathf.Abs(a.b - b.b), Mathf.Abs(a.a - b.a));
}
_goldenWorst = Math.Max(_goldenWorst, worst);
if (worst > GoldenBound) Breaches.Add($"{name}: {worst} > {GoldenBound}");
return worst;
}
public static void Run()
@ -95,15 +129,15 @@ public static class InventoryGridParityCapture
_goldenOut = goldenAt + 1 < args.Length && !args[goldenAt + 1].StartsWith("-") ? args[goldenAt + 1] : GoldenDefault;
Directory.CreateDirectory(_goldenOut);
}
if (Arg("-atlasBound") != null) AtlasBound = int.Parse(Arg("-atlasBound"));
if (Arg("-thermalBound") != null) ThermalHullBound = ThermalBound = double.Parse(Arg("-thermalBound"), System.Globalization.CultureInfo.InvariantCulture);
_goldenIn = Arg("-goldenIn") ?? GoldenDefault;
if (Arg("-goldenBound") != null) GoldenBound = int.Parse(Arg("-goldenBound"));
if (_mutant != "" && !Mutants.Contains(_mutant)) throw new InvalidOperationException("Unknown mutant " + _mutant);
if (_pngOut != null) Directory.CreateDirectory(_pngOut);
Log("mutant=" + (_mutant == "" ? "none" : _mutant));
var hullOnly = Array.IndexOf(args, "-hullOnly") >= 0;
if (!hullOnly) Atlas();
if (!hullOnly) Thermal(Array.IndexOf(args, "-fitThermal") >= 0);
if (!hullOnly) Thermal();
if (!hullOnly) Variants();
if (!hullOnly) Masked();
if (!hullOnly) LateLook();
@ -111,7 +145,7 @@ public static class InventoryGridParityCapture
if (Array.IndexOf(args, "-noHull") < 0) { Hull(); Interact(); }
if (Array.IndexOf(args, "-noHull") < 0) CheckBranchCounts();
Log($"SUMMARY atlasWorst={_atlasWorst} hullWorst={_hullWorst} thermalWorstRms={_thermalWorst:F4} thermalHullRms={_thermalHullWorst:F4} maskedWorst={_maskedWorst} alphaClipWorst={_alphaClipWorst} bounds atlas={AtlasBound} thermal={ThermalBound} thermalHull={ThermalHullBound}");
Log($"SUMMARY goldenWorst={_goldenWorst} maskedWorst={_maskedWorst} ghostWorst={_ghostWorst} bounds golden={GoldenBound} ghost={GhostBound}");
if (Breaches.Count > 0)
{
foreach (var breach in Breaches) Log("BOUND BREACHED " + breach);
@ -202,19 +236,6 @@ public static class InventoryGridParityCapture
}
}
private sealed class Oracle : IDisposable
{
public readonly GameObject PanelObject;
public readonly InventoryPanel Panel;
public Oracle()
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(PrefabPath) ?? throw new InvalidOperationException("No " + PrefabPath);
PanelObject = (GameObject) PrefabUtility.InstantiatePrefab(prefab);
Panel = PanelObject.GetComponent<InventoryPanel>() ?? PanelObject.GetComponentInChildren<InventoryPanel>(true);
}
public void Dispose() => UnityEngine.Object.DestroyImmediate(PanelObject);
}
private static Shader GridShader() => AssetDatabase.LoadAssetAtPath<Shader>(ShaderPath) ?? throw new InvalidOperationException("No " + ShaderPath);
// The look of the new path with the named mutant applied.
@ -272,13 +293,6 @@ public static class InventoryGridParityCapture
private static void Atlas()
{
using var oracle = new Oracle();
var panel = oracle.Panel;
// The texel constants rest on the sheets' pixels per unit (map IG-B1 states 66 for both; the background sheet is 100).
var iconPpu = panel.NodeTextures[0].pixelsPerUnit;
var bgPpu = panel.NodeBackgroundTextures[0].pixelsPerUnit;
Log($"sheets pixelsPerUnit icon={iconPpu} background={bgPpu}");
if (iconPpu != 66f || bgPpu != 100f) Breaches.Add($"sheet pixels per unit {iconPpu} / {bgPpu}, want 66 / 100");
foreach (var width in new[] { 1920, 2560 })
using (var rig = new Rig(width))
foreach (var regime in Regimes)
@ -288,30 +302,8 @@ public static class InventoryGridParityCapture
for (var pass = 0; pass < Passes.Length; pass++)
{
var (iconColor, bgColor) = Passes[pass];
// Old: one two-image cell per mask, the sheet's own sprites.
// One grid per mask, each fed the same record.
ClearPage(rig);
var cells = new List<GameObject>();
for (var m = 0; m < 512; m++)
{
var cell = UnityEngine.Object.Instantiate(panel.NodePrototype.gameObject, rig.Page, false);
cell.SetActive(true);
var rect = (RectTransform) cell.transform;
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.anchoredPosition = new Vector2(8 + m % columns * stride, 8 + m / columns * stride);
rect.sizeDelta = new Vector2(regime.Size, regime.Size);
var node = cell.GetComponent<InventoryCell>();
node.Background.sprite = panel.NodeBackgroundTextures[m & 255];
node.Background.color = bgColor;
node.Icon.sprite = panel.NodeTextures[m];
node.Icon.pixelsPerUnitMultiplier = regime.IconMultiplier;
node.Icon.color = iconColor;
cells.Add(cell);
}
var old = rig.Render();
ClearPage(rig);
// New: one grid per mask at the same rects, fed the same record.
for (var m = 0; m < 512; m++)
{
var go = NewObject("Grid " + m, rig.Page, 8 + m % columns * stride, 8 + m / columns * stride, regime.Size);
@ -324,51 +316,11 @@ public static class InventoryGridParityCapture
});
}
var fresh = rig.Render();
// Judge each cell's pixels; masks 33 and 289 are judged outside their authoring-slip footprint (IG-B3).
var worst = 0;
var worstMask = -1;
var slip = 0;
var pad = 0;
for (var m = 0; m < 512; m++)
{
var x0 = Mathf.Max(0, Mathf.FloorToInt((8 + m % columns * stride) * rig.Scale) - 2);
var y0 = Mathf.Max(0, Mathf.FloorToInt((8 + m / columns * stride) * rig.Scale) - 2);
var x1 = Mathf.CeilToInt((8 + m % columns * stride + regime.Size) * rig.Scale) + 2;
var y1 = Mathf.CeilToInt((8 + m / columns * stride + regime.Size) * rig.Scale) + 2;
var cellTop = (8 + m / columns * stride + regime.Size) * rig.Scale;
var tMin = Mathf.Min(InventoryGrid.TexelOf(66f, regime.IconMultiplier), InventoryGrid.TexelOf(100f, 1f));
var tMax = Mathf.Max(InventoryGrid.TexelOf(66f, regime.IconMultiplier), InventoryGrid.TexelOf(100f, 1f));
var isSlip = m == 33 || m == 289;
// Nodes8_392 and Nodes8BG_136 carry a wrong pad on their top and bottom edge (columns 5 to 8 read 0 where the
// sprite's own edge is filled), so the oracle itself bleeds there; half a texel and a pixel of each edge is not judged.
var isPad = m == 136 || m == 392;
var cellBottom = (8 + m / columns * stride) * rig.Scale;
for (var y = y0; y < y1; y++)
for (var x = x0; x < x1; x++)
{
var i = y * rig.Width + x;
var diff = MaxDifference(old[i], fresh[i]);
if (isPad)
{
var edge = Mathf.Min(cellTop - (y + .5f), y + .5f - cellBottom) / rig.Scale;
if (edge < .5f * tMax + 1.5f) { pad = Mathf.Max(pad, diff); continue; }
}
if (isSlip)
{
var fromTop = (cellTop - (y + .5f)) / rig.Scale;
if (fromTop > 1.5f * tMin - 1.5f && fromTop < 3.5f * tMax + 1.5f) { slip = Mathf.Max(slip, diff); continue; }
}
if (diff > worst) { worst = diff; worstMask = m; }
}
}
Log($"atlas {regime.Name} w={width} pass={pass} max8bitDiff={worst} (mask {worstMask}) slipFootprintMax={slip} padSlipMax={pad}");
_atlasWorst = Math.Max(_atlasWorst, worst);
if (worst > AtlasBound) Breaches.Add($"atlas {regime.Name} w={width} pass={pass}: {worst} > {AtlasBound}");
var atlasRegion = new RectInt(0, 0, Mathf.CeilToInt((8 + columns * stride) * rig.Scale), Mathf.CeilToInt((8 + 16 * stride) * rig.Scale));
WriteGolden($"atlas-{regime.Name}-w{width}-pass{pass}", rig, fresh, atlasRegion);
if (pass == 0 || pass == 2) SaveSideBySide($"atlas-{regime.Name}-{width}-pass{pass}.png", rig, old, fresh, atlasRegion);
_ = cells;
var region = new RectInt(0, 0, Mathf.CeilToInt((8 + columns * stride) * rig.Scale), Mathf.CeilToInt((8 + 16 * stride) * rig.Scale));
var name = $"atlas-{regime.Name}-w{width}-pass{pass}";
var worst = CompareToGolden(name, rig, fresh, region, out var reference);
Log($"atlas {regime.Name} w={width} pass={pass} max8bitDiff against the golden={worst}");
if (pass == 0 || pass == 2) SaveSideBySide($"{name}.png", rig, reference, fresh, region);
}
}
}
@ -522,51 +474,29 @@ public static class InventoryGridParityCapture
}
}
// The vertex alpha (a CanvasGroup fade, the drag ghost's half alpha) and a RectMask2D clip, against the same two on the sprite cells.
// The vertex alpha (a CanvasGroup fade, the drag ghost's half alpha) and a RectMask2D clip, against the golden.
private static void AlphaAndClip()
{
using var oracle = new Oracle();
var panel = oracle.Panel;
using var rig = new Rig(1920);
const float stride = 40;
foreach (var (name, alpha, clip) in new[] { ("opaque", 1f, false), ("quarter alpha", .25f, false), ("half alpha", .5f, false), ("RectMask2D", 1f, true), ("RectMask2D and half alpha", .5f, true) })
{
// Old: the cells under the clip rect (children of a RectMask2D object).
Transform OldRoot()
ClearPage(rig);
Transform root = rig.Page;
if (clip)
{
ClearPage(rig);
if (!clip) return rig.Page;
var mask = NewObject("Clip", rig.Page, 8 + 3 * stride - 9f, 8 + 1 * stride + 5f, 0);
mask.AddComponent<RectMask2D>();
var rect = (RectTransform) mask.transform;
rect.sizeDelta = new Vector2(6 * stride + 3.5f, 4 * stride + 7f);
return rect;
var clipRect = (RectTransform) mask.transform;
clipRect.sizeDelta = new Vector2(6 * stride + 3.5f, 4 * stride + 7f);
root = clipRect;
}
var origin = clip ? new Vector2(8 + 3 * stride - 9f, 8 + 1 * stride + 5f) : Vector2.zero;
var (iconColor, bgColor) = Passes[1];
var oldParent = OldRoot();
for (var m = 0; m < 64; m++)
{
if (m + 128 == 136) continue; // Nodes8BG_136 carries a wrong pad (see the atlas)
var cell = UnityEngine.Object.Instantiate(panel.NodePrototype.gameObject, oldParent, false);
cell.SetActive(true);
var rect = (RectTransform) cell.transform;
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.anchoredPosition = new Vector2(8 + m % 16 * stride, 8 + m / 16 * stride) - origin;
rect.sizeDelta = new Vector2(32, 32);
var node = cell.GetComponent<InventoryCell>();
node.Background.color = new Color(bgColor.r, bgColor.g, bgColor.b, bgColor.a * alpha);
node.Icon.sprite = panel.NodeTextures[m + 128];
node.Background.sprite = panel.NodeBackgroundTextures[(m + 128) & 255];
node.Icon.color = new Color(iconColor.r, iconColor.g, iconColor.b, iconColor.a * alpha);
}
var old = rig.Render();
var newParent = OldRoot();
for (var m = 0; m < 64; m++)
{
if (m + 128 == 136) continue;
var grid = MakeGrid((RectTransform) newParent, 0, 0, 32, 1f);
if (m + 128 == 136) continue; // the cell the sprite sheet could not judge (a wrong pad) stays unplaced, as in the golden
var grid = MakeGrid((RectTransform) root, 0, 0, 32, 1f);
var rect = (RectTransform) grid.transform;
rect.anchoredPosition = new Vector2(8 + m % 16 * stride, 8 + m / 16 * stride) - origin;
grid.color = new Color(1, 1, 1, alpha);
@ -574,20 +504,15 @@ public static class InventoryGridParityCapture
grid.SetCell(new int2(0, 0), SampleRecord(m + 128, iconColor, bgColor));
}
var fresh = rig.Render();
var worst = 0;
var lit = 0;
for (var i = 0; i < old.Length; i++)
{
worst = Mathf.Max(worst, MaxDifference(old[i], fresh[i]));
for (var i = 0; i < fresh.Length; i++)
if (fresh[i].r + fresh[i].g + fresh[i].b > 30) lit++;
}
Log($"{name}: max8bitDiff against the sprite cells = {worst}, {lit} lit pixels");
_alphaClipWorst = Math.Max(_alphaClipWorst, worst);
var region = new RectInt(0, 0, Mathf.CeilToInt(8 + 16 * stride), Mathf.CeilToInt(8 + 4 * stride));
var file = $"alpha-clip-{name.Replace(' ', '-')}";
var worst = CompareToGolden(file, rig, fresh, region, out var reference);
Log($"{name}: max8bitDiff against the golden = {worst}, {lit} lit pixels");
if (lit == 0) Breaches.Add($"{name}: nothing drawn");
if (worst > AtlasBound) Breaches.Add($"{name}: {worst} > {AtlasBound}");
var clipRegion = new RectInt(0, 0, Mathf.CeilToInt(8 + 16 * stride), Mathf.CeilToInt(8 + 4 * stride));
WriteGolden($"alpha-clip-{name.Replace(' ', '-')}", rig, fresh, clipRegion);
SaveSideBySide($"alpha-clip-{name.Replace(' ', '-')}.png", rig, old, fresh, clipRegion);
SaveSideBySide($"{file}.png", rig, reference, fresh, region);
}
}
@ -623,160 +548,33 @@ public static class InventoryGridParityCapture
}
}
// Thermal pipes: the 16 pipe sprites against the grid's blob and capsules, icon layer only. With -fitThermal the four look
// parameters are first fitted to the sprites by least squares (Nelder-Mead on the squared difference of both sizes) and printed.
private static void Thermal(bool fit)
// Thermal pipes: the 16 conductivity masks of the grid's blob and capsules, icon layer only, at two cell sizes, against the golden.
private static void Thermal()
{
using var oracle = new Oracle();
var panel = oracle.Panel;
const float stride = 48;
var sizes = new[] { 32f, 16f };
var rigs = sizes.Select(_ => new Rig(1920)).ToArray();
var olds = new Color32[sizes.Length][];
for (var k = 0; k < sizes.Length; k++)
foreach (var size in new[] { 32f, 16f })
{
var rig = rigs[k];
ClearPage(rig);
using var rig = new Rig(1920);
for (var m = 0; m < 16; m++)
{
var cell = UnityEngine.Object.Instantiate(panel.NodePrototype.gameObject, rig.Page, false);
cell.SetActive(true);
var rect = (RectTransform) cell.transform;
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.anchoredPosition = new Vector2(8 + m * stride, 8);
rect.sizeDelta = new Vector2(sizes[k], sizes[k]);
var node = cell.GetComponent<InventoryCell>();
node.Background.color = new Color(0, 0, 0, 0);
node.Icon.sprite = panel.ThermalTextures[m];
node.Icon.color = Color.white;
}
olds[k] = rig.Render();
ClearPage(rig);
}
var grids = new InventoryGrid[sizes.Length][];
for (var k = 0; k < sizes.Length; k++)
{
grids[k] = new InventoryGrid[16];
for (var m = 0; m < 16; m++)
{
var grid = NewObject("Pipes " + m, rigs[k].Page, 8 + m * stride, 8, sizes[k]).AddComponent<InventoryGrid>();
var grid = NewObject("Pipes " + m, rig.Page, 8 + m * stride, 8, size).AddComponent<InventoryGrid>();
Look(grid, 1f);
grid.Thermal = true;
grid.Resize(1, 1, sizes[k], new RectOffset(), GridOrientation.LowerLeft);
grid.Resize(1, 1, size, new RectOffset(), GridOrientation.LowerLeft);
grid.SetCell(new int2(0, 0), new CellRecord
{
Mask = 0, Present = true, Item = false, Conductivity = (byte) m, Icon = Color.white, Background = new Color(0, 0, 0, 0)
});
grids[k][m] = grid;
}
var fresh = rig.Render();
var region = new RectInt(0, 0, Mathf.CeilToInt(8 + 16 * stride), Mathf.CeilToInt(8 + size + 8));
var name = $"thermal-S{size}";
var worst = CompareToGolden(name, rig, fresh, region, out var reference);
Log($"thermal S{size} max8bitDiff against the golden = {worst}");
SaveSideBySide($"{name}.png", rig, reference, fresh, region);
}
double[] Rms(int k, Color32[] fresh)
{
var result = new double[16];
for (var m = 0; m < 16; m++)
{
double sum = 0;
var n = 0;
for (var y = 6; y < 8 + sizes[k] + 2; y++)
for (var x = 8 + m * (int) stride - 2; x < 8 + m * (int) stride + sizes[k] + 2; x++)
{
var i = y * rigs[k].Width + x;
var d = (olds[k][i].r - fresh[i].r) / 255.0;
sum += d * d;
n++;
}
result[m] = Math.Sqrt(sum / n);
}
return result;
}
void Apply(double[] p)
{
foreach (var row in grids)
foreach (var grid in row)
{
grid.BlobRadius = (float) p[0];
grid.PipeHalfWidth = (float) p[1];
grid.Fillet = (float) p[2];
grid.PipeSoft = (float) p[3];
grid.SetMaterialDirty();
}
}
double Cost(double[] p)
{
Apply(p);
double total = 0;
for (var k = 0; k < sizes.Length; k++) total += Rms(k, rigs[k].Render()).Sum(r => r * r);
return total;
}
var best = new double[] { grids[0][0].BlobRadius, grids[0][0].PipeHalfWidth, grids[0][0].Fillet, grids[0][0].PipeSoft };
if (fit)
{
var simplex = new double[5][];
var cost = new double[5];
for (var i = 0; i < 5; i++)
{
simplex[i] = (double[]) best.Clone();
if (i > 0) simplex[i][i - 1] *= 1.15;
cost[i] = Cost(simplex[i]);
}
for (var iteration = 0; iteration < 120; iteration++)
{
var order = Enumerable.Range(0, 5).OrderBy(i => cost[i]).ToArray();
simplex = order.Select(i => simplex[i]).ToArray();
cost = order.Select(i => cost[i]).ToArray();
var centroid = new double[4];
for (var i = 0; i < 4; i++) for (var d = 0; d < 4; d++) centroid[d] += simplex[i][d] / 4;
double[] Along(double t) => Enumerable.Range(0, 4).Select(d => Math.Max(1e-3, centroid[d] + t * (simplex[4][d] - centroid[d]))).ToArray();
var reflected = Along(-1);
var reflectedCost = Cost(reflected);
if (reflectedCost < cost[0])
{
var expanded = Along(-2);
var expandedCost = Cost(expanded);
if (expandedCost < reflectedCost) { simplex[4] = expanded; cost[4] = expandedCost; }
else { simplex[4] = reflected; cost[4] = reflectedCost; }
}
else if (reflectedCost < cost[3]) { simplex[4] = reflected; cost[4] = reflectedCost; }
else
{
var contracted = Along(.5);
var contractedCost = Cost(contracted);
if (contractedCost < cost[4]) { simplex[4] = contracted; cost[4] = contractedCost; }
else
for (var i = 1; i < 5; i++)
{
for (var d = 0; d < 4; d++) simplex[i][d] = simplex[0][d] + .5 * (simplex[i][d] - simplex[0][d]);
cost[i] = Cost(simplex[i]);
}
}
}
var bestIndex = Enumerable.Range(0, 5).OrderBy(i => cost[i]).First();
best = simplex[bestIndex];
Log($"thermal fit BlobRadius={best[0]:F4} PipeHalfWidth={best[1]:F4} Fillet={best[2]:F4} PipeSoft={best[3]:F4} cost={cost[bestIndex]:F5}");
}
Apply(best);
for (var k = 0; k < sizes.Length; k++)
{
var fresh = rigs[k].Render();
var rms = Rms(k, fresh);
var worst = rms.Max();
Log($"thermal S{sizes[k]} worstRms={worst:F4} (mask {Array.IndexOf(rms, worst)})");
_thermalWorst = Math.Max(_thermalWorst, worst);
if (worst > ThermalBound) Breaches.Add($"thermal S{sizes[k]}: rms {worst:F4} > {ThermalBound}");
var thermalRegion = new RectInt(0, 0, Mathf.CeilToInt(8 + 16 * stride), Mathf.CeilToInt(8 + sizes[k] + 8));
WriteGolden($"thermal-S{sizes[k]}", rigs[k], fresh, thermalRegion);
SaveSideBySide($"thermal-S{sizes[k]}.png", rigs[k], olds[k], fresh, thermalRegion);
}
foreach (var rig in rigs) rig.Dispose();
}
// ---- Real hull ------------------------------------------------------------------------------------------------------
private sealed class Fixture : IDisposable
@ -938,7 +736,6 @@ public static class InventoryGridParityCapture
var panel = panelObject.GetComponent<InventoryPanel>() ?? panelObject.GetComponentInChildren<InventoryPanel>(true);
panel.GameManager = fixture.Manager;
if (!panel.Settings) panel.Settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset");
panel.NodePrototype.gameObject.SetActive(false);
var panelRect = (RectTransform) panel.transform;
if (!state.Hud)
{
@ -947,7 +744,6 @@ public static class InventoryGridParityCapture
panelRect.anchoredPosition = Vector2.zero;
panelRect.sizeDelta = new Vector2(1200, 900);
}
var iconMultiplier = panel.NodePrototype.GetComponent<InventoryCell>().Icon.pixelsPerUnitMultiplier;
var grid = panel.Grid;
state.Setup?.Invoke(panel, fixture);
// A bay shown after the thermal view on the same panel must not draw pipes.
@ -967,6 +763,8 @@ public static class InventoryGridParityCapture
typeof(InventoryPanel).GetMethod("Update", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(panel, null);
}
var records = LiveRecords(grid);
// A bay shown after the thermal view draws cells, not pipes: the golden compares records, which a stale Thermal flag leaves intact.
Check(grid.Thermal == state.Thermal, $"the grid's Thermal flag follows the state ({state.Name}: {grid.Thermal})");
var columns = grid.Width;
var rows = grid.Height;
var gridRect = grid.rectTransform;
@ -976,169 +774,24 @@ public static class InventoryGridParityCapture
// The live panel as it draws.
var fresh = rig.Render();
// The oracle: the sheets' own sprite cells of the same records at the live cell rects, the grid hidden.
var cellRects = new Dictionary<int2, RectTransform>();
var oracle = new Dictionary<int2, InventoryCell>();
foreach (var (v, record) in records)
{
var cell = panel.NodePrototype.Instantiate<InventoryCell>();
// Under the grid's own object: in the same mask as the grid and outside the container's layout group (the menu's), which would
// move them. The grid is hidden by a clear vertex colour, not by disabling it: a disabled grid leaves the layout and the
// container collapses.
cell.transform.SetParent(grid.transform, false);
var rect = (RectTransform) cell.transform;
var at = grid.CellRect(v);
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.sizeDelta = at.size;
rect.position = gridRect.TransformPoint(at.min);
cell.Background.sprite = panel.NodeBackgroundTextures[record.Mask];
cell.Background.color = record.Background;
cell.Icon.sprite = state.Thermal ? panel.ThermalTextures[record.Conductivity] : panel.NodeTextures[record.Mask + (record.Item ? 256 : 0)];
cell.Icon.color = record.Icon;
oracle.Add(v, cell);
cellRects.Add(v, rect);
}
grid.color = Color.clear;
var old = rig.Render();
grid.color = Color.white;
foreach (var cell in oracle.Values) cell.gameObject.SetActive(false);
// Judge the whole panel's pixels; cells whose sprite has a known authoring slip are judged outside its footprint.
// The panel's own pixels have no reference of their own: the atlas golden covers records to pixels, and the records golden
// (-recordsIn) covers the panel to records and rects. The render is kept for the operator's eyes.
var camera = rig.Camera;
Rect PixelRect(RectTransform rect)
{
var corners = new Vector3[4];
rect.GetWorldCorners(corners);
var a = RectTransformUtility.WorldToScreenPoint(camera, corners[0]);
var b = RectTransformUtility.WorldToScreenPoint(camera, corners[2]);
return Rect.MinMaxRect(Mathf.Min(a.x, b.x), Mathf.Min(a.y, b.y), Mathf.Max(a.x, b.x), Mathf.Max(a.y, b.y));
}
var excluded = new bool[rig.Width * rig.Height];
var ties = 0;
var minX = int.MaxValue;
var minY = int.MaxValue;
var maxX = 0;
var maxY = 0;
foreach (var (v, record) in records)
foreach (var (v, _) in records)
{
var pixels = PixelRect(cellRects[v]);
minX = Mathf.Min(minX, Mathf.FloorToInt(pixels.xMin));
minY = Mathf.Min(minY, Mathf.FloorToInt(pixels.yMin));
maxX = Mathf.Max(maxX, Mathf.CeilToInt(pixels.xMax));
maxY = Mathf.Max(maxY, Mathf.CeilToInt(pixels.yMax));
// A pixel centre exactly on a cell boundary (panels at half-pixel offsets at 1920) is not judged. The sprite cells are separate
// quads whose edges the rasteriser resolves by float noise: the pixel comes out as one neighbour or the other, or as both
// (the additive icon doubled), and the choice moves with the panel's offset. The grid draws it from one cell by the
// floor of its coordinate, so a boundary pixel can differ from the sprite cells by one seam's worth of rule or bracket
// tip. Trying the fill rule with float slack in the shader matched no better (the menu stayed at 122, the enemy state
// went from 1 to 131), so the shader keeps the plain floor.
for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin) - 1); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax) + 1); y++)
for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin) - 1); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax) + 1); x++)
if (Mathf.Abs(x + .5f - pixels.xMin) < .01f || Mathf.Abs(x + .5f - pixels.xMax) < .01f ||
Mathf.Abs(y + .5f - pixels.yMin) < .01f || Mathf.Abs(y + .5f - pixels.yMax) < .01f)
{
if (!excluded[y * rig.Width + x]) ties++;
excluded[y * rig.Width + x] = true;
}
var iconMask = record.Mask | (record.Item ? 256 : 0);
var slip = (!state.Thermal && (iconMask == 33 || iconMask == 289)) || record.Mask == 33;
var padSlip = record.Mask == 136 || (!state.Thermal && iconMask == 392);
if (!slip && !padSlip) continue;
var texelMin = Mathf.Min(InventoryGrid.TexelOf(66f, iconMultiplier), InventoryGrid.TexelOf(100f, 1f)) * rig.Scale;
var texelMax = Mathf.Max(InventoryGrid.TexelOf(66f, iconMultiplier), InventoryGrid.TexelOf(100f, 1f)) * rig.Scale;
for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin) - 2); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax) + 2); y++)
for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin) - 2); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax) + 2); x++)
{
var fromTop = pixels.yMax - (y + .5f);
var fromBottom = y + .5f - pixels.yMin;
if (slip && fromTop > 1.5f * texelMin - 1.5f && fromTop < 3.5f * texelMax + 1.5f) excluded[y * rig.Width + x] = true;
if (padSlip && Mathf.Min(fromTop, fromBottom) < .5f * texelMax + 1.5f) excluded[y * rig.Width + x] = true;
}
}
var worst = 0;
var worstAt = (0, 0);
for (var y = Mathf.Max(0, minY - 2); y < Mathf.Min(rig.Height, maxY + 2); y++)
for (var x = Mathf.Max(0, minX - 2); x < Mathf.Min(rig.Width, maxX + 2); x++)
{
var i = y * rig.Width + x;
var diff = MaxDifference(old[i], fresh[i]);
if (!excluded[i] && diff > worst) { worst = diff; worstAt = (x, y); }
}
if (worst > AtlasBound)
{
var perCell = new List<(int diff, int2 v, string at)>();
foreach (var (v, record) in records)
{
var pixels = PixelRect(cellRects[v]);
var cellWorst = 0;
var at = "";
for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin)); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax)); y++)
for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin)); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax)); x++)
if (!excluded[y * rig.Width + x])
{
var d = MaxDifference(old[y * rig.Width + x], fresh[y * rig.Width + x]);
if (d > cellWorst) { cellWorst = d; at = $"px {x},{y} cell px [{pixels.xMin:F2},{pixels.xMax:F2}]x[{pixels.yMin:F2},{pixels.yMax:F2}] old {old[y * rig.Width + x]} new {fresh[y * rig.Width + x]}"; }
}
if (cellWorst > AtlasBound) perCell.Add((cellWorst, v, at));
}
foreach (var (diff, v, where) in perCell.OrderByDescending(c => c.diff).Take(8))
{
var r = records[v];
Log($" worst cell {v.x},{v.y} {where}: diff {diff} mask {r.Mask} ({Convert.ToString(r.Mask, 2).PadLeft(8, '0')}) item {r.Item} icon {r.Icon} bg {r.Background} sprite {oracle[v].Icon.sprite.name}/{oracle[v].Background.sprite.name}");
}
}
Log($"hull {state.Name} w={width} cells={records.Count} max8bitDiff={worst} at {worstAt} boundaryPixelsNotJudged={ties}" + (state.Thermal ? " (thermal: the pipes are a fit, judged by cell rms)" : ""));
if (!state.Thermal) _hullWorst = Math.Max(_hullWorst, worst);
if (!state.Thermal && worst > AtlasBound) Breaches.Add($"hull {state.Name} w={width}: {worst} > {AtlasBound}");
if (state.Thermal)
{
var worstRms = 0.0;
foreach (var (v, _) in records)
{
var pixels = PixelRect(cellRects[v]);
double sum = 0;
var n = 0;
for (var y = Mathf.Max(0, Mathf.FloorToInt(pixels.yMin)); y < Mathf.Min(rig.Height, Mathf.CeilToInt(pixels.yMax)); y++)
for (var x = Mathf.Max(0, Mathf.FloorToInt(pixels.xMin)); x < Mathf.Min(rig.Width, Mathf.CeilToInt(pixels.xMax)); x++)
{
var d = (old[y * rig.Width + x].r - fresh[y * rig.Width + x].r) / 255.0;
sum += d * d;
n++;
}
if (n > 0) worstRms = Math.Max(worstRms, Math.Sqrt(sum / n));
}
Log($"hull thermal w={width} worst cell rms={worstRms:F4}");
// The background layer of every thermal cell, icons hidden in both paths, judged by the atlas bound.
foreach (var cell in oracle.Values)
{
cell.gameObject.SetActive(true);
var hidden = cell.Icon.color;
hidden.a = 0;
cell.Icon.color = hidden;
}
grid.color = Color.clear;
var old2 = rig.Render();
foreach (var cell in oracle.Values) cell.gameObject.SetActive(false);
grid.color = Color.white;
foreach (var (v, record) in records)
{
var hiddenRecord = record;
hiddenRecord.Icon.a = 0;
grid.SetCell(v, hiddenRecord);
}
var fresh2 = rig.Render();
var worstBackground = 0;
for (var y = Mathf.Max(0, minY - 2); y < Mathf.Min(rig.Height, maxY + 2); y++)
for (var x = Mathf.Max(0, minX - 2); x < Mathf.Min(rig.Width, maxX + 2); x++)
if (!excluded[y * rig.Width + x]) worstBackground = Mathf.Max(worstBackground, MaxDifference(old2[y * rig.Width + x], fresh2[y * rig.Width + x]));
Log($"hull thermal w={width} background layer max8bitDiff={worstBackground}");
_hullWorst = Math.Max(_hullWorst, worstBackground);
if (worstBackground > AtlasBound) Breaches.Add($"hull thermal background w={width}: {worstBackground} > {AtlasBound}");
_thermalHullWorst = Math.Max(_thermalHullWorst, worstRms);
if (worstRms > ThermalHullBound) Breaches.Add($"hull thermal w={width}: cell rms {worstRms:F4} > {ThermalHullBound}");
var corners = new Vector3[2] { gridRect.TransformPoint(grid.CellRect(v).min), gridRect.TransformPoint(grid.CellRect(v).max) };
var a = RectTransformUtility.WorldToScreenPoint(camera, corners[0]);
var b = RectTransformUtility.WorldToScreenPoint(camera, corners[1]);
minX = Mathf.Min(minX, Mathf.FloorToInt(Mathf.Min(a.x, b.x)));
minY = Mathf.Min(minY, Mathf.FloorToInt(Mathf.Min(a.y, b.y)));
maxX = Mathf.Max(maxX, Mathf.CeilToInt(Mathf.Max(a.x, b.x)));
maxY = Mathf.Max(maxY, Mathf.CeilToInt(Mathf.Max(a.y, b.y)));
}
Log($"hull {state.Name} w={width} cells={records.Count}");
// Hit-testing: CellAt returns the cell at every cell centre and nothing over an absent cell; empty cells pass clicks through.
var misses = 0;
@ -1162,7 +815,7 @@ public static class InventoryGridParityCapture
var x0 = Mathf.Max(0, minX - 8);
var y0 = Mathf.Max(0, minY - 8);
var region = new RectInt(x0, y0, Mathf.Min(rig.Width, maxX + 8) - x0, Mathf.Min(rig.Height, maxY + 8) - y0);
SaveSideBySide($"hull-{state.Name}-{width}.png", rig, old, fresh, region);
SavePng($"hull-{state.Name}-{width}.png", rig, fresh, region);
}
ClearPage(rig);
}
@ -1207,7 +860,6 @@ public static class InventoryGridParityCapture
panel.GameManager = fixture.Manager;
if (!panel.Settings) panel.Settings = settings;
panel.DragParent = dragParent;
panel.NodePrototype.gameObject.SetActive(false);
var rect = (RectTransform) panel.transform;
rect.anchorMin = rect.anchorMax = new Vector2(.5f, .5f);
rect.pivot = new Vector2(.5f, .5f);
@ -1244,13 +896,16 @@ public static class InventoryGridParityCapture
equipment.Display(ship);
Layout(equipment);
var grid = equipment.Grid;
// The smallest equipped item whose cells are all on the screen with a margin (the hull is taller than the page).
// The smallest equipped item whose cells are all on the screen with a margin (the hull is taller than the page) and inside the
// panel's viewport (its Mask clips the rest, and the ghost, which is not under the mask, is judged against the panel's pixels).
var viewport = ScreenRect(rig.Camera, (RectTransform) grid.GetComponentInParent<Mask>().transform);
bool OnScreen(int2 v)
{
var r = grid.CellRect(v);
var a = ScreenOf(grid, r.min);
var b = ScreenOf(grid, r.max);
return Mathf.Min(a.x, b.x) > 40 && Mathf.Max(a.x, b.x) < rig.Width - 40 && Mathf.Min(a.y, b.y) > 40 && Mathf.Max(a.y, b.y) < rig.Height - 40;
return Mathf.Min(a.x, b.x) > Mathf.Max(40, viewport.xMin + 4) && Mathf.Max(a.x, b.x) < Mathf.Min(rig.Width - 40, viewport.xMax - 4) &&
Mathf.Min(a.y, b.y) > Mathf.Max(40, viewport.yMin + 4) && Mathf.Max(a.y, b.y) < Mathf.Min(rig.Height - 40, viewport.yMax - 4);
}
var equipped = ship.Equipment.Where(e => e.EquippableItem != null)
.Where(e => hull.Shape.Inset(e.Data.Shape, e.Position, e.EquippableItem.Rotation).Coordinates.All(OnScreen))
@ -1294,6 +949,13 @@ public static class InventoryGridParityCapture
var fits = bay.Data.InteriorShape[target] && bay.ItemFits(item, target + offset);
Check(fits, $"an equipped item fits the emptied bay (item {equipped.Data.Name}, shape {equipped.Data.Shape.Width}x{equipped.Data.Shape.Height}, bay {bay.Data.InteriorShape.Width}x{bay.Data.InteriorShape.Height})");
// The panel's grid alone, before the drag starts: the dragged item's cells are ignored (drawn as holes) once it has, and the panel's
// other graphics (the layer under its cells) are not the ghost's to match.
var layers = equipment.GetComponentsInChildren<Graphic>().Where(g => g != grid && g.enabled).ToArray();
foreach (var layer in layers) layer.enabled = false;
Canvas.ForceUpdateCanvases();
var panelPixels = RenderAll();
foreach (var layer in layers) layer.enabled = true;
if (_mutant == "ghost-full-alpha") equipment.DragGhost.color = Color.white;
var press = Centre(grid, itemCells[0]);
ExecuteEvents.Execute(grid.gameObject, Pointer(grid.gameObject, press), ExecuteEvents.beginDragHandler);
@ -1313,48 +975,48 @@ public static class InventoryGridParityCapture
var rectGap = Worst(PageRect(rig, ghost.rectTransform), want);
Check(rectGap <= RectBound, $"the ghost's rect is the union of the item's cell rects (worst {rectGap:F5}, bound {RectBound}; ghost {string.Join(",", PageRect(rig, ghost.rectTransform))}, union {string.Join(",", want)})");
// Its pixels against the sprite cells of the same records at half alpha.
// Its pixels are half the panel's own over the item's cell interiors, before anything moves: the ghost alone with the panel shrunk
// to nothing, against the panel drawn before the drag (its cells are the same records, the ghost's vertex alpha is .5, and the
// shader's output is premultiplied, so rgb and alpha both halve). The target is sRGB, so rgb halves in linear light: the stored
// value is decoded, halved and encoded again; alpha is stored linear.
float HalfOf(byte stored)
{
var c = stored / 255f;
var linear = c <= .04045f ? c / 12.92f : Mathf.Pow((c + .055f) / 1.055f, 2.4f);
linear *= .5f;
return 255f * (linear <= .0031308f ? linear * 12.92f : 1.055f * Mathf.Pow(linear, 1f / 2.4f) - .055f);
}
Canvas.ForceUpdateCanvases();
var withGhost = RenderAll();
ghost.gameObject.SetActive(false);
var excluded = new List<Rect>();
var oracle = new List<GameObject>();
var panelScale = equipment.transform.localScale;
equipment.transform.localScale = Vector3.zero;
var ghostAlone = RenderAll();
equipment.transform.localScale = panelScale;
Canvas.ForceUpdateCanvases();
var ghostRect = ScreenRect(rig.Camera, ghost.rectTransform);
var worstGhost = 0;
var worstAt = "";
var litGhost = 0;
foreach (var v in itemCells)
{
var record = ghost.RecordAt(v - min);
var cell = equipment.NodePrototype.Instantiate<InventoryCell>();
cell.transform.SetParent(rig.Page, false);
var rect = (RectTransform) cell.transform;
var at = ghost.CellRect(v - min);
rect.anchorMin = rect.anchorMax = Vector2.zero;
rect.pivot = Vector2.zero;
rect.sizeDelta = at.size;
rect.position = ghost.rectTransform.TransformPoint(at.min);
cell.Background.sprite = equipment.NodeBackgroundTextures[record.Mask];
cell.Icon.sprite = equipment.NodeTextures[record.Mask + (record.Item ? 256 : 0)];
Color Half(Color32 c) => new Color(c.r / 255f, c.g / 255f, c.b / 255f, c.a / 255f * .5f);
cell.Background.color = Half(record.Background);
cell.Icon.color = Half(record.Icon);
oracle.Add(cell.gameObject);
var iconMask = record.Mask + (record.Item ? 256 : 0);
if (record.Mask == 33 || iconMask == 33 || iconMask == 289 || record.Mask == 136 || iconMask == 392) excluded.Add(ScreenRect(rig.Camera, rect));
var at = grid.CellRect(v);
var a = ScreenOf(grid, at.min);
var b = ScreenOf(grid, at.max);
for (var y = Mathf.CeilToInt(Mathf.Min(a.y, b.y)) + 2; y < Mathf.FloorToInt(Mathf.Max(a.y, b.y)) - 2; y++)
for (var x = Mathf.CeilToInt(Mathf.Min(a.x, b.x)) + 2; x < Mathf.FloorToInt(Mathf.Max(a.x, b.x)) - 2; x++)
{
var p = panelPixels[y * rig.Width + x];
var g = ghostAlone[y * rig.Width + x];
var gap = Mathf.Max(Mathf.Abs(g.r - HalfOf(p.r)), Mathf.Abs(g.g - HalfOf(p.g)), Mathf.Abs(g.b - HalfOf(p.b)), Mathf.Abs(g.a - p.a / 2f));
if (Mathf.CeilToInt(gap) > worstGhost) { worstGhost = Mathf.CeilToInt(gap); worstAt = $"px {x},{y} cell {v.x},{v.y} panel {p} ghost {g}"; }
if (p.r + p.g + p.b > 60) litGhost++;
}
}
var withOracle = RenderAll();
foreach (var cell in oracle) UnityEngine.Object.DestroyImmediate(cell);
var ghostPixels = ScreenRect(rig.Camera, ghost.rectTransform);
var worstGhost = 0;
var litGhost = 0;
for (var y = Mathf.Max(0, Mathf.FloorToInt(ghostPixels.yMin) - 2); y < Mathf.Min(rig.Height, Mathf.CeilToInt(ghostPixels.yMax) + 2); y++)
for (var x = Mathf.Max(0, Mathf.FloorToInt(ghostPixels.xMin) - 2); x < Mathf.Min(rig.Width, Mathf.CeilToInt(ghostPixels.xMax) + 2); x++)
{
if (excluded.Any(r => x + .5f > r.xMin - 2 && x + .5f < r.xMax + 2 && y + .5f > r.yMin - 2 && y + .5f < r.yMax + 2)) continue;
worstGhost = Mathf.Max(worstGhost, MaxDifference(withGhost[y * rig.Width + x], withOracle[y * rig.Width + x]));
if (withOracle[y * rig.Width + x].r > 20) litGhost++;
}
Check(worstGhost <= AtlasBound && litGhost > 100, $"the ghost's pixels equal the oracle cells at half alpha (max channel diff {worstGhost}, bound {AtlasBound}, {litGhost} lit pixels judged, {excluded.Count} slip cells not judged, ghost px {ghostPixels})");
_ghostWorst = Math.Max(_ghostWorst, worstGhost);
Check(worstGhost <= GhostBound && litGhost > 100, $"the ghost's pixels are half the panel's own over the item's cell interiors (max level gap {worstGhost} at {worstAt}, bound {GhostBound}, {litGhost} lit pixels judged, ghost px {ghostRect})");
if (_pngOut != null)
SaveSideBySide("interact-ghost.png", rig, withOracle, withGhost, new RectInt(Mathf.Max(0, (int) ghostPixels.xMin - 16), Mathf.Max(0, (int) ghostPixels.yMin - 16), (int) ghostPixels.width + 32, (int) ghostPixels.height + 32));
ghost.gameObject.SetActive(true);
SavePng("interact-ghost-panel.png", rig, panelPixels, new RectInt(Mathf.Max(0, (int) ghostRect.xMin - 16), Mathf.Max(0, (int) ghostRect.yMin - 16), (int) ghostRect.width + 32, (int) ghostRect.height + 32));
if (_pngOut != null)
SavePng("interact-ghost.png", rig, ghostAlone, new RectInt(Mathf.Max(0, (int) ghostRect.xMin - 16), Mathf.Max(0, (int) ghostRect.yMin - 16), (int) ghostRect.width + 32, (int) ghostRect.height + 32));
// A drag moves the ghost by the pointer's delta.
var before = ghost.rectTransform.position;
@ -1605,7 +1267,20 @@ public static class InventoryGridParityCapture
if (count == 0) Breaches.Add($"no state reached the {branch} branch of RefreshCells");
}
// old | new | abs difference x 8, cropped to the region.
// The render cropped to the region, written as a PNG for the operator.
private static void SavePng(string name, Rig rig, Color32[] pixels, RectInt region)
{
if (_pngOut == null) return;
var crop = Crop(rig, pixels, ref region);
if (region.width <= 0 || region.height <= 0) throw new InvalidOperationException($"{name}: the region {region} lies outside the {rig.Width}x{rig.Height} frame.");
var output = new Texture2D(region.width, region.height, TextureFormat.RGBA32, false);
for (var i = 0; i < crop.Length; i++) crop[i].a = 255;
output.SetPixels32(crop);
File.WriteAllBytes(Path.Combine(_pngOut, name), output.EncodeToPNG());
UnityEngine.Object.DestroyImmediate(output);
}
// golden | new | abs difference x 8, cropped to the region.
private static void SaveSideBySide(string name, Rig rig, Color32[] old, Color32[] fresh, RectInt region)
{
if (_pngOut == null) return;