using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxZones; using RimWorld; using RimWorld.Planet; using Verse; using Verse.AI; namespace BlaxZonesTests { /// /// Shared helpers for tests. Pawns, things and zones made here are removed after each test unless /// passed to Keep() or KeepZone(). Mod settings are restored after each test, so tests may change /// them freely. Terrain, roof and fog changes stay: every TestArea is used once and never handed out /// again in the same run. /// public static class Fixtures { private static readonly List made = new List(); private static readonly HashSet kept = new HashSet(); private static readonly List madeThings = new List(); private static readonly HashSet keptThings = new HashSet(); private static readonly List madeZones = new List(); private static readonly HashSet keptZones = new HashSet(); private static readonly List cleanups = new List(); private static readonly List usedAreas = new List(); /// Cells TestArea clears around the rect it returns, so rings and walls around a zone fit. public const int AreaMargin = 3; public static Map Map => Find.CurrentMap; public static BlaxZonesSettings Settings => BlaxZonesMod.Settings; public static MapComponent_BlaxZones Comp => MapComponent_BlaxZones.Of(Map); // ---- 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 pawn, not spawned. Relations off so no accidental family ties. public static Pawn Generate(PawnKindDef kind, Faction faction, DevelopmentalStage stage = DevelopmentalStage.Adult) { var req = new PawnGenerationRequest(kind, faction, PawnGenerationContext.NonPlayer, forceGenerateNewPawn: true, allowDowned: stage.Baby(), canGeneratePawnRelations: false, colonistRelationChanceFactor: 0f, developmentalStages: stage); Pawn p = PawnGenerator.GeneratePawn(req); made.Add(p); return p; } /// Spawns the pawn at the cell, or near the map center when none is given. public static Pawn Spawn(Pawn p, IntVec3? at = null) { IntVec3 cell = at ?? CellFinder.RandomClosewalkCellNear(Map.Center, Map, 12); GenSpawn.Spawn(p, cell, Map); return p; } /// A spawned free adult colonist. public static Pawn Colonist() => Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer)); /// A spawned slave of the colony. Skips the test without Ideology. public static Pawn ColonySlave(Faction origin = null) { T.NeedsDlc("Ideology", ModsConfig.IdeologyActive); Pawn p = Generate(PawnKindDefOf.Slave, origin ?? FriendlyFaction()); Spawn(p); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave); T.Check(p.IsSlaveOfColony, "slave fixture is not a slave of the colony"); return p; } /// A spawned prisoner of the colony, from a hostile faction when there is one. public static Pawn Prisoner() { Faction from = HostileFaction() ?? FriendlyFaction(); Pawn p = Spawn(Generate(PawnKindDefOf.Slave, from)); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); return p; } /// A spawned baby of the colony. Skips the test without Biotech. public static Pawn Baby() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Baby)); T.Check(p.DevelopmentalStage.Baby(), "baby fixture is " + p.DevelopmentalStage + ", not a baby"); return p; } /// /// An animal of the race (ThingDefOf.Chicken, ThingDefOf.Muffalo, body size 2.4), tamed into the /// colony or wild, spawned at the cell or near the map center. /// public static Pawn Animal(ThingDef race, bool tamed, IntVec3? at = null) { T.NotNull(race, "animal race"); PawnKindDef kind = DefDatabase.AllDefsListForReading.FirstOrDefault(k => k.race == race); T.NotNull(kind, "pawn kind for " + race.defName); return Spawn(Generate(kind, tamed ? Faction.OfPlayer : null), at); } /// 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; } // ---- map areas ------------------------------------------------------------------- /// /// A w x h rect on the current map, carved for terrain tests: the rect plus AreaMargin cells /// around it are cleared of things, set to soil, unroofed and unfogged. It keeps away from map /// edges, colonists, trade beacons, zones, rock and earlier areas, and a free colonist can walk /// into it. Quick-test maps vary per run, so tests must not depend on where it lies. Never /// handed out twice in one run. /// public static CellRect TestArea(int w, int h) { Map map = Map; Rand.PushState(7919 + usedAreas.Count); try { IntVec3 center = map.Center; var origins = new List(); for (int x = 10; x + w + 2 * AreaMargin < map.Size.x - 10; x += 6) for (int z = 10; z + h + 2 * AreaMargin < map.Size.z - 10; z += 6) origins.Add(new IntVec3(x + AreaMargin, 0, z + AreaMargin)); foreach (IntVec3 o in origins.OrderBy(o => Math.Abs((o.x + w / 2) - center.x) + Math.Abs((o.z + h / 2) - center.z)).ThenBy(o => o.x).ThenBy(o => o.z)) { var rect = new CellRect(o.x, o.z, w, h); if (!Usable(map, rect)) continue; Carve(map, rect.ExpandedBy(AreaMargin)); usedAreas.Add(rect); return rect; } } finally { Rand.PopState(); } T.Fail("TestArea: no free " + w + "x" + h + " area on this map"); return default; } private static bool Usable(Map map, CellRect rect) { CellRect carved = rect.ExpandedBy(AreaMargin); CellRect keepOut = carved.ExpandedBy(3); if (!keepOut.InBounds(map)) return false; foreach (CellRect used in usedAreas) { if (used.ExpandedBy(AreaMargin + 2).Overlaps(keepOut)) return false; } foreach (Pawn p in map.mapPawns.AllPawnsSpawned) { if (keepOut.Contains(p.Position)) return false; } foreach (Building_OrbitalTradeBeacon b in map.listerBuildings.AllBuildingsColonistOfClass()) { if (b.Position.InHorDistOf(carved.CenterCell, 12f + Math.Max(carved.Width, carved.Height) / 2f)) return false; } foreach (IntVec3 c in keepOut) { if (map.zoneManager.ZoneAt(c) != null) return false; Building ed = c.GetEdifice(map); if (ed != null && (ed.def.building?.isNaturalRock ?? false)) return false; RoofDef roof = c.GetRoof(map); if (roof != null && roof.isThickRoof) return false; if (ed != null && ed.Faction == Faction.OfPlayer) return false; } // Carve can't remove a steam geyser or any other non-destroyable thing (Thing.cs:1045-1048 logs an error). foreach (IntVec3 c in carved) { foreach (Thing t in c.GetThingList(map)) { if (!t.def.destroyable) return false; } } // A free colonist must reach a standable cell on the ring just outside the carved area. List colonists = map.mapPawns.FreeColonistsSpawned.ToList(); if (colonists.Count == 0) return true; Pawn walker = colonists[0]; foreach (IntVec3 c in carved.ExpandedBy(1).EdgeCells) { if (c.Standable(map) && map.reachability.CanReach(walker.Position, c, PathEndMode.OnCell, TraverseParms.For(TraverseMode.PassDoors))) return true; } return false; } private static void Carve(Map map, CellRect area) { foreach (IntVec3 c in area) { foreach (Thing t in c.GetThingList(map).ToList()) { if (t is Pawn || t.Destroyed) continue; t.Destroy(DestroyMode.Vanish); } map.terrainGrid.SetTerrain(c, TerrainDefOf.Soil); map.roofGrid.SetRoof(c, null); map.snowGrid.SetDepth(c, 0f); map.fogGrid.Unfog(c); } } /// Constructed roof over every cell of the rect. public static void Roof(CellRect rect) { foreach (IntVec3 c in rect) Map.roofGrid.SetRoof(c, RoofDefOf.RoofConstructed); } /// A player wall on the cell (removes zone cells under it, as vanilla does). public static Thing Wall(IntVec3 cell) => SpawnBuilding(ThingDefOf.Wall, cell); /// Shallow water on the cell: walkable, but drop pods refuse water. public static void Water(IntVec3 cell) => Map.terrainGrid.SetTerrain(cell, TerrainDefOf.WaterShallow); /// /// An enclosed animal pen around the rect: fences on the edge of rect.ExpandedBy(2) and a pen /// marker inside the ring at rect.ExpandedBy(1)'s corner, outside the rect itself. Returns the marker. /// public static Thing FenceRing(CellRect rect) { ThingDef fence = DefDatabase.GetNamed("Fence"); ThingDef marker = DefDatabase.GetNamed("PenMarker"); foreach (IntVec3 c in rect.ExpandedBy(2).EdgeCells) SpawnBuilding(fence, c); CellRect inner = rect.ExpandedBy(1); return SpawnBuilding(marker, new IntVec3(inner.minX, 0, inner.minZ)); } /// A player orbital trade beacon on the cell with power on (no power net needed while paused). public static Building_OrbitalTradeBeacon PoweredBeacon(IntVec3 cell) { var b = (Building_OrbitalTradeBeacon)SpawnBuilding(ThingDefOf.OrbitalTradeBeacon, cell); CompPowerTrader power = b.GetComp(); if (power != null) power.PowerOn = true; T.Check(Building_OrbitalTradeBeacon.AllPowered(Map).Contains(b), "beacon fixture is not powered"); return b; } /// A default stockpile over the rect. public static Zone_Stockpile Stockpile(CellRect rect) { var zone = new Zone_Stockpile(StorageSettingsPreset.DefaultStockpile, Map.zoneManager); Map.zoneManager.RegisterZone(zone); madeZones.Add(zone); foreach (IntVec3 c in rect) zone.AddCell(c); return zone; } /// /// A delivery zone over the rect, registered and filled the way the designator does it. A null /// filter keeps the default (all items). /// public static Zone_Delivery DeliveryZone(CellRect rect, ThingFilter filter = null, StoragePriority priority = StoragePriority.Normal, bool orbital = true, bool camp = false) { var zone = new Zone_Delivery(Map.zoneManager); Map.zoneManager.RegisterZone(zone); madeZones.Add(zone); foreach (IntVec3 c in rect) zone.AddCell(c); if (filter != null) zone.filter.CopyAllowancesFrom(filter); zone.priority = priority; zone.acceptOrbital = orbital; zone.campHere = camp; return zone; } /// A filter that allows only the given defs. public static ThingFilter FilterOf(params ThingDef[] defs) { var f = new ThingFilter(); f.SetDisallowAll(); foreach (ThingDef d in defs) f.SetAllow(d, true); return f; } /// A stack of the def, not spawned, removed after the test unless kept. public static Thing Stack(ThingDef def, int count) { Thing t = ThingMaker.MakeThing(def, def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null); t.stackCount = Math.Min(count, def.stackLimit); return Track(t); } public static Zone FindZoneById(int id) { foreach (Map m in Find.Maps) foreach (Zone z in m.zoneManager.AllZones) if (z.ID == id) return z; return null; } private static Thing SpawnBuilding(ThingDef def, IntVec3 cell) { Thing t = ThingMaker.MakeThing(def, def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null); t.SetFactionDirect(Faction.OfPlayer); GenSpawn.Spawn(t, cell, Map, WipeMode.Vanish); return Track(t); } // ---- tracking -------------------------------------------------------------------- /// Destroy this thing after the test unless kept. public static TT Track(TT thing) where TT : Thing { madeThings.Add(thing); return thing; } /// Delete this zone after the test unless kept. public static TZ TrackZone(TZ zone) where TZ : Zone { madeZones.Add(zone); return zone; } public static TT Keep(TT thing) where TT : Thing { keptThings.Add(thing); return thing; } public static TZ KeepZone(TZ zone) where TZ : Zone { keptZones.Add(zone); return zone; } /// Runs after the test, before things and zones are removed (undo a test-only patch, for example). public static void OnCleanup(Action action) => cleanups.Add(action); // ---- 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(); } // ---- 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(BlaxZonesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance)) d[f] = f.GetValue(Settings); return d; } public static void RestoreSettings(Dictionary snapshot) { if (Settings != null) foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value); } public static void Cleanup() { List actions = cleanups.ToList(); cleanups.Clear(); foreach (Action a in actions) { try { a(); } catch (Exception e) { TestRunner.Note("cleanup action threw: " + e.Message); } } Find.Selector?.ClearSelection(); foreach (Zone z in madeZones) { if (z == null || keptZones.Contains(z) || z.zoneManager == null || !z.zoneManager.AllZones.Contains(z)) continue; z.Delete(playSound: false); } madeZones.Clear(); foreach (Thing t in madeThings) { if (t == null || keptThings.Contains(t) || t.Destroyed) continue; if (t.Spawned || t.holdingOwner != null) t.Destroy(DestroyMode.Vanish); } madeThings.Clear(); foreach (Pawn p in made) { if (p == null || kept.Contains(p)) continue; DropRitualObligations(p); 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(); } /// /// A fixture colonist that died gets a funeral obligation, and a living one can get a scarification or /// blinding obligation when it joins or changes status (Ideology). The cleanup destroys the pawn or its /// corpse, so drop those obligations too, or the save warns about a reference to a discarded pawn. /// private static void DropRitualObligations(Pawn p) { if (!ModsConfig.IdeologyActive || Find.IdeoManager == null) return; Corpse corpse = p.Corpse; bool Hits(TargetInfo t) => t.HasThing && (t.Thing == p || (corpse != null && t.Thing == corpse)); foreach (Ideo ideo in Find.IdeoManager.IdeosListForReading) { foreach (Precept precept in ideo.PreceptsListForReading) { if (!(precept is Precept_Ritual ritual) || ritual.activeObligations == null) continue; foreach (RitualObligation o in ritual.activeObligations.ToList()) { if (o != null && (Hits(o.targetA) || Hits(o.targetB) || Hits(o.targetC))) ritual.RemoveObligation(o); } } } } } }