Inventory panels play capture: the Duel arena through MainMenu.Launch, each panel state asserted and written as a PNG of the overlay canvases

InventoryPanelsPlayCapture.Run (-pngOut <dir>): enters play mode from Main Menu.unity, launches the Duel test arena (the player's Longinus carries a Store-All Plus bay, a hostile Longinus is in the zone) and asserts and captures hud, enemy, pulse, menu, cargo, highlight, drag, hover and thermal at 1920x1080 through a camera RenderTexture (overlay canvases switched to ScreenSpaceCamera for the frame, then restored). 300 s real-time budget, exit 0 or 1. Also: the mutation script's named-mutant filter takes effect.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 05:44:01 +01:00
commit b172c35470
3 changed files with 284 additions and 0 deletions

View file

@ -0,0 +1,280 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using int2 = CultMath.int2;
// The inventory panels in a real play session (map IG-S9): the Duel test arena (the player's Longinus carries a Store-All Plus cargo bay,
// a hostile Longinus is placed in the zone) is launched through MainMenu.Launch from the Main Menu scene, and each state of the panels is
// asserted and written as a PNG of the game's overlay canvases at 1920x1080 (hud, enemy, pulse, menu, cargo, highlight, drag, hover,
// thermal). The PNGs are the operator's evidence, not a gate; any failed assertion exits 1.
//
// Unity -batchmode -projectPath <project> -executeMethod InventoryPanelsPlayCapture.Run -pngOut <dir> -logFile <log>
//
// Needs a GPU device; do not pass -nographics or -quit. Run enters play mode (a domain reload), the check runs there as an
// EditorApplication.update stepper with a 300 s real-time budget, and the Editor exits itself, 0 or 1. The overlay canvases are switched to
// ScreenSpaceCamera for the frame a capture renders through a camera into a 1920x1080 RenderTexture, then restored.
[InitializeOnLoad]
public static class InventoryPanelsPlayCapture
{
private const string Flag = "InventoryPanelsPlayCapture.running";
private const string PngKey = "InventoryPanelsPlayCapture.png";
private const double Budget = 300;
// The check and the enumerators it yields (a state's capture), stepped one yield per editor update.
private static readonly Stack<IEnumerator> Steps = new Stack<IEnumerator>();
private static double _started;
private static string _png;
static InventoryPanelsPlayCapture()
{
if (SessionState.GetBool(Flag, false)) EditorApplication.playModeStateChanged += OnPlayMode;
}
private static void Log(string line) => Debug.Log("[InventoryPanelsPlayCapture] " + line);
public static void Run()
{
try
{
var args = Environment.GetCommandLineArgs();
var at = Array.IndexOf(args, "-pngOut");
if (at < 0 || at + 1 >= args.Length) throw new InvalidOperationException("-pngOut <dir> is required.");
Directory.CreateDirectory(args[at + 1]);
SessionState.SetString(PngKey, Path.GetFullPath(args[at + 1]));
EditorSceneManager.playModeStartScene = AssetDatabase.LoadAssetAtPath<SceneAsset>("Assets/Scenes/Main Menu.unity")
?? throw new InvalidOperationException("No Assets/Scenes/Main Menu.unity.");
SessionState.SetBool(Flag, true);
EditorApplication.EnterPlaymode();
}
catch (Exception exception)
{
Debug.LogException(exception);
EditorApplication.Exit(1);
}
}
private static void OnPlayMode(PlayModeStateChange change)
{
if (change != PlayModeStateChange.EnteredPlayMode) return;
_png = SessionState.GetString(PngKey, "");
_started = Time.realtimeSinceStartupAsDouble;
Steps.Push(Check());
EditorApplication.update += Step;
}
private static void Step()
{
try
{
if (Time.realtimeSinceStartupAsDouble - _started > Budget) throw new InvalidOperationException($"The capture did not finish in {Budget} seconds.");
while (Steps.Count > 0)
{
var top = Steps.Peek();
if (!top.MoveNext()) { Steps.Pop(); continue; }
if (top.Current is IEnumerator nested) { Steps.Push(nested); continue; }
return;
}
Finish(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
Finish(1);
}
}
private static void Finish(int code)
{
EditorApplication.update -= Step;
SessionState.SetBool(Flag, false);
EditorSceneManager.playModeStartScene = null;
Log(code == 0 ? "PASS" : "FAILED");
EditorApplication.Exit(code);
}
private static void Require(bool condition, string what)
{
if (!condition) throw new InvalidOperationException("assertion failed: " + what);
Log("ok: " + what);
}
private static int Present(InventoryGrid grid)
{
var count = 0;
for (var y = 0; y < grid.Height; y++)
for (var x = 0; x < grid.Width; x++)
if (grid.RecordAt(new int2(x, y)).Present) count++;
return count;
}
private static uint Pack(Color32 c) => (uint) c.r << 24 | (uint) c.g << 16 | (uint) c.b << 8 | c.a;
// The game's overlay canvases drawn through a camera into a 1920x1080 RenderTexture and written as <state>.png: each root canvas that
// is an overlay is switched to ScreenSpaceCamera for the frames the render needs, then restored.
private static IEnumerator Snap(string state)
{
for (var i = 0; i < 3; i++) yield return null;
var cameraObject = new GameObject("Capture camera");
var camera = cameraObject.AddComponent<Camera>();
camera.orthographic = true;
camera.orthographicSize = 5;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = new Color(.1f, .1f, .12f, 1f);
camera.cullingMask = 1 << LayerMask.NameToLayer("UI");
camera.enabled = false;
var target = new RenderTexture(1920, 1080, 24, RenderTextureFormat.ARGB32);
camera.targetTexture = target;
var canvases = UnityEngine.Object.FindObjectsByType<Canvas>(FindObjectsSortMode.None)
.Where(c => c.isRootCanvas && c.renderMode == RenderMode.ScreenSpaceOverlay && c.gameObject.activeInHierarchy).ToList();
var saved = canvases.Select(c => (c, c.worldCamera, c.planeDistance)).ToList();
foreach (var canvas in canvases)
{
canvas.renderMode = RenderMode.ScreenSpaceCamera;
canvas.worldCamera = camera;
canvas.planeDistance = 10;
}
for (var i = 0; i < 3; i++) yield return null;
Canvas.ForceUpdateCanvases();
foreach (var grid in UnityEngine.Object.FindObjectsByType<InventoryGrid>(FindObjectsSortMode.None)) grid.Flush();
camera.Render();
var previous = RenderTexture.active;
RenderTexture.active = target;
var read = new Texture2D(1920, 1080, TextureFormat.RGBA32, false);
read.ReadPixels(new Rect(0, 0, 1920, 1080), 0, 0);
RenderTexture.active = previous;
var path = Path.Combine(_png, $"play-{state}.png");
File.WriteAllBytes(path, read.EncodeToPNG());
UnityEngine.Object.Destroy(read);
foreach (var (canvas, worldCamera, plane) in saved)
{
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.worldCamera = worldCamera;
canvas.planeDistance = plane;
}
UnityEngine.Object.Destroy(cameraObject);
target.Release();
UnityEngine.Object.Destroy(target);
Log($"wrote {path} ({canvases.Count} overlay canvases)");
yield return null;
}
private static PointerEventData Pointer(Vector2 position, Vector2? press = null) => new PointerEventData(EventSystem.current)
{
position = position, pressPosition = press ?? position, button = PointerEventData.InputButton.Left
};
// Overlay canvases: a cell's world position is its screen position.
private static Vector2 Centre(InventoryGrid grid, int2 v) => grid.rectTransform.TransformPoint(grid.CellRect(v).center);
private static IEnumerator Check()
{
// The Main Menu scene: launch the Duel arena, whose player ship carries a cargo bay and has another ship in the zone.
MainMenu menu = null;
while (!(menu = UnityEngine.Object.FindFirstObjectByType<MainMenu>())) yield return null;
for (var i = 0; i < 30; i++) yield return null;
var scenario = Scenarios.Tests.First(s => s.Id == "duel");
Log($"launching {scenario.Name} ({scenario.Id}): the player's Longinus fits a Store-All Plus cargo bay, a hostile Longinus is placed 900 m away");
menu.Launch(scenario);
ActionGameManager game = null;
while (!((game = ActionGameManager.Instance) && game.CurrentEntity != null && game.ShipPanel && game.ShipPanel.Grid.Width > 0)) yield return null;
for (var i = 0; i < 60; i++) yield return null;
var ship = game.CurrentEntity;
var other = game.Zone.Entities.First(e => e != ship && e is Ship);
var bay = ship.CargoBays.FirstOrDefault();
Require(bay != null, $"the player's {ship.Name} carries a cargo bay ({bay?.Data.Name})");
Log($"player {ship.Name}, other ship {other.Name}");
// hud
var hud = game.ShipPanel;
Require(Present(hud.Grid) > 0 && !hud.Interactive && hud.Grid.GetComponents<UniRx.Triggers.ObservableTriggerBase>().Length == 0, $"the HUD panel draws {Present(hud.Grid)} cells through its grid and takes no pointer input");
yield return Snap("hud");
// enemy: the one target slot names the other ship
typeof(Entity).GetMethod("SetTarget", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(ship, new object[] { new TargetRef(other) });
for (var i = 0; i < 10; i++) yield return null;
var enemy = game.TargetShipPanel;
Require(enemy.gameObject.activeInHierarchy && Present(enemy.Grid) > 0 && enemy.Flip, $"the enemy panel shows {other.Name} through a flipped grid ({Present(enemy.Grid)} cells)");
yield return Snap("enemy");
// pulse: an armor hit makes the cell's background differ from CellBackgroundColor until CellHitPulseTime has passed
var hit = FirstPresent(hud.Grid);
var background = (Color32) hud.CellBackgroundColor;
Require(Pack(hud.Grid.RecordAt(hit).Background) == Pack(background), "before the hit the cell's background is CellBackgroundColor");
ship.ArmorDamage.OnNext((hit, 5f));
Require(Pack(hud.Grid.RecordAt(hit).Background) != Pack(background), "an ArmorDamage hit makes the cell's RecordAt background differ from CellBackgroundColor");
yield return Snap("pulse");
var until = Time.time + hud.CellHitPulseTime + .5f;
while (Time.time < until) yield return null;
Require(Pack(hud.Grid.RecordAt(hit).Background) == Pack(background), $"after CellHitPulseTime ({hud.CellHitPulseTime:F2} s) it is CellBackgroundColor again");
// menu and cargo
game.Menu.ShowTab(MenuTab.Inventory);
for (var i = 0; i < 20; i++) yield return null;
var cargoPanel = game.Inventory.InventoryPanels[0];
var equipmentPanel = game.Inventory.InventoryPanels[1];
Require(Present(equipmentPanel.Grid) > 0 && equipmentPanel.Interactive, $"the menu's equipment panel draws {Present(equipmentPanel.Grid)} cells and takes pointer input");
yield return Snap("menu");
var items = game.ItemManager;
foreach (var commodity in items.ItemData.GetAll<SimpleCommodityData>().Take(3))
bay.TryStore(new SimpleCommodity { Data = items.ItemData.RefOf<ItemData>(commodity), Quantity = 1 });
cargoPanel.Display(bay);
for (var i = 0; i < 5; i++) yield return null;
Require(Present(cargoPanel.Grid) == bay.Data.InteriorShape.Coordinates.Length && cargoPanel.Grid.Thermal == false, $"the cargo panel draws the bay's {Present(cargoPanel.Grid)} cells, holding {bay.Occupancy.Cast<ItemInstance>().Where(i => i != null).Distinct().Count()} items");
yield return Snap("cargo");
// highlight: a click on an item cell
var fitted = ship.Equipment.Where(e => e.EquippableItem != null).OrderBy(e => e.Data.Shape.Coordinates.Length).First();
var hull = (HullData) game.ItemManager.GetData(ship.Hull);
var itemCells = hull.Shape.Inset(fitted.Data.Shape, fitted.Position, fitted.EquippableItem.Rotation).Coordinates;
var grid = equipmentPanel.Grid;
var click = Pointer(Centre(grid, itemCells[0]));
ExecuteEvents.Execute(grid.gameObject, click, ExecuteEvents.pointerClickHandler);
Require(itemCells.All(v => Pack(grid.RecordAt(v).Icon) == Pack(equipmentPanel.GetColor(v, true))) && itemCells.All(v => Pack(equipmentPanel.GetColor(v, true)) != Pack(equipmentPanel.GetColor(v))),
$"a click on {fitted.Data.Name} highlights its {itemCells.Length} cells");
yield return Snap("highlight");
// drag: the ghost; hover: the other panel's FakeOccupancy
var press = Centre(grid, itemCells[0]);
ExecuteEvents.Execute(grid.gameObject, Pointer(press), ExecuteEvents.beginDragHandler);
var ghost = equipmentPanel.DragGhost;
Require(ghost.gameObject.activeSelf && Present(ghost) == itemCells.Length, "a begin drag shows the drag ghost with the item's cells");
ExecuteEvents.Execute(grid.gameObject, Pointer(press + new Vector2(120, 40), press), ExecuteEvents.dragHandler);
yield return Snap("drag");
var cargoGrid = cargoPanel.Grid;
var emptied = bay.Occupancy.Cast<ItemInstance>().Where(i => i != null).Distinct().ToArray();
foreach (var stored in emptied) bay.Remove(stored);
cargoPanel.RefreshCells();
var offset = fitted.Position - itemCells[0];
var target = bay.Data.InteriorShape.AllCoordinates.FirstOrDefault(h => bay.Data.InteriorShape[h] && bay.ItemFits(fitted.EquippableItem, h + offset));
Require(bay.ItemFits(fitted.EquippableItem, target + offset), "the dragged item fits the emptied bay");
ExecuteEvents.Execute(cargoGrid.gameObject, Pointer(Centre(cargoGrid, target)), ExecuteEvents.pointerMoveHandler);
Require(cargoPanel.FakeOccupancy != null && cargoPanel.FakeOccupancy.Coordinates.Length > 0, "the pointer over a fitting cell sets the other panel's FakeOccupancy");
yield return Snap("hover");
ExecuteEvents.Execute(cargoGrid.gameObject, Pointer(Centre(cargoGrid, target)), ExecuteEvents.pointerExitHandler);
ExecuteEvents.Execute(grid.gameObject, Pointer(press + new Vector2(120, 40), press), ExecuteEvents.endDragHandler);
Require(!ghost.gameObject.activeSelf && cargoPanel.FakeOccupancy == null, "the drag ends: ghost hidden, FakeOccupancy cleared");
// thermal: the Thermal button
equipmentPanel.Thermal.onClick.Invoke();
for (var i = 0; i < 5; i++) yield return null;
Require(equipmentPanel.Grid.Thermal && Enumerable.Range(0, grid.Height).SelectMany(y => Enumerable.Range(0, grid.Width).Select(x => grid.RecordAt(new int2(x, y)))).Any(r => r.Present && r.Conductivity != 0),
"the Thermal button switches the grid to the pipes view with conducting cells");
yield return Snap("thermal");
}
private static int2 FirstPresent(InventoryGrid grid)
{
for (var y = 0; y < grid.Height; y++)
for (var x = 0; x < grid.Width; x++)
if (grid.RecordAt(new int2(x, y)).Present) return new int2(x, y);
throw new InvalidOperationException("The grid has no present cell.");
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 901479284564b1d44a6e766e7c8a0a46

View file

@ -163,6 +163,8 @@ def run_switch(golden: str, only: list[str]) -> int:
failures.append("switch control: expected exit 0 and PASS on the unmutated tree")
print(f"switch control: exit {code}")
for name, (arg, edit, kills) in SWITCH_MUTANTS.items():
if only and name not in only:
continue
print(f"\n=== switch mutant {name} (killed by: {kills}) ===")
original = replace_unique(*edit) if edit else None
try: