using System; using System.Collections.Generic; using System.Linq; using HarmonyLib; using RimWorld; using Verse; namespace BlaxDefaults { /// /// A stockpile type: the vanilla stockpile, the vanilla dumping stockpile, or a modded subclass of /// Designator_ZoneAddStockpile, which is a type of its own. A Zone_Stockpile doesn't remember which /// designator made it, so on a stockpile every type is offered. /// public sealed class StockpileType { public readonly string Key; public readonly StorageSettingsPreset Preset; /// Null for the two vanilla types; the designator class for a modded type. public readonly Type DesignatorType; private readonly string moddedLabel; public StockpileType(string key, StorageSettingsPreset preset, Type designatorType, string moddedLabel) { Key = key; Preset = preset; DesignatorType = designatorType; this.moddedLabel = moddedLabel; } public bool IsVanilla => DesignatorType == null; /// "stockpile", "dumping stockpile", or a modded designator's NewZoneLabel. public string Label { get { if (Key == DefaultsKeys.Stockpile) return "BlaxDefaults_KindStockpile".Translate(); if (Key == DefaultsKeys.Dumping) return "BlaxDefaults_KindDumping".Translate(); return moddedLabel.NullOrEmpty() ? DesignatorType.Name : moddedLabel; } } public string LabelPlural { get { if (Key == DefaultsKeys.Stockpile) return "BlaxDefaults_KindStockpilePlural".Translate(); if (Key == DefaultsKeys.Dumping) return "BlaxDefaults_KindDumpingPlural".Translate(); return StorageKinds.PluralOf(Label); } } public override string ToString() => Key; } /// /// One kind that has its own storage default: a stockpile type, a storage building def, or (1.1) a forbid /// rule, whose filter is a template too. Knows its key, label, parent filter and the game's default, and /// loads a default onto settings. /// public sealed class StorageKind { public readonly string Key; /// The building def, or null for a stockpile type. public readonly ThingDef Def; /// The stockpile type, or null for a building. public readonly StockpileType Stockpile; /// The forbid rule whose filter this is, or null for storage. public readonly ForbidRule Forbid; public StorageKind(ThingDef def) { Def = def; Key = DefaultsKeys.ForStorage(def); } public StorageKind(StockpileType stockpile) { Stockpile = stockpile; Key = stockpile.Key; } public StorageKind(ForbidRule rule) { Forbid = rule; Key = rule.Key; } public bool IsStockpile => Stockpile != null; /// A forbid rule's filter: no priority, the unlisted rule is Refuse or Allow. public bool IsForbid => Forbid != null; /// "shelf", "stockpile", "gear enemies drop". public string Label => Def != null ? Def.label : Forbid != null ? Forbid.Label : Stockpile.Label; /// /// "shelves", "stockpiles". A key BlaxDefaults_Plural_<defName> in the active language wins over /// StorageKinds.PluralOf. /// public string LabelPlural { get { if (Forbid != null) return Forbid.Label; if (Def == null) return Stockpile.LabelPlural; string key = "BlaxDefaults_Plural_" + Def.defName; return key.CanTranslate() ? key.Translate().Resolve() : StorageKinds.PluralOf(Def.label); } } /// What settings of this kind may ever allow: the building's fixedStorageSettings, else every storable item. public ThingFilter ParentFilter => Def != null ? StorageKinds.ParentFilterFor(Def) : Forbid != null ? ForbidRules.ParentFilter : StorageKinds.StockpileParentFilter; /// The saved default, or null. public StorageTemplate Saved => DefaultsLibrary.Get(Key); /// A fresh scratch StorageSettings holding the game's default for this kind. public StorageSettings GameDefault() => Def != null ? StorageKinds.GameDefaultFor(Def) : Forbid != null ? ForbidRules.BaseSettings() : StorageKinds.GameDefaultFor(Stockpile); /// Replaces the target's priority, filter, special filters and ranges with the game's default. public void LoadGameDefault(StorageSettings target) => target.CopyFrom(GameDefault()); /// /// The game's default with the template on top, written in one CopyFrom: the same settings a new /// thing of this kind gets. Without a template, the game's default. /// public void LoadDefault(StorageSettings target, StorageTemplate template) { StorageSettings scratch = GameDefault(); template?.ApplyTo(scratch, ParentFilter); target.CopyFrom(scratch); } /// A template of these settings under this kind's key (unlisted = Game), not yet saved. public StorageTemplate Capture(StorageSettings settings) => StorageTemplate.Capture(Key, settings, ParentFilter); public override string ToString() => Key; } /// The kinds Defaults covers and the game's defaults for them. public static class StorageKinds { /// The protected preset field of the vanilla stockpile designators. public static readonly AccessTools.FieldRef PresetRef = AccessTools.FieldRefAccess("preset"); private static readonly Func NewZoneLabelGetter = AccessTools.MethodDelegate>(AccessTools.PropertyGetter(typeof(Designator_ZoneAdd), "NewZoneLabel")); private static List everStorable; private static List stockpileTypes; public static readonly StockpileType VanillaStockpile = new StockpileType(DefaultsKeys.Stockpile, StorageSettingsPreset.DefaultStockpile, null, null); public static readonly StockpileType VanillaDumping = new StockpileType(DefaultsKeys.Dumping, StorageSettingsPreset.DumpingStockpile, null, null); /// Every def with EverStorable(willMinifyIfPossible: true), in def order. Built once. public static List EverStorableDefs => everStorable ??= DefDatabase.AllDefsListForReading.Where(d => d.EverStorable(willMinifyIfPossible: true)).ToList(); /// Every storable def the parent filter allows (all storable defs when it is null). public static IEnumerable StorableDefs(ThingFilter parentFilter) { foreach (ThingDef def in EverStorableDefs) { if (parentFilter == null || parentFilter.Allows(def)) yield return def; } } public static ThingFilter StockpileParentFilter => StorageSettings.EverStorableFixedSettings().filter; /// The vanilla stockpile, the vanilla dumping stockpile, then one type per modded stockpile designator. public static List StockpileTypes => stockpileTypes ??= BuildStockpileTypes(); /// /// The type a designator makes: _Resources and _Expand give the vanilla stockpile, _Dumping the dumping /// stockpile, any other subclass its own type. /// public static StockpileType StockpileTypeOf(Designator_ZoneAddStockpile designator) { if (designator == null) return null; Type t = designator.GetType(); if (IsVanillaStockpileDesignator(t)) return PresetRef(designator) == StorageSettingsPreset.DumpingStockpile ? VanillaDumping : VanillaStockpile; string key = DefaultsKeys.ForStockpileDesignator(t); return StockpileTypes.FirstOrDefault(s => s.Key == key) ?? new StockpileType(key, PresetRef(designator), t, SafeNewZoneLabel(designator)); } public static StockpileType StockpileTypeForKey(string key) => StockpileTypes.FirstOrDefault(s => s.Key == key); public static bool IsVanillaStockpileDesignator(Type t) => t == typeof(Designator_ZoneAddStockpile_Resources) || t == typeof(Designator_ZoneAddStockpile_Expand) || t == typeof(Designator_ZoneAddStockpile_Dumping); /// True when the def's blueprint is a Blueprint_Storage or a subclass: shelves, bookcases, the hopper, fridges, weapon racks. public static bool HasStorageBlueprint(ThingDef def) => def?.building?.blueprintClass != null && typeof(Blueprint_Storage).IsAssignableFrom(def.building.blueprintClass); /// /// Building kinds that get a default when made and a Defaults button. 1.0: defs with a storage /// blueprint. 1.1 widens this to every def with a storage tab. /// public static bool IsCovered(ThingDef def) => HasStorageBlueprint(def); /// Every covered building def, in def order. public static IEnumerable CoveredDefs() => DefDatabase.AllDefsListForReading.Where(IsCovered); public static ThingFilter ParentFilterFor(ThingDef def) => def?.building?.fixedStorageSettings?.filter ?? StockpileParentFilter; /// /// The game's default for a building on a scratch StorageSettings: a copy of /// def.building.defaultStorageSettings, or, when the def has none, an empty filter at the priority a /// fresh StorageSettings(parent) takes (the fixed settings' priority, else Normal), as PostMake leaves it. /// Defaults never edits defaultStorageSettings, so this always holds the loaded value. /// public static StorageSettings GameDefaultFor(ThingDef def) { var s = new StorageSettings(); StorageSettings d = def?.building?.defaultStorageSettings; if (d != null) s.CopyFrom(d); else s.Priority = def?.building?.fixedStorageSettings?.Priority ?? StoragePriority.Normal; return s; } /// The game's default for a stockpile type: SetFromPreset with its preset at Normal, as the Zone_Stockpile constructor does. public static StorageSettings GameDefaultFor(StockpileType type) { var s = new StorageSettings(); s.SetFromPreset(type?.Preset ?? StorageSettingsPreset.DefaultStockpile); s.Priority = StoragePriority.Normal; return s; } /// /// The plural of a kind's label for the menu, tooltips and the settings page: the active language worker's, /// with two fixes for English, whose rule appends "s" after any last character /// (Verse/LanguageWorker_English.cs:140-152): a label ending in "shelf" ends in "shelves", and a note in /// parentheses at the end stays there ("Weapon Rack (1 slot)" gives "Weapon Racks (1 slot)", not /// "Weapon Rack (1 slot)s"). An English label that doesn't end in a letter is returned unchanged. /// public static string PluralOf(string label) { if (label.NullOrEmpty()) return label; LanguageWorker worker = Find.ActiveLanguageWorker; if (!(worker is LanguageWorker_English)) return worker != null ? worker.Pluralize(label) : label; string head = label, note = ""; int open = label.LastIndexOf(" (", StringComparison.Ordinal); if (open > 0 && label.EndsWith(")", StringComparison.Ordinal)) { head = label.Substring(0, open); note = label.Substring(open); } if (head.Length == 0 || !char.IsLetter(head[head.Length - 1])) return label; if (head.EndsWith("shelf", StringComparison.OrdinalIgnoreCase)) return head.Substring(0, head.Length - 1) + (char.IsUpper(head[head.Length - 1]) ? "VES" : "ves") + note; return worker.Pluralize(head) + note; } public static StorageKind ForDef(ThingDef def) => def == null ? null : new StorageKind(def); public static StorageKind ForStockpile(StockpileType type) => type == null ? null : new StorageKind(type); public static StorageKind ForForbid(ForbidRule rule) => rule == null ? null : new StorageKind(rule); /// The kind for a library key, or null when its def or designator is not loaded. public static StorageKind ForKey(string key) { if (DefaultsKeys.IsStorage(key)) return ForDef(DefDatabase.GetNamedSilentFail(DefaultsKeys.NameOf(key))); if (DefaultsKeys.IsStockpile(key)) return ForStockpile(StockpileTypeForKey(key)); if (DefaultsKeys.IsForbid(key)) return ForForbid(ForbidRules.ForKey(key)); return null; } private static List BuildStockpileTypes() { var list = new List { VanillaStockpile, VanillaDumping }; // Modded designators: the instances the game made for its architect menu carry their preset. var seen = new HashSet(); foreach (DesignationCategoryDef cat in DefDatabase.AllDefsListForReading) { if (cat.AllResolvedDesignators == null) continue; foreach (Designator d in cat.AllResolvedDesignators) { if (!(d is Designator_ZoneAddStockpile zd) || IsVanillaStockpileDesignator(d.GetType()) || !seen.Add(d.GetType())) continue; list.Add(new StockpileType(DefaultsKeys.ForStockpileDesignator(d.GetType()), PresetRef(zd), d.GetType(), SafeNewZoneLabel(zd))); } } return list; } private static string SafeNewZoneLabel(Designator_ZoneAdd d) { try { return NewZoneLabelGetter(d); } catch { return null; } } } }