373 lines
17 KiB
C#
373 lines
17 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using BlaxLaws;
|
|
using RimWorld;
|
|
using RimWorld.Planet;
|
|
using Verse;
|
|
using Verse.AI;
|
|
|
|
namespace BlaxLawsTests
|
|
{
|
|
/// <summary>
|
|
/// Shared helpers for tests. Pawns and things made here are removed after each test unless passed to
|
|
/// Keep(). Mod settings are restored after each test, and lawbook rows a test added are deleted unless
|
|
/// passed to KeepLaw(), so tests may change both freely.
|
|
/// </summary>
|
|
public static partial 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 HashSet<int> keptLaws = new HashSet<int>();
|
|
private static readonly List<Action> cleanups = new List<Action>();
|
|
|
|
public static Map Map => Find.CurrentMap;
|
|
|
|
public static BlaxLawsSettings Settings => BlaxLawsMod.Settings;
|
|
|
|
public static GameComponent_BlaxLaws Comp => GameComponent_BlaxLaws.Instance;
|
|
|
|
// ---- 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>
|
|
/// A standable, unfogged cell near the map center that belongs to a district, so pawns spawned there
|
|
/// path, find beds and count as in a room like any colonist. The district reaches the map edge: never
|
|
/// the inside of a room a fixture built, such as a prison cell, where no other pawn fits beside it.
|
|
/// </summary>
|
|
public static IntVec3 PawnCell()
|
|
{
|
|
Map map = Map;
|
|
if (CellFinder.TryFindRandomCellNear(map.Center, map, 20,
|
|
c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) is District d && d.TouchesMapEdge && c.GetFirstPawn(map) == null, out IntVec3 cell))
|
|
return cell;
|
|
if (CellFinder.TryFindRandomCellNear(map.Center, map, 60, c => c.Standable(map) && c.GetDistrict(map) != null, out cell))
|
|
return cell;
|
|
T.Fail("no standable cell with a district near the map center");
|
|
return IntVec3.Invalid;
|
|
}
|
|
|
|
/// <summary>Spawns the pawn at the cell, or on PawnCell() when none is given.</summary>
|
|
public static Pawn Spawn(Pawn p, IntVec3? at = null)
|
|
{
|
|
IntVec3 cell = at ?? PawnCell();
|
|
T.Check(cell.GetDistrict(Map) != null, "spawn cell " + cell + " has no district");
|
|
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 child of the colony. Skips the test without Biotech.</summary>
|
|
public static Pawn Child()
|
|
{
|
|
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
|
|
Pawn p = Spawn(Generate(PawnKindDefOf.Colonist, Faction.OfPlayer, DevelopmentalStage.Child));
|
|
T.Check(p.DevelopmentalStage.Child(), "child fixture is " + p.DevelopmentalStage + ", not a child");
|
|
return p;
|
|
}
|
|
|
|
/// <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;
|
|
}
|
|
|
|
// ---- things ----------------------------------------------------------------------
|
|
|
|
/// <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;
|
|
}
|
|
|
|
public static TT Keep<TT>(TT thing) where TT : Thing
|
|
{
|
|
keptThings.Add(thing);
|
|
return thing;
|
|
}
|
|
|
|
/// <summary>A thing a test made or kept, so a fixture never clears it away.</summary>
|
|
public static bool IsFixtureThing(Thing t) => madeThings.Contains(t) || keptThings.Contains(t);
|
|
|
|
/// <summary>
|
|
/// Ground a fixture building may go on once cleared, as a player clears a building site: walkable terrain
|
|
/// that is not water, unfogged, in the district, with no building and no pawn, and nothing on it but plants,
|
|
/// filth and items no test made. A wild map (a dense jungle) has few cells free of trees and starting items.
|
|
/// </summary>
|
|
public static bool Buildable(IntVec3 c, Map map, District district)
|
|
{
|
|
if (!c.InBounds(map) || c.Fogged(map) || c.GetDistrict(map) != district)
|
|
return false;
|
|
TerrainDef terrain = c.GetTerrain(map);
|
|
if (terrain.IsWater || terrain.passability != Traversability.Standable)
|
|
return false;
|
|
List<Thing> things = c.GetThingList(map);
|
|
for (int i = 0; i < things.Count; i++)
|
|
{
|
|
Thing t = things[i];
|
|
if (t is Plant || t.def.category == ThingCategory.Filth || t.def.category == ThingCategory.Mote)
|
|
continue;
|
|
if (t.def.category == ThingCategory.Item && !IsFixtureThing(t))
|
|
continue;
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/// <summary>Removes the plants and items on the cells, so a building fits (see Buildable).</summary>
|
|
public static void ClearGround(IEnumerable<IntVec3> cells, Map map)
|
|
{
|
|
foreach (IntVec3 c in cells)
|
|
{
|
|
if (!c.InBounds(map))
|
|
continue;
|
|
foreach (Thing t in c.GetThingList(map).ToList())
|
|
{
|
|
if ((t is Plant || t.def.category == ThingCategory.Item) && !IsFixtureThing(t) && !t.Destroyed)
|
|
t.Destroy(DestroyMode.Vanish);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- lawbook ---------------------------------------------------------------------
|
|
|
|
/// <summary>
|
|
/// Adds a row through Lawbook.TryAdd and returns it; fails the test when a row with the key exists.
|
|
/// Deleted after the test unless passed to KeepLaw.
|
|
/// </summary>
|
|
public static Law LawRow(string actKey, string option, LawStage stage, LawSeverity severity, string punishment, int days,
|
|
string savedMod = null, string savedPackageId = null)
|
|
{
|
|
var law = new Law
|
|
{
|
|
actKey = actKey,
|
|
option = option,
|
|
stage = stage,
|
|
severity = severity,
|
|
punishment = punishment,
|
|
days = days,
|
|
enabled = true,
|
|
savedLabel = ActKey.NameOf(actKey),
|
|
savedMod = savedMod,
|
|
savedPackageId = savedPackageId,
|
|
};
|
|
T.Check(Lawbook.TryAdd(law, out Law existing), "LawRow " + actKey + ": refused, existing " + existing);
|
|
return law;
|
|
}
|
|
|
|
public static Law KeepLaw(Law law)
|
|
{
|
|
keptLaws.Add(law.id);
|
|
return law;
|
|
}
|
|
|
|
/// <summary>The ids of the rows before a test (used by the runner).</summary>
|
|
public static HashSet<int> SnapshotLawbook() => new HashSet<int>(Lawbook.Laws.Select(l => l.id));
|
|
|
|
/// <summary>Deletes every row a test added that it didn't keep (used by the runner).</summary>
|
|
public static void RestoreLawbook(HashSet<int> before)
|
|
{
|
|
foreach (Law l in Lawbook.Laws.ToList())
|
|
{
|
|
if (!before.Contains(l.id) && !keptLaws.Contains(l.id))
|
|
Lawbook.Delete(l);
|
|
}
|
|
}
|
|
|
|
/// <summary>Runs after the test, before things 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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// No incidents, and no mental break a test didn't start: the quick test's own colonists sleep on the
|
|
/// ground, eat what they find and hear of every fixture colonist that dies, so over the suite's
|
|
/// simulated days their mood sinks and they would break (MentalBreaker checks
|
|
/// DebugSettings.enableRandomMentalStates first). Tests start breaks with forced: true, which ignores it.
|
|
/// </summary>
|
|
public static void QuietStoryteller()
|
|
{
|
|
Find.Storyteller.incidentQueue.Clear();
|
|
Find.Storyteller.storytellerComps.Clear();
|
|
DebugSettings.enableRandomMentalStates = false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Before each phase-1 test: the pawns no test made stay out of the next test's way. The quick test's
|
|
/// colonists are fed and taken out of any break, and an animal in a manhunter state calms down. A
|
|
/// starving or breaking colonist wanders off and can turn an animal manhunter, and a manhunter is an
|
|
/// active threat that keeps every later enforcement waiting for the danger to pass
|
|
/// (Enforcers.DangerBlocks; RimWorld/GenHostility.cs:227). Each such fix is noted in the results.
|
|
/// </summary>
|
|
public static void CalmBystanders()
|
|
{
|
|
Map map = Map;
|
|
if (map == null)
|
|
return;
|
|
foreach (Pawn p in map.mapPawns.AllPawnsSpawned.ToList())
|
|
{
|
|
if (p == null || p.Dead || kept.Contains(p) || made.Contains(p))
|
|
continue;
|
|
if (p.IsFreeColonist)
|
|
{
|
|
if (p.needs?.food != null)
|
|
p.needs.food.CurLevel = p.needs.food.MaxLevel;
|
|
if (p.needs?.joy != null)
|
|
p.needs.joy.CurLevel = 1f;
|
|
}
|
|
if ((p.IsFreeColonist || p.RaceProps.Animal) && p.InMentalState)
|
|
{
|
|
TestRunner.Note("calmed " + p.LabelShort + " out of " + p.MentalStateDef.defName + " before the test");
|
|
p.MentalState.RecoverFromState();
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- 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(BlaxLawsSettings).GetFields(BindingFlags.Public | BindingFlags.Instance))
|
|
d[f] = f.GetValue(Settings);
|
|
return d;
|
|
}
|
|
|
|
public static void RestoreSettings(Dictionary<FieldInfo, object> snapshot)
|
|
{
|
|
if (Settings == null) return;
|
|
foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value);
|
|
BlaxLawsMod.ApplyTabVisibility();
|
|
}
|
|
|
|
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 (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();
|
|
|
|
// Two passes: a pawn another fixture pawn carries (an arrest or capture cut off by the test's end) is
|
|
// held, not spawned, and destroying the carrier drops it onto the map, where it would stay as a
|
|
// prisoner that claims the next test's prisoner bed.
|
|
for (int pass = 0; pass < 2; pass++)
|
|
{
|
|
foreach (Pawn p in made)
|
|
{
|
|
if (p == null || kept.Contains(p) || p.Destroyed) continue;
|
|
if (pass == 0) DropRitualObligations(p);
|
|
if (p.Corpse != null && (p.Corpse.Spawned || p.Corpse.holdingOwner != null)) p.Corpse.Destroy(DestroyMode.Vanish);
|
|
else if (p.Spawned || p.holdingOwner != null) 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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|