using System; using System.Collections.Generic; using RimWorld.Planet; using Verse; namespace BlaxCastes { /// /// All Blax Castes state for one game: the castes, the default caste, the memberships, the join rows, /// the join queue and the former-caste records. Nothing is stored on vanilla objects; the only vanilla /// data Castes writes is a pawn's own policy fields, medical care, timetable and work priorities, plus /// its Weapons Tab Reborn loadout through that mod's API. Read through the properties; change through /// CasteManager. Added to a running save by Game.ExposeData (FillComponents), so adding the mod /// mid-save works. /// public class GameComponent_BlaxCastes : GameComponent { public const int SweepInterval = 2500; private List castes = new List(); private int nextCasteId = 1; private Caste defaultCaste; private Dictionary memberships = new Dictionary(); private List joinRows = new List(); private List joinQueue = new List(); private Dictionary formerCastes = new Dictionary(); private bool firstLoadMessageShown; private bool starterCastesSeeded; private List overlapWarned = new List(); // Pawns that left the player side, checked on the next tick. Not saved: the 2500-tick sweep ends // any membership a save cut short. Held here so it goes away with the game. private readonly HashSet leftPawns = new HashSet(); private List membershipKeys; private List membershipValues; private List formerKeys; private List formerValues; // Weak, so the main menu never keeps the last game and its pawns alive. private static readonly System.WeakReference cached = new System.WeakReference(null); private static readonly System.WeakReference cachedGame = new System.WeakReference(null); private static bool tickErrorLogged; public GameComponent_BlaxCastes() { EnsureRows(); } /// Called by the game for a new game and for a loaded one, before anything of the save is read. public GameComponent_BlaxCastes(Game game) : this() { // A Weapons Tab Reborn call that failed in the last game is tried again in this one. WeaponsTab.ResetForGame(); } /// The component of the running game, or null when no game is loaded. public static GameComponent_BlaxCastes Instance { get { Game game = Current.Game; if (game == null) return null; if (cachedGame.TryGetTarget(out Game g) && g == game && cached.TryGetTarget(out GameComponent_BlaxCastes c) && c != null) return c; GameComponent_BlaxCastes found = game.GetComponent(); if (found != null) Remember(found, game); return found; } } private static void Remember(GameComponent_BlaxCastes comp, Game game) { cached.SetTarget(comp); cachedGame.SetTarget(game); } /// The castes in display order. Do not change the list; use CasteManager. public List Castes => castes; /// What join rows set to "Default caste" use. Null: those rows act as No caste. public Caste DefaultCaste => defaultCaste; public IReadOnlyDictionary Memberships => memberships; public IReadOnlyList JoinRows => joinRows; /// Joins waiting for the next tick. Owned by JoinDefaults. public List JoinQueue => joinQueue; /// Former-caste records by ThingID. Read here; written through CasteManager and JoinDefaults. public IReadOnlyDictionary FormerCastes => formerCastes; /// Pawns that left the player side since the last tick. Owned by JoinDefaults. internal HashSet LeftPawns => leftPawns; public int NextCasteId => nextCasteId; /// The message that points to Assign > Manage castes was posted in this save. public bool FirstLoadMessageShown => firstLoadMessageShown; /// The starter castes were added to this save (or the save already had castes when it was checked). public bool StarterCastesSeeded => starterCastesSeeded; // ---- lookups ----------------------------------------------------------------------- public CasteMembership MembershipOf(Pawn pawn) { if (pawn == null) return null; memberships.TryGetValue(pawn, out CasteMembership m); return m; } /// The pawn's caste, or null when it has none or is casteless by choice. public Caste CasteOf(Pawn pawn) => MembershipOf(pawn)?.caste; public List MembersOf(Caste caste) { var result = new List(); if (caste == null) return result; foreach (KeyValuePair kv in memberships) { if (kv.Key != null && kv.Value != null && kv.Value.caste == caste) result.Add(kv.Key); } return result; } public bool HasCaste(Caste caste) => caste != null && castes.Contains(caste); public Caste CasteById(int id) { for (int i = 0; i < castes.Count; i++) { if (castes[i] != null && castes[i].id == id) return castes[i]; } return null; } /// The pawn's former-caste record, or null. public FormerCaste FormerOf(Pawn pawn) { if (pawn == null) return null; formerCastes.TryGetValue(pawn.ThingID, out FormerCaste f); return f; } /// The row for a join reason, created at No caste if the save has none yet. public JoinRow GetRow(string reason) { for (int i = 0; i < joinRows.Count; i++) { if (joinRows[i].reason == reason) return joinRows[i]; } var row = new JoinRow(reason); joinRows.Add(row); return row; } /// The caste a join row puts a pawn into, or null for No caste. public Caste ResolveRow(string reason) { JoinRow row = GetRow(reason); switch (row.mode) { case JoinRowMode.DefaultCaste: return HasCaste(defaultCaste) ? defaultCaste : null; case JoinRowMode.SpecificCaste: return HasCaste(row.caste) ? row.caste : null; default: return null; } } public bool OverlapWarned(string packageId) => overlapWarned.Contains(packageId.ToLowerInvariant()); internal void MarkOverlapWarned(string packageId) { string id = packageId.ToLowerInvariant(); if (!overlapWarned.Contains(id)) overlapWarned.Add(id); } // ---- writes, for CasteManager and JoinDefaults only -------------------------------- internal int TakeNextId() { int max = 0; foreach (Caste c in castes) { if (c != null && c.id > max) max = c.id; } if (nextCasteId <= max) nextCasteId = max + 1; return nextCasteId++; } internal void AddCaste(Caste caste) => castes.Add(caste); internal void RemoveCaste(Caste caste) => castes.Remove(caste); internal void SetDefaultRaw(Caste caste) => defaultCaste = caste; internal void SetMembership(Pawn pawn, CasteMembership membership) => memberships[pawn] = membership; internal bool RemoveMembership(Pawn pawn) => pawn != null && memberships.Remove(pawn); internal void SetRowRaw(string reason, JoinRowMode mode, Caste caste) { JoinRow row = GetRow(reason); row.mode = mode; row.caste = mode == JoinRowMode.SpecificCaste ? caste : null; } internal void SetFormer(Pawn pawn, FormerCaste record) { if (pawn != null && record != null) formerCastes[pawn.ThingID] = record; } internal bool RemoveFormer(Pawn pawn) => pawn != null && formerCastes.Remove(pawn.ThingID); internal void MarkStarterCastesSeeded() => starterCastesSeeded = true; internal void MarkFirstLoadMessageShown() => firstLoadMessageShown = true; // ---- upkeep ------------------------------------------------------------------------ /// /// Drops membership and queue entries whose pawn is null, discarded, or destroyed without being /// dead, and former-caste records that are stale or point at a deleted caste. A dead pawn keeps its /// caste in case it is resurrected, as long as its corpse or the world still holds it, so its /// reference resolves on load. Returns the number removed. /// public int Purge() { int removed = 0; List gone = null; foreach (KeyValuePair kv in memberships) { if (IsGone(kv.Key) || kv.Value == null) (gone ??= new List()).Add(kv.Key); } if (gone != null) { foreach (Pawn p in gone) { if (memberships.Remove(p)) removed++; } } removed += joinQueue.RemoveAll(q => q == null || IsGone(q.pawn)); removed += PruneFormerCastes(); return removed; } /// /// Removes former-caste records older than formerCasteDays, and records whose caste is gone (a No /// caste record has none). Returns the number removed. /// public int PruneFormerCastes() { int now = Find.TickManager?.TicksGame ?? 0; List stale = null; foreach (KeyValuePair kv in formerCastes) { if (kv.Key.NullOrEmpty() || kv.Value == null || (!kv.Value.casteless && CasteById(kv.Value.casteId) == null) || JoinDefaults.FormerExpired(kv.Value, now)) (stale ??= new List()).Add(kv.Key); } if (stale == null) return 0; foreach (string id in stale) formerCastes.Remove(id); return stale.Count; } /// Removes every former-caste record that points at this caste id. internal int RemoveFormerCastesOf(int casteId) { List hit = null; foreach (KeyValuePair kv in formerCastes) { if (kv.Value != null && !kv.Value.casteless && kv.Value.casteId == casteId) (hit ??= new List()).Add(kv.Key); } if (hit == null) return 0; foreach (string id in hit) formerCastes.Remove(id); return hit.Count; } public static bool IsGone(Pawn pawn) { if (pawn == null || pawn.Discarded) return true; if (!pawn.Destroyed) return false; if (!pawn.Dead) return true; return pawn.Corpse == null && !pawn.IsWorldPawn(); } /// Ends the memberships of pawns that are no longer player faction or player prisoners. public int Sweep() { Purge(); List left = null; foreach (Pawn p in memberships.Keys) { if (!CasteUtility.IsPlayerSide(p)) (left ??= new List()).Add(p); } if (left == null) return 0; foreach (Pawn p in left) CasteManager.EndMembership(p); return left.Count; } public override void GameComponentTick() { try { JoinDefaults.ApplyQueue(); if (Find.TickManager.TicksGame % SweepInterval == 0) Sweep(); } catch (Exception e) { if (!tickErrorLogged) { tickErrorLogged = true; Log.Error("[Blax Castes] Tick failed (logged once per game): " + e); } } } public override void FinalizeInit() { Remember(this, Current.Game); // Log-once flags count per game, so a failure in a later save is not silent. tickErrorLogged = false; JoinHooks.ResetLogOnce(); } /// /// A new game: the starter castes, then the starting pawns go into the caste of their status row. /// Joins queued while the colony was generated are not joins, so the queue starts empty. /// public override void StartedNewGame() { try { joinQueue.Clear(); leftPawns.Clear(); if (StarterCastes.SeedNewGame(this) && JoinDefaults.Active) CasteManager.AssignByStatus(); } catch (Exception e) { Log.Error("[Blax Castes] Adding the starter castes failed: " + e); } ShowFirstLoadMessageOnce(); ShowOverlapMessage(); } /// /// A loaded save: the starter castes once, only if the save has no castes, with one message that /// replaces the first-load message. Nobody is moved; the manager's "Assign by status" does that. /// public override void LoadedGame() { bool seeded = false; try { seeded = StarterCastes.SeedOnLoad(this); } catch (Exception e) { Log.Error("[Blax Castes] Adding the starter castes failed: " + e); } if (seeded) ShowSeededMessage(); else ShowFirstLoadMessageOnce(); ShowOverlapMessage(); } /// The message that points to Assign > Manage castes, once per save. private void ShowFirstLoadMessageOnce() { try { if (!firstLoadMessageShown) firstLoadMessageShown = Dialog_ManageCastes.ShowFirstLoadMessage(); } catch (Exception e) { Log.Error("[Blax Castes] First-load message failed: " + e); } } private void ShowSeededMessage() { try { StarterCastes.ShowSeededMessage(this); firstLoadMessageShown = true; } catch (Exception e) { Log.Error("[Blax Castes] Starter caste message failed: " + e); } } private void ShowOverlapMessage() { try { OverlapWarnings.ShowMessageOnce(this); } catch (Exception e) { Log.Error("[Blax Castes] Overlap warning failed: " + e); } } // ---- save -------------------------------------------------------------------------- public override void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving) { Purge(); CasteManager.CheckSlots(this); } Scribe_Collections.Look(ref castes, "castes", LookMode.Deep); Scribe_Values.Look(ref nextCasteId, "nextCasteId", 1); Scribe_References.Look(ref defaultCaste, "defaultCaste"); Scribe_Collections.Look(ref memberships, "memberships", LookMode.Reference, LookMode.Deep, ref membershipKeys, ref membershipValues, logNullErrors: false, saveDestroyedKeys: true); Scribe_Collections.Look(ref joinRows, "joinRows", LookMode.Deep); Scribe_Collections.Look(ref joinQueue, "joinQueue", LookMode.Deep); Scribe_Collections.Look(ref formerCastes, "formerCastes", LookMode.Value, LookMode.Deep, ref formerKeys, ref formerValues); Scribe_Values.Look(ref firstLoadMessageShown, "firstLoadMessageShown"); Scribe_Values.Look(ref starterCastesSeeded, "starterCastesSeeded"); Scribe_Collections.Look(ref overlapWarned, "overlapWarned", LookMode.Value); if (Scribe.mode == LoadSaveMode.LoadingVars) Remember(this, Current.Game); if (Scribe.mode == LoadSaveMode.PostLoadInit) { EnsureState(); Purge(); CasteManager.CheckSlots(this); } } /// Missing lists (older saves), null entries and rows that point at nothing. private void EnsureState() { castes ??= new List(); castes.RemoveAll(c => c == null); memberships ??= new Dictionary(); joinRows ??= new List(); joinRows.RemoveAll(r => r == null || r.reason.NullOrEmpty()); joinQueue ??= new List(); formerCastes ??= new Dictionary(); overlapWarned ??= new List(); EnsureRows(); if (defaultCaste != null && !castes.Contains(defaultCaste)) defaultCaste = null; foreach (JoinRow row in joinRows) { if (row.mode == JoinRowMode.SpecificCaste && !HasCaste(row.caste)) { row.mode = JoinRowMode.NoCaste; row.caste = null; } if (row.mode != JoinRowMode.SpecificCaste) row.caste = null; } foreach (CasteMembership m in memberships.Values) { if (m != null && m.caste != null && !castes.Contains(m.caste)) m.caste = null; } foreach (Caste c in castes) { if (c.id >= nextCasteId) nextCasteId = c.id + 1; } } private void EnsureRows() { foreach (string reason in JoinReason.Rows) GetRow(reason); } } }