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

328 lines
16 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The work priorities slot: work type defName to priority 0 (off) to 4; a type that is not listed is
/// left alone. Names resolve with GetNamedSilentFail. Work types the pawn cannot do
/// (Pawn.WorkTypeIsDisabled) are skipped, which avoids the SetPriority error. The caste's own number is
/// stored even while manual priorities are off: the game then reads any nonzero value as on, and the
/// number takes effect once manual priorities are turned on, so members still match the caste after the
/// switch. The Follow rule works per type. The slot is off while the manageWorkPriorities setting is
/// off or an automatic work manager is active. A listed type of an official DLC that is off (Childcare
/// without Biotech) stays listed and is skipped, so it works again once the DLC is back.
/// </summary>
public static class WorkSlot
{
public const int Off = 0;
public const int Highest = 1;
public const int Lowest = Pawn_WorkSettings.LowestPriority;
/// <summary>The automatic work managers, by package id, with the names the player sees.</summary>
public static readonly KeyValuePair<string, string>[] Managers =
{
new KeyValuePair<string, string>(Compat.WorkTab, "Work Tab"),
new KeyValuePair<string, string>(Compat.FreeWill, "Free Will"),
new KeyValuePair<string, string>(Compat.FreeWillUnstable, "Free Will"),
new KeyValuePair<string, string>(Compat.WorkManager, "Work Manager"),
new KeyValuePair<string, string>(Compat.AutoPriorities, "AutoPriorities"),
new KeyValuePair<string, string>(Compat.WorkRoles, "WorkRoles"),
};
/// <summary>Package ids treated as active on top of the real mod list. For tests only.</summary>
public static readonly HashSet<string> SimulatedActive = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// The mod list can't change without a restart, so the real detection runs once.
private static string detectedManager;
private static bool detectionDone;
/// <summary>The name of the first active automatic work manager, or null.</summary>
public static string ActiveManager()
{
if (!detectionDone)
{
detectionDone = true;
detectedManager = Managers.Where(m => Compat.IsActive(m.Key)).Select(m => m.Value).FirstOrDefault();
}
if (detectedManager != null || SimulatedActive.Count == 0)
return detectedManager;
return Managers.Where(m => SimulatedActive.Contains(m.Key)).Select(m => m.Value).FirstOrDefault();
}
public static bool SettingOn => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.manageWorkPriorities;
/// <summary>The slot is written: the setting is on and no automatic work manager is active.</summary>
public static bool Active => SettingOn && ActiveManager() == null;
/// <summary>The game's "manual priorities" switch. Off: a work type is only on or off.</summary>
public static bool ManualPriorities => Current.Game?.playSettings == null || Current.Game.playSettings.useWorkPriorities;
/// <summary>A priority as the game treats it right now: with manual priorities off, any nonzero value is 3.</summary>
public static int Effective(int priority)
{
if (priority <= Off)
return Off;
return ManualPriorities ? priority : Pawn_WorkSettings.DefaultPriority;
}
/// <summary>The work types the manager lists: the visible ones, in the Work tab's order.</summary>
public static List<WorkTypeDef> Types() => WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder.Where(d => d.visible).ToList();
public static WorkTypeDef Resolve(string defName) => defName.NullOrEmpty() ? null : DefDatabase<WorkTypeDef>.GetNamedSilentFail(defName);
/// <summary>
/// A listed work type of an official DLC that is off (Childcare without Biotech, Dark study without
/// Anomaly, Fishing without Odyssey): the caste keeps it and skips it until the DLC is on again.
/// </summary>
public static bool IsDlcOff(string defName) =>
!defName.NullOrEmpty() && Resolve(defName) == null && DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), defName) != null;
/// <summary>Every listed type is of a DLC that is off, so writing the slot changes nothing. False for no entries.</summary>
public static bool AllDlcOff(IReadOnlyDictionary<string, int> values) =>
values != null && values.Count > 0 && values.Keys.All(IsDlcOff);
/// <summary>
/// "Start from nothing" turns the other work off only while at least one listed type is in the game,
/// so a caste that lists only work of a DLC that is off never leaves its members without work.
/// </summary>
public static bool StripsOthers(IReadOnlyDictionary<string, int> values, bool startFromNothing) =>
startFromNothing && values != null && values.Keys.Any(k => Resolve(k) != null);
/// <summary>
/// Work type defName to priority from a value: a dictionary or any list of name and priority pairs.
/// Entries without a name or outside 0 to 4 are dropped. Null for null, anything else, or no entries.
/// </summary>
public static Dictionary<string, int> Normalize(object value)
{
if (!(value is IEnumerable<KeyValuePair<string, int>> pairs))
return null;
var result = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> kv in pairs)
{
if (!kv.Key.NullOrEmpty() && kv.Value >= Off && kv.Value <= Lowest)
result[kv.Key] = kv.Value;
}
return result.Count == 0 ? null : result;
}
public static bool Fits(object value) => value == null || value is IEnumerable<KeyValuePair<string, int>>;
/// <summary>The pawn has initialized work settings.</summary>
public static bool HasWorkSettings(Pawn pawn) => pawn?.workSettings != null && pawn.workSettings.EverWork;
/// <summary>The pawn can take this work type: it exists and is not disabled for the pawn.</summary>
public static bool CanDo(Pawn pawn, WorkTypeDef def) => def != null && HasWorkSettings(pawn) && !pawn.WorkTypeIsDisabled(def);
/// <summary>
/// The pawn already has the caste's value for this type, as the game treats both right now. A type
/// the pawn cannot do, or that no longer exists, never counts as different.
/// </summary>
public static bool Matches(Pawn pawn, string defName, int casteValue)
{
WorkTypeDef def = Resolve(defName);
if (!CanDo(pawn, def))
return true;
return Effective(pawn.workSettings.GetPriority(def)) == Effective(casteValue);
}
public static bool MatchesAll(Pawn pawn, IReadOnlyDictionary<string, int> values)
{
if (values == null || !HasWorkSettings(pawn))
return false;
foreach (KeyValuePair<string, int> kv in values)
{
if (!Matches(pawn, kv.Key, kv.Value))
return false;
}
return true;
}
/// <summary>The listed types where the pawn's priority differs from the caste's, in the Work tab's order.</summary>
public static List<WorkTypeDef> Differences(Pawn pawn, IReadOnlyDictionary<string, int> values)
{
var result = new List<WorkTypeDef>();
if (values == null || !HasWorkSettings(pawn))
return result;
foreach (WorkTypeDef def in WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder)
{
if (values.TryGetValue(def.defName, out int v) && !Matches(pawn, def.defName, v))
result.Add(def);
}
return result;
}
/// <summary>
/// Writes one type. Skipped (false) when the type is gone or disabled for the pawn. The value is
/// stored as it is, also while manual priorities are off (the game then reads any nonzero value as
/// on, and GetPriority hides the stored number, so it is always written).
/// </summary>
public static bool WriteType(Pawn pawn, string defName, int value)
{
WorkTypeDef def = Resolve(defName);
if (!CanDo(pawn, def) || value < Off || value > Lowest)
return false;
if (!ManualPriorities || pawn.workSettings.GetPriority(def) != value)
pawn.workSettings.SetPriority(def, value);
return true;
}
/// <summary>
/// Patient and Bed rest: the work types that send a hurt or sick pawn to bed. Every pawn starts with
/// them on and no backstory can turn them off (alwaysStartActive and no work tags), and a colonist or
/// slave has no other way to go to bed for treatment or rest. "Start from nothing" keeps them.
/// </summary>
public static bool IsSelfCare(WorkTypeDef def) => def != null && def.alwaysStartActive && def.workTags == WorkTags.None;
/// <summary>The self-care work types (IsSelfCare), in the Work tab's order.</summary>
public static List<WorkTypeDef> SelfCareTypes() => WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder.Where(IsSelfCare).ToList();
/// <summary>
/// Writes the listed types. startFromNothing first turns off every other work type except the
/// self-care ones (IsSelfCare), which stay as they are, for castes that should do only their listed
/// work; not while no listed type is in the game (StripsOthers). True when anything was written.
/// </summary>
public static bool Write(Pawn pawn, IReadOnlyDictionary<string, int> values, bool startFromNothing)
{
if (!HasWorkSettings(pawn) || values == null || values.Count == 0)
return false;
bool any = false;
if (StripsOthers(values, startFromNothing))
{
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
if (values.ContainsKey(def.defName) || IsSelfCare(def) || pawn.workSettings.GetPriority(def) == Off)
continue;
pawn.workSettings.SetPriority(def, Off);
}
any = true;
}
foreach (KeyValuePair<string, int> kv in values)
{
if (WriteType(pawn, kv.Key, kv.Value))
any = true;
}
return any;
}
/// <summary>
/// Every work type the caste decides, with its value: the listed ones, and with "Start from nothing"
/// (while it applies, StripsOthers) every other one except the self-care types, at off. Null while the
/// caste leaves work alone.
/// </summary>
public static Dictionary<string, int> Decided(Caste caste)
{
if (caste == null || !caste.IsManaged(CasteSlot.Work))
return null;
var result = new Dictionary<string, int>(caste.WorkPriorities);
if (StripsOthers(caste.WorkPriorities, caste.WorkStartFromNothing))
{
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
if (!result.ContainsKey(def.defName) && !IsSelfCare(def))
result[def.defName] = Off;
}
}
return result;
}
/// <summary>The pawn's priority for every work type (activeOnly: only the types that are on), or null without work settings.</summary>
public static Dictionary<string, int> Of(Pawn pawn, bool activeOnly = false)
{
if (!HasWorkSettings(pawn))
return null;
var result = new Dictionary<string, int>();
foreach (WorkTypeDef def in DefDatabase<WorkTypeDef>.AllDefsListForReading)
{
int priority = pawn.workSettings.GetPriority(def);
if (!activeOnly || priority > Off)
result[def.defName] = priority;
}
return result;
}
/// <summary>The cycle of the manager's button: leave alone, 1, 2, 3, 4, off, leave alone.</summary>
public static int? Next(int? priority)
{
if (priority == null)
return Highest;
if (priority.Value == Off)
return null;
return priority.Value >= Lowest ? Off : priority.Value + 1;
}
/// <summary>The cycle backwards: leave alone, off, 4, 3, 2, 1, leave alone.</summary>
public static int? Previous(int? priority)
{
if (priority == null)
return Off;
if (priority.Value == Off)
return Lowest;
return priority.Value <= Highest ? (int?)null : priority.Value - 1;
}
/// <summary>A priority as the manager shows it: "-" for leave alone, "off", or the number.</summary>
public static string PriorityLabel(int? priority)
{
if (priority == null)
return "BlaxCastes_WorkLeaveAloneShort".Translate();
return priority.Value == Off ? (string)"BlaxCastes_WorkOff".Translate() : priority.Value.ToString();
}
public static string TypeLabel(WorkTypeDef def) => def == null ? "" : (def.labelShort.NullOrEmpty() ? def.label : def.labelShort).CapitalizeFirst();
public static string TypeLabel(string defName) => Resolve(defName) is WorkTypeDef def ? TypeLabel(def) : defName;
/// <summary>
/// The listed types with their priority, in the Work tab's order: "Firefight 1, Grow 1". Off types say
/// "off". A type of a DLC that is off comes last with its DLC: "Childcare 1 (needs Biotech)".
/// </summary>
public static string Summary(IReadOnlyDictionary<string, int> values)
{
if (values == null || values.Count == 0)
return "BlaxCastes_Unmanaged".Translate();
var parts = new List<string>();
var listed = new HashSet<string>();
foreach (WorkTypeDef def in WorkTypeDefsUtility.WorkTypeDefsInPriorityOrder)
{
if (!values.TryGetValue(def.defName, out int v))
continue;
listed.Add(def.defName);
parts.Add(TypeLabel(def) + " " + PriorityLabel(v));
}
foreach (KeyValuePair<string, int> kv in values)
{
if (listed.Contains(kv.Key))
continue;
parts.Add(IsDlcOff(kv.Key) ? DlcOffLabel(kv.Key, kv.Value) : kv.Key + " " + PriorityLabel(kv.Value));
}
return string.Join(", ", parts);
}
/// <summary>The listed types of a DLC that is off, as Summary words them; empty when there are none.</summary>
public static List<string> DlcOffLabels(IReadOnlyDictionary<string, int> values)
{
var result = new List<string>();
if (values == null)
return result;
foreach (KeyValuePair<string, int> kv in values.OrderBy(kv => kv.Key))
{
if (IsDlcOff(kv.Key))
result.Add(DlcOffLabel(kv.Key, kv.Value));
}
return result;
}
/// <summary>"Dark study 1 (needs Anomaly)": the def is not loaded, so its name comes from the defName.</summary>
private static string DlcOffLabel(string defName, int priority)
{
string name = GenText.SplitCamelCase(defName).ToLowerInvariant().CapitalizeFirst();
return "BlaxCastes_NeedsDlc".Translate((name + " " + PriorityLabel(priority)).Named("WHAT"),
DlcSupport.InactiveDlcFor(typeof(WorkTypeDef), defName).Named("DLC"));
}
}
}