Inventory grid parity: the hud and enemy states use the real ARPG.unity panels, -recordsOut writes the golden (records, cell rects, temperature rect)

Taken from the old sprite panels before any switch code. HUD and Enemy are copied from the scene as authored (no emulated multiplier, Flip, start corner or rect), the other five states keep the prefab. The golden is a run output kept outside git. FrameTime goes: it times the sprite writer the switch deletes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 04:17:42 +01:00
commit afb6d69b76

View file

@ -4,6 +4,7 @@ using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.UI;
using UniRx.Triggers;
@ -13,7 +14,10 @@ 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.
//
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridParityCapture.Run [-pngOut <dir>] [-mutant <name>] -logFile <log>
// Unity -batchmode -projectPath <project> -executeMethod InventoryGridParityCapture.Run [-pngOut <dir>] [-mutant <name>] [-hullOnly] [-recordsOut <file>] -logFile <log>
//
// -recordsOut writes the golden of the real-hull states (every cell's record and rect in page canvas units, and the temperature display's
// rect), read off the panel as it stands. The golden is a run output, kept outside git; Soul regenerates it from the first commit of the cut.
//
// 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.
@ -37,7 +41,7 @@ public static class InventoryGridParityCapture
private static double _thermalWorst, _thermalHullWorst;
private static string _mutant = "";
private static string _pngOut;
private static string _pngOut, _recordsOut;
private static readonly List<string> Breaches = new List<string>();
public static readonly string[] Mutants =
@ -54,6 +58,7 @@ public static class InventoryGridParityCapture
var args = Environment.GetCommandLineArgs();
string Arg(string name) { var i = Array.IndexOf(args, name); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; }
_pngOut = Arg("-pngOut");
_recordsOut = Arg("-recordsOut");
_mutant = Arg("-mutant") ?? "";
if (Arg("-atlasBound") != null) AtlasBound = int.Parse(Arg("-atlasBound"));
if (Arg("-thermalBound") != null) ThermalHullBound = ThermalBound = double.Parse(Arg("-thermalBound"), System.Globalization.CultureInfo.InvariantCulture);
@ -69,6 +74,7 @@ public static class InventoryGridParityCapture
if (!hullOnly) LateLook();
if (!hullOnly) AlphaAndClip();
if (Array.IndexOf(args, "-noHull") < 0) Hull();
if (_recordsOut != null) WriteGolden();
Log($"SUMMARY atlasWorst={_atlasWorst} hullWorst={_hullWorst} thermalWorstRms={_thermalWorst:F4} thermalHullRms={_thermalHullWorst:F4} maskedWorst={_maskedWorst} alphaClipWorst={_alphaClipWorst} bounds atlas={AtlasBound} thermal={ThermalBound} thermalHull={ThermalHullBound}");
if (Breaches.Count > 0)
@ -862,66 +868,7 @@ public static class InventoryGridParityCapture
foreach (var width in new[] { 1920, 2560 })
using (var rig = new Rig(width))
foreach (var state in states)
HullStateCheck(rig, fixture, state, width, width == 1920 && state.Name == "menu" ? FrameTime : (Action<Rig, InventoryPanel, InventoryGrid, Dictionary<int2, CellRecord>>) null);
}
// A reading, not a gate: 101 paired, interleaved iterations of the menu real-hull state. Each times a full refresh with changed content
// plus Canvas.ForceUpdateCanvases plus camera.Render plus a 1-pixel ReadPixels sync. The writer stays in both: the sprite cells time
// RefreshCells; the grid times RefreshCells (its match predicates, GetColor and sprite sets still run until the switch cut) plus SetCell
// for every cell plus the texture Apply. The writer alone is timed too.
private static void FrameTime(Rig rig, InventoryPanel panel, InventoryGrid grid, Dictionary<int2, CellRecord> recordsA)
{
var fixtureShip = (Entity) panel.GameManager.CurrentEntity;
var hull = (HullData) panel.GameManager.ItemManager.GetData(fixtureShip.Hull);
var item = fixtureShip.Equipment.First(e => e.EquippableItem != null);
var shape = hull.Shape.Inset(item.Data.Shape, item.Position, item.EquippableItem.Rotation);
foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(true);
panel.IgnoreOccupancy = shape;
panel.RefreshCells();
var recordsB = ReadRecords(panel, false);
panel.IgnoreOccupancy = null;
panel.RefreshCells();
var one = new Texture2D(1, 1, TextureFormat.RGBA32, false);
void Sync()
{
Canvas.ForceUpdateCanvases();
rig.Camera.Render();
var previous = RenderTexture.active;
RenderTexture.active = rig.Camera.targetTexture;
one.ReadPixels(new Rect(0, 0, 1, 1), 0, 0);
RenderTexture.active = previous;
}
double OldIteration(int i)
{
foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(true);
grid.gameObject.SetActive(false);
Sync();
var watch = System.Diagnostics.Stopwatch.StartNew();
panel.IgnoreOccupancy = i % 2 == 0 ? shape : null;
panel.RefreshCells();
Sync();
return watch.Elapsed.TotalMilliseconds;
}
double NewIteration(int i)
{
foreach (var cell in panel.CellInstances.Values) cell.gameObject.SetActive(false);
grid.gameObject.SetActive(true);
Sync();
panel.IgnoreOccupancy = i % 2 == 0 ? shape : null;
var watch = System.Diagnostics.Stopwatch.StartNew();
panel.RefreshCells();
foreach (var (v, record) in i % 2 == 0 ? recordsB : recordsA) grid.SetCell(v, record);
grid.Flush();
Sync();
return watch.Elapsed.TotalMilliseconds;
}
for (var i = 0; i < 5; i++) { OldIteration(i); NewIteration(i); }
var olds = new List<double>();
var news = new List<double>();
for (var i = 0; i < 101; i++) { olds.Add(OldIteration(i)); news.Add(NewIteration(i)); }
double Percentile(List<double> values, double q) { var sorted = values.OrderBy(v => v).ToList(); return sorted[(int) Math.Round(q * (sorted.Count - 1))]; }
Log($"frame time (ms, 101 paired iterations, menu real hull, {panel.CellInstances.Count} cells) old median {Percentile(olds, .5):F2} [p25 {Percentile(olds, .25):F2}, p75 {Percentile(olds, .75):F2}], new median {Percentile(news, .5):F2} [p25 {Percentile(news, .25):F2}, p75 {Percentile(news, .75):F2}]");
UnityEngine.Object.DestroyImmediate(one);
HullStateCheck(rig, fixture, state, width);
}
// Every cell's record, read back from the sprite cells: the mask from the sprite name's index, plus the two colours.
@ -944,36 +891,45 @@ public static class InventoryGridParityCapture
return records;
}
private static void HullStateCheck(Rig rig, Fixture fixture, HullState state, int width, Action<Rig, InventoryPanel, InventoryGrid, Dictionary<int2, CellRecord>> afterwards = null)
// The scene's own panel, copied into the rig page as it is authored: nothing about its rect, cell size, start corner, Flip or
// multiplier is set here. The scene is opened additively for the copy and closed.
private static GameObject SceneClone(string path, RectTransform page)
{
var scene = EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Additive);
try
{
var slash = path.IndexOf('/');
var root = scene.GetRootGameObjects().FirstOrDefault(o => o.name == path.Substring(0, slash)) ?? throw new InvalidOperationException("No root " + path.Substring(0, slash) + " in ARPG.unity");
var found = root.transform.Find(path.Substring(slash + 1)) ?? throw new InvalidOperationException("No " + path + " in ARPG.unity");
var copy = UnityEngine.Object.Instantiate(found.gameObject, page, false);
copy.SetActive(true);
return copy;
}
finally { EditorSceneManager.CloseScene(scene, true); }
}
private static void HullStateCheck(Rig rig, Fixture fixture, HullState state, int width)
{
ClearPage(rig);
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(PrefabPath);
var panelObject = (GameObject) PrefabUtility.InstantiatePrefab(prefab, rig.Page);
var panelObject = state.Hud
? SceneClone(state.Enemy ? "Canvas/Gameplay/Enemy Inventory" : "Canvas/Gameplay/Hud Schematic/Inventory", rig.Page)
: (GameObject) PrefabUtility.InstantiatePrefab(prefab, rig.Page);
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;
panelRect.anchorMin = panelRect.anchorMax = new Vector2(.5f, .5f);
panelRect.pivot = new Vector2(.5f, .5f);
panelRect.anchoredPosition = Vector2.zero;
panelRect.sizeDelta = new Vector2(1200, 900);
if (!state.Hud)
{
panelRect.anchorMin = panelRect.anchorMax = new Vector2(.5f, .5f);
panelRect.pivot = new Vector2(.5f, .5f);
panelRect.anchoredPosition = Vector2.zero;
panelRect.sizeDelta = new Vector2(1200, 900);
}
var content = (RectTransform) panel.Grid.transform;
var fitter = content.GetComponent<ContentSizeFitter>();
var iconMultiplier = state.Hud ? 1.5f : 1f;
panel.NodePrototype.GetComponent<InventoryCell>().Icon.pixelsPerUnitMultiplier = iconMultiplier;
panel.Flip = state.Enemy;
panel.Grid.startCorner = state.Enemy ? GridLayoutGroup.Corner.UpperRight : GridLayoutGroup.Corner.LowerLeft;
panel.FitToContent = state.Hud;
if (state.Hud)
{
// The HUD's schematic rect: no fitter, a fixed rect the cells are sized to.
if (fitter) fitter.enabled = false;
content.anchorMin = content.anchorMax = new Vector2(.5f, .5f);
content.pivot = new Vector2(.5f, .5f);
content.sizeDelta = state.Enemy ? new Vector2(260, 260) : new Vector2(254, 260);
content.anchoredPosition = Vector2.zero;
}
var iconMultiplier = panel.NodePrototype.GetComponent<InventoryCell>().Icon.pixelsPerUnitMultiplier;
// The thermal branch subscribes to a click trigger the edit-mode instance of the prefab does not carry.
var prototypeCell = panel.NodePrototype.GetComponent<InventoryCell>();
if ((state.Thermal || state.Cargo) && !prototypeCell.PointerClickTrigger) prototypeCell.PointerClickTrigger = prototypeCell.gameObject.AddComponent<ObservablePointerClickTrigger>();
@ -991,6 +947,13 @@ public static class InventoryGridParityCapture
LayoutRebuilder.ForceRebuildLayoutImmediate(content);
Canvas.ForceUpdateCanvases();
// The temperature display follows the first cell in Update, which edit mode never runs: run it once, without the labels, which
// need the player's settings.
if (panel.TemperatureDisplay && state.Name != "cargo")
{
panel.MinTempLabel = panel.MaxTempLabel = null;
typeof(InventoryPanel).GetMethod("Update", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(panel, null);
}
var records = ReadRecords(panel, state.Thermal);
var columns = panel.Grid.constraintCount;
var rows = (panel.CellInstances.Count + panel.EmptyCells.Count) / columns;
@ -999,6 +962,7 @@ public static class InventoryGridParityCapture
var orientation = panel.Grid.startCorner == GridLayoutGroup.Corner.UpperRight ? GridOrientation.UpperRight : GridOrientation.LowerLeft;
var cellRects = panel.CellInstances.ToDictionary(pair => pair.Key, pair => (RectTransform) pair.Value.transform);
if (width == 1920) RecordGolden(rig, state.Name, records, cellRects, panel.TemperatureDisplay && state.Name != "cargo" ? (RectTransform) panel.TemperatureDisplay.transform : null);
var old = rig.Render();
// New: the grid in the content's place over the same rect; the cells off.
@ -1182,10 +1146,62 @@ public static class InventoryGridParityCapture
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);
}
afterwards?.Invoke(rig, panel, grid, records);
ClearPage(rig);
}
// ---- The golden ------------------------------------------------------------------------------------------------------
[Serializable] private sealed class GoldenCell
{
public int x, y, mask, conductivity;
public bool present, item;
public uint icon, background;
public float[] rect;
}
[Serializable] private sealed class GoldenState
{
public string name;
public GoldenCell[] cells;
public float[] temperature;
}
[Serializable] private sealed class Golden { public GoldenState[] states; }
private static readonly List<GoldenState> GoldenStates = new List<GoldenState>();
private static float[] PageRect(Rig rig, RectTransform rect)
{
var corners = new Vector3[4];
rect.GetWorldCorners(corners);
var a = rig.Page.InverseTransformPoint(corners[0]);
var b = rig.Page.InverseTransformPoint(corners[2]);
return new[] { a.x, a.y, b.x - a.x, b.y - a.y };
}
private static uint Pack(Color32 c) => (uint) c.r << 24 | (uint) c.g << 16 | (uint) c.b << 8 | c.a;
private static void RecordGolden(Rig rig, string name, Dictionary<int2, CellRecord> records, Dictionary<int2, RectTransform> rects, RectTransform temperature)
{
GoldenStates.Add(new GoldenState
{
name = name,
cells = records.OrderBy(p => p.Key.y).ThenBy(p => p.Key.x).Select(p => new GoldenCell
{
x = p.Key.x, y = p.Key.y, mask = p.Value.Mask, conductivity = p.Value.Conductivity, present = p.Value.Present, item = p.Value.Item,
icon = Pack(p.Value.Icon), background = Pack(p.Value.Background), rect = PageRect(rig, rects[p.Key])
}).ToArray(),
temperature = temperature ? PageRect(rig, temperature) : null
});
}
private static void WriteGolden()
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(_recordsOut))!);
File.WriteAllText(_recordsOut, JsonUtility.ToJson(new Golden { states = GoldenStates.ToArray() }, true));
Log($"golden written to {_recordsOut}: {GoldenStates.Count} states, {GoldenStates.Sum(s => s.cells.Length)} cells");
}
// old | new | abs difference x 8, cropped to the region.
private static void SaveSideBySide(string name, Rig rig, Color32[] old, Color32[] fresh, RectInt region)
{