789 lines
51 KiB
C#
789 lines
51 KiB
C#
#if UNITY_EDITOR || DEVELOPMENT_BUILD
|
|
using System;
|
|
using System.Collections;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using KernelPanic.Combat;
|
|
using KernelPanic.Core;
|
|
using KernelPanic.Data;
|
|
using KernelPanic.Meta;
|
|
using KernelPanic.UI;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace KernelPanic.Run
|
|
{
|
|
/// <summary>Opt-in standalone development-build integration check with an isolated save.</summary>
|
|
public sealed class PlayerSmokeRunner : MonoBehaviour
|
|
{
|
|
private string _output;
|
|
private string _failure;
|
|
private string _campaignSuccess;
|
|
private string _stage = "startup";
|
|
private float _deadline;
|
|
|
|
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
|
|
private static void Install()
|
|
{
|
|
string[] args = Environment.GetCommandLineArgs();
|
|
int flag = Array.IndexOf(args, "--kernel-panic-smoke");
|
|
if (flag < 0) return;
|
|
int saveFlag = Array.IndexOf(args, "--kernel-panic-save-path");
|
|
if (saveFlag < 0 || saveFlag + 1 >= args.Length || !Path.IsPathRooted(args[saveFlag + 1]) || File.Exists(args[saveFlag + 1]) || File.Exists(args[saveFlag + 1] + ".bak"))
|
|
{
|
|
Debug.LogError("Smoke check requires an absolute, unused --kernel-panic-save-path.");
|
|
Application.Quit(2);
|
|
return;
|
|
}
|
|
// Install before the menu's OnEnable can schedule the animated boot sequence.
|
|
UIPreferences.ReducedMotion = true; // Session only; never writes preferences.
|
|
var owner = new GameObject("Player smoke verification");
|
|
Application.runInBackground = true;
|
|
DontDestroyOnLoad(owner);
|
|
var runner = owner.AddComponent<PlayerSmokeRunner>();
|
|
runner._output = Path.GetDirectoryName(args[saveFlag + 1]);
|
|
Directory.CreateDirectory(runner._output);
|
|
runner._deadline = Time.realtimeSinceStartup + 900;
|
|
Application.logMessageReceived += runner.ObserveLog;
|
|
}
|
|
|
|
private void ObserveLog(string message, string trace, LogType type)
|
|
{
|
|
if (type == LogType.Exception || type == LogType.Error || type == LogType.Assert)
|
|
_failure ??= message + "\n" + trace;
|
|
}
|
|
|
|
private IEnumerator Start()
|
|
{
|
|
// Pump manually so an exception writes a useful result and exits instead of hanging CI.
|
|
var scenario = Scenario();
|
|
while (true)
|
|
{
|
|
bool next = false;
|
|
object yielded = null;
|
|
try
|
|
{
|
|
if (_failure != null) throw new InvalidOperationException(_failure);
|
|
if (Time.realtimeSinceStartup > _deadline) throw new TimeoutException("Smoke check timed out at " + _stage);
|
|
next = scenario.MoveNext();
|
|
if (next) yielded = scenario.Current;
|
|
}
|
|
catch (Exception ex) { _failure = ex.ToString(); }
|
|
if (_failure != null || !next) break;
|
|
yield return yielded;
|
|
}
|
|
Application.logMessageReceived -= ObserveLog;
|
|
if (_failure == null && _campaignSuccess != null)
|
|
{
|
|
File.WriteAllText(Path.Combine(_output, "player-smoke-result.txt"), _campaignSuccess);
|
|
Debug.Log("PLAYER_SMOKE_PASS");
|
|
Application.Quit(0);
|
|
yield break;
|
|
}
|
|
File.WriteAllText(Path.Combine(_output, "player-smoke-result.txt"), _failure == null ? "PASS: starter selection -> configured run -> pile tabs/search/grouping/cost details/keyboard focus -> combat -> repository purchase -> save and exit without payout -> exact repository resume -> next wave -> shutdown -> run archive command/navigation -> original build details/copy seed/load setup -> saved rewards/history -> same-seed retry -> new-seed retry -> natural defeat with attributed damage" : "FAIL at " + _stage + "\n" + _failure);
|
|
Debug.Log(_failure == null ? "PLAYER_SMOKE_PASS" : "PLAYER_SMOKE_FAIL: " + _failure);
|
|
Application.Quit(_failure == null ? 0 : 1);
|
|
}
|
|
|
|
private IEnumerator Scenario()
|
|
{
|
|
// Preference loading is also a BeforeSceneLoad callback; reapply the session
|
|
// override after all such callbacks, regardless of their registration order.
|
|
UIPreferences.ReducedMotion = true;
|
|
_stage = "starter selection";
|
|
yield return new WaitForSecondsRealtime(2);
|
|
var menu = FindFirstObjectByType<MainMenuController>();
|
|
Require(menu != null, "Main menu scene did not initialize.");
|
|
var starter = Field<StarterSelectionController>(menu, "starterSelection");
|
|
if (!starter.IsActive)
|
|
{
|
|
// Exercise the normal "any key" boot skip; hidden windows need not run
|
|
// the animated panel scheduler at the same cadence as a visible window.
|
|
var startupRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
|
using var skipIntro = KeyDownEvent.GetPooled(' ', KeyCode.Space, EventModifiers.None);
|
|
skipIntro.target = startupRoot;
|
|
startupRoot.SendEvent(skipIntro);
|
|
}
|
|
float starterDeadline = Time.realtimeSinceStartup + 30;
|
|
while (!starter.IsActive && Time.realtimeSinceStartup < starterDeadline) yield return null;
|
|
Require(starter.IsActive, $"Fresh profile did not show starter selection; boot elapsed={Field<float>(menu, "_bootIntroElapsed")}, starterChosen={new SaveService().Load().starterChosen}.");
|
|
var choices = Field<System.Collections.Generic.IReadOnlyList<DistroDefinition>>(starter, "_activeStarters");
|
|
int ubuntuIndex = choices.ToList().FindIndex(distro => distro.Id == "ubuntu");
|
|
Require(ubuntuIndex >= 0, "Ubuntu starter not available.");
|
|
Call(starter, "Select", ubuntuIndex);
|
|
using (var key = KeyDownEvent.GetPooled('\n', KeyCode.Return, EventModifiers.None)) starter.HandleKeyDown(key);
|
|
using (var key = KeyDownEvent.GetPooled('y', KeyCode.Y, EventModifiers.None)) starter.HandleKeyDown(key);
|
|
yield return null;
|
|
Require(new SaveService().Load().IsUnitOwned("ubuntu"), "Starter choice was not persisted.");
|
|
var training = TutorialScenario();
|
|
while (training.MoveNext()) yield return training.Current;
|
|
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-tutorial-smoke"))
|
|
{
|
|
_campaignSuccess = "PASS: two-wave guided tutorial, real targeting/revival/queue/stack, full clears, shop purchase, same-run resume, one-time 1000 Bandwidth + 1000 Entropy, clean normal-run workspace.";
|
|
yield break;
|
|
}
|
|
menu = FindFirstObjectByType<MainMenuController>();
|
|
_stage = "run setup";
|
|
ConfigureMenu(menu);
|
|
yield return null;
|
|
Call(menu, "BootSelectedPackage");
|
|
CombatManager combat = null;
|
|
while (combat == null || !combat.CanSurrenderRun)
|
|
{
|
|
yield return null;
|
|
combat = FindFirstObjectByType<CombatManager>();
|
|
}
|
|
Require(combat.RunConfig.RunSeed == 12345, "Run seed was not handed off.");
|
|
string originalBuild = BuildSignature(combat.RunConfig);
|
|
var view = FindFirstObjectByType<CombatSceneController>();
|
|
var previewRoot = view.GetComponent<UIDocument>().rootVisualElement;
|
|
var executionPreview = previewRoot.Q<Foldout>("ExecutionPreview");
|
|
int drawsBeforePreview = RandomRoll.DrawCount;
|
|
executionPreview.value = true;
|
|
yield return null;
|
|
var previewContents = previewRoot.Q("ExecutionPreviewPopup") ?? executionPreview;
|
|
Require(RandomRoll.DrawCount == drawsBeforePreview && previewContents.Q<Label>(className: "terminal-body") != null,
|
|
"Execution preview changed RNG or did not render its explanation.");
|
|
executionPreview.value = false;
|
|
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-campaign-smoke"))
|
|
{
|
|
var campaign = CampaignScenario(combat, view);
|
|
while (campaign.MoveNext()) yield return campaign.Current;
|
|
yield break;
|
|
}
|
|
var guide = Field<FirstBattleGuide>(view, "_firstBattleGuide");
|
|
guide.Begin(combat.RunConfig, true);
|
|
var capture = CapturePanel(view.GetComponent<UIDocument>(), "first-battle");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
_stage = "pile inspection";
|
|
var inspection = InspectPiles(view, combat);
|
|
while (inspection.MoveNext()) yield return inspection.Current;
|
|
_stage = "combat";
|
|
int actions = 0;
|
|
while (!combat.AwaitingWaveContinue && !combat.RunLost)
|
|
{
|
|
if (combat.CanSurrenderRun)
|
|
{
|
|
bool played = false;
|
|
for (int i = 0; i < combat.Enemies.Count; i++)
|
|
{
|
|
if (!combat.Enemies[i].State.IsDefeated) { combat.SelectEnemy(i); break; }
|
|
}
|
|
foreach (var card in combat.HandController.Cards.ToArray())
|
|
{
|
|
if (combat.PlayCard(card)) { played = true; break; }
|
|
}
|
|
if (!played) combat.EndPlayerTurn();
|
|
Require(++actions < 500, "Bot exceeded action budget before clearing wave one.");
|
|
}
|
|
yield return null;
|
|
}
|
|
Require(!combat.RunLost, "Seeded starter bot died before repository.");
|
|
yield return null;
|
|
_stage = "repository";
|
|
var run = combat.GetComponent<RunManager>();
|
|
Require(run.WavesCleared == 1 && run.RepositoryVisitActive, "Wave completion did not open repository.");
|
|
Submit(view.GetComponent<UIDocument>().rootVisualElement.Q<Button>("RouteChallenge"));
|
|
Require(run.Journey.selectedRoute == WaveRoute.Challenge, "Elite route selection did not reach the run model.");
|
|
var offer = run.RepositoryOffers.FirstOrDefault(item => item.Price <= run.Bits);
|
|
Require(offer != null, "No affordable repository offer.");
|
|
int bits = run.Bits;
|
|
Require(run.BuyOffer(offer, combat.PlayerState), "Repository purchase failed.");
|
|
Require(run.Bits == bits - offer.Price, "Purchase charged incorrect Bits.");
|
|
capture = CapturePanel(view.GetComponent<UIDocument>(), "repository");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
yield return null;
|
|
|
|
_stage = "repository checkpoint and suspension";
|
|
string runId = run.RunId;
|
|
string deckBefore = DeckSignature(run);
|
|
string offersBefore = OfferSignature(run);
|
|
RunCheckpoint beforeSuspend = run.CaptureCheckpoint(combat);
|
|
string combatBefore = JsonUtility.ToJson(beforeSuspend.combat);
|
|
int bankedBits = run.Bits;
|
|
var beforeSave = new SaveService().Load();
|
|
Call(view, "SaveAndExitRun");
|
|
menu = null;
|
|
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
|
var suspended = new SaveService().Load();
|
|
Require(suspended.activeRun != null && suspended.activeRun.runId == runId, "Repository checkpoint was not persisted.");
|
|
Require(suspended.bandwidthBalance == beforeSave.bandwidthBalance && suspended.entropyBalance == beforeSave.entropyBalance,
|
|
"Suspending the run paid out rewards.");
|
|
Require(suspended.recentRuns.Count == beforeSave.recentRuns.Count, "Suspending created a completed-run history entry.");
|
|
Require(JsonUtility.ToJson(suspended.activeRun.combat) == combatBefore, "Saved checkpoint changed carried combat state or RNG cursor.");
|
|
_stage = "repository resume";
|
|
Call(menu, "ResumeSavedRun");
|
|
combat = null;
|
|
while (combat == null || !combat.AwaitingWaveContinue)
|
|
{
|
|
yield return null;
|
|
combat = FindFirstObjectByType<CombatManager>();
|
|
}
|
|
view = FindFirstObjectByType<CombatSceneController>();
|
|
run = combat.GetComponent<RunManager>();
|
|
Require(run.RepositoryVisitActive && run.RunId == runId && run.CurrentWaveNumber == beforeSuspend.wave
|
|
&& run.WavesCleared == beforeSuspend.wavesCleared && run.Bits == bankedBits, "Resume changed run identity, wave or currency.");
|
|
Require(DeckSignature(run) == deckBefore && OfferSignature(run) == offersBefore, "Resume changed cards, upgrades or repository offers.");
|
|
Require(JsonUtility.ToJson(run.CaptureCheckpoint(combat).combat) == combatBefore, "Resume changed carried combat state or RNG cursor.");
|
|
Require(BuildSignature(combat.RunConfig) == originalBuild, "Resume changed the original build.");
|
|
Require(run.Journey.selectedRoute == WaveRoute.Challenge, "Resume lost the selected elite route.");
|
|
Require(new SaveService().Load().activeRun == null, "Resumed checkpoint was not claimed exactly once.");
|
|
capture = CapturePanel(view.GetComponent<UIDocument>(), "repository-resumed");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
combat.ContinueToNextWave();
|
|
while (!combat.CanSurrenderRun) yield return null;
|
|
Require(run.CurrentWaveNumber == 2, "Next wave failed to start.");
|
|
_stage = "defeat and reward settlement";
|
|
int reward = run.AccruedBandwidth + TutorialCampaign.BandwidthReward;
|
|
Call(view, "ConfirmSurrender");
|
|
yield return null;
|
|
Require(combat.RunLost && run.RewardsSettled, "Defeat did not settle rewards.");
|
|
var saved = new SaveService().Load();
|
|
Require(saved.bandwidthBalance == reward && saved.GetBestWave("ubuntu") == 2, "Run rewards/stats were not persisted exactly once.");
|
|
Require(saved.activeRun == null && saved.recentRuns.Count == 1 && saved.recentRuns[0].runId == runId
|
|
&& saved.recentRuns[0].surrendered && !string.IsNullOrWhiteSpace(saved.recentRuns[0].cause), "Completed resumed run did not save a single useful history entry.");
|
|
Require(saved.recentRuns[0].finalRound >= 1, "Next wave accepted shutdown before its first round was ready.");
|
|
capture = CapturePanel(view.GetComponent<UIDocument>(), "run-report");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
yield return null;
|
|
_stage = "return to menu and run archive";
|
|
SceneLoader.LoadMainMenu(view.GetComponent<UIDocument>().rootVisualElement);
|
|
menu = null;
|
|
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
|
Require(!Field<StarterSelectionController>(menu, "starterSelection").IsActive, "Returning profile unexpectedly needs a starter.");
|
|
Require(new SaveService().Load().bandwidthBalance == reward, "Scene unload paid rewards twice.");
|
|
var menuRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
|
yield return null;
|
|
var homePanel = menuRoot.Q("MainMenuPanel");
|
|
Require(homePanel != null && homePanel.resolvedStyle.display != DisplayStyle.None, "Returning profile did not show the main menu.");
|
|
Require(homePanel.Q("RetrySameSeedButton") == null && homePanel.Q("RetryNewSeedButton") == null
|
|
&& homePanel.Q("RecentRunsButton") == null, "Archived run actions still appear on the main menu.");
|
|
var archiveCommand = menuRoot.Q("CommandRunArchive");
|
|
Require(archiveCommand != null && archiveCommand.parent.IndexOf(archiveCommand) == archiveCommand.parent.IndexOf(menuRoot.Q("CommandSettings")) + 1
|
|
&& archiveCommand.parent.IndexOf(menuRoot.Q("CommandQuit")) == archiveCommand.parent.IndexOf(archiveCommand) + 1,
|
|
"Run archive command is not between Settings and Quit.");
|
|
capture = CapturePanel(menu.GetComponent<UIDocument>(), "home-menu");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
OpenRunArchive(menuRoot);
|
|
yield return null;
|
|
RequireArchiveVisible(menuRoot);
|
|
capture = CapturePanel(menu.GetComponent<UIDocument>(), "run-archive");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
_stage = "recent runs within archive";
|
|
Submit(menuRoot.Q<Button>("RecentRunsButton"));
|
|
yield return null;
|
|
Require(menuRoot.Q("RunHistoryOverlay") != null, "Recent runs did not open.");
|
|
var archived = new SaveService().Load().recentRuns[0];
|
|
Require(RunHistory.HasBuildSnapshot(archived) && archived.build.seed == 12345
|
|
&& archived.build.startingDeckCardIds.Count > 4, "Run history did not preserve the original starting build.");
|
|
menuRoot.Q<Foldout>("ArchivedBuildDetails_0").value = true;
|
|
string previousClipboard = GUIUtility.systemCopyBuffer;
|
|
try
|
|
{
|
|
Submit(menuRoot.Q<Button>("CopyRunSeed_0"));
|
|
Require(GUIUtility.systemCopyBuffer == "12345", "Archive copy-seed action copied the wrong seed.");
|
|
}
|
|
finally { GUIUtility.systemCopyBuffer = previousClipboard; }
|
|
capture = CapturePanel(menu.GetComponent<UIDocument>(), "run-history");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
string retryBeforeLoad = JsonUtility.ToJson(new SaveService().Load().lastRunLoadout);
|
|
Submit(menuRoot.Q<Button>("LoadArchivedBuild_0"));
|
|
yield return null;
|
|
Require(menuRoot.Q("RunSetupPanel").resolvedStyle.display != DisplayStyle.None
|
|
&& !Field<bool>(menu, "_runLaunchPending") && Field<string>(menu, "_runSeedText") == "12345",
|
|
"Archive load did not open setup without launching a run.");
|
|
Require(JsonUtility.ToJson(new SaveService().Load().lastRunLoadout) == retryBeforeLoad,
|
|
"Loading an archived build changed the frozen retry build.");
|
|
Submit(menuRoot.Q("RunSetupPanel").Q<Button>(className: "screen-back"));
|
|
yield return null;
|
|
OpenRunArchive(menuRoot);
|
|
yield return null;
|
|
Submit(menuRoot.Q<Button>("RecentRunsButton"));
|
|
Submit(menuRoot.Q<Button>("CloseRunHistory"));
|
|
Require(menuRoot.Q("RunHistoryOverlay") == null, "Recent runs did not close.");
|
|
RequireArchiveVisible(menuRoot);
|
|
_stage = "run archive back navigation";
|
|
using (var escape = KeyDownEvent.GetPooled('\0', KeyCode.Escape, EventModifiers.None))
|
|
{
|
|
escape.target = menuRoot.Q("RunArchivePanel");
|
|
menuRoot.Q("RunArchivePanel").SendEvent(escape);
|
|
}
|
|
yield return null;
|
|
Require(homePanel.resolvedStyle.display != DisplayStyle.None && menuRoot.Q("RunArchivePanel").resolvedStyle.display == DisplayStyle.None,
|
|
"Escape did not return from run archive to the main menu.");
|
|
using (var click = ClickEvent.GetPooled())
|
|
{
|
|
click.target = archiveCommand;
|
|
archiveCommand.SendEvent(click);
|
|
}
|
|
yield return null;
|
|
RequireArchiveVisible(menuRoot);
|
|
Submit(menuRoot.Q("RunArchivePanel").Q<Button>(className: "screen-back"));
|
|
yield return null;
|
|
Require(homePanel.resolvedStyle.display != DisplayStyle.None && menuRoot.Q("RunArchivePanel").resolvedStyle.display == DisplayStyle.None,
|
|
"Archive Back button did not return to the main menu.");
|
|
OpenRunArchive(menuRoot);
|
|
yield return null;
|
|
RequireArchiveVisible(menuRoot);
|
|
_stage = "same-seed retry";
|
|
Submit(menuRoot.Q<Button>("RetrySameSeedButton"));
|
|
combat = null;
|
|
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
|
Require(combat.CurrentWaveNumber == 1 && combat.RunConfig.RunSeed == 12345, "Restart did not produce a fresh seeded run.");
|
|
Require(BuildSignature(combat.RunConfig) == originalBuild && combat.GetComponent<RunManager>().RunId != runId,
|
|
"Same-seed retry lost the saved build or reused the completed run identity.");
|
|
Call(FindFirstObjectByType<CombatSceneController>(), "ConfirmSurrender");
|
|
yield return null;
|
|
SceneLoader.LoadMainMenu(combat.GetComponent<UIDocument>().rootVisualElement);
|
|
menu = null;
|
|
while (menu == null) { yield return null; menu = FindFirstObjectByType<MainMenuController>(); }
|
|
Require(new SaveService().Load().bandwidthBalance == reward, "Empty second run changed earned rewards.");
|
|
_stage = "new-seed retry";
|
|
menuRoot = menu.GetComponent<UIDocument>().rootVisualElement;
|
|
OpenRunArchive(menuRoot);
|
|
yield return null;
|
|
RequireArchiveVisible(menuRoot);
|
|
Submit(menuRoot.Q<Button>("RetryNewSeedButton"));
|
|
combat = null;
|
|
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
|
Require(combat.CurrentWaveNumber == 1 && combat.RunConfig.RunSeed != 12345 && BuildSignature(combat.RunConfig) == originalBuild,
|
|
"New-seed retry did not preserve the build with a fresh seed.");
|
|
Require(new SaveService().Load().lastRunLoadout.runSeed == combat.RunConfig.RunSeed, "New seed was not persisted for the next retry.");
|
|
_stage = "natural defeat and damage attribution";
|
|
string finalRunId = combat.GetComponent<RunManager>().RunId;
|
|
int idleTurns = 0;
|
|
while (!combat.RunLost)
|
|
{
|
|
if (combat.CanSurrenderRun)
|
|
{
|
|
combat.EndPlayerTurn();
|
|
Require(++idleTurns < 200, "Enemies did not defeat the idle starter within 200 turns.");
|
|
}
|
|
yield return null;
|
|
}
|
|
yield return null;
|
|
saved = new SaveService().Load();
|
|
var naturalDefeat = saved.recentRuns.FirstOrDefault(entry => entry.runId == finalRunId);
|
|
Require(naturalDefeat != null && !naturalDefeat.surrendered && naturalDefeat.finalRound >= 1
|
|
&& naturalDefeat.damageTaken > 0 && naturalDefeat.finalHits.Count > 0, "Natural defeat did not persist incoming damage and final-round history.");
|
|
Require(!string.IsNullOrWhiteSpace(naturalDefeat.cause)
|
|
&& naturalDefeat.cause.IndexOf("Uptime reached 0", StringComparison.OrdinalIgnoreCase) < 0
|
|
&& naturalDefeat.cause.IndexOf("Unattributed", StringComparison.OrdinalIgnoreCase) < 0
|
|
&& naturalDefeat.cause.IndexOf("Shutdown", StringComparison.OrdinalIgnoreCase) < 0,
|
|
"Natural defeat did not identify the killing action: " + naturalDefeat.cause);
|
|
capture = CapturePanel(combat.GetComponent<UIDocument>(), "natural-defeat");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
// Exercise scene-unload settlement after both retry modes before reporting PASS.
|
|
SceneLoader.LoadMainMenu(combat.GetComponent<UIDocument>().rootVisualElement);
|
|
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
|
saved = new SaveService().Load();
|
|
Require(saved.bandwidthBalance == reward && saved.recentRuns.Count == 3 && saved.activeRun == null,
|
|
"Retry settlement duplicated rewards/history or resurrected the consumed checkpoint.");
|
|
}
|
|
|
|
private IEnumerator TutorialScenario()
|
|
{
|
|
var save = new SaveService();
|
|
var initial = save.Load();
|
|
Require(TutorialCampaign.Required(initial), "Starter did not enroll in required training.");
|
|
CombatManager combat = null;
|
|
while (combat == null || combat.CurrentPhase != TurnPhase.Execute)
|
|
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
|
Require(combat.RunConfig.IsTutorial, "Fresh starter bypassed training.");
|
|
var view = FindFirstObjectByType<CombatSceneController>();
|
|
var flow = Field<TutorialFlow>(view, "_tutorial");
|
|
var document = view.GetComponent<UIDocument>();
|
|
var capture = CapturePanel(document, "tutorial-intro");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
int actions = 0;
|
|
bool resumed = false;
|
|
var capturedSteps = new System.Collections.Generic.HashSet<string>();
|
|
while (TutorialCampaign.Required(save.Load()))
|
|
{
|
|
_stage = "training wave " + flow.Lesson + " / " + flow.Guide.Step?.Id;
|
|
Require(!combat.RunLost, "Training bot lost: " + _stage);
|
|
if (flow.Guide.Active)
|
|
{
|
|
if (!combat.TutorialInputReady) { yield return null; continue; }
|
|
var step = flow.Guide.Step;
|
|
if (capturedSteps.Add(flow.Lesson + step.Id) && step.Id is "select-attack" or "target-zombie" or "pending-revival" or "revived" or "queued-haskell")
|
|
{
|
|
capture = CapturePanel(document, "tutorial-" + step.Id);
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
}
|
|
var root = document.rootVisualElement;
|
|
if (flow.Reading)
|
|
{
|
|
var before = combat.CurrentPhase; combat.EndPlayerTurn();
|
|
Require(combat.CurrentPhase == before, "Reading allowed combat input.");
|
|
Submit(root.Q<Button>("TutorialNext"));
|
|
}
|
|
else if (step.Action is TutorialAction.SelectCard or TutorialAction.PlayShield)
|
|
{
|
|
int cycles = combat.PlayerState.Cycles;
|
|
var button = root.Query<Button>(className: "hand-card").ToList().FirstOrDefault(b => b.userData == flow.Guide.Card);
|
|
Require(button != null && button.enabledInHierarchy, "Guided card unavailable: " + step.Id);
|
|
Submit(button);
|
|
if (combat.PendingTargetCard != null) Require(combat.PlayerState.Cycles == cycles, "Selection spent Cycles before targeting.");
|
|
}
|
|
else if (step.Action == TutorialAction.TargetEnemy)
|
|
{
|
|
var button = root.Query<Button>(className: "enemy-card").ToList().FirstOrDefault(b => b.userData == flow.Guide.Enemy);
|
|
Require(button != null && button.enabledInHierarchy, "Guided target unavailable: " + step.Id);
|
|
Submit(button);
|
|
}
|
|
else if (step.Action == TutorialAction.EndTurn)
|
|
Submit(root.Q<Button>("TutorialEndTurn"));
|
|
}
|
|
else if (combat.AwaitingWaveContinue)
|
|
{
|
|
Require(combat.Enemies.All(enemy => enemy.State.IsDefeated && !enemy.PendingRevive), "Shop opened with surviving enemies.");
|
|
var root = document.rootVisualElement;
|
|
var shopNext = root.Q<Button>("TutorialShopNext");
|
|
var buy = root.Q<Button>("TutorialBuy");
|
|
if (shopNext != null) Submit(shopNext);
|
|
else if (buy?.enabledSelf == true)
|
|
{
|
|
capture = CapturePanel(document, "tutorial-shop");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
Submit(buy);
|
|
}
|
|
else
|
|
{
|
|
string runId = FindFirstObjectByType<RunManager>().RunId;
|
|
int uptime = combat.PlayerState.CurrentUptime;
|
|
var next = root.Q<Button>("TutorialContinue");
|
|
Require(next != null && next.enabledSelf, "Tutorial progression blocked.");
|
|
Submit(next);
|
|
if (!resumed && save.Load().tutorialCheckpoint != null)
|
|
{
|
|
resumed = true;
|
|
Require(save.Load().tutorialCheckpoint.offers.Any(offer => offer.sold), "Shop purchase was not saved.");
|
|
SceneLoader.LoadMainMenu(document.rootVisualElement);
|
|
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
|
combat = null;
|
|
while (combat == null || combat.CurrentPhase != TurnPhase.Execute)
|
|
{ yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
|
view = FindFirstObjectByType<CombatSceneController>();
|
|
document = view.GetComponent<UIDocument>(); flow = Field<TutorialFlow>(view, "_tutorial");
|
|
Require(flow.Lesson == 2 && flow.Reading && FindFirstObjectByType<RunManager>().RunId == runId,
|
|
"Restart did not resume the same run at wave two.");
|
|
Require(combat.PlayerState.CurrentUptime == uptime, "Resume reset remaining Uptime.");
|
|
}
|
|
}
|
|
}
|
|
else if (combat.CanSurrenderRun)
|
|
{
|
|
int target = -1;
|
|
for (int i = 0; i < combat.Enemies.Count; i++)
|
|
if (!combat.Enemies[i].State.IsDefeated && !combat.Enemies[i].PendingRevive
|
|
&& (target < 0 || combat.Enemies[i].CurrentUptime < combat.Enemies[target].CurrentUptime)) target = i;
|
|
if (target >= 0) combat.SelectEnemy(target);
|
|
var card = combat.HandController.Cards.Where(card => !card.Definition.IsToken && !card.IsBroken && !card.IsLocked
|
|
&& combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles)
|
|
.OrderByDescending(card =>
|
|
{
|
|
var p = CardPreviewService.Build(combat, card);
|
|
return (p.MinimumDamage + p.MaximumDamage + p.Shield + p.Heal + 1f) / (p.Cost + 1);
|
|
}).FirstOrDefault();
|
|
if (card == null || combat.CardsPlayedThisRound >= 64 || !combat.PlayCard(card)) combat.EndPlayerTurn();
|
|
}
|
|
Require(++actions < 1500, "Tutorial exceeded action budget: " + _stage);
|
|
yield return null;
|
|
}
|
|
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
|
var final = save.Load();
|
|
Require(final.recentRuns.Count == 0 && final.activeRun == null && final.tutorialCheckpoint == null && final.tutorialRewardClaimed
|
|
&& final.bandwidthBalance == initial.bandwidthBalance + TutorialCampaign.BandwidthReward
|
|
&& final.entropyBalance == initial.entropyBalance + TutorialCampaign.EntropyReward
|
|
&& final.lastRunLoadout.cardIds.Count == initial.lastRunLoadout.cardIds.Count,
|
|
"Training rewards or isolation are incorrect.");
|
|
if (Environment.GetCommandLineArgs().Contains("--kernel-panic-tutorial-smoke"))
|
|
{
|
|
var menu = FindFirstObjectByType<MainMenuController>();
|
|
ConfigureMenu(menu); Call(menu, "BootSelectedPackage");
|
|
combat = null;
|
|
while (combat == null || !combat.CanSurrenderRun) { yield return null; combat = FindFirstObjectByType<CombatManager>(); }
|
|
view = FindFirstObjectByType<CombatSceneController>(); document = view.GetComponent<UIDocument>();
|
|
Require(!combat.RunConfig.IsTutorial && document.rootVisualElement.Q("EncounterBrief").resolvedStyle.display == DisplayStyle.None
|
|
&& !Field<FirstBattleGuide>(view, "_firstBattleGuide").Visible, "Normal run still has automatic instructional text.");
|
|
capture = CapturePanel(document, "normal-run-clean");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
Require(save.Load().bandwidthBalance == final.bandwidthBalance && save.Load().entropyBalance == final.entropyBalance,
|
|
"Scene change paid the tutorial reward again.");
|
|
}
|
|
}
|
|
|
|
private static void OpenRunArchive(VisualElement root)
|
|
{
|
|
var commandInput = root.Q<TextField>("CommandInput");
|
|
Require(commandInput != null && commandInput.enabledInHierarchy, "Main menu command prompt is unavailable.");
|
|
commandInput.value = "history --runs";
|
|
using var enter = KeyDownEvent.GetPooled('\n', KeyCode.Return, EventModifiers.None);
|
|
enter.target = commandInput;
|
|
commandInput.SendEvent(enter);
|
|
}
|
|
|
|
private IEnumerator CampaignScenario(CombatManager combat, CombatSceneController view)
|
|
{
|
|
var run = combat.GetComponent<RunManager>();
|
|
var document = view.GetComponent<UIDocument>();
|
|
int actions = 0;
|
|
bool capturedBoss = false;
|
|
bool capturedPreview = false;
|
|
while (!run.CampaignChoicePending && !combat.RunFinished)
|
|
{
|
|
_stage = "campaign wave " + run.CurrentWaveNumber;
|
|
if (combat.AwaitingWaveContinue)
|
|
{
|
|
foreach (var offer in run.RepositoryOffers.Where(offer => !offer.Sold)
|
|
.OrderByDescending(offer => offer.Kind == RepositoryOfferKind.StatUpgrade && offer.StatUpgradeKind == RunStatUpgradeKind.Heal
|
|
&& combat.PlayerState.CurrentUptime < combat.PlayerState.MaxUptime / 2 ? 100
|
|
: offer.Kind == RepositoryOfferKind.CardUpgrade && offer.CardUpgradeKind == CardUpgradeKind.DrawRider ? 90
|
|
: offer.Kind == RepositoryOfferKind.CardUpgrade ? 80 : 10).ToArray())
|
|
if (offer.Price <= run.Bits) run.BuyOffer(offer, combat.PlayerState);
|
|
Submit(document.rootVisualElement.Q<Button>("RouteRepair"));
|
|
combat.ContinueToNextWave();
|
|
}
|
|
else if (combat.CanSurrenderRun)
|
|
{
|
|
if (!capturedPreview && combat.InterpreterQueue.Count > 0)
|
|
{
|
|
capturedPreview = true;
|
|
var preview = document.rootVisualElement.Q<Foldout>("ExecutionPreview");
|
|
preview.value = true;
|
|
var capture = CapturePanel(document, "execution-preview");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
preview.value = false;
|
|
}
|
|
if (run.CurrentWaveNumber == RunJourney.BossWave && !capturedBoss)
|
|
{
|
|
capturedBoss = true;
|
|
Require(combat.Enemies.Any(enemy => enemy.Archetype.Tier == EnemyTier.Boss), "Boss encounter did not spawn.");
|
|
var capture = CapturePanel(document, "boss-encounter");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
}
|
|
int target = -1;
|
|
for (int i = 0; i < combat.Enemies.Count; i++)
|
|
if (!combat.Enemies[i].State.IsDefeated && (target < 0 || combat.Enemies[i].CurrentUptime < combat.Enemies[target].CurrentUptime)) target = i;
|
|
if (target >= 0) combat.SelectEnemy(target);
|
|
var card = combat.HandController.Cards.Where(card => card.Definition != null && !card.Definition.IsToken
|
|
&& !card.IsBroken && !card.IsLocked && combat.GetDisplayedPlayCost(card) <= combat.PlayerState.Cycles)
|
|
.OrderByDescending(card =>
|
|
{
|
|
var preview = CardPreviewService.Build(combat, card);
|
|
return ((preview.MinimumDamage + preview.MaximumDamage) * 0.5 + preview.Shield * 0.7 + preview.Heal * 1.5 + 1) / (preview.Cost + 1);
|
|
}).FirstOrDefault();
|
|
if (card == null || combat.CardsPlayedThisRound >= 64 || !combat.PlayCard(card)) combat.EndPlayerTurn();
|
|
Require(++actions < 2000, "Campaign bot exceeded action budget.");
|
|
}
|
|
yield return null;
|
|
}
|
|
Require(!combat.RunLost && run.WavesCleared == 5 && capturedBoss, "Seeded campaign bot did not clear the boss.");
|
|
_stage = "campaign milestone";
|
|
var milestone = CapturePanel(document, "campaign-milestone");
|
|
while (milestone.MoveNext()) yield return milestone.Current;
|
|
int expectedBandwidth = run.AccruedBandwidth + TutorialCampaign.BandwidthReward;
|
|
int expectedEntropy = run.AccruedEntropy + TutorialCampaign.EntropyReward;
|
|
string runId = run.RunId;
|
|
bool endless = Environment.GetCommandLineArgs().Contains("--kernel-panic-endless-smoke");
|
|
if (endless)
|
|
{
|
|
Submit(document.rootVisualElement.Q<Button>("ContinueEndlessButton"));
|
|
while (!combat.CanSurrenderRun) yield return null;
|
|
Require(run.Journey.endless && run.CurrentWaveNumber == 6 && run.RunId == runId && !run.RewardsSettled,
|
|
"Endless continuation reset the build/run or settled rewards early.");
|
|
var capture = CapturePanel(document, "endless-encounter");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
combat.SurrenderRun();
|
|
}
|
|
else Submit(document.rootVisualElement.Q<Button>("FinishCampaignButton"));
|
|
yield return null;
|
|
var saved = new SaveService().Load();
|
|
Require(run.RewardsSettled && saved.recentRuns.Count == 1 && saved.recentRuns[0].victory == !endless,
|
|
"Campaign outcome did not settle a single correct history record.");
|
|
Require(saved.bandwidthBalance == expectedBandwidth && saved.entropyBalance == expectedEntropy, "Campaign reward settlement mismatch.");
|
|
var report = CapturePanel(document, "campaign-report");
|
|
while (report.MoveNext()) yield return report.Current;
|
|
SceneLoader.LoadMainMenu(document.rootVisualElement);
|
|
while (FindFirstObjectByType<MainMenuController>() == null) yield return null;
|
|
saved = new SaveService().Load();
|
|
Require(saved.recentRuns.Count == 1 && saved.bandwidthBalance == expectedBandwidth, "Scene unload duplicated campaign rewards.");
|
|
_campaignSuccess = "PASS: real five-wave campaign, repair route, purchases, boss, "
|
|
+ (endless ? "endless continuation, surrender" : "victory") + ", saved rewards/history exactly once, menu return.";
|
|
}
|
|
|
|
private static void RequireArchiveVisible(VisualElement root)
|
|
{
|
|
var archive = root.Q("RunArchivePanel");
|
|
Require(archive != null && archive.resolvedStyle.display != DisplayStyle.None
|
|
&& root.Q("MainMenuPanel").resolvedStyle.display == DisplayStyle.None, "Run archive did not become the active screen.");
|
|
Require(archive.Q<Button>("RetrySameSeedButton") != null && archive.Q<Button>("RetryNewSeedButton") != null
|
|
&& archive.Q<Button>("RecentRunsButton") != null, "Run archive does not contain all three run actions.");
|
|
}
|
|
|
|
private static void ConfigureMenu(MainMenuController menu)
|
|
{
|
|
Call(menu, "HandleStartRunClicked");
|
|
var distro = Field<DistroDatabase>(menu, "distroDatabase").FindById("ubuntu");
|
|
var loadout = Field<CardLoadout>(menu, "_cardLoadout");
|
|
foreach (var card in distro.ExclusiveCards.Take(4))
|
|
if (!loadout.GetEquippedCardIds(distro.Id).Contains(card.Id)) Call(menu, "ToggleCardInSelectedLoadout", distro, card);
|
|
var languages = Field<System.Collections.Generic.List<Language>>(menu, "_selectedRunLanguages");
|
|
if (!languages.Contains(Language.Python)) Call(menu, "ToggleRunLanguage", Language.Python);
|
|
if (!languages.Contains(Language.JavaScript)) Call(menu, "ToggleRunLanguage", Language.JavaScript);
|
|
var root = menu.GetComponent<UIDocument>().rootVisualElement;
|
|
var seed = root.Q<TextField>("RunSeedInput");
|
|
Require(seed != null, "Seed input is missing.");
|
|
seed.value = "12345";
|
|
Require(root.Q<Button>("BootRunButton").enabledSelf, "Configured boot button is disabled.");
|
|
}
|
|
|
|
private IEnumerator InspectPiles(CombatSceneController view, CombatManager combat)
|
|
{
|
|
var root = view.GetComponent<UIDocument>().rootVisualElement;
|
|
var originalOrder = combat.DeckController.DrawPile.ToArray();
|
|
Require(originalOrder.Length > 0, "Smoke setup needs a non-empty draw pile.");
|
|
Submit(root.Q<Button>("InspectPile_draw"));
|
|
yield return null;
|
|
var inspector = root.Q("CardPileInspector");
|
|
Require(inspector != null, "Draw pile inspector did not open.");
|
|
var overlay = inspector.parent;
|
|
Require(overlay.ClassListContains("pile-overlay"), "Pile inspector did not use its centered overlay layout.");
|
|
var grid = inspector.Q("PileCardGrid");
|
|
Require(grid != null, "Pile inspector card grid is missing.");
|
|
var names = grid.Query<VisualElement>("PileCard").ToList()
|
|
.Select(card => card.Q<Label>(className: "software-name").text).ToArray();
|
|
Require(names.SequenceEqual(CardPileView.GroupIdenticalCopies(originalOrder, combat.GetPileCostDetails).Select(group => group[0].Definition.DisplayName)),
|
|
"Draw pile inspector did not present an alphabetically sorted inventory.");
|
|
Require(grid.Query<VisualElement>("PileCard").ToList().Sum(face => (int)face.userData) == originalOrder.Length,
|
|
"Grouping did not preserve the actual card count.");
|
|
inspector.Q<Toggle>("PileGroupCopies").value = false;
|
|
var search = inspector.Q<TextField>("PileSearch");
|
|
var clear = inspector.Q<Button>("ClearPileSearch");
|
|
Require(clear != null && !clear.enabledSelf, "Empty pile search should have a disabled Clear button.");
|
|
search.value = "__no_matching_card__";
|
|
Require(grid.Query<VisualElement>("PileCard").ToList().Count == 0, "Pile search did not filter cards.");
|
|
Require(grid.Q<Label>("PileEmptyState")?.text.StartsWith("No matching cards.", StringComparison.Ordinal) == true,
|
|
"Nonmatching pile search did not explain how to recover.");
|
|
Submit(clear);
|
|
for (int frame = 0; frame < 3; frame++) yield return null;
|
|
Require(search.value.Length == 0 && grid.Query<VisualElement>("PileCard").ToList().Count == originalOrder.Length
|
|
&& grid.Q("PileEmptyState") == null && !clear.enabledSelf, "Clearing pile search did not restore every card.");
|
|
var focused = root.focusController.focusedElement as VisualElement;
|
|
Require(focused == search || (focused != null && search.Contains(focused)), "Clearing pile search did not restore search focus.");
|
|
search.value = originalOrder[0].Definition.Id;
|
|
Require(grid.Query<VisualElement>("PileCard").ToList().Count > 0, "Pile search could not find an existing card.");
|
|
Submit(inspector.Q<Button>("PileTab_discard"));
|
|
Require(search.value.Length == 0 && inspector.Q<Label>("PileEmptyState")?.text == "This pile is empty.",
|
|
"Discard tab did not retain its own empty search and pile.");
|
|
Submit(inspector.Q<Button>("PileTab_exhaust"));
|
|
Require(inspector.Q<Button>("PileTab_exhaust").ClassListContains("selected"), "Exhaust tab did not become selected.");
|
|
Submit(inspector.Q<Button>("PileTab_draw"));
|
|
Require(search.value == originalOrder[0].Definition.Id && !inspector.Q<Toggle>("PileGroupCopies").value,
|
|
"Returning to Draw did not preserve its search and grouping preference.");
|
|
Submit(clear);
|
|
inspector.Q<Toggle>("PileGroupCopies").value = true;
|
|
var costDetails = grid.Q<Foldout>("PileCostDetails");
|
|
Require(costDetails != null, "Current cost explanation is missing.");
|
|
costDetails.value = true;
|
|
var languageFilter = inspector.Q<DropdownField>("PileLanguageFilter");
|
|
var costFilter = inspector.Q<DropdownField>("PileCostFilter");
|
|
languageFilter.Focus();
|
|
yield return null;
|
|
using (var next = NavigationMoveEvent.GetPooled(NavigationMoveEvent.Direction.Next))
|
|
{
|
|
next.target = languageFilter;
|
|
languageFilter.SendEvent(next);
|
|
}
|
|
yield return null;
|
|
var filterFocus = root.focusController.focusedElement as VisualElement;
|
|
Require(filterFocus == costFilter || costFilter.Contains(filterFocus), "Runtime modal navigation skipped the cost filter.");
|
|
var capture = CapturePanel(view.GetComponent<UIDocument>(), "pile-inspector");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
Require(Mathf.Abs(inspector.worldBound.center.x - overlay.worldBound.center.x) <= 2
|
|
&& Mathf.Abs(inspector.worldBound.center.y - overlay.worldBound.center.y) <= 2,
|
|
"Pile inspector is not centered in the combat overlay.");
|
|
var faces = grid.Query<VisualElement>("PileCard").ToList();
|
|
if (Screen.width >= 1200)
|
|
Require(faces.Count >= 2 && Mathf.Abs(faces[0].worldBound.yMin - faces[1].worldBound.yMin) <= 2
|
|
&& faces[1].worldBound.xMin > faces[0].worldBound.xMax,
|
|
"Wide-screen pile inspector did not display multiple card columns with a gutter.");
|
|
Submit(inspector.Q<Button>("ClosePileInspector"));
|
|
Require(root.Q("CardPileInspector") == null && !overlay.ClassListContains("pile-overlay")
|
|
&& combat.DeckController.DrawPile.SequenceEqual(originalOrder),
|
|
"Inspecting or closing the draw pile changed its live order.");
|
|
foreach (string pile in new[] { "discard", "exhaust" })
|
|
{
|
|
Submit(root.Q<Button>("InspectPile_" + pile));
|
|
yield return null;
|
|
inspector = root.Q("CardPileInspector");
|
|
Require(inspector != null, pile + " inspector did not open.");
|
|
Require(inspector.Q("PileCardGrid").Query<VisualElement>("PileCard").ToList().Count == 0
|
|
&& inspector.Q<Label>("PileEmptyState")?.text == "This pile is empty.",
|
|
pile + " did not display its empty state before any cards were played.");
|
|
capture = CapturePanel(view.GetComponent<UIDocument>(), "pile-" + pile + "-empty");
|
|
while (capture.MoveNext()) yield return capture.Current;
|
|
Submit(inspector.Q<Button>("ClosePileInspector"));
|
|
Require(root.Q("CardPileInspector") == null && !overlay.ClassListContains("pile-overlay"),
|
|
"Closing the " + pile + " inspector left its modal layout active.");
|
|
}
|
|
Require(combat.DeckController.DrawPile.SequenceEqual(originalOrder), "Pile inspection changed the original draw order.");
|
|
}
|
|
|
|
private static string BuildSignature(RunConfig config) => $"{config.Distro.Id}|{config.DistroVersion}|{config.PrimaryLanguage}|{config.SecondaryLanguage}|"
|
|
+ string.Join(",", config.StartingDeck.Select(card => card.Id)) + "|"
|
|
+ string.Join(",", config.EquippedPackages.Select(package => package.Definition.Id + ":" + package.UpgradeLevel));
|
|
|
|
private static string DeckSignature(RunManager run) => string.Join("|", run.RunDeck.Select(card =>
|
|
$"{card.InstanceId}:{card.Definition.Id}:{card.PermanentCostDelta}:{card.MagnitudeBonus}:{card.DrawRider}:{card.UpgradeLevel}"));
|
|
|
|
private static string OfferSignature(RunManager run) => string.Join("|", run.RepositoryOffers.Select(offer =>
|
|
$"{offer.Kind}:{offer.CardDefinition?.Id}:{offer.TargetCard?.InstanceId}:{offer.CardUpgradeKind}:{offer.StatUpgradeKind}:{offer.Price}:{offer.Sold}"));
|
|
|
|
private static void Submit(Button button)
|
|
{
|
|
Require(button != null && button.enabledInHierarchy, "Expected enabled UI command is unavailable.");
|
|
using var submit = NavigationSubmitEvent.GetPooled();
|
|
submit.target = button;
|
|
button.SendEvent(submit);
|
|
}
|
|
|
|
private IEnumerator CapturePanel(UIDocument document, string name)
|
|
{
|
|
// A hidden Windows swap chain can return black screenshots. Render the actual
|
|
// runtime panel to a texture for deterministic visual inspection of the same UI.
|
|
var settings = document.panelSettings;
|
|
var previous = settings.targetTexture;
|
|
var target = new RenderTexture(Screen.width, Screen.height, 24);
|
|
target.Create();
|
|
settings.targetTexture = target;
|
|
try
|
|
{
|
|
for (int frame = 0; frame < 8; frame++) yield return null;
|
|
var root = document.rootVisualElement;
|
|
File.WriteAllText(Path.Combine(_output, name + "-panel.txt"),
|
|
$"panel={root.panel != null}; bounds={root.worldBound}; opacity={root.resolvedStyle.opacity}; display={root.resolvedStyle.display}; visibility={root.resolvedStyle.visibility}; children={root.childCount}; renderedFrames={Time.renderedFrameCount}; graphics={SystemInfo.graphicsDeviceType}; focused={Application.isFocused}");
|
|
var previousActive = RenderTexture.active;
|
|
var pixels = new Texture2D(target.width, target.height, TextureFormat.RGB24, false);
|
|
try
|
|
{
|
|
RenderTexture.active = target;
|
|
pixels.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0);
|
|
pixels.Apply();
|
|
File.WriteAllBytes(Path.Combine(_output, name + ".png"), pixels.EncodeToPNG());
|
|
Require(pixels.GetPixels32().Any(pixel => pixel.r > 20 || pixel.g > 20 || pixel.b > 20), "Runtime panel rendered an empty image: " + name);
|
|
}
|
|
finally { RenderTexture.active = previousActive; Destroy(pixels); }
|
|
}
|
|
finally { settings.targetTexture = previous; target.Release(); Destroy(target); }
|
|
}
|
|
|
|
private static T Field<T>(object owner, string name) => (T)owner.GetType().GetField(name, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(owner);
|
|
private static void Call(object owner, string name, params object[] args) => owner.GetType().GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(owner, args);
|
|
private static void Require(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
|
|
}
|
|
}
|
|
#endif
|