using System; using System.Collections.Generic; using HarmonyLib; using RimWorld; using RimWorld.Planet; using Verse; namespace BlaxSlaves { /// /// "Owning slaves is normal": while the game hands out thoughts about something the colony did to a /// slave, free colonists don't take the negative ones. Pacifists (Kind, or incapable of violence) still /// do, and so does family when the relation-grief setting is on. /// /// Thought givers rarely say who the victim was, so the patches below open a "frame" around the /// places where the victim is still known, and one gate on TryGainMemory reads the innermost frame. /// public static class SlaveHarm { public sealed class Frame { public Pawn victim; public bool protectedVictim; public Frame previous; } [ThreadStatic] private static Frame top; public static Frame Top => top; /// /// Slaves, and branded pawns who aren't free members of the colony (runaways, prisoners, sold /// slaves). A branded pawn who became a free colonist is mourned like anyone else. /// public static bool IsProtected(Pawn pawn) => pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike && (pawn.IsSlave || (pawn.Faction != Faction.OfPlayer && BrandUtility.IsBranded(pawn))); public static Frame Push(Pawn victim, bool forceProtected = false) { var frame = new Frame { victim = victim, protectedVictim = forceProtected || IsProtected(victim), previous = top, }; top = frame; return frame; } public static void Pop(Frame frame) { if (frame != null) top = frame.previous; } public static bool IsPacifist(Pawn pawn) => pawn.story?.traits?.HasTrait(TraitDefOf.Kind) == true || pawn.WorkTagIsDisabled(WorkTags.Violent); public static bool ShouldSuppress(Pawn recipient, Thought thought, Pawn victim) { try { if (!BlaxSlavesMod.Settings.suppressSlaveHarmMood || recipient == null || recipient == victim) return false; if (recipient.Faction != Faction.OfPlayer || recipient.IsSlave || recipient.RaceProps == null || !recipient.RaceProps.Humanlike) return false; ThoughtStage stage = thought?.CurStage; if (stage == null || (stage.baseMoodEffect >= 0f && stage.baseOpinionOffset >= 0f)) return false; if (IsPacifist(recipient)) return false; if (BlaxSlavesMod.Settings.keepRelationGrief && victim != null && recipient.GetMostImportantRelation(victim) != null) return false; return true; } catch (Exception e) { Log.ErrorOnce("[Blax Slaves] mood gate failed, letting the thought through: " + e, 0x6B1A5E); return false; } } /// /// Deaths and losses only count when the colony caused them: banishment, executions and surgery /// kills, or a killer from the player faction. Raiders, animals, disease and kidnapping don't. /// public static bool CausedByColony(DamageInfo? dinfo, PawnDiedOrDownedThoughtsKind kind) { switch (kind) { case PawnDiedOrDownedThoughtsKind.Banished: case PawnDiedOrDownedThoughtsKind.BanishedToDie: return true; case PawnDiedOrDownedThoughtsKind.Died: if (!dinfo.HasValue) return false; DamageInfo d = dinfo.Value; if (d.Def != null && (d.Def.execution || d.Def == DamageDefOf.SurgicalCut)) return true; return d.Instigator != null && d.Instigator.Faction == Faction.OfPlayer; default: return false; } } } // ---- the gate ------------------------------------------------------------------------------- [HarmonyPatch(typeof(MemoryThoughtHandler), nameof(MemoryThoughtHandler.TryGainMemory), new[] { typeof(Thought_Memory), typeof(Pawn) })] [HarmonyPriority(Priority.Last)] public static class Patch_SlaveHarmGate { public static bool Prefix(MemoryThoughtHandler __instance, Thought_Memory newThought) { SlaveHarm.Frame frame = SlaveHarm.Top; if (frame == null || !frame.protectedVictim) return true; return !SlaveHarm.ShouldSuppress(__instance.pawn, newThought, frame.victim); } } // ---- frames: places where the victim is known ----------------------------------------------- [HarmonyPatch(typeof(ThoughtUtility), nameof(ThoughtUtility.GiveThoughtsForPawnExecuted))] public static class Frame_Executed { public static void Prefix(Pawn victim, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(victim); public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } } [HarmonyPatch(typeof(ThoughtUtility), nameof(ThoughtUtility.GiveThoughtsForPawnOrganHarvested))] public static class Frame_OrganHarvested { public static void Prefix(Pawn victim, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(victim); public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } } /// Death, banishment and loss thoughts, protected only when the colony caused them. [HarmonyPatch(typeof(PawnDiedOrDownedThoughtsUtility), nameof(PawnDiedOrDownedThoughtsUtility.TryGiveThoughts), new[] { typeof(Pawn), typeof(DamageInfo?), typeof(PawnDiedOrDownedThoughtsKind) })] public static class Frame_DiedOrDowned { public static void Prefix(Pawn victim, DamageInfo? dinfo, PawnDiedOrDownedThoughtsKind thoughtsKind, out SlaveHarm.Frame __state) { // Always push, so this victim's frame also shadows an outer frame about someone else. __state = SlaveHarm.Push(victim); if (__state.protectedVictim && !SlaveHarm.CausedByColony(dinfo, thoughtsKind)) __state.protectedVictim = false; } public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } } /// Gene death events (BloodfeederDied) fire after the death thoughts, outside their frame. [HarmonyPatch(typeof(Pawn_GeneTracker), nameof(Pawn_GeneTracker.Notify_PawnDied))] public static class Frame_GenesDied { public static void Prefix(Pawn_GeneTracker __instance, DamageInfo? dinfo, out SlaveHarm.Frame __state) { __state = SlaveHarm.Push(__instance.pawn); if (__state.protectedVictim && !SlaveHarm.CausedByColony(dinfo, PawnDiedOrDownedThoughtsKind.Died)) __state.protectedVictim = false; } public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } } /// A failed surgery that kills the patient (other mods' postfixes give thoughts here). [HarmonyPatch(typeof(Recipe_Surgery), "CheckSurgeryFail")] public static class Frame_SurgeryFail { public static void Prefix(Pawn patient, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(patient); public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } } /// Selling a slave. Its slave status is cleared before the SoldSlave event fires, so decide up front. [HarmonyPatch(typeof(Tradeable_Pawn), nameof(Tradeable_Pawn.ResolveTrade))] public static class Frame_SoldSlave { public static void Prefix(Tradeable_Pawn __instance, out SlaveHarm.Frame __state) { __state = null; if (__instance.ActionToDo != TradeAction.PlayerSells || __instance.thingsColony == null) return; foreach (Thing thing in __instance.thingsColony) { if (thing is Pawn pawn && SlaveHarm.IsProtected(pawn)) { __state = SlaveHarm.Push(pawn, forceProtected: true); return; } } } public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } } /// /// Gifting slaves by transport pod fires one SoldSlave event per pawn that isn't going home, in /// container order. Queue those pawns so each event gets its own victim. /// [HarmonyPatch(typeof(TransportersArrivalAction_GiveGift), nameof(TransportersArrivalAction_GiveGift.Arrived))] public static class Frame_GiftArrived { [ThreadStatic] internal static Queue soldInGift; public static void Prefix(List transporters, Settlement ___settlement, out Queue __state) { __state = soldInGift; var queue = new Queue(); Faction to = ___settlement?.Faction; if (transporters != null) { foreach (ActiveTransporterInfo info in transporters) { if (info?.innerContainer == null) continue; foreach (Thing thing in info.innerContainer) { if (thing is Pawn pawn && pawn.RaceProps.Humanlike && pawn.HomeFaction != to) queue.Enqueue(pawn); } } } soldInGift = queue; } public static Exception Finalizer(Exception __exception, Queue __state) { soldInGift = __state; return __exception; } } /// /// History events that name the victim: butchering (VICTIM), seeing a corpse (SUBJECT), /// blinding and scarification rituals (the target is the DOER), pod-gifted slaves (queued above). /// Events that name nobody push nothing, so an outer frame (an execution) stays in charge. /// [HarmonyPatch(typeof(HistoryEventsManager), nameof(HistoryEventsManager.RecordEvent))] public static class Frame_HistoryEvent { public static void Prefix(HistoryEvent historyEvent, out SlaveHarm.Frame __state) { __state = null; try { if (historyEvent.def == null) return; if (historyEvent.def == HistoryEventDefOf.SoldSlave && Frame_GiftArrived.soldInGift != null && Frame_GiftArrived.soldInGift.Count > 0) { __state = SlaveHarm.Push(Frame_GiftArrived.soldInGift.Dequeue()); return; } Pawn victim = null; if (historyEvent.args.TryGetArg(HistoryEventArgsNames.Victim, out Pawn named)) victim = named; else if (historyEvent.args.TryGetArg(HistoryEventArgsNames.Subject, out Corpse corpse)) victim = corpse?.InnerPawn; else if ((historyEvent.def == HistoryEventDefOf.GotBlinded || historyEvent.def == HistoryEventDefOf.GotScarified) && historyEvent.args.TryGetArg(HistoryEventArgsNames.Doer, out Pawn target)) victim = target; if (victim != null && victim.RaceProps != null && victim.RaceProps.Humanlike) __state = SlaveHarm.Push(victim); } catch (Exception e) { Log.ErrorOnce("[Blax Slaves] history event frame failed: " + e, 0x6B1A5F); } } public static Exception Finalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } } /// A slave's corpse in a gibbet cage doesn't scare non-pacifist colonists. [HarmonyPatch(typeof(Building_GibbetCage), nameof(Building_GibbetCage.GiveObservedThought))] public static class Patch_GibbetCage { public static void Postfix(Building_GibbetCage __instance, Pawn observer, ref Thought_Memory __result) { if (__result == null) return; Pawn victim = __instance.Corpse?.InnerPawn; if (victim != null && SlaveHarm.IsProtected(victim) && SlaveHarm.ShouldSuppress(observer, __result, victim)) __result = null; } } // ---- banish / abandon confirmation dialogs ---------------------------------------------------- /// The previews build their thought lists through GetThoughts; mark when that happens for a preview. [HarmonyPatch] public static class Patch_ThoughtPreviewScope { [ThreadStatic] internal static int depth; public static IEnumerable TargetMethods() { foreach (System.Reflection.MethodInfo m in typeof(PawnDiedOrDownedThoughtsUtility).GetMethods()) { if (m.Name == nameof(PawnDiedOrDownedThoughtsUtility.BuildMoodThoughtsListString)) yield return m; } } public static void Prefix() => depth++; public static Exception Finalizer(Exception __exception) { depth--; return __exception; } } /// Drop the thoughts the gate will suppress from the preview, so the dialog doesn't overstate the cost. [HarmonyPatch(typeof(PawnDiedOrDownedThoughtsUtility), nameof(PawnDiedOrDownedThoughtsUtility.GetThoughts))] public static class Patch_ThoughtPreview { public static void Postfix(Pawn victim, DamageInfo? dinfo, PawnDiedOrDownedThoughtsKind thoughtsKind, List outIndividualThoughts, List outAllColonistsThoughts) { if (Patch_ThoughtPreviewScope.depth <= 0 || !BlaxSlavesMod.Settings.suppressSlaveHarmMood) return; if (!SlaveHarm.IsProtected(victim) || !SlaveHarm.CausedByColony(dinfo, thoughtsKind)) return; outIndividualThoughts?.RemoveAll(t => SlaveHarm.ShouldSuppress(t.addTo, t.thought, victim)); // No recipient to check here: drop negative all-colonist lines from the preview only. outAllColonistsThoughts?.RemoveAll(t => t.thoughtDef?.stages != null && t.thoughtDef.stages.Count > 0 && t.thoughtDef.stages[0].baseMoodEffect < 0f); } } // ---- other mods ------------------------------------------------------------------------------ public static class Compat { public static int Apply(Harmony harmony) { int applied = 0; var finalizer = new HarmonyMethod(typeof(Compat), nameof(FrameFinalizer)); // War Crimes Expanded 2: torture recipes give precept thoughts with no victim attached. var torture = AccessTools.Method("WarCrimesExpanded2.WCE2_ThoughtHelper:WCE2_GiveThoughtsForPawnTortured"); if (torture != null && TryPatch(harmony, torture, new HarmonyMethod(typeof(Compat), nameof(VictimPrefix)), null, finalizer, "War Crimes Expanded 2")) applied++; // Harvest Organs Post Mortem: autopsy thoughts come from a postfix on MakeRecipeProducts. if (IsActive("Smuffle.HarvestOrgansPostMortem")) { var make = AccessTools.Method(typeof(GenRecipe), nameof(GenRecipe.MakeRecipeProducts)); if (make != null && TryPatch(harmony, make, new HarmonyMethod(typeof(Compat), nameof(CorpseIngredientPrefix)), null, finalizer, "Harvest Organs Post Mortem")) applied++; } // Hospitality: visitor groups reuse world pawns of the visiting faction, pending runaways included. if (IsActive("Orion.Hospitality")) { var validGuest = AccessTools.Method("Hospitality.Utilities.SpawnGroupUtility:ValidGuest"); if (validGuest != null && TryPatch(harmony, validGuest, null, new HarmonyMethod(typeof(Compat), nameof(NotPendingPostfix)), null, "Hospitality")) applied++; } return applied; } private static bool IsActive(string packageId) => ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null; private static bool TryPatch(Harmony harmony, System.Reflection.MethodBase target, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod finalizer, string label) { try { harmony.Patch(target, prefix: prefix, postfix: postfix, finalizer: finalizer); return true; } catch (Exception e) { Log.Warning("[Blax Slaves] " + label + " compatibility patch failed: " + e.Message); return false; } } public static void VictimPrefix(Pawn victim, out SlaveHarm.Frame __state) => __state = SlaveHarm.Push(victim); public static void CorpseIngredientPrefix(List ingredients, out SlaveHarm.Frame __state) { __state = null; if (ingredients == null) return; foreach (Thing thing in ingredients) { if (thing is Corpse corpse && SlaveHarm.IsProtected(corpse.InnerPawn)) { __state = SlaveHarm.Push(corpse.InnerPawn, forceProtected: true); return; } } } public static Exception FrameFinalizer(Exception __exception, SlaveHarm.Frame __state) { SlaveHarm.Pop(__state); return __exception; } public static void NotPendingPostfix(Pawn pawn, ref bool __result) { if (__result && GameComponent_BlaxRunaways.IsPending(pawn)) __result = false; } } }