using System; using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; namespace BlaxCastes { /// Which player-side status a pawn has, for join classification. public enum JoinSide { None, Colonist, Slave, Prisoner, } /// /// Join defaults: puts a pawn that joins, or changes status, into the caste of its join row. /// /// The join hooks (JoinHooks: Pawn.SetFaction, Pawn_GuestTracker.SetGuestStatus, Pawn.PreTraded) /// classify the join where it happens and call Enqueue with the innermost scope's reason, or with /// StatusFallback. The queue lives in GameComponent_BlaxCastes.JoinQueue, so it survives a save. /// GameComponentTick calls ApplyQueue every tick, which applies entries queued on an earlier tick: /// never inside SetFaction or SetGuestStatus, and only while the pawn is still player-side. /// /// Order at apply time: a caste picked by hand after the join was queued, then the previous caste or /// No caste (a former-caste record with the same status, younger than formerCasteDays; the pawn's own /// settings from when it left come back with it), then the row. Reason /// to row, first match wins: the scope ("bought": the final status picks bought as slave or bought /// as colonist; a row id is used as it is), then the status fallback from the final status: new /// colonist, new slave or new prisoner. /// public static class JoinDefaults { /// Queue reason when no scope covered the join: the final status picks the row. public const string StatusFallback = "status"; private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance; private static int Now => Find.TickManager?.TicksGame ?? 0; /// Castes is on and the join defaults setting is on. public static bool Active => BlaxCastesMod.Enabled && (BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.enableJoinDefaults); private static bool ReturnToPrevious => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.returnToPreviousCaste; private static int FormerCasteDays => BlaxCastesMod.Settings?.formerCasteDays ?? BlaxCastesSettings.DefaultFormerCasteDays; // ---- classification ---------------------------------------------------------------- public static JoinSide SideOf(Pawn pawn) { if (pawn == null) return JoinSide.None; Pawn_GuestTracker guest = pawn.guest; return Classify(pawn.Faction, guest != null, guest != null ? guest.guestStatusInt : GuestStatus.Guest, guest?.HostFaction); } /// /// Player faction: slave, prisoner of the colony (an arrested colonist) or colonist (also one held /// by another faction, so it keeps its caste when it comes back). Another faction: prisoner of the /// colony or nothing. /// internal static JoinSide Classify(Faction faction, bool hasGuest, GuestStatus status, Faction host) { Faction player = Faction.OfPlayerSilentFail; if (player == null) return JoinSide.None; bool prisonerOfColony = hasGuest && status == GuestStatus.Prisoner && host == player; if (faction == player) { if (hasGuest && status == GuestStatus.Slave) return JoinSide.Slave; return prisonerOfColony ? JoinSide.Prisoner : JoinSide.Colonist; } return prisonerOfColony ? JoinSide.Prisoner : JoinSide.None; } /// Humanlike, not a baby, not a quest lodger, not a mutant without policies. Others never join a caste. public static bool Eligible(Pawn pawn) => pawn != null && pawn.RaceProps != null && pawn.RaceProps.Humanlike && !pawn.DevelopmentalStage.Baby() && !pawn.IsQuestLodger() && !(pawn.IsMutant && pawn.mutant.Def.disablePolicies); /// A scope reason or a row id, as opposed to the status fallback. public static bool IsSpecific(string reason) => !reason.NullOrEmpty() && reason != StatusFallback; /// /// The join row a queued reason resolves to for the pawn's status now, or null when the pawn has /// no player-side status. /// public static string RowFor(string reason, Pawn pawn) { JoinSide side = SideOf(pawn); if (reason == JoinScopes.Bought) { if (side == JoinSide.Slave) return JoinReason.BoughtSlave; if (side == JoinSide.Colonist) return JoinReason.BoughtColonist; } else if (JoinReason.IsRow(reason)) { return reason; } switch (side) { case JoinSide.Colonist: return JoinReason.NewColonist; case JoinSide.Slave: return JoinReason.NewSlave; case JoinSide.Prisoner: return JoinReason.NewPrisoner; default: return null; } } // ---- previous caste ---------------------------------------------------------------- /// A former-caste record older than formerCasteDays. public static bool FormerExpired(FormerCaste record, int now) => record == null || now - record.tick > FormerCasteDays * GenDate.TicksPerDay; /// /// The former-caste record the pawn would leave right now: its caste, or No caste when it is casteless /// by choice, the status (colonist or slave), and its own settings with the caste's slots it follows. /// Null for another status or a pawn with no membership record (it never had a caste, so a status /// change moves it by its row). The join hooks take it before a status change, because the game /// resets medical care inside the change. /// internal static FormerCaste Capture(Pawn pawn, JoinSide side) { if (side != JoinSide.Colonist && side != JoinSide.Slave) return null; GameComponent_BlaxCastes comp = Comp; CasteMembership m = comp?.MembershipOf(pawn); if (m == null || (m.caste != null && !comp.HasCaste(m.caste))) return null; var record = new FormerCaste(m.caste?.id ?? Caste.Unmanaged, side, m.auto, Now) { casteless = m.caste == null }; CasteUtility.Snapshot(pawn, m.caste, record); return record; } /// /// Writes the pawn's former-caste record: it had this status (colonist or slave) and is leaving the /// player side, being sold or becoming a prisoner. captured is the record taken before the change /// (Capture); without one it is taken now. A pawn with no membership record writes none. /// internal static void NoteFormer(Pawn pawn, JoinSide side, FormerCaste captured = null) { if (side != JoinSide.Colonist && side != JoinSide.Slave) return; GameComponent_BlaxCastes comp = Comp; if (comp == null || pawn == null) return; FormerCaste record = captured != null && captured.side == side ? captured : Capture(pawn, side); if (record == null) return; record.tick = Now; comp.SetFormer(pawn, record); } /// /// The pawn's former-caste record when it applies now: it has the pawn's current status (colonist or /// slave), is younger than formerCasteDays, and its caste still exists (a No caste record always /// does). Null otherwise, or while returnToPreviousCaste is off. /// public static FormerCaste UsableFormer(Pawn pawn) { if (!ReturnToPrevious || pawn == null) return null; GameComponent_BlaxCastes comp = Comp; FormerCaste record = comp?.FormerOf(pawn); if (record == null || FormerExpired(record, Now)) return null; JoinSide side = SideOf(pawn); if ((side != JoinSide.Colonist && side != JoinSide.Slave) || record.side != side) return null; if (!record.casteless && comp.CasteById(record.casteId) == null) return null; return record; } /// /// The caste a returning pawn gets back (UsableFormer). Null when there is none, and when the pawn /// goes back to No caste. /// public static Caste PreviousCasteFor(Pawn pawn) { FormerCaste record = UsableFormer(pawn); return record == null || record.casteless ? null : Comp.CasteById(record.casteId); } // ---- queue ------------------------------------------------------------------------- /// The pawn's waiting join, or null. public static QueuedJoin QueuedFor(Pawn pawn) { GameComponent_BlaxCastes comp = Comp; if (comp == null || pawn == null) return null; List queue = comp.JoinQueue; for (int i = 0; i < queue.Count; i++) { if (queue[i] != null && queue[i].pawn == pawn) return queue[i]; } return null; } /// True while the pawn waits for its join to be applied. public static bool IsQueued(Pawn pawn) => QueuedFor(pawn) != null; /// /// True while the pawn waits for a join that will change its caste: the previous caste or the row /// gives it one, or a No caste row will take it out of a caste a join row put it in. The column /// shows "(pending)" only then. /// public static bool WillChange(Pawn pawn) { QueuedJoin q = QueuedFor(pawn); GameComponent_BlaxCastes comp = Comp; if (q == null || comp == null || !Active || !Eligible(pawn) || !CasteUtility.IsPlayerSide(pawn)) return false; CasteMembership m = comp.MembershipOf(pawn); if (HandPickedSince(m, q)) return false; FormerCaste record = UsableFormer(pawn); if (record != null) return record.casteless ? m == null || m.caste != null : m?.caste == null || m.caste.id != record.casteId; string row = RowFor(q.reason, pawn); if (row == null) return false; if (comp.ResolveRow(row) != null) return true; return m?.caste != null && m.auto; } /// /// A caste (or No caste) picked by hand after the join was queued: a manual membership that is /// not the one the pawn had when the join was queued (after a load, one set on or after the /// queueing tick). A restored previous caste or a deleted caste never counts as a pick. /// private static bool HandPickedSince(CasteMembership m, QueuedJoin q) { if (m == null || m.auto || m.reason == JoinReason.CasteDeleted || m.reason == JoinReason.PreviousCaste) return false; if (q.seenKnown) return !ReferenceEquals(m, q.seen); return m.tick >= q.tick; } /// /// Queues a join for the next tick: a scope reason, a row id or StatusFallback. One entry per pawn; /// a specific reason replaces a status fallback, never the other way round. Does nothing while /// Castes or the join defaults are off, and for pawns that never join a caste. /// public static void Enqueue(Pawn pawn, string reason) { if (!Active || pawn == null) return; GameComponent_BlaxCastes comp = Comp; if (comp == null || GameComponent_BlaxCastes.IsGone(pawn) || !Eligible(pawn)) return; if (reason.NullOrEmpty()) reason = StatusFallback; comp.LeftPawns.Remove(pawn); int now = Now; QueuedJoin queued = QueuedFor(pawn); if (queued == null) { queued = new QueuedJoin(pawn, reason, now); comp.JoinQueue.Add(queued); } else { if (IsSpecific(reason) || !IsSpecific(queued.reason)) queued.reason = reason; if (now > queued.tick) queued.tick = now; } // A pick made before this status change is not a pick "after the join": the new status moves the pawn. queued.seen = comp.MembershipOf(pawn); queued.seenKnown = true; } /// A pawn left the player side. Its membership ends on the next tick if it has not come back. internal static void NoteLeft(Pawn pawn) { if (pawn == null) return; Comp?.LeftPawns.Add(pawn); } /// /// Applies the joins queued on an earlier tick and ends the memberships of pawns that left. /// Called by GameComponent_BlaxCastes every tick. /// public static void ApplyQueue() { GameComponent_BlaxCastes comp = Comp; if (comp == null || Find.TickManager == null) return; EndLeftMemberships(comp); List queue = comp.JoinQueue; if (queue.Count == 0) return; int now = Now; List due = null; foreach (QueuedJoin q in queue) { if (q == null || q.tick < now) (due ??= new List()).Add(q); } if (due == null) return; queue.RemoveAll(q => q == null || q.tick < now); Dictionary> joined = null; foreach (QueuedJoin q in due) { if (q == null) continue; try { Caste caste = ApplyOne(comp, q); if (caste != null) { joined ??= new Dictionary>(); if (!joined.TryGetValue(caste, out List pawns)) joined[caste] = pawns = new List(); pawns.Add(q.pawn); } } catch (Exception e) { JoinHooks.LogOnce("Applying a join", e); } } if (joined != null) SendMessages(joined); } /// Applies one join. Returns the caste the pawn joined, or null. private static Caste ApplyOne(GameComponent_BlaxCastes comp, QueuedJoin q) { Pawn pawn = q.pawn; if (GameComponent_BlaxCastes.IsGone(pawn) || pawn.Dead || pawn.Destroyed) return null; if (!CasteUtility.IsPlayerSide(pawn)) { // Sold, released or gone over to another faction before the join was applied. CasteManager.EndMembership(pawn); return null; } if (!Active || !Eligible(pawn)) return null; CasteMembership membership = comp.MembershipOf(pawn); if (HandPickedSince(membership, q)) return null; FormerCaste record = UsableFormer(pawn); if (record != null) { comp.RemoveFormer(pawn); return Restore(comp, pawn, record, membership); } string row = RowFor(q.reason, pawn); if (row == null) return null; Caste caste = comp.ResolveRow(row); bool rowSet = membership?.caste != null && membership.auto; if (caste != null) { // Moving on from a caste a join row gave it: what that caste set and the new one leaves alone goes back. if (rowSet && membership.caste != caste) RevertSlots(pawn, membership.caste, caste); return CasteManager.Assign(pawn, caste, true, row) ? caste : null; } // A No caste row only undoes what a join row did; a caste picked by hand stays. if (rowSet) LeaveCaste(pawn, membership.caste); return null; } /// /// A returning pawn gets its former caste, or No caste, back, and its own settings from when it /// left: each slot of that caste it followed gets the caste's current value (edits made while it was /// away included), each one it had changed by hand gets that value back. A slot the caste leaves /// alone is touched only to undo the caste the pawn got while it was away (the new-prisoner caste's /// food): while the pawn still has that caste's value, it gets its own from when it left. So an /// arrest and release, or a sale and buy-back, keeps the pawn's hand changes. Returns the caste for /// the join message, or null when the pawn's caste does not change or it goes back to No caste. /// private static Caste Restore(GameComponent_BlaxCastes comp, Pawn pawn, FormerCaste record, CasteMembership membership) { if (!CasteUtility.CanBeMember(pawn)) return null; Caste previous = record.casteless ? null : comp.CasteById(record.casteId); Caste away = membership?.caste; comp.SetMembership(pawn, new CasteMembership(previous, record.auto, JoinReason.PreviousCaste, Now)); CasteUtility.Restore(pawn, previous, away == previous ? null : away, record); return previous != null && previous != away ? previous : null; } /// /// The pawn's join row is No caste while a join row had put it in a caste: it leaves the caste and /// RevertSlots runs with no new caste. /// private static void LeaveCaste(Pawn pawn, Caste caste) { CasteManager.EndMembership(pawn); RevertSlots(pawn, caste, null); } /// /// A join row takes the pawn out of a caste a join row had put it in, to No caste or to another /// caste. With revertOnLeave, each policy and medical care slot the old caste manages and the new /// one leaves alone, where the pawn still has the old caste's value, goes back to the database /// default (medical care to the game's default for its status), so a recruited prisoner does not /// keep the prisoner food. Slots changed by hand stay (the Follow rule). The schedule, work /// priorities and loadout have no database default and stay as they are. /// private static void RevertSlots(Pawn pawn, Caste from, Caste to) { if (from == null || !BlaxCastesMod.Enabled || (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.revertOnLeave)) return; foreach (CasteSlot slot in CasteUtility.PolicySlots) { if (!from.IsManaged(slot) || (to != null && to.IsManaged(slot)) || !CasteUtility.CanUse(pawn, slot)) continue; if (!CasteUtility.SameValue(CasteUtility.CurrentValue(pawn, slot), from.GetSlot(slot))) continue; if (slot == CasteSlot.MedCare) { pawn.playerSettings.ResetMedicalCare(); continue; } object value = DatabaseDefault(slot); if (value != null) CasteUtility.WriteSlot(pawn, slot, value); } } private static object DatabaseDefault(CasteSlot slot) { Game game = Current.Game; switch (slot) { case CasteSlot.Apparel: return game?.outfitDatabase?.DefaultOutfit(); case CasteSlot.Food: return game?.foodRestrictionDatabase?.DefaultFoodRestriction(); case CasteSlot.Drug: return game?.drugPolicyDatabase?.DefaultDrugPolicy(); case CasteSlot.Reading: return game?.readingPolicyDatabase?.DefaultReadingPolicy(); default: return null; } } private static void EndLeftMemberships(GameComponent_BlaxCastes comp) { HashSet left = comp.LeftPawns; if (left.Count == 0) return; List pawns = left.ToList(); left.Clear(); foreach (Pawn pawn in pawns) { try { if (!GameComponent_BlaxCastes.IsGone(pawn) && !pawn.Dead && !CasteUtility.IsPlayerSide(pawn)) CasteManager.EndMembership(pawn); } catch (Exception e) { JoinHooks.LogOnce("Ending a membership", e); } } } /// One message per caste per tick, so buying ten slaves does not post ten messages. private static void SendMessages(Dictionary> joined) { if (BlaxCastesMod.Settings != null && !BlaxCastesMod.Settings.joinMessages) return; foreach (KeyValuePair> kv in joined) { List pawns = kv.Value; string text = MessageText(kv.Key, pawns); if (!text.NullOrEmpty()) Messages.Message(text, new LookTargets(pawns), MessageTypeDefOf.NeutralEvent, historical: false); } } /// The join message for pawns that joined one caste. public static string MessageText(Caste caste, List pawns) { if (caste == null || pawns == null || pawns.Count == 0) return null; if (pawns.Count == 1) return "BlaxCastes_JoinedCaste".Translate(pawns[0].Named("PAWN"), caste.label.Named("CASTE")); string names = pawns.Select(p => p.LabelShort).ToCommaList(useAnd: true); return "BlaxCastes_JoinedCasteMany".Translate(pawns.Count.Named("COUNT"), caste.label.Named("CASTE"), names.Named("PAWNS")); } } }