rimworld-blax-laws/Source/BlaxLaws/GameComponent_BlaxLaws.cs

482 lines
19 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// 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.
/// </summary>
public class GameComponent_BlaxLaws : GameComponent
{
private List<Law> laws = new List<Law>();
private int nextLawId = 1;
private List<LawCase> cases = new List<LawCase>();
private int nextCaseId = 1;
// The court places, at most about one per map plus crated ones; no map key (design: "Court place").
private List<CourtPlaceEntry> courtPlaces = new List<CourtPlaceEntry>();
/// <summary>A random number per save, for ids Laws hands to other mods later. Never 0 after the first tick.</summary>
private int saveToken;
// Not saved: cases by offender, rebuilt on load and kept on every add and prune.
private readonly Dictionary<Pawn, List<LawCase>> byOffender = new Dictionary<Pawn, List<LawCase>>();
// Weak, so the main menu never keeps the last game and its pawns alive.
private static readonly System.WeakReference<GameComponent_BlaxLaws> cached = new System.WeakReference<GameComponent_BlaxLaws>(null);
private static readonly System.WeakReference<Game> cachedGame = new System.WeakReference<Game>(null);
private static readonly List<LawCase> EmptyCases = new List<LawCase>();
public GameComponent_BlaxLaws()
{
}
/// <summary>Called by the game for a new game and for a loaded one, before anything of the save is read.</summary>
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);
}
/// <summary>The component of the running game, or null when no game is loaded.</summary>
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<GameComponent_BlaxLaws>();
if (found != null)
Remember(found, game);
return found;
}
}
// Internal for the old-save test, which loads a second component and then gives the game's back.
internal 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 ---------------------------------------------------------------------------
/// <summary>The lawbook rows in display order. Do not change the list; use Lawbook.</summary>
public IReadOnlyList<Law> Laws => laws;
/// <summary>Every case, oldest first. Do not change the list.</summary>
public IReadOnlyList<LawCase> 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;
}
/// <summary>The cases filed against this pawn, oldest first. Empty for null or a pawn without cases.</summary>
public IReadOnlyList<LawCase> CasesOf(Pawn pawn)
{
if (pawn != null && byOffender.TryGetValue(pawn, out List<LawCase> list))
return list;
return EmptyCases;
}
/// <summary>True while any case isn't closed. The tick's fast path reads it.</summary>
public bool AnyOpenCase
{
get
{
for (int i = cases.Count - 1; i >= 0; i--)
{
if (!cases[i].IsClosed)
return true;
}
return false;
}
}
/// <summary>The cases that aren't closed, as a new list (safe to change cases while walking it).</summary>
public List<LawCase> OpenCases()
{
var result = new List<LawCase>();
foreach (LawCase c in cases)
{
if (!c.IsClosed)
result.Add(c);
}
return result;
}
/// <summary>Open cases a row runs for, for "deleting a law with open cases asks first and names the count".</summary>
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;
}
/// <summary>
/// The pawn's newest case outside a break whose did-it row is this one, open or closed, or null. The
/// cooldown reads it.
/// </summary>
public LawCase LatestActCaseOf(Pawn pawn, int lawId)
{
IReadOnlyList<LawCase> 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;
}
/// <summary>Ticks two break start ticks may differ by and still name the same break (MentalState.age moves in steps of 30).</summary>
public const int BreakStartTolerance = 120;
/// <summary>The pawn's case for this break (same state def, started at the same tick), open or closed, or null.</summary>
public LawCase BreakCaseOf(Pawn pawn, string stateDefName, int breakStartTick)
{
if (stateDefName.NullOrEmpty())
return null;
IReadOnlyList<LawCase> 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);
}
/// <summary>Closes the case with a CaseOutcomes key. A closed case is pruned after "Keep closed cases".</summary>
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;
}
/// <summary>
/// Removes closed cases that closed more than the given ticks ago. Returns the number removed.
/// Runs on every save with "Keep closed cases".
/// </summary>
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<LawCase> list))
byOffender[c.offender] = list = new List<LawCase>();
list.Add(c);
}
private void RebuildIndex()
{
byOffender.Clear();
foreach (LawCase c in cases)
Index(c);
}
// ---- court place, for CourtPlace ------------------------------------------------------------
/// <summary>The stored entries, newest set last. Do not change the list; use CourtPlace.</summary>
public IReadOnlyList<CourtPlaceEntry> CourtPlaceEntries => courtPlaces;
/// <summary>A place is stored, crated ones included. The spawn hook's gate.</summary>
internal bool AnyCourtPlace => courtPlaces.Count > 0;
/// <summary>
/// The map's court place: of the entries spawned on the map, the one set last; null when it fails
/// CourtPlace.Valid (claimed by another faction). A map never holds two spawned entries for long: Set
/// drops the map's others and a stored place that spawns drops the older ones at once
/// (CourtPlaceSpawned), so a place lost later never falls back to an older one.
/// One count check while no place exists.
/// </summary>
internal Building CourtPlaceOn(Map map)
{
if (map == null || courtPlaces.Count == 0)
return null;
CourtPlaceEntry best = null;
for (int i = 0; i < courtPlaces.Count; i++)
{
CourtPlaceEntry e = courtPlaces[i];
Building b = e?.building;
if (b == null || b.Destroyed || !b.Spawned || b.Map != map)
continue;
if (best == null || e.setTick >= best.setTick)
best = e;
}
return best != null && CourtPlace.Valid(best.building) ? best.building : null;
}
internal void SetCourtPlace(Building b)
{
Map map = b.Map;
courtPlaces.RemoveAll(e => e?.building == null || e.building == b || e.building.MapHeld == map);
courtPlaces.Add(new CourtPlaceEntry(b, Find.TickManager?.TicksGame ?? 0));
}
/// <summary>
/// A building spawned on a map (hook P, Building.SpawnSetup). When it is a stored place, installed from
/// its crate, only the entry set last among those spawned on that map stays, as CleanCourtPlaces keeps
/// it: a crate that arrives on a map with a newer place loses to it, and a newer crate replaces the
/// older place. Resolved now, not at the next save, so the result never depends on save timing.
/// </summary>
internal void CourtPlaceSpawned(Building b)
{
Map map = b.Map;
if (map == null)
return;
bool stored = false;
CourtPlaceEntry best = null;
for (int i = 0; i < courtPlaces.Count; i++)
{
CourtPlaceEntry e = courtPlaces[i];
Building other = e?.building;
if (other == b)
stored = true;
if (other == null || other.Destroyed || !other.Spawned || other.Map != map)
continue;
if (best == null || e.setTick >= best.setTick)
best = e;
}
if (!stored || best == null)
return;
courtPlaces.RemoveAll(e => e != best && e?.building != null && !e.building.Destroyed && e.building.Spawned && e.building.Map == map);
}
internal void ClearCourtPlace(Map map)
{
if (map == null)
return;
courtPlaces.RemoveAll(e => e?.building == null || e.building.MapHeld == map);
}
/// <summary>
/// Drops entries whose building is gone: null, destroyed (deconstructed, burnt, a destroyed crate, a
/// removed map, Verse/Thing.cs:1123-1143) or unspawned outside any container, which nothing would save.
/// Keeps a crated or carried place, so it follows its crate. Of the entries spawned on one map, only the
/// one set last stays: a crate installed on a map that already has a place loses to the place set later.
/// Only after the maps have spawned their things (FinalizeInit, saving, a write).
/// </summary>
internal void CleanCourtPlaces()
{
if (courtPlaces.Count == 0)
return;
courtPlaces.RemoveAll(e => e?.building == null || e.building.Destroyed || (!e.building.Spawned && e.building.holdingOwner == null));
for (int i = courtPlaces.Count - 1; i >= 0; i--)
{
CourtPlaceEntry e = courtPlaces[i];
if (!e.building.Spawned)
continue;
for (int j = 0; j < courtPlaces.Count; j++)
{
CourtPlaceEntry o = courtPlaces[j];
if (j == i || !o.building.Spawned || o.building.Map != e.building.Map)
continue;
if (o.setTick > e.setTick || (o.setTick == e.setTick && j > i))
{
courtPlaces.RemoveAt(i);
break;
}
}
}
}
// ---- 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;
if (LawsTestHooks.TickSuspended)
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);
}
// Maps have spawned their things by now (Verse/Game.cs:614-636), so unspawned entries are real.
HookGuard.Run("Cleaning court places", CleanCourtPlaces);
}
// ---- save ----------------------------------------------------------------------------
public override void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
try
{
PruneClosedCases(BlaxLawsMod.S.KeepClosedTicks);
}
catch (Exception e)
{
HookGuard.Fail("Pruning closed cases", e);
}
HookGuard.Run("Saving court places", CleanCourtPlaces);
}
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);
// Deep, not a bare reference list: a 1.0.0 save without this node loads it as null and registers
// no ids (Verse/Scribe_Collections.cs:372-379), where a missing reference list would warn on every
// load (Verse/LoadIDsWantedBank.cs:33-55).
Scribe_Collections.Look(ref courtPlaces, "courtPlaces", LookMode.Deep);
if (Scribe.mode == LoadSaveMode.LoadingVars)
Remember(this, Current.Game);
if (Scribe.mode == LoadSaveMode.PostLoadInit)
EnsureState();
}
/// <summary>Missing lists, null entries and ids that would repeat.</summary>
private void EnsureState()
{
laws ??= new List<Law>();
laws.RemoveAll(l => l == null || l.actKey.NullOrEmpty());
cases ??= new List<LawCase>();
cases.RemoveAll(c => c == null);
// Things on maps spawn after this (Verse/Game.cs:611-619): drop only what is gone for sure here.
courtPlaces ??= new List<CourtPlaceEntry>();
courtPlaces.RemoveAll(e => e?.building == null || e.building.Destroyed);
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();
}
}
}