using System; using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; namespace BlaxLaws { /// /// Base class of the category workers (ActCategoryDef.workerClass). A worker walks its DefDatabase once /// and returns the category's entries: one ActEntry.ForDef per def and one ActEntry.ForGroup per group, /// groups in the order the picker shows them. It never reads the lawbook and keeps no state of a game. /// public class ActCategoryWorker { public ActCategoryDef def; /// Every entry of the category, def and group entries both. Default: none. public virtual IEnumerable MakeEntries() { yield break; } /// The category's tooltip in the picker. Default: the def's description. public virtual string Tooltip => def?.description; } /// /// The act catalogue: every entry the loaded game has, by category (design: "The act catalogue is built /// from the game's defs, saved as names"). Built once, on first use or at the first game start, from the /// ActCategoryDefs' workers; never saved. The picker searches it; nothing else walks it. Lookups by key /// are a dictionary read. /// public static class ActCatalogue { private static bool built; private static bool building; private static readonly List all = new List(); private static readonly Dictionary byKey = new Dictionary(); private static readonly Dictionary> byCategory = new Dictionary>(); private static readonly List categories = new List(); private static readonly List chemicalOptions = new List(); private static readonly List Empty = new List(); /// Bumped on every build, for caches keyed on the catalogue. public static int Version { get; private set; } public static bool Built => built; /// Every entry, category by category in picker order. public static IReadOnlyList All { get { EnsureBuilt(); return all; } } /// The categories in picker order. public static IReadOnlyList Categories { get { EnsureBuilt(); return categories; } } /// A category's entries: groups first, in the worker's order, then every def A to Z. public static IReadOnlyList EntriesOf(string categoryId) { EnsureBuilt(); return categoryId != null && byCategory.TryGetValue(categoryId, out List list) ? list : Empty; } /// The entry for a key, or null when it is missing (a DLC or mod that isn't loaded, a typo). public static ActEntry Get(string key) { if (key == null) return null; EnsureBuilt(); byKey.TryGetValue(key, out ActEntry e); return e; } public static bool TryGet(string key, out ActEntry entry) { entry = Get(key); return entry != null; } /// The single-def entry of a def in a category, or null. public static ActEntry EntryFor(string categoryId, Def def) => def == null ? null : Get(ActKey.Of(categoryId, def.defName)); /// The group behind a group key, or null. public static ActGroup GroupOf(string key) => Get(key)?.group; /// /// Drug options after Any, Hard and Social: the defName of every ChemicalDef a drug's /// CompProperties_Drug names, A to Z by label. No other chemical is listed. /// public static IReadOnlyList ChemicalOptions { get { EnsureBuilt(); return chemicalOptions; } } public static void EnsureBuilt() { if (!built && !building) Build(); } /// Builds the catalogue from the loaded defs. A worker that throws logs once and leaves its category empty. public static void Build() { building = true; try { all.Clear(); byKey.Clear(); byCategory.Clear(); categories.Clear(); chemicalOptions.Clear(); BreakLinks.ClearCache(); categories.AddRange(DefDatabase.AllDefsListForReading.OrderBy(c => c.order).ThenBy(c => c.defName)); foreach (ActCategoryDef cat in categories) { var list = new List(); try { foreach (ActEntry e in cat.Worker.MakeEntries() ?? Enumerable.Empty()) { if (e == null || e.key.NullOrEmpty()) continue; if (e.categoryId != cat.defName) { LawsLog.WarningOnce("catalogue-category:" + e.key, "Catalogue entry " + e.key + " came from category " + cat.defName + "; skipped."); continue; } if (byKey.ContainsKey(e.key)) continue; byKey[e.key] = e; list.Add(e); } } catch (Exception ex) { LawsLog.Once("Catalogue category " + cat.defName, ex); } Finish(cat, list); byCategory[cat.defName] = list; all.AddRange(list); } BuildChemicalOptions(); Version++; built = true; } finally { building = false; } } /// Drops the catalogue; the next read builds it again. Tests only. public static void Reset() { built = false; all.Clear(); byKey.Clear(); byCategory.Clear(); categories.Clear(); chemicalOptions.Clear(); } /// Group sizes, the stage and break fields, and the picker order: groups first, defs A to Z. private static void Finish(ActCategoryDef cat, List list) { List defs = list.Where(e => e.def != null).ToList(); foreach (ActEntry g in list) { if (g.group == null) continue; g.group.size = g.group.IsAny ? defs.Count : defs.Count(d => SafeMatches(g.group, d.def)); } bool breaks = cat.defName == ActCategories.Break; foreach (ActEntry e in list) { if (!breaks) { e.hasPlanning = false; e.hasDidIt = true; continue; } e.hasPlanning = true; e.links.Clear(); if (e.def is MentalStateDef state) { BreakLinkDef link = BreakLinks.For(state); if (link != null) e.links.Add(link); e.hostileBreak = BreakLinks.IsHostile(state); } else if (e.group != null) { bool anyMember = false, allHostile = true; foreach (ActEntry d in defs) { if (!(d.def is MentalStateDef s) || !(e.group.IsAny || SafeMatches(e.group, s))) continue; anyMember = true; if (!BreakLinks.IsHostile(s)) allHostile = false; BreakLinkDef link = BreakLinks.For(s); if (link != null && !e.links.Contains(link)) e.links.Add(link); } e.hostileBreak = anyMember && allHostile; } e.hasDidIt = e.links.Count > 0; e.hasDrugOption = e.links.Any(l => l.usesDrugOption); } List ordered = list.Where(e => e.group != null) .Concat(list.Where(e => e.group == null).OrderBy(e => e.label, StringComparer.CurrentCultureIgnoreCase).ThenBy(e => e.key)) .ToList(); list.Clear(); list.AddRange(ordered); } private static bool SafeMatches(ActGroup g, Def def) { try { return g.MatchesDef(def); } catch (Exception ex) { LawsLog.Once("Catalogue group " + g.Key, ex); return false; } } private static void BuildChemicalOptions() { var chems = new HashSet(); foreach (ThingDef t in DefDatabase.AllDefsListForReading) { if (t.comps == null) continue; foreach (CompProperties c in t.comps) { if (c is CompProperties_Drug drug && drug.chemical != null) chems.Add(drug.chemical); } } chemicalOptions.AddRange(chems.OrderBy(c => c.label ?? c.defName, StringComparer.CurrentCultureIgnoreCase).Select(c => c.defName)); } } }