rimworld-blax-castes/Source/BlaxCastes/GameComponent_BlaxCastes.cs

534 lines
20 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using RimWorld.Planet;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// 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.
/// </summary>
public class GameComponent_BlaxCastes : GameComponent
{
public const int SweepInterval = 2500;
private List<Caste> castes = new List<Caste>();
private int nextCasteId = 1;
private Caste defaultCaste;
private Dictionary<Pawn, CasteMembership> memberships = new Dictionary<Pawn, CasteMembership>();
private List<JoinRow> joinRows = new List<JoinRow>();
private List<QueuedJoin> joinQueue = new List<QueuedJoin>();
private Dictionary<string, FormerCaste> formerCastes = new Dictionary<string, FormerCaste>();
private bool firstLoadMessageShown;
private bool starterCastesSeeded;
private bool slaveCasteOwed;
private List<string> overlapWarned = new List<string>();
// 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<Pawn> leftPawns = new HashSet<Pawn>();
private List<Pawn> membershipKeys;
private List<CasteMembership> membershipValues;
private List<string> formerKeys;
private List<FormerCaste> formerValues;
// Weak, so the main menu never keeps the last game and its pawns alive.
private static readonly System.WeakReference<GameComponent_BlaxCastes> cached = new System.WeakReference<GameComponent_BlaxCastes>(null);
private static readonly System.WeakReference<Game> cachedGame = new System.WeakReference<Game>(null);
private static bool tickErrorLogged;
public GameComponent_BlaxCastes()
{
EnsureRows();
}
/// <summary>Called by the game for a new game and for a loaded one, before anything of the save is read.</summary>
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();
}
/// <summary>The component of the running game, or null when no game is loaded.</summary>
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<GameComponent_BlaxCastes>();
if (found != null)
Remember(found, game);
return found;
}
}
private static void Remember(GameComponent_BlaxCastes comp, Game game)
{
cached.SetTarget(comp);
cachedGame.SetTarget(game);
}
/// <summary>The castes in display order. Do not change the list; use CasteManager.</summary>
public List<Caste> Castes => castes;
/// <summary>What join rows set to "Default caste" use. Null: those rows act as No caste.</summary>
public Caste DefaultCaste => defaultCaste;
public IReadOnlyDictionary<Pawn, CasteMembership> Memberships => memberships;
public IReadOnlyList<JoinRow> JoinRows => joinRows;
/// <summary>Joins waiting for the next tick. Owned by JoinDefaults.</summary>
public List<QueuedJoin> JoinQueue => joinQueue;
/// <summary>Former-caste records by ThingID. Read here; written through CasteManager and JoinDefaults.</summary>
public IReadOnlyDictionary<string, FormerCaste> FormerCastes => formerCastes;
/// <summary>Pawns that left the player side since the last tick. Owned by JoinDefaults.</summary>
internal HashSet<Pawn> LeftPawns => leftPawns;
public int NextCasteId => nextCasteId;
/// <summary>The message that points to Assign > Manage castes was posted in this save.</summary>
public bool FirstLoadMessageShown => firstLoadMessageShown;
/// <summary>The starter castes were added to this save (or the save already had castes when it was checked).</summary>
public bool StarterCastesSeeded => starterCastesSeeded;
/// <summary>The starter castes were added without Ideology, so the Slave caste comes on the first load with it (StarterCastes.AddSlaveCasteIfOwed).</summary>
public bool SlaveCasteOwed => slaveCasteOwed;
// ---- lookups -----------------------------------------------------------------------
public CasteMembership MembershipOf(Pawn pawn)
{
if (pawn == null)
return null;
memberships.TryGetValue(pawn, out CasteMembership m);
return m;
}
/// <summary>The pawn's caste, or null when it has none or is casteless by choice.</summary>
public Caste CasteOf(Pawn pawn) => MembershipOf(pawn)?.caste;
public List<Pawn> MembersOf(Caste caste)
{
var result = new List<Pawn>();
if (caste == null)
return result;
foreach (KeyValuePair<Pawn, CasteMembership> 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;
}
/// <summary>The pawn's former-caste record, or null.</summary>
public FormerCaste FormerOf(Pawn pawn)
{
if (pawn == null)
return null;
formerCastes.TryGetValue(pawn.ThingID, out FormerCaste f);
return f;
}
/// <summary>The row for a join reason, created at No caste if the save has none yet.</summary>
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;
}
/// <summary>The caste a join row puts a pawn into, or null for No caste.</summary>
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 SetSlaveCasteOwed(bool owed) => slaveCasteOwed = owed;
internal void MarkFirstLoadMessageShown() => firstLoadMessageShown = true;
// ---- upkeep ------------------------------------------------------------------------
/// <summary>
/// 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.
/// </summary>
public int Purge()
{
int removed = 0;
List<Pawn> gone = null;
foreach (KeyValuePair<Pawn, CasteMembership> kv in memberships)
{
if (IsGone(kv.Key) || kv.Value == null)
(gone ??= new List<Pawn>()).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;
}
/// <summary>
/// Removes former-caste records older than formerCasteDays, and records whose caste is gone (a No
/// caste record has none). Returns the number removed.
/// </summary>
public int PruneFormerCastes()
{
int now = Find.TickManager?.TicksGame ?? 0;
List<string> stale = null;
foreach (KeyValuePair<string, FormerCaste> 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<string>()).Add(kv.Key);
}
if (stale == null)
return 0;
foreach (string id in stale)
formerCastes.Remove(id);
return stale.Count;
}
/// <summary>Removes every former-caste record that points at this caste id.</summary>
internal int RemoveFormerCastesOf(int casteId)
{
List<string> hit = null;
foreach (KeyValuePair<string, FormerCaste> kv in formerCastes)
{
if (kv.Value != null && !kv.Value.casteless && kv.Value.casteId == casteId)
(hit ??= new List<string>()).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();
}
/// <summary>Ends the memberships of pawns that are no longer player faction or player prisoners.</summary>
public int Sweep()
{
Purge();
List<Pawn> left = null;
foreach (Pawn p in memberships.Keys)
{
if (!CasteUtility.IsPlayerSide(p))
(left ??= new List<Pawn>()).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();
}
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>
/// A loaded save: the starter castes once, only if the save has no castes, with one message that
/// replaces the first-load message. A save seeded without Ideology gets the Slave caste on its first
/// load with Ideology, with its own message. Nobody is moved; the manager's "Assign by status" does that.
/// </summary>
public override void LoadedGame()
{
bool seeded = false;
Caste slaveAdded = null;
try
{
seeded = StarterCastes.SeedOnLoad(this);
slaveAdded = StarterCastes.AddSlaveCasteIfOwed(this);
}
catch (Exception e)
{
Log.Error("[Blax Castes] Adding the starter castes failed: " + e);
}
if (seeded)
ShowSeededMessage();
else
ShowFirstLoadMessageOnce();
if (slaveAdded != null)
{
try
{
StarterCastes.ShowSlaveCasteAddedMessage(slaveAdded);
}
catch (Exception e)
{
Log.Error("[Blax Castes] Slave caste message failed: " + e);
}
}
ShowOverlapMessage();
}
/// <summary>The message that points to Assign > Manage castes, once per save.</summary>
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_Values.Look(ref slaveCasteOwed, "slaveCasteOwed");
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);
}
}
/// <summary>Missing lists (older saves), null entries and rows that point at nothing.</summary>
private void EnsureState()
{
castes ??= new List<Caste>();
castes.RemoveAll(c => c == null);
memberships ??= new Dictionary<Pawn, CasteMembership>();
joinRows ??= new List<JoinRow>();
joinRows.RemoveAll(r => r == null || r.reason.NullOrEmpty());
joinQueue ??= new List<QueuedJoin>();
formerCastes ??= new Dictionary<string, FormerCaste>();
overlapWarned ??= new List<string>();
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);
}
}
}