474 lines
20 KiB
C#
474 lines
20 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public static class Fixtures
|
|
{
|
|
private static readonly List<Pawn> made = new List<Pawn>();
|
|
private static readonly HashSet<Pawn> kept = new HashSet<Pawn>();
|
|
private static readonly List<Thing> madeThings = new List<Thing>();
|
|
private static readonly HashSet<Thing> keptThings = new HashSet<Thing>();
|
|
private static readonly List<Zone> madeZones = new List<Zone>();
|
|
private static readonly HashSet<Zone> keptZones = new HashSet<Zone>();
|
|
private static readonly List<Action> cleanups = new List<Action>();
|
|
private static readonly List<CellRect> usedAreas = new List<CellRect>();
|
|
|
|
/// <summary>Cells TestArea clears around the rect it returns, so rings and walls around a zone fit.</summary>
|
|
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 --------------------------------------------------------------------
|
|
|
|
/// <summary>A visible, non-player, humanlike faction that is not hostile to the player.</summary>
|
|
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();
|
|
|
|
/// <summary>A visible, non-player, humanlike faction hostile to the player.</summary>
|
|
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 -----------------------------------------------------------------------
|
|
|
|
/// <summary>A fresh pawn, not spawned. Relations off so no accidental family ties.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>Spawns the pawn at the cell, or near the map center when none is given.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>A spawned free adult colonist.</summary>
|
|
public static Pawn Colonist() => Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer));
|
|
|
|
/// <summary>A spawned slave of the colony. Skips the test without Ideology.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>A spawned prisoner of the colony, from a hostile faction when there is one.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>A spawned baby of the colony. Skips the test without Biotech.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public static Pawn Animal(ThingDef race, bool tamed, IntVec3? at = null)
|
|
{
|
|
T.NotNull(race, "animal race");
|
|
PawnKindDef kind = DefDatabase<PawnKindDef>.AllDefsListForReading.FirstOrDefault(k => k.race == race);
|
|
T.NotNull(kind, "pawn kind for " + race.defName);
|
|
return Spawn(Generate(kind, tamed ? Faction.OfPlayer : null), at);
|
|
}
|
|
|
|
/// <summary>Exclude a pawn from the per-test cleanup (phase-1 setup for phase-2 checks).</summary>
|
|
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 -------------------------------------------------------------------
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<IntVec3>();
|
|
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<Building_OrbitalTradeBeacon>())
|
|
{
|
|
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<Pawn> 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);
|
|
}
|
|
}
|
|
|
|
/// <summary>Constructed roof over every cell of the rect.</summary>
|
|
public static void Roof(CellRect rect)
|
|
{
|
|
foreach (IntVec3 c in rect)
|
|
Map.roofGrid.SetRoof(c, RoofDefOf.RoofConstructed);
|
|
}
|
|
|
|
/// <summary>A player wall on the cell (removes zone cells under it, as vanilla does).</summary>
|
|
public static Thing Wall(IntVec3 cell) => SpawnBuilding(ThingDefOf.Wall, cell);
|
|
|
|
/// <summary>Shallow water on the cell: walkable, but drop pods refuse water.</summary>
|
|
public static void Water(IntVec3 cell) => Map.terrainGrid.SetTerrain(cell, TerrainDefOf.WaterShallow);
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public static Thing FenceRing(CellRect rect)
|
|
{
|
|
ThingDef fence = DefDatabase<ThingDef>.GetNamed("Fence");
|
|
ThingDef marker = DefDatabase<ThingDef>.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));
|
|
}
|
|
|
|
/// <summary>A player orbital trade beacon on the cell with power on (no power net needed while paused).</summary>
|
|
public static Building_OrbitalTradeBeacon PoweredBeacon(IntVec3 cell)
|
|
{
|
|
var b = (Building_OrbitalTradeBeacon)SpawnBuilding(ThingDefOf.OrbitalTradeBeacon, cell);
|
|
CompPowerTrader power = b.GetComp<CompPowerTrader>();
|
|
if (power != null)
|
|
power.PowerOn = true;
|
|
T.Check(Building_OrbitalTradeBeacon.AllPowered(Map).Contains(b), "beacon fixture is not powered");
|
|
return b;
|
|
}
|
|
|
|
/// <summary>A default stockpile over the rect.</summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A delivery zone over the rect, registered and filled the way the designator does it. A null
|
|
/// filter keeps the default (all items).
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>A filter that allows only the given defs.</summary>
|
|
public static ThingFilter FilterOf(params ThingDef[] defs)
|
|
{
|
|
var f = new ThingFilter();
|
|
f.SetDisallowAll();
|
|
foreach (ThingDef d in defs)
|
|
f.SetAllow(d, true);
|
|
return f;
|
|
}
|
|
|
|
/// <summary>A stack of the def, not spawned, removed after the test unless kept.</summary>
|
|
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 --------------------------------------------------------------------
|
|
|
|
/// <summary>Destroy this thing after the test unless kept.</summary>
|
|
public static TT Track<TT>(TT thing) where TT : Thing
|
|
{
|
|
madeThings.Add(thing);
|
|
return thing;
|
|
}
|
|
|
|
/// <summary>Delete this zone after the test unless kept.</summary>
|
|
public static TZ TrackZone<TZ>(TZ zone) where TZ : Zone
|
|
{
|
|
madeZones.Add(zone);
|
|
return zone;
|
|
}
|
|
|
|
public static TT Keep<TT>(TT thing) where TT : Thing
|
|
{
|
|
keptThings.Add(thing);
|
|
return thing;
|
|
}
|
|
|
|
public static TZ KeepZone<TZ>(TZ zone) where TZ : Zone
|
|
{
|
|
keptZones.Add(zone);
|
|
return zone;
|
|
}
|
|
|
|
/// <summary>Runs after the test, before things and zones are removed (undo a test-only patch, for example).</summary>
|
|
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<FieldInfo, object> SnapshotSettings()
|
|
{
|
|
var d = new Dictionary<FieldInfo, object>();
|
|
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<FieldInfo, object> snapshot)
|
|
{
|
|
if (Settings != null)
|
|
foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value);
|
|
}
|
|
|
|
public static void Cleanup()
|
|
{
|
|
List<Action> 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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|