rimworld-blax-slaves/Tests/BlaxSlavesTests/Source/RunawayTests.cs

671 lines
36 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxSlaves;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using RimWorld.QuestGen;
using Verse;
using Verse.AI.Group;
namespace BlaxSlavesTests
{
/// <summary>
/// Branded runaways (Runaways.cs). Escapes end the way a vanilla slave rebellion ends: the slave
/// is in a LordJob_SlaveRebellion lord and calls Pawn.ExitMap(true, edge) like JobDriver_Goto does
/// at the map edge. Vanilla then passes them to the world, where Pawn.Notify_PassedToWorld frees
/// them and hands them a random non-colony humanlike faction (hostile ones included), so each
/// escape is seeded and retried a bounded number of times until that faction is not hostile
/// (and, where the test needs it, not the slave's origin faction either).
/// </summary>
public static class RunawayTests
{
// Vanilla weights the freed escapee's faction pick, so a non-hostile faction other than the
// origin can come up as rarely as ~1 in 5 (one civil outlander faction as origin, Empire
// the only other non-hostile one). 30 seeded tries keep a vacuous skip below ~0.2%.
private const int MaxEscapeAttempts = 30;
private const int CheckInterval = 250;
private const int MaxLandingTicks = 3000;
private const string CarryPawn = "runaways.pawn";
private const string CarryOrigin = "runaways.origin";
private const string CarryFinder = "runaways.finder";
private const string CarryDueTick = "runaways.dueTick";
private const string SearchMessageKey = "BlaxSlaves_RunawaySearchMessage";
private const string GoneMessageKey = "BlaxSlaves_RunawayGoneMessage";
private const string KeptLabelKey = "BlaxSlaves_RunawayKeptLabel";
private const string ReturnedLabelKey = "BlaxSlaves_RunawayReturnedLabel";
/// <summary>Every pawn this class let escape in the current test, forgotten by the mod afterwards.</summary>
private static readonly List<Pawn> escapees = new List<Pawn>();
// ---- registered and returned --------------------------------------------------------
[BlaxTest("runaways: branded escapee is registered, then returned as our slave")]
public static void BrandedEscapeeIsReturned()
{
try
{
RequireExitMapPatch();
BlaxSlavesSettings s = Fixtures.Settings;
s.returnRunaways = true;
s.returnChance = 1f;
s.returnDelayMinDays = 3;
s.returnDelayMaxDays = 3;
Map map = Fixtures.Map;
// distinctFinder: if vanilla handed the escapee back to its origin faction, the
// SlaveFaction/HomeFaction checks after delivery would pass without the restore.
Escapee e = EscapeUntilNonHostileFinder(1100, BrandForPlayerNoInteraction, playerBrand: true, distinctFinder: true);
Pawn pawn = e.pawn;
T.Check(GameComponent_BlaxRunaways.IsPending(pawn),
$"{pawn} escaped with the player's brand to non-hostile {pawn.Faction} but GameComponent_BlaxRunaways.IsPending is false (the ExitMap patch did not register it)");
T.Check(Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn),
$"pending runaway {pawn} is not in Find.WorldPawns.ForcefullyKeptPawns, world pawn GC could discard it");
RunawayRecord r = RecordOf(pawn);
T.NotNull(r, "runaway record for " + pawn);
T.Equal(e.origin, r.origin, "record origin (SlaveFaction before the escape)");
T.Equal(pawn.Faction, r.finder, "record finder (the faction vanilla gave the escapee)");
T.Equal(map, r.map, "record map");
T.Equal(SlaveInteractionModeDefOf.NoInteraction, r.mode, "record slave interaction mode");
T.Equal(e.escapeTick + 3 * GenDate.TicksPerDay, r.dueTick, "record dueTick with returnDelayMin/MaxDays = 3");
T.Check(r.pinnedByUs, "record.pinnedByUs is false although the pawn was not pinned before");
T.Check(HasMessage(e.since, SearchMessageKey, pawn, r.finder), "no 'may bring them back' message for " + pawn);
T.Check(!HasMessage(e.since, GoneMessageKey, pawn), "'nobody will bring them back' message sent although returnChance = 1");
// Not due yet: the 250-tick check has to leave the record alone.
Fixtures.Tick(CheckInterval + 10);
T.Check(GameComponent_BlaxRunaways.IsPending(pawn) && pawn.IsWorldPawn() && RecordOf(pawn) != null,
$"{pawn} left the pending state {CheckInterval + 10} ticks after escaping, 3 days before its dueTick (pending={GameComponent_BlaxRunaways.IsPending(pawn)}, world pawn={pawn.IsWorldPawn()})");
Faction finder = r.finder;
T.Check(finder != e.origin, $"precondition: finder {finder} must differ from origin {e.origin}");
SetDecoyMode(pawn, r.mode);
DeliverNow(pawn, r, map);
AssertReturned(e.since, pawn, e.origin, SlaveInteractionModeDefOf.NoInteraction, finder, map);
}
finally
{
ForgetEscapees();
}
}
// ---- not registered -----------------------------------------------------------------
[BlaxTest("runaways: unbranded escapee is not registered")]
public static void UnbrandedEscapeeNotRegistered()
{
try
{
RequireExitMapPatch();
Fixtures.Settings.returnRunaways = true;
Fixtures.Settings.returnChance = 1f;
Escapee e = EscapeUntilNonHostileFinder(1200, p =>
{
T.Check(!BrandUtility.IsBranded(p), "fixture slave " + p + " is already branded");
}, playerBrand: false);
AssertNotRegistered(e.pawn, "without a brand");
AssertNoRunawayMessages(e.since, e.pawn, "without a brand");
}
finally
{
ForgetEscapees();
}
}
[BlaxTest("runaways: escapee with another faction's brand is not registered")]
public static void ForeignBrandedEscapeeNotRegistered()
{
try
{
RequireExitMapPatch();
Fixtures.Settings.returnRunaways = true;
Fixtures.Settings.returnChance = 1f;
Faction owner = Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction();
if (owner == null)
T.Skip("no non-player faction to own the brand");
Escapee e = EscapeUntilNonHostileFinder(1300, p =>
{
BrandUtility.Brand(p, owner);
T.Check(BrandUtility.IsBranded(p) && !BrandUtility.IsBrandedByPlayer(p),
$"brand on {p} should belong to {owner}, owner is {BrandUtility.BrandOf(p)?.owner.ToStringSafe()}");
}, playerBrand: false);
T.Equal(owner, BrandUtility.BrandOf(e.pawn)?.owner, "brand owner after the escape");
AssertNotRegistered(e.pawn, "carrying " + owner + "'s brand");
AssertNoRunawayMessages(e.since, e.pawn, "carrying " + owner + "'s brand");
}
finally
{
ForgetEscapees();
}
}
[BlaxTest("runaways: returnRunaways off, branded escapee is not registered")]
public static void ReturnRunawaysOffNotRegistered()
{
try
{
RequireExitMapPatch();
Fixtures.Settings.returnRunaways = false;
Fixtures.Settings.returnChance = 1f;
Escapee e = EscapeUntilNonHostileFinder(1400, BrandForPlayerNoInteraction, playerBrand: true);
AssertNotRegistered(e.pawn, "with returnRunaways = false");
T.Check(HasMessage(e.since, GoneMessageKey, e.pawn),
$"no 'nobody will bring them back' message for {e.pawn}; with returnRunaways = false the escape should still be reported");
T.Check(!HasMessage(e.since, SearchMessageKey, e.pawn, e.pawn.Faction), "'may bring them back' message sent although returnRunaways = false");
}
finally
{
ForgetEscapees();
}
}
[BlaxTest("runaways: returnChance 0, not pinned, only a message")]
public static void ReturnChanceZeroOnlyMessage()
{
try
{
RequireExitMapPatch();
Fixtures.Settings.returnRunaways = true;
Fixtures.Settings.returnChance = 0f;
Escapee e = EscapeUntilNonHostileFinder(1500, BrandForPlayerNoInteraction, playerBrand: true);
AssertNotRegistered(e.pawn, "with returnChance = 0");
T.Check(HasMessage(e.since, GoneMessageKey, e.pawn), $"no 'nobody will bring them back' message for {e.pawn} with returnChance = 0");
T.Check(!HasMessage(e.since, SearchMessageKey, e.pawn, e.pawn.Faction), "'may bring them back' message sent although returnChance = 0");
T.Check(FindLetter(e.since, KeptLabelKey, e.pawn) == null && FindLetter(e.since, ReturnedLabelKey, e.pawn) == null,
"a runaway letter was sent for " + e.pawn + " with returnChance = 0; only a message was expected");
}
finally
{
ForgetEscapees();
}
}
// ---- blocked from redress and quests --------------------------------------------------
[BlaxTest("runaways: pending runaway is not redressed or taken by quests")]
public static void PendingBlockedFromRedressAndQuests()
{
try
{
Fixtures.Settings.returnRunaways = true;
Fixtures.Settings.returnChance = 1f;
Fixtures.Settings.returnDelayMinDays = 5;
Fixtures.Settings.returnDelayMaxDays = 5;
Escapee e = EscapeUntilNonHostileFinder(1600, BrandForPlayerNoInteraction, playerBrand: true);
Pawn pawn = e.pawn;
T.Check(GameComponent_BlaxRunaways.IsPending(pawn), $"{pawn} is not pending after a branded escape, nothing to check");
MethodInfo redress = AccessTools.Method(typeof(PawnGenerator), "IsValidCandidateToRedress");
T.NotNull(redress, "PawnGenerator.IsValidCandidateToRedress");
// Loose request (no faction, so no faction-xenotype filter) that vanilla should accept the escapee for.
var request = new PawnGenerationRequest(pawn.kindDef, null, PawnGenerationContext.NonPlayer,
allowDowned: true, canGeneratePawnRelations: true, allowGay: true, allowPregnant: true,
allowAddictions: true, worldPawnFactionDoesntMatter: true, developmentalStages: DevelopmentalStage.Adult);
MethodInfo goodPawn = AccessTools.Method(typeof(QuestNode_GetPawn), "IsGoodPawn");
T.NotNull(goodPawn, "QuestNode_GetPawn.IsGoodPawn");
var node = new QuestNode_GetPawn();
var slate = new Slate();
int verified = 0;
verified += CheckBlockedWhilePending("PawnGenerator.IsValidCandidateToRedress", pawn,
() => (bool)redress.Invoke(null, new object[] { pawn, request }));
verified += CheckBlockedWhilePending("QuestNode_GetPawn.IsGoodPawn", pawn,
() => (bool)goodPawn.Invoke(node, new object[] { pawn, slate }));
if (verified == 0)
T.Skip("vanilla rejects the escapee in both methods even when it is not pending, so the patches can't be told apart from vanilla");
}
finally
{
ForgetEscapees();
}
}
// ---- save and reload ----------------------------------------------------------------
[BlaxTest("runaways: set up a pending runaway for the reload check")]
public static void SetupPendingRunawayForReload()
{
Pawn keep = null;
try
{
RequireExitMapPatch();
BlaxSlavesSettings s = Fixtures.Settings;
s.returnRunaways = true;
s.returnChance = 1f;
s.returnDelayMinDays = 20;
s.returnDelayMaxDays = 20;
Escapee e = EscapeUntilNonHostileFinder(1700, BrandForPlayerNoInteraction, playerBrand: true, distinctFinder: true);
Pawn pawn = e.pawn;
T.Check(GameComponent_BlaxRunaways.IsPending(pawn), $"{pawn} is not pending after a branded escape");
RunawayRecord r = RecordOf(pawn);
T.NotNull(r, "runaway record for " + pawn);
T.Equal(e.escapeTick + 20 * GenDate.TicksPerDay, r.dueTick, "record dueTick with a 20-day delay");
T.NotNull(r.finder, "record finder");
T.Equal(e.origin, r.origin, "record origin");
T.Equal(SlaveInteractionModeDefOf.NoInteraction, r.mode, "record slave interaction mode");
keep = Fixtures.Keep(pawn);
T.Carry[CarryPawn] = pawn.ThingID;
T.Carry[CarryOrigin] = e.origin.GetUniqueLoadID();
T.Carry[CarryFinder] = r.finder.GetUniqueLoadID();
T.Carry[CarryDueTick] = r.dueTick.ToString();
T.Info($"kept pending runaway {pawn} ({pawn.ThingID}), origin {e.origin}, finder {r.finder}, due tick {r.dueTick}");
}
finally
{
ForgetEscapees(keep);
}
}
[BlaxTest("runaways: pending runaway survives save and reload, then is returned", phase: 2)]
public static void PendingRunawaySurvivesReload()
{
if (!T.Carry.TryGetValue(CarryPawn, out string id))
T.Skip("phase 1 stored no pending runaway; see 'runaways: set up a pending runaway for the reload check'");
Pawn pawn = Fixtures.FindPawnById(id);
T.NotNull(pawn, "pending runaway " + id + " after reload");
// The runner silences the storyteller only before phase 1; loading the save rebuilt its
// comps, so a raid could land during the delivery ticks below.
Fixtures.QuietStoryteller();
try
{
Faction origin = FactionByLoadId(T.Carry[CarryOrigin]);
Faction finder = FactionByLoadId(T.Carry[CarryFinder]);
T.NotNull(origin, "origin faction " + T.Carry[CarryOrigin] + " after reload");
int dueTick = int.Parse(T.Carry[CarryDueTick]);
Map map = Fixtures.Map;
T.Check(pawn.IsWorldPawn() && !pawn.Spawned,
$"{pawn} should still be a world pawn after reload: spawned={pawn.Spawned}, world pawn={pawn.IsWorldPawn()}");
T.Check(GameComponent_BlaxRunaways.IsPending(pawn),
$"{pawn} not pending after reload: the static pending set was not rebuilt from the saved records");
RunawayRecord r = RecordOf(pawn);
T.NotNull(r, "runaway record for " + pawn + " after reload");
T.Equal(origin, r.origin, "record origin after reload");
T.Equal(finder, r.finder, "record finder after reload");
T.Equal(dueTick, r.dueTick, "record dueTick after reload");
T.Equal(map, r.map, "record map after reload");
T.Equal(SlaveInteractionModeDefOf.NoInteraction, r.mode, "record mode after reload");
T.Check(r.dueTick > Find.TickManager.TicksGame,
$"record already due ({r.dueTick} <= {Find.TickManager.TicksGame}) before the test forced it");
T.Check(r.pinnedByUs, "record.pinnedByUs lost over save and reload");
T.Check(Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn), $"{pawn} not in ForcefullyKeptPawns after reload");
T.Check(BrandUtility.IsBrandedByPlayer(pawn), $"{pawn} lost the player's brand over save and reload");
// Other phase-1 tests may have soured relations; a hostile holder rightly keeps them.
if (pawn.Faction != null && pawn.Faction.HostileTo(Faction.OfPlayer))
T.Skip($"reload state checked; {pawn}'s faction {pawn.Faction} turned hostile during phase 1, so delivery would rightly be cancelled");
T.Check(r.finder != origin, $"precondition: finder {r.finder} must differ from origin {origin}");
Faction deliverer = r.finder;
SetDecoyMode(pawn, r.mode);
var since = new Snapshot();
DeliverNow(pawn, r, map);
AssertReturned(since, pawn, origin, SlaveInteractionModeDefOf.NoInteraction, deliverer, map);
}
finally
{
escapees.Add(pawn);
ForgetEscapees();
Dispose(pawn);
}
}
// ---- escape helpers -----------------------------------------------------------------
private sealed class Escapee
{
public Pawn pawn;
public Faction origin;
public int escapeTick;
public Snapshot since; // letters and messages that existed just before the escape
}
/// <summary>Letters and archived messages that already exist, so lookups only see newer ones.</summary>
private sealed class Snapshot
{
public readonly HashSet<Letter> letters = new HashSet<Letter>(Find.LetterStack.LettersListForReading);
public readonly HashSet<Message> messages = new HashSet<Message>(Find.Archive.ArchivablesListForReading.OfType<Message>());
}
private static void BrandForPlayerNoInteraction(Pawn p)
{
BrandUtility.Brand(p, Faction.OfPlayer);
p.guest.slaveInteractionMode = SlaveInteractionModeDefOf.NoInteraction;
T.Check(BrandUtility.IsBrandedByPlayer(p), $"BrandUtility.Brand did not mark {p} as the player's");
}
/// <summary>
/// The live interaction mode never changes between escape and delivery (SetGuestStatus keeps
/// it for a pawn that was enslaved before), so checking it after delivery proves nothing
/// unless it differs from the record. Set it to something else on the free world pawn: only
/// RunawayDelivery copying record.mode back can make the post-delivery check pass.
/// </summary>
private static void SetDecoyMode(Pawn pawn, SlaveInteractionModeDef recorded)
{
SlaveInteractionModeDef decoy = recorded == SlaveInteractionModeDefOf.Suppress
? SlaveInteractionModeDefOf.NoInteraction
: SlaveInteractionModeDefOf.Suppress;
pawn.guest.slaveInteractionMode = decoy;
}
/// <summary>
/// A non-hostile humanlike faction to enslave from. Prefers one vanilla rarely picks for a
/// freed escapee (below Medieval: weight 0.1 in TryGetRandomNonColonyHumanlikeFaction), so a
/// finder different from the origin comes up more often.
/// </summary>
private static Faction OriginFaction() =>
Find.FactionManager.AllFactionsVisible
.Where(f => !f.IsPlayer && !f.defeated && !f.temporary && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer))
.OrderBy(f => f.def.techLevel >= TechLevel.Medieval ? 1 : 0)
.ThenBy(f => f.loadID)
.FirstOrDefault();
/// <summary>
/// Enslaves a pawn from a non-hostile faction, prepares it and lets it escape like vanilla,
/// under Rand seed + attempt. Retries while vanilla hands the escapee a hostile faction, or,
/// with distinctFinder, the origin faction itself.
/// </summary>
private static Escapee EscapeUntilNonHostileFinder(int seed, Action<Pawn> prepare, bool playerBrand, bool distinctFinder = false)
{
Faction origin = OriginFaction();
if (origin == null)
T.Skip("no visible non-hostile humanlike faction to enslave a pawn from");
var hostile = new List<string>();
for (int attempt = 0; attempt < MaxEscapeAttempts; attempt++)
{
Pawn slave;
int tick;
Snapshot since;
Rand.PushState(seed + attempt);
try
{
slave = Fixtures.ColonySlave(origin);
escapees.Add(slave);
T.Check(slave.IsSlaveOfColony, $"fixture pawn {slave} is not a slave of the colony");
T.Equal(origin, slave.SlaveFaction, "SlaveFaction of the fixture slave");
prepare?.Invoke(slave);
tick = Find.TickManager.TicksGame;
since = new Snapshot();
EscapeLikeVanilla(slave);
}
finally
{
Rand.PopState();
}
T.Check(!slave.Spawned && slave.IsWorldPawn(),
$"after ExitMap {slave} should be a world pawn: spawned={slave.Spawned}, world pawn={slave.IsWorldPawn()}, caravan={slave.IsCaravanMember()}");
T.Check(!slave.IsSlave && slave.Faction != Faction.OfPlayer,
$"vanilla should have freed {slave} on passing to the world: faction={slave.Faction.ToStringSafe()}, slave={slave.IsSlave}");
Faction got = slave.Faction;
if (got == null)
T.Skip($"vanilla left escapee {slave} without a faction (no humanlike faction to hand them to)");
if (distinctFinder && got == origin && !got.HostileTo(Faction.OfPlayer))
{
// Back with its origin: useless for the restore checks. Drop it from the mod now.
ForgetOne(slave);
hostile.Add(got.Name + " (the origin)");
continue;
}
if (!got.HostileTo(Faction.OfPlayer))
{
T.Check(Find.WorldPawns.GetSituation(slave) == WorldPawnSituation.Free,
$"escapee {slave} has world situation {Find.WorldPawns.GetSituation(slave)}, expected Free");
if (attempt > 0)
T.Info($"escape attempt {attempt + 1}: {slave} went to non-hostile {got}");
return new Escapee { pawn = slave, origin = origin, escapeTick = tick, since = since };
}
// A hostile faction keeps them: never pinned; the player's brand still gets a letter.
T.Check(!GameComponent_BlaxRunaways.IsPending(slave), $"{slave} ran to hostile {got} but was registered as pending");
T.Check(!Find.WorldPawns.ForcefullyKeptPawns.Contains(slave), $"{slave} ran to hostile {got} but was pinned as a world pawn");
bool kept = FindLetter(since, KeptLabelKey, slave) != null;
if (playerBrand)
T.Check(kept, $"{slave} with the player's brand ran to hostile {got}, expected a 'Runaway kept' letter");
else
T.Check(!kept, $"'Runaway kept' letter for {slave}, who did not carry the player's brand");
hostile.Add(got.Name);
}
T.Skip($"vanilla gave all {MaxEscapeAttempts} escapees an unusable faction (hostile{(distinctFinder ? " or the origin " + origin : "")}: {string.Join(", ", hostile)}), so this path can't be reached");
return null;
}
/// <summary>
/// The end of a slave rebellion: the slave is in a LordJob_SlaveRebellion lord (as
/// SlaveRebellionUtility.StartSlaveRebellion makes it, but for this slave only) and reaches the
/// edge, where JobDriver_Goto calls ExitMap(allowedToJoinOrCreateCaravan: true, closest edge).
/// </summary>
private static void EscapeLikeVanilla(Pawn slave)
{
Map map = slave.Map;
IntVec3 exit = new IntVec3(0, 0, slave.Position.z);
LordMaker.MakeNewLord(slave.Faction, new LordJob_SlaveRebellion(slave.Position, exit, -1, passive: true), map, new List<Pawn> { slave });
T.Check(SlaveRebellionUtility.IsRebelling(slave), $"{slave} is not rebelling after joining a LordJob_SlaveRebellion lord");
slave.ExitMap(allowedToJoinOrCreateCaravan: true, CellRect.WholeMap(map).GetClosestEdge(slave.Position));
}
private static void RequireExitMapPatch()
{
MethodInfo exitMap = AccessTools.Method(typeof(Pawn), nameof(Pawn.ExitMap));
HarmonyLib.Patches info = exitMap == null ? null : Harmony.GetPatchInfo(exitMap);
bool ok = info != null
&& info.Prefixes.Any(p => p.owner == "blax.slaves")
&& info.Postfixes.Any(p => p.owner == "blax.slaves");
T.Check(ok, "Pawn.ExitMap has no blax.slaves prefix and postfix: Patch_RunawayExitMap did not apply");
}
/// <summary>
/// Drops this test's escapees from the runaway component (record, pending set, our pin), so
/// nothing stale reaches later tests or the save. Never throws: it runs in finally blocks.
/// </summary>
private static void ForgetEscapees(Pawn keep = null)
{
foreach (Pawn p in escapees)
{
if (p == null || p == keep)
continue;
try
{
ForgetOne(p);
// A failed test can leave a delivered pawn inside a falling drop pod, which
// Fixtures.Cleanup does not see (neither spawned nor a world pawn).
if (!p.Destroyed && !p.Spawned && !p.IsWorldPawn() && p.SpawnedOrAnyParentSpawned)
p.Destroy(DestroyMode.Vanish);
}
catch (Exception ex)
{
T.Info("forgetting escapee " + p.ToStringSafe() + " threw: " + ex.Message);
}
}
escapees.Clear();
}
/// <summary>Removes one pawn's record, pending entry and our pin from the runaway component.</summary>
private static void ForgetOne(Pawn p)
{
GameComponent_BlaxRunaways comp = GameComponent_BlaxRunaways.Instance;
var records = comp == null ? null : AccessTools.Field(typeof(GameComponent_BlaxRunaways), "records")?.GetValue(comp) as List<RunawayRecord>;
var pending = AccessTools.Field(typeof(GameComponent_BlaxRunaways), "pending")?.GetValue(null) as HashSet<Pawn>;
bool pinnedByUs = false;
if (records != null)
{
foreach (RunawayRecord r in records.Where(r => r != null && r.pawn == p).ToList())
{
pinnedByUs |= r.pinnedByUs;
records.Remove(r);
}
}
pending?.Remove(p);
if (pinnedByUs && Find.WorldPawns.Contains(p))
Find.WorldPawns.ForcefullyKeptPawns.Remove(p);
}
// ---- delivery -----------------------------------------------------------------------
/// <summary>Makes the record due now, ticks past the 250-tick check, then until the pawn is on the map.</summary>
private static void DeliverNow(Pawn pawn, RunawayRecord record, Map map)
{
record.dueTick = Find.TickManager.TicksGame;
int waited = 0;
while (GameComponent_BlaxRunaways.IsPending(pawn) && waited < CheckInterval + 10)
{
Fixtures.Tick(1);
waited++;
}
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn),
$"{pawn} still pending {waited} ticks after its record fell due (dueTick now {record.dueTick}; it moves on Retry), world pawn={pawn.IsWorldPawn()}, situation={Find.WorldPawns.GetSituation(pawn)}");
T.Check(!pawn.IsWorldPawn(),
$"{pawn} left the pending set but is still a world pawn: delivery was cancelled (faction {pawn.Faction.ToStringSafe()}, situation {Find.WorldPawns.GetSituation(pawn)})");
int landing = 0;
while (!(pawn.Spawned && pawn.Map == map) && landing < MaxLandingTicks)
{
Fixtures.Tick(10);
landing += 10;
}
T.Check(pawn.Spawned && pawn.Map == map,
$"{pawn} not on the home map {MaxLandingTicks} ticks after delivery: spawned={pawn.Spawned}, map={pawn.MapHeld.ToStringSafe()}, holder={pawn.ParentHolder.ToStringSafe()}, destroyed={pawn.Destroyed}");
T.Info($"{pawn} delivered after {waited} ticks, on the map {landing} ticks later");
}
private static void AssertReturned(Snapshot since, Pawn pawn, Faction origin, SlaveInteractionModeDef mode, Faction deliverer, Map map)
{
T.Check(pawn.Spawned && pawn.Map == map, $"{pawn} is not spawned on the home map");
T.Check(pawn.IsSlaveOfColony,
$"returned {pawn} is not a slave of the colony: faction={pawn.Faction.ToStringSafe()}, slave={pawn.IsSlave}, prisoner={pawn.IsPrisoner}");
T.Equal(origin, pawn.SlaveFaction, "SlaveFaction after the return (origin restored before re-enslaving)");
T.Equal(origin, pawn.HomeFaction, "HomeFaction after the return");
T.Equal(mode, pawn.guest.slaveInteractionMode, "slave interaction mode after the return");
T.Check(BrandUtility.IsBrandedByPlayer(pawn),
$"returned {pawn} lost the player's brand (branded={BrandUtility.IsBranded(pawn)}, owner={BrandUtility.BrandOf(pawn)?.owner.ToStringSafe()})");
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn), $"returned {pawn} is still pending");
T.Check(RecordOf(pawn) == null, $"returned {pawn} still has a runaway record");
T.Check(!Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn), $"returned {pawn} is still pinned in ForcefullyKeptPawns");
Letter letter = FindLetter(since, ReturnedLabelKey, pawn);
if (letter == null)
{
string fresh = string.Join(" | ", Find.LetterStack.LettersListForReading.Where(l => !since.letters.Contains(l)).Select(l => l.Label.RawText));
T.Fail($"no 'Runaway returned' letter for {pawn} in Find.LetterStack; letters since the escape: [{fresh}]");
}
T.Equal(LetterDefOf.PositiveEvent, letter.def, "returned letter def");
T.Equal(deliverer, letter.relatedFaction, "returned letter faction (the finder who brought them back)");
T.Check(letter.lookTargets != null && letter.lookTargets.targets.Any(t => t.Thing == pawn), "returned letter does not point at " + pawn);
}
// ---- negative checks ----------------------------------------------------------------
private static void AssertNotRegistered(Pawn pawn, string why)
{
T.Check(!GameComponent_BlaxRunaways.IsPending(pawn), $"escapee {pawn} {why} is pending (registered), expected not");
T.Check(RecordOf(pawn) == null, $"escapee {pawn} {why} has a runaway record, expected none");
T.Check(!Find.WorldPawns.ForcefullyKeptPawns.Contains(pawn), $"escapee {pawn} {why} is pinned in ForcefullyKeptPawns, expected not");
}
private static void AssertNoRunawayMessages(Snapshot since, Pawn pawn, string why)
{
T.Check(!HasMessage(since, SearchMessageKey, pawn, pawn.Faction), $"'may bring them back' message for escapee {pawn} {why}");
T.Check(!HasMessage(since, GoneMessageKey, pawn), $"'nobody will bring them back' message for escapee {pawn} {why}; the mod should ignore this escape");
T.Check(FindLetter(since, KeptLabelKey, pawn) == null && FindLetter(since, ReturnedLabelKey, pawn) == null, $"runaway letter for escapee {pawn} {why}");
}
/// <summary>
/// Runs a patched vanilla check with the pawn pending and, as the control, with it taken out of
/// the pending set. Returns 1 when verified, 0 when vanilla itself rejects the pawn.
/// </summary>
private static int CheckBlockedWhilePending(string what, Pawn pawn, Func<bool> check)
{
bool whilePending = check();
HashSet<Pawn> pending = PendingSet();
bool removed = pending.Remove(pawn);
bool notPending;
try
{
notPending = check();
}
finally
{
if (removed)
pending.Add(pawn);
}
T.Check(removed, $"{pawn} was not in GameComponent_BlaxRunaways' pending set");
if (!notPending)
{
T.Info($"{what} rejects {pawn} even when it is not pending; this check can't tell the patch from vanilla");
return 0;
}
T.Check(!whilePending, $"{what} accepted pending runaway {pawn}: expected false while pending (it returns true once the pawn is not pending)");
return 1;
}
// ---- lookups ------------------------------------------------------------------------
private static List<RunawayRecord> Records()
{
GameComponent_BlaxRunaways comp = GameComponent_BlaxRunaways.Instance;
T.NotNull(comp, "GameComponent_BlaxRunaways.Instance");
var list = AccessTools.Field(typeof(GameComponent_BlaxRunaways), "records")?.GetValue(comp) as List<RunawayRecord>;
T.NotNull(list, "GameComponent_BlaxRunaways.records");
return list;
}
private static RunawayRecord RecordOf(Pawn pawn) => Records().FirstOrDefault(r => r != null && r.pawn == pawn);
private static HashSet<Pawn> PendingSet()
{
var set = AccessTools.Field(typeof(GameComponent_BlaxRunaways), "pending")?.GetValue(null) as HashSet<Pawn>;
T.NotNull(set, "GameComponent_BlaxRunaways.pending");
return set;
}
private static Faction FactionByLoadId(string loadId) =>
Find.FactionManager.AllFactionsListForReading.FirstOrDefault(f => f.GetUniqueLoadID() == loadId);
/// <summary>A message archived after the snapshot with exactly the text the mod sends for this pawn (and faction).</summary>
private static bool HasMessage(Snapshot since, string key, Pawn pawn, Faction faction = null)
{
string text = faction == null
? (string)key.Translate(pawn.Named("PAWN"))
: (string)key.Translate(pawn.Named("PAWN"), faction.Named("FACTION"));
text = text.CapitalizeFirst();
return Find.Archive.ArchivablesListForReading.OfType<Message>().Any(m => !since.messages.Contains(m) && m.text == text);
}
/// <summary>The newest letter received after the snapshot whose label is the mod's label for this pawn.</summary>
private static Letter FindLetter(Snapshot since, string labelKey, Pawn pawn)
{
string label = labelKey.Translate(pawn.Named("PAWN")).CapitalizeFirst().RawText;
return Find.LetterStack.LettersListForReading.LastOrDefault(l => !since.letters.Contains(l) && l.Label.RawText == label);
}
/// <summary>Phase-2 pawns are not tracked by Fixtures, so remove this one by hand.</summary>
private static void Dispose(Pawn pawn)
{
if (pawn == null)
return;
if (!pawn.Destroyed && !pawn.IsWorldPawn())
pawn.Destroy(DestroyMode.Vanish); // spawned, or still inside a drop pod
if (pawn.IsWorldPawn())
Find.WorldPawns.RemoveAndDiscardPawnViaGC(pawn); // alive, or passed to the world as dead by Pawn.Destroy
}
}
}