using System; using System.Collections.Generic; using Verse; namespace BlaxLaws { /// /// All Blax Laws state of one game: the lawbook rows and the cases (design: "Lawbook and cases in one /// GameComponent"). Laws are colony policy across every map, caravan and world pawn, so this is a /// GameComponent. Game.FillComponents adds it to a new game and after loading (Verse/Game.cs:345, /// 443-446, 472-489), so a save made without Laws loads with an empty book. After a plain unsubscribe /// the node loads as null with exactly 2 errors and FillComponents drops it (Verse/Game.cs:474). /// /// Read through the properties and lookups. Rows change only through Lawbook, cases only through /// CaseFiler, Enforcement and the punishment workers (CloseCase). Nothing of Laws is stored on vanilla /// objects, and no Laws def enters a vanilla save list. /// public class GameComponent_BlaxLaws : GameComponent { private List laws = new List(); private int nextLawId = 1; private List cases = new List(); private int nextCaseId = 1; /// A random number per save, for ids Laws hands to other mods later. Never 0 after the first tick. private int saveToken; // Not saved: cases by offender, rebuilt on load and kept on every add and prune. private readonly Dictionary> byOffender = new Dictionary>(); // 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 readonly List EmptyCases = new List(); public GameComponent_BlaxLaws() { } /// Called by the game for a new game and for a loaded one, before anything of the save is read. public GameComponent_BlaxLaws(Game game) : this() { // The hot-path flags and the queue belong to the last game: clear them before this one's hooks run. Watch.Clear(); Enforcement.Reset(); saveToken = NewToken(); if (game != null) Remember(this, game); } /// The component of the running game, or null when no game is loaded. public static GameComponent_BlaxLaws Instance { get { Game game = Current.Game; if (game == null) return null; if (cachedGame.TryGetTarget(out Game g) && g == game && cached.TryGetTarget(out GameComponent_BlaxLaws c) && c != null) return c; GameComponent_BlaxLaws found = game.GetComponent(); if (found != null) Remember(found, game); return found; } } private static void Remember(GameComponent_BlaxLaws comp, Game game) { cached.SetTarget(comp); cachedGame.SetTarget(game); } private static int NewToken() => new Random(Environment.TickCount ^ Guid.NewGuid().GetHashCode()).Next(1, int.MaxValue); // ---- reads --------------------------------------------------------------------------- /// The lawbook rows in display order. Do not change the list; use Lawbook. public IReadOnlyList Laws => laws; /// Every case, oldest first. Do not change the list. public IReadOnlyList Cases => cases; public int NextLawId => nextLawId; public int NextCaseId => nextCaseId; public int SaveToken => saveToken; public Law LawById(int id) { if (id <= 0) return null; for (int i = 0; i < laws.Count; i++) { if (laws[i].id == id) return laws[i]; } return null; } public LawCase CaseById(int id) { if (id <= 0) return null; for (int i = cases.Count - 1; i >= 0; i--) { if (cases[i].id == id) return cases[i]; } return null; } /// The cases filed against this pawn, oldest first. Empty for null or a pawn without cases. public IReadOnlyList CasesOf(Pawn pawn) { if (pawn != null && byOffender.TryGetValue(pawn, out List list)) return list; return EmptyCases; } /// True while any case isn't closed. The tick's fast path reads it. public bool AnyOpenCase { get { for (int i = cases.Count - 1; i >= 0; i--) { if (!cases[i].IsClosed) return true; } return false; } } /// The cases that aren't closed, as a new list (safe to change cases while walking it). public List OpenCases() { var result = new List(); foreach (LawCase c in cases) { if (!c.IsClosed) result.Add(c); } return result; } /// Open cases a row runs for, for "deleting a law with open cases asks first and names the count". public int OpenCaseCount(Law law) { if (law == null) return 0; int n = 0; foreach (LawCase c in cases) { if (!c.IsClosed && (c.planningLawId == law.id || c.didItLawId == law.id)) n++; } return n; } /// /// The pawn's newest case outside a break whose did-it row is this one, open or closed, or null. The /// cooldown reads it. /// public LawCase LatestActCaseOf(Pawn pawn, int lawId) { IReadOnlyList list = CasesOf(pawn); for (int i = list.Count - 1; i >= 0; i--) { LawCase c = list[i]; if (!c.IsBreakCase && c.didItLawId == lawId) return c; } return null; } /// Ticks two break start ticks may differ by and still name the same break (MentalState.age moves in steps of 30). public const int BreakStartTolerance = 120; /// The pawn's case for this break (same state def, started at the same tick), open or closed, or null. public LawCase BreakCaseOf(Pawn pawn, string stateDefName, int breakStartTick) { if (stateDefName.NullOrEmpty()) return null; IReadOnlyList list = CasesOf(pawn); for (int i = list.Count - 1; i >= 0; i--) { LawCase c = list[i]; if (c.breakState == stateDefName && Math.Abs(c.breakStartTick - breakStartTick) <= BreakStartTolerance) return c; } return null; } // ---- writes, for Lawbook, CaseFiler and Enforcement ---------------------------------------- internal int TakeLawId() { foreach (Law l in laws) { if (l.id >= nextLawId) nextLawId = l.id + 1; } return nextLawId++; } internal int TakeCaseId() { if (cases.Count > 0 && cases[cases.Count - 1].id >= nextCaseId) nextCaseId = cases[cases.Count - 1].id + 1; return nextCaseId++; } internal void AddLaw(Law law) => laws.Add(law); internal bool RemoveLaw(Law law) => laws.Remove(law); internal void MoveLaw(Law law, int index) { if (!laws.Remove(law)) return; laws.Insert(Math.Max(0, Math.Min(index, laws.Count)), law); } internal void AddCase(LawCase c) { cases.Add(c); Index(c); } /// Closes the case with a CaseOutcomes key. A closed case is pruned after "Keep closed cases". public void CloseCase(LawCase c, string outcome) { if (c == null) return; c.status = CaseStatus.Closed; c.outcome = outcome; c.closeTick = Find.TickManager?.TicksGame ?? 0; c.activePunishment = null; c.waitReason = null; } /// /// Removes closed cases that closed more than the given ticks ago. Returns the number removed. /// Runs on every save with "Keep closed cases". /// public int PruneClosedCases(int olderThanTicks) { int now = Find.TickManager?.TicksGame ?? 0; int removed = cases.RemoveAll(c => c == null || (c.IsClosed && c.closeTick >= 0 && now - c.closeTick > olderThanTicks)); if (removed > 0) RebuildIndex(); return removed; } private void Index(LawCase c) { if (c?.offender == null) return; if (!byOffender.TryGetValue(c.offender, out List list)) byOffender[c.offender] = list = new List(); list.Add(c); } private void RebuildIndex() { byOffender.Clear(); foreach (LawCase c in cases) Index(c); } // ---- game hooks ---------------------------------------------------------------------- public override void GameComponentTick() { // The empty book costs one count and one field read per tick. if (cases.Count == 0 && Enforcement.Pending == 0) return; try { Enforcement.Tick(this); } catch (Exception e) { HookGuard.Fail("Enforcement tick", e); } } public override void FinalizeInit() { Remember(this, Current.Game); // Log-once flags count per game, so a failure in a later game is not silent. LawsLog.ResetOnce(); try { ActCatalogue.EnsureBuilt(); Watch.Rebuild(); Enforcement.Reset(); Enforcement.Refill(this); } catch (Exception e) { HookGuard.Fail("Game start", e); } } // ---- save ---------------------------------------------------------------------------- public override void ExposeData() { if (Scribe.mode == LoadSaveMode.Saving) { try { PruneClosedCases(BlaxLawsMod.S.KeepClosedTicks); } catch (Exception e) { HookGuard.Fail("Pruning closed cases", e); } } Scribe_Values.Look(ref saveToken, "saveToken"); Scribe_Values.Look(ref nextLawId, "nextLawId", 1); Scribe_Collections.Look(ref laws, "laws", LookMode.Deep); Scribe_Values.Look(ref nextCaseId, "nextCaseId", 1); Scribe_Collections.Look(ref cases, "cases", LookMode.Deep); if (Scribe.mode == LoadSaveMode.LoadingVars) Remember(this, Current.Game); if (Scribe.mode == LoadSaveMode.PostLoadInit) EnsureState(); } /// Missing lists, null entries and ids that would repeat. private void EnsureState() { laws ??= new List(); laws.RemoveAll(l => l == null || l.actKey.NullOrEmpty()); cases ??= new List(); cases.RemoveAll(c => c == null); if (saveToken == 0) saveToken = NewToken(); foreach (Law l in laws) { if (l.id >= nextLawId) nextLawId = l.id + 1; } foreach (LawCase c in cases) { if (c.id >= nextCaseId) nextCaseId = c.id + 1; } RebuildIndex(); } } }