using System; using System.Collections.Generic; using System.Linq; using HarmonyLib; using RimWorld; using Verse; using Verse.AI; namespace BlaxDefaults { /// /// One downing or death in progress: the pawn, its group read while it was alive, and every thing the game /// forbade inside the call (allowed before, forbidden after). Never saved. /// public sealed class ForbidScope { public readonly Pawn Pawn; public readonly ForbidGroup Group; /// True for Pawn_HealthTracker.MakeDowned, false for Pawn.Kill. public readonly bool Downing; public readonly List Recorded = new List(); public ForbidScope(Pawn pawn, ForbidGroup group, bool downing) { Pawn = pawn; Group = group; Downing = downing; } } /// /// The forbid rules' hooks. Work package "forbid" (design.md, 1.1 "Gear rules for your colony and for /// enemies", "Stripping forbids what doesn't match", "Corpses outside the home area stay allowed"). /// /// Scopes: prefixes on Pawn.Kill(DamageInfo?, Hediff) and the private Pawn_HealthTracker.MakeDowned(DamageInfo?, /// Hediff) push the pawn and its group onto a [ThreadStatic] stack while the game is playing, no map is being /// made and a rule or corpse switch could act; a finalizer pops it, even on an exception. Recorder: a prefix and /// a postfix on the CompForbiddable.Forbidden setter add a thing that went from allowed to forbidden to the /// innermost scope. So a scope holds exactly what the game forbade in that call. Apply, in the postfixes of /// Kill and MakeDowned: a corpse goes to the corpse switches, any other thing is allowed when its group's rule /// acts, its cell passes "Where" and the filter allows it: at once when the map has no active threat, else /// through ForbidWaitList. A downed colonist's remembered weapon always waits (ForbidWaitList keeps it while /// the colonist still remembers it). Strip: a prefix records what the pawn wears, holds and carries, and the /// postfix forbids each of those now on a map, inside "Where", that the filter refuses; nothing while /// butchering's ingredient step (Toils_Recipe.CalculateIngredients) runs. Never patched: /// ForbidUtility.SetForbidden, which player designators use, and SetForbiddenIfOutsideHomeArea, five lines /// the JIT may inline. /// public static class ForbidHooks { [ThreadStatic] private static List stack; [ThreadStatic] private static int butchering; /// True while a downing or death scope is open on this thread. public static bool ScopeOpen { get { List s = stack; return s != null && s.Count > 0; } } /// True while butchering's ingredient step runs on this thread: stripping stays vanilla then. public static bool Butchering => butchering > 0; /// A scope opens while the game plays, no map is being made, and a rule or corpse switch could act. public static bool ShouldOpen => Current.ProgramState == ProgramState.Playing && MapGenerator.mapBeingGenerated == null && ForbidRules.AnyDropRuleOn; public static ForbidScope Push(Pawn pawn, bool downing) { var scope = new ForbidScope(pawn, ForbidRules.GroupOf(pawn), downing); (stack ??= new List()).Add(scope); return scope; } public static void Pop(ForbidScope scope) { List s = stack; if (s == null || scope == null) return; int i = s.LastIndexOf(scope); if (i >= 0) s.RemoveAt(i); } /// The recorder: a thing the game just forbade inside a scope goes to the innermost one. public static void Record(Thing t) { List s = stack; if (t == null || s == null || s.Count == 0) return; List recorded = s[s.Count - 1].Recorded; if (!recorded.Contains(t)) recorded.Add(t); } internal static void EnterButchering() => butchering++; internal static void LeaveButchering() { if (butchering > 0) butchering--; } /// /// What the postfix of Kill or MakeDowned does with the things its scope recorded. A thing no longer /// spawned or no longer forbidden is skipped; a corpse goes to the corpse switches; any other thing to its /// group's rule. A downed colonist's remembered weapon goes on the wait list with its owner. /// public static void Apply(ForbidScope scope) { if (scope == null || scope.Recorded.Count == 0) return; ForbidRule rule = ForbidRules.For(scope.Group); Thing remembered = scope.Downing && scope.Group == ForbidGroup.Colony ? scope.Pawn?.mindState?.droppedWeapon : null; foreach (Thing thing in scope.Recorded.ToList()) { if (thing == null || thing.Destroyed || !thing.Spawned || !ForbidRules.IsForbiddenFlag(thing)) continue; if (thing is Corpse corpse) { ApplyCorpse(corpse, scope); continue; } if (rule == null || !rule.Active) continue; if (thing == remembered) { ForbidWaitList.Add(thing, rule, null, scope.Pawn); continue; } if (rule.InsideWhere(thing) && rule.Allows(thing)) AllowOrWait(thing, rule, null); } } private static void ApplyCorpse(Corpse corpse, ForbidScope scope) { Map map = corpse.Map; if (map == null || map.areaManager.Home[corpse.Position]) return; Pawn inner = corpse.InnerPawn; CorpseKind kind = inner == scope.Pawn ? ForbidRules.CorpseKindOf(inner, scope.Group) : ForbidRules.CorpseKindOf(inner, ForbidRules.GroupOfDead(inner)); if (ForbidRules.CorpseSwitch(kind)) AllowOrWait(corpse, null, kind); } /// Allows the thing now when its map has no active threat, else puts it on the wait list. private static void AllowOrWait(Thing thing, ForbidRule rule, CorpseKind? corpse) { if (GenHostility.AnyHostileActiveThreatToPlayer(thing.Map)) ForbidWaitList.Add(thing, rule, corpse, null); else thing.SetForbidden(false, warnOnFail: false); } /// What the strip prefix recorded: the rule of the stripped pawn's group and what it had. public sealed class StripRecord { public ForbidRule Rule; public List Things; } /// The strip prefix: null when the pawn's group has no strip switch acting. public static StripRecord BeforeStrip(Pawn pawn) { if (pawn == null || Butchering || Current.ProgramState != ProgramState.Playing || !ForbidRules.On) return null; if (!ForbidRules.Colony.StripActive && !ForbidRules.Enemies.StripActive) return null; ForbidGroup group = pawn.Dead ? ForbidRules.GroupOfDead(pawn) : ForbidRules.GroupOf(pawn); ForbidRule rule = ForbidRules.For(group); if (rule == null || !rule.StripActive) return null; var things = new List(); if (pawn.equipment != null) things.AddRange(pawn.equipment.AllEquipmentListForReading); if (pawn.apparel != null) things.AddRange(pawn.apparel.WornApparel); if (pawn.inventory != null) things.AddRange(pawn.inventory.innerContainer); return things.Count == 0 ? null : new StripRecord { Rule = rule, Things = things }; } /// The strip postfix: forbids each recorded thing now on a map, inside "Where", that the filter refuses. public static void AfterStrip(StripRecord record) { if (record?.Rule == null || !record.Rule.StripActive) return; foreach (Thing t in record.Things) { if (t == null || t.Destroyed || !t.Spawned || ForbidRules.IsForbiddenFlag(t)) continue; if (record.Rule.InsideWhere(t) && !record.Rule.Allows(t)) t.SetForbidden(true, warnOnFail: false); } } } /// /// Things a rule allows wait here while an enemy that can still fight is on their map. Work package "forbid" /// (design.md, 1.1 "Wait until the fight is over"). An unsaved list of thing, rule (or corpse switch) and, for /// a remembered weapon, its owner, with the Game it belongs to: a different Current.Game clears it, so a save /// and reload forgets it and things still waiting stay forbidden, as in vanilla. /// /// Every 250 ticks, per map with entries (Map.MapPostTick postfix, which returns at once while the list is /// empty): an entry whose thing is no longer spawned on that map leaves; a remembered weapon stays while /// owner.mindState.droppedWeapon is still that weapon; if any other entry is left and /// GenHostility.AnyHostileActiveThreatToPlayer(map) is false, each whose rule still acts, that is still /// forbidden, inside "Where" and allowed by the current filter is allowed, and all of them leave the list. /// Changing a waiting thing's flag outside a scope (the player, a mod) takes it off the list. /// public static class ForbidWaitList { public const int CheckInterval = 250; public sealed class Entry { public Thing Thing; /// The gear rule, or null for a corpse. public ForbidRule Rule; /// The corpse switch, for a corpse. public CorpseKind? Corpse; /// The colonist that remembers this weapon, or null. public Pawn Owner; public Map Map; } private static readonly List entries = new List(); private static Game game; /// No entries: the tick postfix returns at once. public static bool IsEmpty => entries.Count == 0; public static int Count { get { CheckGame(); return entries.Count; } } /// True while the thing waits. public static bool Contains(Thing t) { CheckGame(); return t != null && entries.Any(e => e.Thing == t); } /// The waiting entry of the thing, or null. public static Entry EntryOf(Thing t) { CheckGame(); return t == null ? null : entries.FirstOrDefault(e => e.Thing == t); } public static void Add(Thing thing, ForbidRule rule, CorpseKind? corpse, Pawn owner) { if (thing == null || thing.Map == null) return; CheckGame(); game = Current.Game; entries.RemoveAll(e => e.Thing == thing); entries.Add(new Entry { Thing = thing, Rule = rule, Corpse = corpse, Owner = owner, Map = thing.Map }); } public static void Remove(Thing thing) { if (thing == null || entries.Count == 0) return; entries.RemoveAll(e => e.Thing == thing); } /// Empties the list. Tests only (and a game change). public static void Clear() { entries.Clear(); game = null; } private static void CheckGame() { if (entries.Count > 0 && game != Current.Game) Clear(); } /// The tick postfix: every CheckInterval ticks, the check for this map. public static void MapTick(Map map) { if (entries.Count == 0 || map == null) return; CheckGame(); if (entries.Count == 0 || Find.TickManager.TicksGame % CheckInterval != 0) return; Check(map); } /// The check for one map, as described above. public static void Check(Map map) { CheckGame(); List maps = Find.Maps; entries.RemoveAll(e => e.Map == null || !maps.Contains(e.Map)); var ready = new List(); foreach (Entry e in entries.Where(x => x.Map == map).ToList()) { if (e.Thing == null || e.Thing.Destroyed || !e.Thing.Spawned || e.Thing.Map != map) { entries.Remove(e); continue; } if (e.Owner != null && e.Owner.mindState != null && e.Owner.mindState.droppedWeapon == e.Thing) continue; ready.Add(e); } if (ready.Count == 0 || GenHostility.AnyHostileActiveThreatToPlayer(map)) return; foreach (Entry e in ready) { entries.Remove(e); if (ShouldAllow(e)) e.Thing.SetForbidden(false, warnOnFail: false); } } private static bool ShouldAllow(Entry e) { if (!ForbidRules.IsForbiddenFlag(e.Thing)) return false; if (e.Corpse.HasValue) return ForbidRules.CorpseSwitch(e.Corpse.Value); ForbidRule rule = e.Rule; return rule != null && rule.Active && rule.InsideWhere(e.Thing) && rule.Allows(e.Thing); } } // ---- patches --------------------------------------------------------------------- [HarmonyPatch(typeof(Pawn), nameof(Pawn.Kill), new[] { typeof(DamageInfo?), typeof(Hediff) })] public static class Patch_Pawn_Kill { public static void Prefix(Pawn __instance, out ForbidScope __state) { __state = null; try { if (ForbidHooks.ShouldOpen) __state = ForbidHooks.Push(__instance, downing: false); } catch (Exception e) { HookGuard.Report("Pawn.Kill prefix", e); } } public static void Postfix(ForbidScope __state) { if (__state == null) return; try { ForbidHooks.Apply(__state); } catch (Exception e) { HookGuard.Report("Pawn.Kill", e); } } public static void Finalizer(ForbidScope __state) { if (__state != null) ForbidHooks.Pop(__state); } } [HarmonyPatch(typeof(Pawn_HealthTracker), "MakeDowned", new[] { typeof(DamageInfo?), typeof(Hediff) })] public static class Patch_Pawn_HealthTracker_MakeDowned { public static void Prefix(Pawn ___pawn, out ForbidScope __state) { __state = null; try { if (ForbidHooks.ShouldOpen) __state = ForbidHooks.Push(___pawn, downing: true); } catch (Exception e) { HookGuard.Report("Pawn_HealthTracker.MakeDowned prefix", e); } } public static void Postfix(ForbidScope __state) { if (__state == null) return; try { ForbidHooks.Apply(__state); } catch (Exception e) { HookGuard.Report("Pawn_HealthTracker.MakeDowned", e); } } public static void Finalizer(ForbidScope __state) { if (__state != null) ForbidHooks.Pop(__state); } } /// The recorder. It never changes a flag: it only reads the old value and notes the change. [HarmonyPatch(typeof(CompForbiddable), nameof(CompForbiddable.Forbidden), MethodType.Setter)] public static class Patch_CompForbiddable_Forbidden { public static void Prefix(CompForbiddable __instance, out bool __state) { __state = false; if (!ForbidHooks.ScopeOpen && ForbidWaitList.IsEmpty) return; __state = __instance.Forbidden; } public static void Postfix(CompForbiddable __instance, bool __state) { if (!ForbidHooks.ScopeOpen && ForbidWaitList.IsEmpty) return; try { bool now = __instance.Forbidden; if (ForbidHooks.ScopeOpen) { if (!__state && now) ForbidHooks.Record(__instance.parent); } else if (__state != now) { ForbidWaitList.Remove(__instance.parent); } } catch (Exception e) { HookGuard.Report("CompForbiddable.Forbidden", e); } } } [HarmonyPatch(typeof(Pawn), nameof(Pawn.Strip))] public static class Patch_Pawn_Strip { public static void Prefix(Pawn __instance, out ForbidHooks.StripRecord __state) { __state = null; try { __state = ForbidHooks.BeforeStrip(__instance); } catch (Exception e) { HookGuard.Report("Pawn.Strip prefix", e); } } public static void Postfix(ForbidHooks.StripRecord __state) { if (__state == null) return; try { ForbidHooks.AfterStrip(__state); } catch (Exception e) { HookGuard.Report("Pawn.Strip", e); } } } /// Butchering's ingredient step strips corpses (autoStripCorpses); the strip switch leaves that vanilla. [HarmonyPatch(typeof(Toils_Recipe), "CalculateIngredients")] public static class Patch_Toils_Recipe_CalculateIngredients { public static void Prefix() => ForbidHooks.EnterButchering(); public static void Finalizer() => ForbidHooks.LeaveButchering(); } [HarmonyPatch(typeof(Map), nameof(Map.MapPostTick))] public static class Patch_Map_MapPostTick { public static void Postfix(Map __instance) { if (ForbidWaitList.IsEmpty) return; try { ForbidWaitList.MapTick(__instance); } catch (Exception e) { HookGuard.Report("Map.MapPostTick", e); } } } }