using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxSlaves; using RimWorld; using RimWorld.Planet; using Verse; namespace BlaxSlavesTests { /// /// Shared helpers for tests. Pawns made here are destroyed after each test unless passed to /// Keep(). Mod settings are restored after each test, so tests may change them freely. /// public static class Fixtures { private static readonly List made = new List(); private static readonly HashSet kept = new HashSet(); public static Map Map => Find.CurrentMap; public static BlaxSlavesSettings Settings => BlaxSlavesMod.Settings; // ---- factions -------------------------------------------------------------------- /// A visible, non-player, humanlike faction that is not hostile to the player. public static Faction FriendlyFaction() => Find.FactionManager.AllFactionsVisible .Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer)) .OrderBy(f => f.loadID).FirstOrDefault(); /// A visible, non-player, humanlike faction hostile to the player. public static Faction HostileFaction() => Find.FactionManager.AllFactionsVisible .Where(f => !f.IsPlayer && !f.defeated && f.def.humanlikeFaction && f.HostileTo(Faction.OfPlayer)) .OrderBy(f => f.loadID).FirstOrDefault(); // ---- pawns ----------------------------------------------------------------------- /// A fresh adult pawn, not spawned. Relations off so no accidental family ties. public static Pawn Generate(PawnKindDef kind, Faction faction) { var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer, forceGenerateNewPawn: true, canGeneratePawnRelations: false, colonistRelationChanceFactor: 0f, developmentalStages: DevelopmentalStage.Adult); Pawn p = PawnGenerator.GeneratePawn(req); made.Add(p); return p; } /// /// Spawns the pawn on a random open cell near the map's anchor. Vanilla's RandomClosewalkCellNear /// falls back to its root when it finds nothing, so on a map whose center lies in rock the pawn /// would stand inside the rock with no district: vanilla AI then throws (a prisoner's escape check /// reads the district) and the mood gate scenes find no room around the victim. /// public static Pawn Spawn(Pawn p) { Map map = Map; IntVec3 root = Anchor(map); if (!CellFinder.TryRandomClosewalkCellNear(root, map, 12, out IntVec3 cell, c => IsOpen(c, map))) cell = root; GenSpawn.Spawn(p, cell, map); return p; } private static Map anchorMap; private static IntVec3 anchor = IntVec3.Invalid; /// Standable, not fogged and inside a district: a cell vanilla AI and the scenes can work with. public static bool IsOpen(IntVec3 c, Map map) => c.InBounds(map) && c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) != null; /// The map center when it is open, else the open cell closest to it. Skips the test when the map has none. private static IntVec3 Anchor(Map map) { IntVec3 center = map.Center; if (IsOpen(center, map)) return center; if (map == anchorMap && anchor.IsValid && IsOpen(anchor, map)) return anchor; IntVec3 best = IntVec3.Invalid; int bestDist = int.MaxValue; foreach (IntVec3 c in map.AllCells) { int dist = (c - center).LengthHorizontalSquared; if (dist < bestDist && IsOpen(c, map)) { best = c; bestDist = dist; } } if (!best.IsValid) T.Skip("setup: no standable, unfogged cell on the map to spawn test pawns on"); T.Info("map center " + center + " is not open (rock, fog or no district), test pawns spawn near " + best); anchorMap = map; anchor = best; return best; } /// A spawned free colonist. pacifist = has the Kind trait; otherwise Kind is removed. public static Pawn Colonist(bool pacifist = false) { Pawn p = Generate(PawnKindDefOf.Colonist, Faction.OfPlayer); Trait kind = p.story.traits.GetTrait(TraitDefOf.Kind); if (pacifist && kind == null) p.story.traits.GainTrait(new Trait(TraitDefOf.Kind)); if (!pacifist && kind != null) p.story.traits.RemoveTrait(kind); return Spawn(p); } /// A spawned slave of the colony, enslaved from origin (default: a friendly faction). Skips the test without Ideology. public static Pawn ColonySlave(Faction origin = null) { RequireIdeology(); Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction()); Spawn(p); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); return p; } /// A spawned prisoner of the colony, from a hostile faction when there is one. public static Pawn ColonyPrisoner(Faction from = null) { Pawn p = Spawn(Generate(PawnKindDefOf.Slave, from ?? HostileFaction() ?? FriendlyFaction())); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); return p; } /// /// A spawned colony slave even without Ideology, as a save made with Ideology and loaded without it /// leaves one: vanilla keeps the slave status, but there is no suppression and no interaction mode. /// With Ideology it is a normal colony slave. /// public static Pawn LeftoverSlave() { if (ModsConfig.IdeologyActive) return ColonySlave(); Pawn p = Spawn(Generate(PawnKindDefOf.Slave, FriendlyFaction())); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); T.Check(p.IsSlaveOfColony, "setup: vanilla refused to make a colony slave without Ideology"); return p; } // ---- DLCs ------------------------------------------------------------------------ /// Skips the test without Ideology: slaves, brands and everything that acts on them need it. public static void RequireIdeology() { if (!ModsConfig.IdeologyActive) T.Skip("needs Ideology"); } /// The active DLCs for the DLCS line of the results file, "none" for core only. public static string ActiveDlcs() { var dlcs = new List(); if (ModsConfig.RoyaltyActive) dlcs.Add("Royalty"); if (ModsConfig.IdeologyActive) dlcs.Add("Ideology"); if (ModsConfig.BiotechActive) dlcs.Add("Biotech"); if (ModsConfig.AnomalyActive) dlcs.Add("Anomaly"); if (ModsConfig.OdysseyActive) dlcs.Add("Odyssey"); return dlcs.Count == 0 ? "none" : string.Join(",", dlcs); } private static readonly FieldInfo IdeologyActiveField = typeof(ModsConfig).GetField("ideologyActive", BindingFlags.NonPublic | BindingFlags.Static); /// /// Runs a DLC-off check. Without Ideology it simply runs. With Ideology loaded, ModsConfig.IdeologyActive /// reads false for the body only, so the same check also guards the mod's own Ideology gates in a /// full run (a real -NoDlc run is still what proves the game loads and plays without it). Keep the body /// to direct calls into Blax Slaves and plain reads: never tick the game or run vanilla systems inside. /// public static void AsIfIdeologyOff(System.Action body) { if (!ModsConfig.IdeologyActive) { body(); return; } if (IdeologyActiveField == null || IdeologyActiveField.FieldType != typeof(bool)) T.Skip("ModsConfig.ideologyActive not found (renamed in this game version?), so Ideology can't be switched off for this check; a -NoDlc run covers it"); IdeologyActiveField.SetValue(null, false); try { T.Check(!ModsConfig.IdeologyActive, "setup: ModsConfig.IdeologyActive still true after switching ideologyActive off"); body(); } finally { IdeologyActiveField.SetValue(null, true); } } /// Errors and warnings the game logs while the body runs (any source), one line each. public static List LoggedProblems(System.Action body) { var found = new List(); UnityEngine.Application.LogCallback handler = (text, stack, type) => { if (type == UnityEngine.LogType.Error || type == UnityEngine.LogType.Exception || type == UnityEngine.LogType.Warning) lock (found) found.Add(type + ": " + text); }; UnityEngine.Application.logMessageReceivedThreaded += handler; try { body(); } finally { UnityEngine.Application.logMessageReceivedThreaded -= handler; } return found; } /// Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks). public static Pawn Keep(Pawn p) { kept.Add(p); return p; } public static Pawn FindPawnById(string thingId) { if (thingId == null) return null; foreach (Map m in Find.Maps) foreach (Pawn p in m.mapPawns.AllPawns) if (p.ThingID == thingId) return p; foreach (Pawn p in Find.WorldPawns.AllPawnsAliveOrDead) if (p.ThingID == thingId) return p; return null; } // ---- time ------------------------------------------------------------------------ public static void Tick(int ticks) { for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick(); } public static void QuietStoryteller() { Find.Storyteller.incidentQueue.Clear(); Find.Storyteller.storytellerComps.Clear(); } // ---- thoughts -------------------------------------------------------------------- /// Snapshot of a pawn's memories with their age, to spot new or renewed ones. public static Dictionary Memories(Pawn p) { var d = new Dictionary(); var list = p.needs?.mood?.thoughts?.memories?.Memories; if (list != null) foreach (Thought_Memory m in list) d[m] = m.age; return d; } /// Memories added or renewed since the snapshot that lower mood or opinion. public static List NewBadMemories(Pawn p, Dictionary before) { var result = new List(); var list = p.needs?.mood?.thoughts?.memories?.Memories; if (list == null) return result; foreach (Thought_Memory m in list) { bool fresh = !before.TryGetValue(m, out int oldAge) || m.age < oldAge; if (!fresh) continue; bool bad = m.MoodOffset() < 0f || (m is ISocialThought s && s.OpinionOffset() < 0f); if (bad) result.Add(m); } return result; } public static string Describe(IEnumerable memories) => string.Join(", ", memories.Select(m => m.def.defName + (m.otherPawn != null ? "(" + m.otherPawn.LabelShort + ")" : ""))); // ---- settings and cleanup (used by the runner) ----------------------------------- public static Dictionary SnapshotSettings() { var d = new Dictionary(); if (Settings == null) return d; foreach (FieldInfo f in typeof(BlaxSlavesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance)) d[f] = f.GetValue(Settings); return d; } public static void RestoreSettings(Dictionary snapshot) { if (Settings == null) return; foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value); } public static void Cleanup() { foreach (Pawn p in made) { if (p == null || kept.Contains(p)) continue; if (p.Corpse != null && p.Corpse.Spawned) p.Corpse.Destroy(DestroyMode.Vanish); else if (p.Spawned) p.Destroy(DestroyMode.Vanish); else if (p.IsWorldPawn()) Find.WorldPawns.RemoveAndDiscardPawnViaGC(p); } made.Clear(); } } }