using System.Reflection; using UnityEngine; using Wizard; using Wizard.Battle; using Wizard.Battle.Phase; using Wizard.Battle.Recovery; using Wizard.Battle.Replay; using Wizard.Battle.Resource; using Wizard.Battle.View.Vfx; using Wizard.BattleMgr; namespace SVSim.BattleEngine.Tests { // Initializes the global engine state a headless battle assumes exists. In the real client this // is populated from /load/index at login; here we author the minimum the resolution path reads. public static class HeadlessEngineEnv { // Simplest zero-skill vanilla follower in cards.json: neutral (clan 0), cost 1, 1/2, no skill. public const int FollowerId = 100011010; // M3 next-hardest deterministic card: a fixed-damage spell. 900124030 is an ELF (clan 1, matches // PlayerClassId) cost-3 spell whose sole skill is `when_play` `damage=3` to `card_type=class` // (the enemy leader) — auto-targeted (no select_count), no RNG. Deterministic burn to the face. public const int SpellId = 900124030; // M4 next-hardest deterministic card: a when_play SELF-BUFF follower. 103111050 is an ELF // (clan 1) cost-1 1/1 whose sole non-evo skill is `when_play` `powerup` `add_offense=1&add_life=1` // with skill_target `character=me&target=self` — it buffs ITSELF, so no target selection (the // fanfare auto-resolves). Fixed +1/+1 => a deterministic stat-delta oracle. The skill is gated on // `play_count>2`; the headless harness seeds that via the public AddCurrentTrunPlayCount (see the // oracle test). Base 1/1 -> 2/2 after the fanfare. public const int BuffFollowerId = 103111050; public const int BuffAddOffense = 1; public const int BuffAddLife = 1; // M5 next-hardest deterministic card: a when_play SUMMON_TOKEN spell. 800134010 is an ELF // (clan 1) cost-1 spell whose sole skill is `when_play` `summon_token=100011020` with // `skill_target=none` and an UNGATED condition (`character=me`, trivially the caster): it // summons exactly ONE neutral 2/2 follower TOKEN onto the caster's board — no target // selection, no RNG (Skill_summon_token's random branch is `num >= 0 && !IsForecast`, and // this option carries no `random_count`, so num=-1 => the deterministic literal-id path). // The new oracle dimension over M2/M3/M4 is a BOARD-COUNT DELTA from a SKILL-CREATED card: // a token that was never in the hand/deck appears in play. This is also the first headless // exercise of the PUBLIC prefab card-creation path (CardCreatorBase.CreateCard, // createNullView:false, via BattlePlayerBase.CreateNextIndexCard) — class-card construction // hits `default: return null` and the M2-M4 hand cards used the private null-view seam, so // the view-building creation path is genuinely new here. public const int TokenSpellId = 800134010; public const int SummonedTokenId = 100011020; // neutral 2/2 follower token public const int SummonedTokenAtk = 2; public const int SummonedTokenLife = 2; // M6 next milestone: the first card requiring TARGET SELECTION — exercises the selectedCards // path of ActionProcessor.PlayCard (dormant through M2-M5, all of which played // selectedCards: null). 800134020 is an ELF (clan 1) cost-1 SPELL whose sole skill is // `when_play` `damage=5` to a SELECTED enemy follower // (skill_target=character=op&target=inplay&card_type=unit&select_count=1), ungated // (character=me), no RNG, no dynamic `{}` value. The new oracle dimension is SELECTION // ROUTING: with TWO followers on the enemy board and ONE passed as selectedCards, only the // selected follower takes the 5 damage and the un-selected one is untouched. public const int TargetSpellId = 800134020; public const int TargetSpellDamage = 5; // Two zero-skill vanilla NEUTRAL followers placed on the ENEMY board. Both have life > the // 5 damage so they SURVIVE — this gives a differential life-delta oracle (selected -5, // un-selected -0) that reads the authoritative damage path M3 already proved, without // depending on follower death/board-removal timing (a separate, unproven mechanic). Distinct // base life (13 vs 7) so the two post-states can't coincidentally match. public const int SelectTargetFollowerId = 900041010; // neutral 13/13 public const int UnselectTargetFollowerId = 102011010; // neutral 6/7 private static bool _done; public static void EnsureInitialized() { if (_done) return; // Wizard.Data.Load: static /load/index snapshot. The ctor's CreateBackgroundId reads // Data.Load.data._userTutorial (LoadDetail self-inits _userTutorial). Suppress VFX too. Wizard.Data.Load = new Load { data = new LoadDetail() }; // CardParameter(CardCSVData) reads Data.Crossover.RestrictedCard for deck-limit calc; // an empty Crossover returns the default count (no restriction). Private setter -> reflect. typeof(Wizard.Data).GetProperty("Crossover", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public) .SetValue(null, new Wizard.Crossover()); BattleManagerBase.IsForecast = true; // CardMaster must be non-null before construction (the leader/class card looks up id 0). // Load the M2 vanilla follower + the M3 fixed-damage spell + the M4 self-buff follower + // the M5 summon-token spell AND the token it summons so each oracle can create + look up // real stats. The summoned token id must be present: Skill_summon_token resolves it // through CardMaster.GetCardParameterFromId during creation. HeadlessCardMaster.Load(FollowerId, SpellId, BuffFollowerId, TokenSpellId, SummonedTokenId, TargetSpellId, SelectTargetFollowerId, UnselectTargetFollowerId); // Master reference data (class-character list) for leader/class card resolution. HeadlessMasterData.Install(); // Player/enemy leaders (chara ids must map to a ClassCharacterMasterData in Master). // Set the backing fields directly: the public SetPlayerCharaId() also pulls MyRotation/ // AvatarBattle info (more null statics) which the resolution path doesn't need (the // TryGet* accessors are null-tolerant). var dm = GameMgr.GetIns().GetDataMgr(); SetField(dm, "_playerCharaId", HeadlessMasterData.PlayerCharaId); SetField(dm, "_enemyCharaId", HeadlessMasterData.EnemyCharaId); _done = true; } // Seed each leader's starting life on a freshly-constructed mgr. The engine does this in // BattleManagerBase.SetupInitialGameState -> InitializeClassLife (InitBaseMaxLife per leader), // but the full SetupInitialGameState also cascades into rotation/avatar/turn-panel UI init // that is irrelevant (and hostile) to a headless resolution test, so apply just the // InitializeClassLife subset. Without this a leader's BaseMaxLife defaults to 0 — which reads // as already-dead/game-over and silently blocks any card play (the M2 follower oracle never // noticed because it only asserted leader life *unchanged*, and 0 == 0). public const int DefaultLeaderLife = 20; public static void InitLeaderLife(BattleManagerBase mgr, int life = DefaultLeaderLife) { ((ClassBattleCardBase)mgr.BattlePlayer.Class).InitBaseMaxLife(life); ((ClassBattleCardBase)mgr.BattleEnemy.Class).InitBaseMaxLife(life); } // The PUBLIC prefab card-creation path (CardCreatorBase.CreateCard, createNullView:false) — // used by anything the engine creates INTERNALLY (summons, token-draws, etc.), as opposed to // the test's direct private null-view seam for hand cards — clones card-template prefabs held // on BattleManagerBase.SBattleLoad. The real async battle load (CoLoad) builds these; the bare // `new SingleBattleMgr(...)` construction path leaves SBattleLoad null (the M2 NRE was here). // Seed it with non-null no-op CardTemplates: their `.gameObject` is a lazy shim no-op, and the // shim's CloneObjectToParent + self-consistent object graph carry the rest. Nothing here // computes game state — the token's authoritative stats come from CardCSVData, not the view. public static void InitCardTemplates(BattleManagerBase mgr) { mgr.SBattleLoad = new SBattleLoad { UnitCardTemplate = new CardTemplate(), SpellCardTemplate = new CardTemplate(), FieldCardTemplate = new CardTemplate(), }; // The created card's transform is positioned/parented under the battle's 3D scene-graph // containers (CardCreatorBase.CreateCardTypeBuildInfo reads ins.CardHolder/ECardHolder/ // PCardPlace/Battle3DContainer). The real battle load instantiates these; seed non-null // no-op GameObjects so the positioning resolves (no-op transforms; nothing rendered). mgr.Battle3DContainer = new GameObject(); mgr.CardHolder = new GameObject(); mgr.ECardHolder = new GameObject(); mgr.PCardPlace = new GameObject(); mgr.ChoiceCardHolder = new GameObject(); mgr.EvolveCardHolder = new GameObject(); } // The shared headless card-creation primitive. CardCreatorBase.CreateCardWithoutResources is // the engine's own null-view creation path (CreateBase -> new *BattleCard(buildInfo).Setup( // createNullView:true)); it's private, so reflect it rather than reimplement the 14-arg // BuildInfo wiring. The public CardCreatorBase.CreateCard goes through prefab cloning. // // The engine's CreateCard also calls owner.SetupCardEvent(card); the raw // CreateCardWithoutResources seam skips it, so we fold it in here. SetupCardEvent wires the // per-card play events (BattlePlayerBase.cs:1452): for a SPELL/amulet it attaches // OnPlay -> RemoveSpellCardFromHand and OnFinishWhenPlaySkill -> AddSpellCardToCemetery, which // are how a non-follower leaves the hand at all (a follower's hand->field move is intrinsic to // SetUpInplay, not event-driven). For a follower SetupCardEvent only attaches an OnEvolve hook // that never fires on a vanilla play, so folding it in is a no-op there — making this a single // primitive both follower and non-follower oracles can share. public static BattleCardBase CreateHeadlessHandCard(int cardId, int index, bool isPlayer, BattleManagerBase mgr) { var io = mgr.CreatePlayerInnerOptionsBuilder(); var m = typeof(CardCreatorBase).GetMethod("CreateCardWithoutResources", BindingFlags.NonPublic | BindingFlags.Static); var card = (BattleCardBase)m.Invoke(null, new object[] { cardId, index, isPlayer, mgr, io }); BattlePlayerBase owner = isPlayer ? (BattlePlayerBase)mgr.BattlePlayer : mgr.BattleEnemy; owner.SetupCardEvent(card); return card; } // Put a follower DIRECTLY onto a player's board headless (vs as a side-effect of PlayCard), // for setting up a target board state. Create it through the shared null-view seam, then drive // the engine's own hand->field move: HandCardToField requires the card to be in HandCardList, // then AddInplayCards it + removes it from hand (BattlePlayerBase.cs:2568). For a vanilla // follower the OnAddPlayCard/StopBattleHandCard/OnSummonAfter events it fires are no-ops (no // fanfare), so the follower lands on the board at its CardCSVData base stats. M2 proved the // hand->field placement path resolves headless. public static BattleCardBase PutFollowerInPlay(BattleManagerBase mgr, int cardId, int index, bool isPlayer) { var card = CreateHeadlessHandCard(cardId, index, isPlayer, mgr); BattlePlayerBase owner = isPlayer ? (BattlePlayerBase)mgr.BattlePlayer : mgr.BattleEnemy; owner.HandCardList.Add(card); owner.HandCardToField(card); return card; } private static void SetField(object obj, string name, object value) { var f = obj.GetType().GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public); if (f == null) throw new System.InvalidOperationException( $"{obj.GetType().Name} has no field '{name}'"); f.SetValue(obj, value); } } // Test-side replica of the engine's own StandardBattleMgrContentsCreator (the practice/solo // init path: GameMgr.cs:244 `new SingleBattleMgr(new StandardBattleMgrContentsCreator(null, null))`). // Authored here (not copied) so we control the seed deterministically; uses the real engine // managers verbatim. The real StandardBattleMgrContentsCreator + SingleBattlePhaseCreator were // cut from the M1 copy set (entry-point constructors), so we reproduce them minimally. public sealed class HeadlessContentsCreator : IBattleMgrContentsCreator { public int RandomSeed => 12345; // fixed; vanilla follower has no RNG so value is irrelevant // No-op managers (vs the practice path's file-backed SingleBattleRecoveryRecordManager): // the ctor's FirstRecoverySetting/FirstReplaySetting dereference these, and recovery/replay // recording is irrelevant to the M2 oracle, so use the engine's own null implementations. public IRecoveryManager RecoveryManager { get; } = new NullRecoveryManager(); public IRecoveryRecordManager RecoveryRecordManager { get; } = new NullRecoveryRecordManager(); public IReplayRecordManager ReplayRecordManager { get; } = new NullReplayRecordManager(); public IBattleResourceMgr CreateResourceMgr() => new BattleResourceMgr(); public VfxMgr CreateVfxMgr() => new VfxMgr(); public IPhaseCreator CreatePhaseCreator(BattleManagerBase battleMgr) => new HeadlessPhaseCreator(battleMgr); } // Equivalent of the engine's SingleBattlePhaseCreator: inherits PhaseCreatorBase wholesale. public sealed class HeadlessPhaseCreator : PhaseCreatorBase { public HeadlessPhaseCreator(BattleManagerBase battleMgr) : base(battleMgr) { } } }