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

498 lines
22 KiB
C#

using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// Every change to castes, memberships, join rows and the default caste goes through here, so the
/// rules (member sync, delete fallbacks, the enabled switch) hold no matter which window or hook
/// made the change. Methods do nothing and return false or null when no game is loaded.
/// </summary>
public static class CasteManager
{
private static GameComponent_BlaxCastes Comp => GameComponent_BlaxCastes.Instance;
private static int Now => Find.TickManager?.TicksGame ?? 0;
// ---- castes ------------------------------------------------------------------------
/// <summary>A new caste with the next free id, labelled "Caste N", managing nothing.</summary>
public static Caste CreateCaste(string label = null)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null)
return null;
int id = comp.TakeNextId();
var caste = new Caste(id, label.NullOrEmpty() ? (string)"BlaxCastes_NewCasteLabel".Translate(id) : label);
comp.AddCaste(caste);
return caste;
}
/// <summary>A new caste with every slot copied from the source, the vanilla duplicate way.</summary>
public static Caste DuplicateCaste(Caste source)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || source == null)
return null;
Caste copy = CreateCaste();
copy.CopyFrom(source);
return copy;
}
/// <summary>
/// Removes the caste. Its members become casteless and keep their current policies, join rows
/// that point at it fall back to No caste, it stops being the default, and former-caste records
/// that point at it are dropped.
/// </summary>
public static bool DeleteCaste(Caste caste)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste))
return false;
comp.RemoveFormerCastesOf(caste.id);
foreach (Pawn member in comp.MembersOf(caste))
{
if (CasteUtility.CanBeMember(member))
comp.SetMembership(member, new CasteMembership(null, false, JoinReason.CasteDeleted, Now));
else
comp.RemoveMembership(member);
}
foreach (JoinRow row in comp.JoinRows)
{
if (row.mode == JoinRowMode.SpecificCaste && row.caste == caste)
comp.SetRowRaw(row.reason, JoinRowMode.NoCaste, null);
}
if (comp.DefaultCaste == caste)
comp.SetDefaultRaw(null);
comp.RemoveCaste(caste);
return true;
}
/// <summary>Sets the caste that "Default caste" rows use. Null clears it, so those rows act as No caste.</summary>
public static bool SetDefault(Caste caste)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || (caste != null && !comp.HasCaste(caste)))
return false;
comp.SetDefaultRaw(caste);
return true;
}
/// <summary>
/// Changes one slot. Members still on the old value get the new one; members on another value
/// keep it (the Follow rule). A slot that was unmanaged had no old value, so every member gets
/// the new one. Unmanaging a slot changes no pawn. The schedule compares the whole day; work
/// priorities go type by type (see SetWorkPriority). Returns how many members were moved.
/// </summary>
public static int SetSlot(Caste caste, CasteSlot slot, object newValue)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste))
return 0;
if (!CasteUtility.FitsSlot(slot, newValue))
{
Log.Warning("[Blax Castes] " + newValue.GetType().Name + " does not fit the " + slot + " slot of " + caste.label + ".");
return 0;
}
newValue = CasteUtility.NormalizeSlotValue(slot, newValue);
if (CasteUtility.IsPolicySlot(slot) && slot != CasteSlot.MedCare && newValue != null && !CasteUtility.PolicyExists((Policy)newValue))
{
Log.Warning("[Blax Castes] Policy " + ((Policy)newValue).label + " is not in the game's database; " + caste.label + " keeps its " + slot + " slot.");
return 0;
}
if (slot == CasteSlot.Loadout && newValue is int id && id >= 0 && !WeaponsTab.Exists(id))
{
Log.Warning("[Blax Castes] Weapon loadout " + id + " is not one of Weapons Tab Reborn's loadouts; " + caste.label + " keeps its loadout slot.");
return 0;
}
object oldValue = caste.GetSlot(slot);
bool wasManaged = caste.IsManaged(slot);
if (CasteUtility.SameValue(oldValue, newValue))
return 0;
caste.SetSlotRaw(slot, newValue);
if (!caste.IsManaged(slot) || !BlaxCastesMod.Enabled)
return 0;
if (slot == CasteSlot.Work)
return SyncWork(comp, caste, oldValue as IReadOnlyDictionary<string, int>);
int moved = 0;
foreach (Pawn member in comp.MembersOf(caste))
{
if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, slot))
continue;
if (wasManaged && !CasteUtility.Matches(member, slot, oldValue))
continue;
if (CasteUtility.WriteSlot(member, slot, newValue))
moved++;
}
return moved;
}
/// <summary>
/// The Follow rule per work type: for each type whose priority changed, members whose priority equals
/// the old one get the new one; a type that was not listed before reaches every member. A type that
/// is no longer listed moves nobody.
/// </summary>
private static int SyncWork(GameComponent_BlaxCastes comp, Caste caste, IReadOnlyDictionary<string, int> oldValues)
{
int moved = 0;
foreach (Pawn member in comp.MembersOf(caste))
{
if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, CasteSlot.Work))
continue;
bool wrote = false;
foreach (KeyValuePair<string, int> kv in caste.WorkPriorities)
{
if (oldValues != null && oldValues.TryGetValue(kv.Key, out int old))
{
if (old == kv.Value || !WorkSlot.Matches(member, kv.Key, old))
continue;
}
if (WorkSlot.WriteType(member, kv.Key, kv.Value))
wrote = true;
}
if (wrote)
moved++;
}
return moved;
}
/// <summary>
/// Sets one work type's priority (0 to 4), or leaves it alone with null. Members follow per type.
/// Returns how many members were moved.
/// </summary>
public static int SetWorkPriority(Caste caste, string workTypeDefName, int? priority)
{
if (caste == null || workTypeDefName.NullOrEmpty())
return 0;
var values = new Dictionary<string, int>(caste.WorkPriorities);
if (priority == null)
values.Remove(workTypeDefName);
else
values[workTypeDefName] = priority.Value;
return SetSlot(caste, CasteSlot.Work, values);
}
/// <summary>
/// The members that follow one work type of the caste right now: those whose priority equals the
/// caste's value, or every member while the caste leaves the type alone (the next value reaches them
/// all). The manager's cycle button takes them before its first click on a type, so the clicks after
/// it move only them, never a pawn that happens to sit on a value the cycle passes through.
/// </summary>
public static List<Pawn> WorkFollowers(Caste caste, string workTypeDefName)
{
var result = new List<Pawn>();
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste) || workTypeDefName.NullOrEmpty())
return result;
int? value = caste.WorkPriorityOf(workTypeDefName);
foreach (Pawn member in comp.MembersOf(caste))
{
if (GameComponent_BlaxCastes.IsGone(member) || !CasteUtility.CanUse(member, CasteSlot.Work))
continue;
if (value == null || WorkSlot.Matches(member, workTypeDefName, value.Value))
result.Add(member);
}
return result;
}
/// <summary>
/// Sets one work type's priority (0 to 4, or null to leave it alone) and writes it to the given
/// members only, those WorkFollowers listed before a run of edits to this type. Members that left the
/// caste since are skipped. Returns how many members were moved.
/// </summary>
public static int SetWorkPriority(Caste caste, string workTypeDefName, int? priority, IEnumerable<Pawn> followers)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste) || workTypeDefName.NullOrEmpty())
return 0;
if (priority != null && (priority.Value < WorkSlot.Off || priority.Value > WorkSlot.Lowest))
return 0;
var values = new Dictionary<string, int>(caste.WorkPriorities);
if (priority == null)
values.Remove(workTypeDefName);
else
values[workTypeDefName] = priority.Value;
caste.SetSlotRaw(CasteSlot.Work, WorkSlot.Normalize(values));
if (priority == null || followers == null || !BlaxCastesMod.Enabled)
return 0;
int moved = 0;
foreach (Pawn member in followers)
{
if (GameComponent_BlaxCastes.IsGone(member) || comp.CasteOf(member) != caste || !CasteUtility.CanUse(member, CasteSlot.Work))
continue;
if (WorkSlot.WriteType(member, workTypeDefName, priority.Value))
moved++;
}
return moved;
}
/// <summary>
/// "Start from nothing": applying the caste turns every work type off before writing its listed ones.
/// Moves no member now; it takes effect on the next assign, Reset to caste or Apply to all members.
/// </summary>
public static bool SetWorkStartFromNothing(Caste caste, bool value)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste))
return false;
caste.SetWorkStartFromNothingRaw(value);
return true;
}
// ---- memberships -------------------------------------------------------------------
/// <summary>
/// Puts the pawn into the caste and writes every managed slot it can take. auto: a join row did
/// it, not the player. A null caste makes the pawn casteless. False if the pawn can't be a member
/// (not humanlike, gone, or not player faction or player prisoner) or the caste isn't in this game.
/// </summary>
public static bool Assign(Pawn pawn, Caste caste, bool auto, string reason)
{
if (caste == null)
return MakeCasteless(pawn, auto, reason);
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste) || !CasteUtility.CanBeMember(pawn))
return false;
comp.SetMembership(pawn, new CasteMembership(caste, auto, reason ?? JoinReason.Manual, Now));
CasteUtility.Apply(pawn, caste);
return true;
}
/// <summary>Casteless by choice: the pawn leaves its caste and keeps its current policies.</summary>
public static bool MakeCasteless(Pawn pawn, bool auto = false, string reason = JoinReason.Manual)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !CasteUtility.CanBeMember(pawn))
return false;
comp.SetMembership(pawn, new CasteMembership(null, auto, reason ?? JoinReason.Manual, Now));
return true;
}
/// <summary>Re-writes every managed slot of the pawn's caste, clearing its overrides.</summary>
public static bool ResetToCaste(Pawn pawn)
{
GameComponent_BlaxCastes comp = Comp;
Caste caste = comp?.CasteOf(pawn);
if (caste == null || !CasteUtility.CanBeMember(pawn))
return false;
CasteUtility.Apply(pawn, caste);
return true;
}
/// <summary>Removes the pawn's record, as if it never had a caste. Its policies stay as they are.</summary>
public static bool EndMembership(Pawn pawn)
{
GameComponent_BlaxCastes comp = Comp;
return comp != null && comp.RemoveMembership(pawn);
}
/// <summary>The caste's members that are alive and player-side (the manager's member count).</summary>
public static List<Pawn> LiveMembers(Caste caste)
{
var result = new List<Pawn>();
GameComponent_BlaxCastes comp = Comp;
if (comp == null || caste == null)
return result;
foreach (Pawn p in comp.MembersOf(caste))
{
if (!p.Dead && CasteUtility.CanBeMember(p))
result.Add(p);
}
return result;
}
/// <summary>
/// "Apply to all members": writes every managed slot of the caste to every live member, clearing
/// their hand changes. Returns how many members it wrote to.
/// </summary>
public static int ApplyToAll(Caste caste)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || !comp.HasCaste(caste) || !BlaxCastesMod.Enabled)
return 0;
int count = 0;
foreach (Pawn p in LiveMembers(caste))
{
if (CasteUtility.Apply(p, caste).Count > 0)
count++;
}
return count;
}
/// <summary>
/// The pawns "Assign by status" would place: player colonists, slaves and prisoners that can join a
/// caste, have no membership record (casteless-by-choice pawns have one), are not waiting for a join,
/// and whose status row resolves to a caste.
/// </summary>
public static List<Pawn> PawnsToAssignByStatus()
{
var result = new List<Pawn>();
GameComponent_BlaxCastes comp = Comp;
if (comp == null || Current.Game == null)
return result;
var seen = new HashSet<Pawn>();
foreach (Pawn p in PlayerSidePawns())
{
if (!seen.Add(p) || p.Dead || comp.MembershipOf(p) != null || JoinDefaults.IsQueued(p))
continue;
if (!JoinDefaults.Eligible(p) || !CasteUtility.CanBeMember(p))
continue;
string row = JoinDefaults.RowFor(JoinDefaults.StatusFallback, p);
if (row != null && comp.ResolveRow(row) != null)
result.Add(p);
}
return result;
}
private static IEnumerable<Pawn> PlayerSidePawns()
{
foreach (Pawn p in PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_OfPlayerFaction.ToArray())
yield return p;
foreach (Pawn p in PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_PrisonersOfColony.ToArray())
yield return p;
}
/// <summary>
/// "Assign pawns without a caste by status": puts each pawn of PawnsToAssignByStatus into the caste
/// of its new colonist, new slave or new prisoner row. Returns how many were assigned.
/// </summary>
public static int AssignByStatus()
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null)
return 0;
int count = 0;
foreach (Pawn p in PawnsToAssignByStatus())
{
string row = JoinDefaults.RowFor(JoinDefaults.StatusFallback, p);
Caste caste = row == null ? null : comp.ResolveRow(row);
if (caste != null && Assign(p, caste, true, row))
count++;
}
return count;
}
/// <summary>
/// The managed slots of the pawn's caste where the pawn has another value (a hand change or a
/// vanilla reset). Slots the pawn can't take are never overrides.
/// </summary>
public static List<CasteSlot> Overrides(Pawn pawn)
{
var result = new List<CasteSlot>();
Caste caste = Comp?.CasteOf(pawn);
if (caste == null)
return result;
foreach (CasteSlot slot in CasteUtility.AllSlots)
{
if (!caste.IsManaged(slot) || !CasteUtility.CanUse(pawn, slot))
continue;
if (!CasteUtility.Matches(pawn, slot, caste.GetSlot(slot)))
result.Add(slot);
}
return result;
}
/// <summary>The work types of the pawn's caste where the pawn's priority differs, in the Work tab's order.</summary>
public static List<WorkTypeDef> WorkOverrides(Pawn pawn)
{
Caste caste = Comp?.CasteOf(pawn);
if (caste == null || !caste.IsManaged(CasteSlot.Work) || !CasteUtility.CanUse(pawn, CasteSlot.Work))
return new List<WorkTypeDef>();
return WorkSlot.Differences(pawn, caste.WorkPriorities);
}
// ---- join rows ---------------------------------------------------------------------
/// <summary>Sets what a join row does. SpecificCaste needs a caste of this game.</summary>
public static bool SetJoinRow(string reason, JoinRowMode mode, Caste caste = null)
{
GameComponent_BlaxCastes comp = Comp;
if (comp == null || reason.NullOrEmpty())
return false;
if (mode == JoinRowMode.SpecificCaste && !comp.HasCaste(caste))
return false;
comp.SetRowRaw(reason, mode, caste);
return true;
}
// ---- save safety -------------------------------------------------------------------
/// <summary>
/// Checks every caste's slots after a load, before a save and while the manager is open: a policy
/// that left its database or a loadout Weapons Tab Reborn no longer has becomes unmanaged, a schedule
/// hour with an unknown time assignment becomes Anything, and a work type that no longer exists is
/// dropped. One warning per caste and problem.
/// </summary>
internal static void CheckSlots(GameComponent_BlaxCastes comp)
{
if (comp == null)
return;
foreach (Caste caste in comp.Castes)
{
UnmanageMissingPolicies(caste);
FixScheduleAndWork(caste);
}
}
/// <summary>
/// Unmanages the caste's slots whose policy is no longer in its database, and its loadout when Weapons
/// Tab Reborn is active and no longer has it (without the mod the id is kept). Returns how many.
/// </summary>
internal static int UnmanageMissingPolicies(Caste caste)
{
if (caste == null || Current.Game == null)
return 0;
List<string> missing = null;
foreach (CasteSlot slot in CasteUtility.PolicySlots)
{
if (slot == CasteSlot.MedCare || !(caste.GetSlot(slot) is Policy policy))
continue;
if (CasteUtility.PolicyExists(policy))
continue;
(missing ??= new List<string>()).Add(slot + " (" + policy.label + ")");
caste.SetSlotRaw(slot, null);
}
if (caste.IsManaged(CasteSlot.Loadout) && WeaponsTab.Available && !WeaponsTab.Exists(caste.LoadoutId))
{
(missing ??= new List<string>()).Add("weapon loadout (id " + caste.LoadoutId + ")");
caste.SetSlotRaw(CasteSlot.Loadout, Caste.Unmanaged);
}
if (missing == null)
return 0;
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": " + string.Join(", ", missing)
+ " no longer in the game. The slot is now unmanaged.");
return missing.Count;
}
/// <summary>
/// Schedule hours whose time assignment no longer exists (a removed mod, Meditate without Royalty)
/// become Anything, and work types that no longer exist are dropped, each with one warning.
/// </summary>
internal static void FixScheduleAndWork(Caste caste)
{
if (caste == null)
return;
IReadOnlyList<string> schedule = caste.Schedule;
if (schedule != null && schedule.Any(n => !ScheduleSlot.IsKnown(n)))
{
List<string> unknown = schedule.Where(n => !ScheduleSlot.IsKnown(n)).Distinct().ToList();
caste.SetSlotRaw(CasteSlot.Schedule, schedule.ToList()); // Normalize turns unknown names into Anything
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": time assignment " + string.Join(", ", unknown)
+ " no longer in the game. Those schedule hours are now Anything.");
}
if (caste.WorkPriorities.Keys.Any(k => WorkSlot.Resolve(k) == null))
{
List<string> gone = caste.WorkPriorities.Keys.Where(k => WorkSlot.Resolve(k) == null).ToList();
var kept = caste.WorkPriorities.Where(kv => !gone.Contains(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);
caste.SetSlotRaw(CasteSlot.Work, kept);
Log.Warning("[Blax Castes] Caste \"" + caste.label + "\": work type " + string.Join(", ", gone)
+ " no longer in the game. The caste leaves it alone now.");
}
}
}
}