using System; using System.Collections.Generic; using System.Reflection; using HarmonyLib; using RimWorld; using UnityEngine; using Verse; namespace BlaxSlaves { /// /// The buy-only generator Blax Slaves adds to trader kinds that would otherwise turn captives /// away. Its own subclass so it can be told apart from a vanilla or modded StockGenerator_BuySlaves /// (Royalty's tribute collector, Everybody Buys Slaves) and removed again without touching theirs. /// public class StockGenerator_BlaxBuySlaves : StockGenerator_BuySlaves { } /// /// "Every trader buys slaves" and "Slave stock ignores colony size". Both change trader defs: once at /// startup and again whenever the settings window closes (BlaxSlavesMod.SettingsChanged, never raised /// during a trade session). Turning a setting off undoes exactly what it changed, so the defs end up /// as the game and other mods left them. /// [StaticConstructorOnStartup] public static class TraderBuyers { /// /// Hospitality's guest "trader" kind: guests shop in your colony, they don't buy pawns. Matched by /// defName, the same way Everybody Buys Slaves skips it. /// public const string HospitalityGuestKind = "Guest"; /// Hospitality's packageId. With it, visitor groups arrive as its guests, who never buy captives. public const string HospitalityPackageId = "Orion.Hospitality"; // Private in vanilla. Null if a game update renames it; the stock feature then stands down. private static readonly AccessTools.FieldRef respectPopulationIntent = BindRespectPopulationIntent(); // Each slave generator's own respectPopulationIntent, recorded the first time Apply sees it. private static readonly Dictionary originalRespect = new Dictionary(); // Generators whose HandlesThingDef threw, so the warning is logged once per generator. private static readonly HashSet warnedGenerators = new HashSet(); static TraderBuyers() { Apply(); BlaxSlavesMod.SettingsChanged += Apply; } /// /// Brings every TraderKindDef in line with the current settings. Safe to call any number of times: /// each trader kind ends up with at most one of our generators, and only where nothing else buys humans. /// public static void Apply() { // The settings window works its notes out again the next time it opens. notes = null; BlaxSlavesSettings s = BlaxSlavesMod.Settings; if (s == null) return; int added = 0, removed = 0, flags = 0; try { ApplyBuyers(s, ref added, ref removed); } catch (Exception e) { Log.Error("[Blax Slaves] Every trader buys slaves: applying failed: " + e); } try { flags = ApplyStock(s); } catch (Exception e) { Log.Error("[Blax Slaves] Slave stock ignores colony size: applying failed: " + e); } if (added + removed + flags > 0) Log.Message("[Blax Slaves] Trader kinds: " + added + " now buy captives, " + removed + " stopped, " + flags + " slave stocks changed their colony-size rule."); } // ---- every trader buys slaves ---------------------------------------------------------------- /// Hospitality's guest kind never buys pawns. public static bool IsExcluded(TraderKindDef def) => def == null || def.defName == HospitalityGuestKind; /// Trader kinds some faction sends as visitors. They follow visitorsBuySlaves instead of allTradersBuySlaves. public static HashSet VisitorKinds() { var set = new HashSet(); foreach (FactionDef f in DefDatabase.AllDefsListForReading) { if (f?.visitorTraderKinds == null) continue; foreach (TraderKindDef k in f.visitorTraderKinds) if (k != null) set.Add(k); } return set; } /// /// Whether any generator other than ours buys humans. Found through HandlesThingDef, never by class /// name, so modded humanlike generators (and Everybody Buys Slaves' XML) count and we never add a second. /// public static bool OthersBuyHumans(TraderKindDef def) { List gens = def?.stockGenerators; if (gens == null) return false; for (int i = 0; i < gens.Count; i++) { StockGenerator g = gens[i]; if (g != null && !(g is StockGenerator_BlaxBuySlaves) && Handles(g, ThingDefOf.Human)) return true; } return false; } /// Whether this trader kind should carry our generator under these settings. public static bool WantsOurBuyer(TraderKindDef def, BlaxSlavesSettings s, HashSet visitorKinds) { if (s == null || IsExcluded(def) || def.stockGenerators == null) return false; bool on = visitorKinds != null && visitorKinds.Contains(def) ? s.visitorsBuySlaves : s.allTradersBuySlaves; return on && !OthersBuyHumans(def); } private static void ApplyBuyers(BlaxSlavesSettings s, ref int added, ref int removed) { HashSet visitors = VisitorKinds(); foreach (TraderKindDef def in DefDatabase.AllDefsListForReading) { List gens = def?.stockGenerators; if (gens == null) continue; bool want = WantsOurBuyer(def, s, visitors); int ours = 0; for (int i = 0; i < gens.Count; i++) if (gens[i] is StockGenerator_BlaxBuySlaves) ours++; if (want && ours == 1) continue; if (ours > 0) removed += gens.RemoveAll(g => g is StockGenerator_BlaxBuySlaves); if (want) { // Appended last, so PriceTypeFor and the stock generators already there keep their order. var gen = new StockGenerator_BlaxBuySlaves(); gen.ResolveReferences(def); gens.Add(gen); added++; } } } private static bool Handles(StockGenerator g, ThingDef td) { try { return g.HandlesThingDef(td); } catch (Exception e) { if (warnedGenerators.Add(g)) Log.Warning("[Blax Slaves] " + g.GetType().FullName + " on " + g.trader?.defName + " threw in HandlesThingDef(" + td?.defName + "): " + e.Message); return false; } } // ---- settings-window notes ------------------------------------------------------------------- /// When the Trade tab warns that a "buy" checkbox can't take buyers away. public struct SettingNotes { /// Everybody Buys Slaves' own buyers sit on non-visitor kinds, so "every trader" off leaves them buying. public bool everybodyBuysTraders; /// The same on visitor kinds. False when XML Extensions' "exclude visitors" kept them out. public bool everybodyBuysVisitors; /// Hospitality runs visitor groups as its guests, so "visitors" only reaches other visitors. public bool hospitality; } private static SettingNotes? notes; /// /// The notes for the current defs. DoTrade reads this every frame, so it walks the defs once and keeps /// the result until Apply runs again (each time the settings window closes). /// public static SettingNotes Notes => notes ?? (notes = FindNotes(Compat.IsActive(Compat.EverybodyBuysSlaves), Compat.IsActive(HospitalityPackageId))).Value; /// /// Works the notes out from the defs, not just from which mods are active: a buyer must actually sit on /// that group of kinds. The mod flags are parameters so the tests can try both. /// public static SettingNotes FindNotes(bool everybodyBuysActive, bool hospitalityActive) { var n = new SettingNotes { hospitality = hospitalityActive }; if (!everybodyBuysActive) return n; HashSet visitors = VisitorKinds(); foreach (TraderKindDef def in DefDatabase.AllDefsListForReading) { if (IsExcluded(def) || !HasPlainBuyer(def)) continue; if (visitors.Contains(def)) n.everybodyBuysVisitors = true; else n.everybodyBuysTraders = true; } return n; } /// /// Carries a generator of exactly StockGenerator_BuySlaves, the class Everybody Buys Slaves' XML adds. /// Our subclass doesn't count, and neither do other humanlike generators such as the slavers' StockGenerator_Slaves. /// public static bool HasPlainBuyer(TraderKindDef def) { List gens = def?.stockGenerators; if (gens == null) return false; for (int i = 0; i < gens.Count; i++) if (gens[i] != null && gens[i].GetType() == typeof(StockGenerator_BuySlaves)) return true; return false; } // ---- anti-slavery traders -------------------------------------------------------------------- /// /// Any of the faction's ideoligions rejects slavery, the same rule vanilla's slave stock and slaver /// caravans use (all ideoligions must approve). Factions without ideoligions don't reject. /// public static bool RejectsSlavery(Faction faction) { if (faction?.ideos == null) return false; foreach (Ideo ideo in faction.ideos.AllIdeos) if (ideo != null && !ideo.IdeoApprovesOfSlavery()) return true; return false; } /// /// Refuse mode only: true when this trader turns down this colony slave or prisoner because its /// faction rejects slavery. Their own people are bought back (ransom), factionless traders always /// buy. Patch_TraderRefusesCaptiveReason reads it to explain the greyed-out row. /// public static bool TraderRefusesCaptive(Pawn pawn, ITrader trader) { BlaxSlavesSettings s = BlaxSlavesMod.Settings; if (s == null || s.antiSlaveryTraders != BlaxSlavesSettings.AntiSlaveryRefuse || !ModsConfig.IdeologyActive) return false; if (pawn == null || trader == null || pawn.RaceProps == null || !pawn.RaceProps.Humanlike) return false; if (!pawn.IsSlaveOfColony && !pawn.IsPrisonerOfColony) return false; Faction faction = trader.Faction; if (faction == null || faction.IsPlayer || pawn.HomeFaction == faction) return false; return RejectsSlavery(faction); } // ---- slave stock ignores colony size --------------------------------------------------------- /// Whether the colony-size field could be bound (false after a game update renamed it). public static bool StockFeatureAvailable => respectPopulationIntent != null; private static int ApplyStock(BlaxSlavesSettings s) { if (respectPopulationIntent == null) return 0; int changed = 0; foreach (TraderKindDef def in DefDatabase.AllDefsListForReading) { List gens = def?.stockGenerators; if (gens == null) continue; foreach (StockGenerator g in gens) { if (!(g is StockGenerator_Slaves slaves)) continue; if (!originalRespect.TryGetValue(slaves, out bool original)) { original = respectPopulationIntent(slaves); originalRespect[slaves] = original; } // Only the flag: slaveKindDef (Royalty's Slave_Empire) and vanilla's ideoligion check stay. bool target = !s.slaveStockIgnoresColonySize && original; ref bool field = ref respectPopulationIntent(slaves); if (field != target) { field = target; changed++; } } } return changed; } private static AccessTools.FieldRef BindRespectPopulationIntent() { try { return AccessTools.FieldRefAccess("respectPopulationIntent"); } catch (Exception e) { Log.Warning("[Blax Slaves] StockGenerator_Slaves.respectPopulationIntent not found, slave stock keeps vanilla's colony-size rule: " + e.Message); return null; } } } /// /// Refuse mode: traders whose faction rejects slavery won't take colony slaves or prisoners, except /// their own people. Postfix on the base getter (Tradeable_Pawn doesn't override it), so vanilla's /// trade row greys the pawn out with "won't trade" instead of hiding it. Gifts stay untouched. /// [HarmonyPatch(typeof(Tradeable), nameof(Tradeable.TraderWillTrade), MethodType.Getter)] public static class Patch_AntiSlaveryTradersRefuse { public static void Postfix(Tradeable __instance, ref bool __result) { // Runs for every trade row each frame: the setting check comes first and is cheap. if (!__result || BlaxSlavesMod.Settings == null || BlaxSlavesMod.Settings.antiSlaveryTraders != BlaxSlavesSettings.AntiSlaveryRefuse) return; if (TradeSession.giftMode) return; if (__instance?.FirstThingColony is Pawn pawn && TraderBuyers.TraderRefusesCaptive(pawn, TradeSession.trader)) __result = false; } } /// /// Refuse mode: says why a colony captive's row reads "won't trade". The reason is a tooltip on vanilla's /// "won't trade" text, the way vanilla explains a negotiator who won't sell slaves, and on vanilla's slave /// icon next to the name. A postfix, so it still runs when another mod's prefix skips the original, and it /// never skips anything itself; vanilla's icon and curX stay as they are. No stand-down for Trade as Slave /// or Colonist: that mod only takes over the trader-stock branch, and the refuse gate never stands down. /// [HarmonyPatch(typeof(TransferableUIUtility), nameof(TransferableUIUtility.DrawCaptiveTradeInfo))] public static class Patch_TraderRefusesCaptiveReason { // TradeUI.DrawTradeableRow in row-group coordinates: 175 px of trader count and price at the right edge, // then the 240 px column where "won't trade" is written. Vanilla's captive icons are 24 px wide. public const float TraderColumnsWidth = 175f, WillNotTradeWidth = 240f, CaptiveIconWidth = 24f; /// TradeUI calls DrawCaptiveTradeInfo only with Ideology, and refuse mode needs it too. public static bool Prepare(MethodBase original) => ModsConfig.IdeologyActive; /// Only records curX, so the postfix can tell whether the original drew its icon. public static void Prefix(ref float curX, out float __state) => __state = curX; public static void Postfix(Transferable trad, ITrader trader, Rect rect, ref float curX, float __state) { // Runs for every row each frame: the setting check first, then hover, the ideoligion walk last. BlaxSlavesSettings s = BlaxSlavesMod.Settings; if (s == null || s.antiSlaveryTraders != BlaxSlavesSettings.AntiSlaveryRefuse) return; Rect willNot = WillNotTradeRect(rect); // Vanilla's slave icon sits where curX now points, if the original moved it left by one icon. Rect icon = new Rect(curX, (rect.height - CaptiveIconWidth) / 2f, CaptiveIconWidth, CaptiveIconWidth); bool overText = Mouse.IsOver(willNot); bool overIcon = Mathf.Approximately(__state - curX, CaptiveIconWidth) && Mouse.IsOver(icon); if (!overText && !overIcon) return; if (!Explains(trad, trader, out Pawn pawn)) return; TaggedString reason = Reason(pawn, trader); if (overText) { Widgets.DrawHighlight(willNot); TooltipHandler.TipRegion(willNot, reason); } if (overIcon) TooltipHandler.TipRegion(icon, reason); } /// Where TradeUI writes "won't trade" in a row of this size. public static Rect WillNotTradeRect(Rect row) => new Rect(row.width - TraderColumnsWidth - WillNotTradeWidth, 0f, WillNotTradeWidth, row.height); /// /// True when this row is a colony captive greyed out because the trader's faction rejects slavery. Not in /// gift mode, where the gate stays out. Reads TraderWillTrade last, so a row another mod re-enabled gets no reason. /// public static bool Explains(Transferable trad, ITrader trader, out Pawn pawn) { pawn = null; if (TradeSession.giftMode || !(trad is Tradeable t) || !(t.FirstThingColony is Pawn p)) return false; if (!TraderBuyers.TraderRefusesCaptive(p, trader) || t.TraderWillTrade) return false; pawn = p; return true; } public static TaggedString Reason(Pawn pawn, ITrader trader) => "BlaxSlaves_TraderRefusesCaptive".Translate(trader.Faction.Named("FACTION"), pawn.Named("PAWN")); } }