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
/// and the join queue. Nothing is stored on vanilla objects; the only vanilla data Castes writes is a
/// pawn's own policy fields. 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 bool firstLoadMessageShown;
private List membershipKeys;
private List membershipValues;
private static GameComponent_BlaxCastes cached;
private static Game cachedGame;
private static bool tickErrorLogged;
public GameComponent_BlaxCastes()
{
EnsureRows();
}
public GameComponent_BlaxCastes(Game game) : this()
{
}
/// 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)
{
// Don't keep the last game alive from the main menu.
cached = null;
cachedGame = null;
return null;
}
if (cachedGame == game && cached != null)
return cached;
GameComponent_BlaxCastes found = game.GetComponent();
if (found != null)
{
cached = found;
cachedGame = game;
}
return found;
}
}
/// 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;
public int NextCasteId => nextCasteId;
/// The message that points to Assign > Manage castes was posted in this save.
public bool FirstLoadMessageShown => firstLoadMessageShown;
// ---- 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);
/// 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;
}
}
// ---- writes, for CasteManager 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;
}
// ---- upkeep ------------------------------------------------------------------------
///
/// Drops membership and queue entries whose pawn is null, discarded, or destroyed without being
/// dead. 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));
return removed;
}
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): " + e);
}
}
}
public override void FinalizeInit()
{
cached = this;
cachedGame = Current.Game;
}
public override void StartedNewGame() => ShowFirstLoadMessageOnce();
public override void LoadedGame() => ShowFirstLoadMessageOnce();
/// 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);
}
}
// ---- save --------------------------------------------------------------------------
public override void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
Purge();
CasteManager.CheckPolicies(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_Values.Look(ref firstLoadMessageShown, "firstLoadMessageShown");
if (Scribe.mode == LoadSaveMode.LoadingVars)
{
cached = this;
cachedGame = Current.Game;
}
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
EnsureState();
Purge();
CasteManager.CheckPolicies(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();
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);
}
}
}