rimworld-blax-defaults/Source/BlaxDefaults/ForbidRules.cs

383 lines
16 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxDefaults
{
/// <summary>Who a pawn that goes down, dies or is stripped belongs to, for the forbid rules.</summary>
public enum ForbidGroup
{
/// <summary>Neutral visitors, traders, quest lodgers and anyone else: the game's rules.</summary>
None,
/// <summary>Colonists, slaves, colony mechs, colony animals and prisoners, breaking out or rebelling included.</summary>
Colony,
/// <summary>Everyone else hostile to the player.</summary>
Enemies,
}
/// <summary>Which corpse switch a corpse falls under; the first kind that fits decides.</summary>
public enum CorpseKind
{
Animal,
Enemy,
Other,
}
/// <summary>
/// One forbid rule: "Gear your colony drops" or "Gear enemies drop". Work package "forbid" (design.md, 1.1
/// "Gear rules for your colony and for enemies"). Its filter is a StorageTemplate in the defaults library under
/// forbid:colony or forbid:enemies (priority unused, unlisted Refuse or Allow); its switches live in mod
/// settings. The rule acts only when it is ticked and has a filter: a ticked rule whose filter is missing (the
/// defaults file failed to load) acts as off, and the settings page says why.
/// </summary>
public sealed class ForbidRule
{
public readonly ForbidGroup Group;
public readonly string Key;
private StorageTemplate filterFor;
private ThingFilter filter;
public ForbidRule(ForbidGroup group, string key)
{
Group = group;
Key = key;
}
private static BlaxDefaultsSettings S => BlaxDefaultsMod.Settings;
/// <summary>The rule's checkbox: colonyGearRule or enemyGearRule.</summary>
public bool Ticked
{
get => S != null && (Group == ForbidGroup.Colony ? S.colonyGearRule : S.enemyGearRule);
set
{
if (S == null) return;
if (Group == ForbidGroup.Colony) S.colonyGearRule = value;
else S.enemyGearRule = value;
}
}
/// <summary>"Where": true for anywhere (the default), false for only inside the home area.</summary>
public bool Anywhere
{
get => S == null || (Group == ForbidGroup.Colony ? S.colonyGearAnywhere : S.enemyGearAnywhere);
set
{
if (S == null) return;
if (Group == ForbidGroup.Colony) S.colonyGearAnywhere = value;
else S.enemyGearAnywhere = value;
}
}
/// <summary>"Stripping forbids what doesn't match": colonyStripRule or enemyStripRule.</summary>
public bool StripTicked
{
get => S != null && (Group == ForbidGroup.Colony ? S.colonyStripRule : S.enemyStripRule);
set
{
if (S == null) return;
if (Group == ForbidGroup.Colony) S.colonyStripRule = value;
else S.enemyStripRule = value;
}
}
/// <summary>The saved filter, or null.</summary>
public StorageTemplate Template => DefaultsLibrary.Get<StorageTemplate>(Key);
public bool HasFilter => Template != null;
/// <summary>The gear rule acts: the forbid rules are on, the rule is ticked and it has a filter.</summary>
public bool Active => ForbidRules.On && Ticked && HasFilter;
/// <summary>The strip switch acts: the forbid rules are on, the switch is ticked and the rule has a filter.</summary>
public bool StripActive => ForbidRules.On && StripTicked && HasFilter;
/// <summary>"Gear your colony drops" or "Gear enemies drop".</summary>
public string Label => (Group == ForbidGroup.Colony ? "BlaxDefaults_ForbidColonyRule" : "BlaxDefaults_ForbidEnemyRule").Translate();
/// <summary>
/// The filter built from the saved template, kept until the template changes (the library replaces an entry
/// on every change, so the reference tells). Null without a saved template.
/// </summary>
public ThingFilter Filter
{
get
{
StorageTemplate t = Template;
if (t == null)
{
filterFor = null;
filter = null;
return null;
}
if (!ReferenceEquals(t, filterFor) || filter == null)
{
filter = ForbidRules.BuildFilter(t);
filterFor = t;
}
return filter;
}
}
/// <summary>The filter allows the thing (def, hit points, quality, special filters). False without a filter.</summary>
public bool Allows(Thing t)
{
ThingFilter f = Filter;
return f != null && t != null && f.Allows(t);
}
/// <summary>The thing's cell passes "Where": anywhere, or inside the home area of its map.</summary>
public bool InsideWhere(Thing t)
{
if (Anywhere)
return true;
Map map = t?.MapHeld;
if (map == null)
return false;
IntVec3 c = t.PositionHeld;
return c.InBounds(map) && map.areaManager.Home[c];
}
/// <summary>
/// The suggested setup, applied only when the player asks (or ticks a rule without a filter). Enemies:
/// every item, hit points 50 to 100%, Normal or better, stripping on. Your colony: every item, full ranges,
/// stripping off. Both anywhere, with unlisted items allowed, so items a mod adds later follow the ranges.
/// </summary>
public StorageTemplate Suggested()
{
var t = new StorageTemplate(Key) { unlisted = UnlistedRule.Allow };
if (Group == ForbidGroup.Enemies)
{
t.hitPoints = new FloatRange(0.5f, 1f);
t.quality = new QualityRange(QualityCategory.Normal, QualityCategory.Legendary);
}
return t;
}
/// <summary>The strip switch the suggested setup sets.</summary>
public bool SuggestedStrip => Group == ForbidGroup.Enemies;
/// <summary>
/// Saves the suggested setup as the filter and sets "Where" to anywhere and the strip switch as the setup
/// says. Leaves the rule's checkbox as it is. Returns whether the defaults file was written.
/// </summary>
public bool UseSuggested()
{
bool ok = DefaultsLibrary.Set(Suggested());
Anywhere = true;
StripTicked = SuggestedStrip;
return ok;
}
/// <summary>
/// Ticks or unticks the rule from the settings page. Ticking a rule that has no filter yet saves the
/// suggested setup first (strip switch included) and returns true, so the page can say so (decided
/// 2026-11-30, design.md "Defaults I picked").
/// </summary>
public bool SetTicked(bool on)
{
bool usedSuggested = false;
if (on && !HasFilter)
{
UseSuggested();
usedSuggested = true;
}
Ticked = on;
return usedSuggested;
}
/// <summary>Forget: deletes the filter and turns the rule and its strip switch off.</summary>
public void Forget()
{
DefaultsLibrary.Forget(Key);
Ticked = false;
StripTicked = false;
}
public override string ToString() => Key;
}
/// <summary>
/// The two forbid rules, the corpse switches and the shared pieces: groups, the parent filter, filters built
/// from templates and the row summary. Work package "forbid" (design.md, 1.1 Forbid rules).
/// </summary>
public static class ForbidRules
{
public static readonly ForbidRule Colony = new ForbidRule(ForbidGroup.Colony, DefaultsKeys.ForbidColony);
public static readonly ForbidRule Enemies = new ForbidRule(ForbidGroup.Enemies, DefaultsKeys.ForbidEnemies);
public static readonly ForbidRule[] All = { Colony, Enemies };
private static ThingFilter parentFilter;
/// <summary>The forbid rules category is on (and the master switch).</summary>
public static bool On => BlaxDefaultsMod.ForbidOn;
public static ForbidRule For(ForbidGroup group) =>
group == ForbidGroup.Colony ? Colony : group == ForbidGroup.Enemies ? Enemies : null;
public static ForbidRule ForKey(string key) => All.FirstOrDefault(r => r.Key == key);
/// <summary>Anything a downing or a death could change: a gear rule acting or a corpse switch on.</summary>
public static bool AnyDropRuleOn =>
On && (Colony.Active || Enemies.Active || CorpseSwitch(CorpseKind.Animal) || CorpseSwitch(CorpseKind.Enemy) || CorpseSwitch(CorpseKind.Other));
/// <summary>
/// The group of a living pawn: your colony when its faction is the player's and it is not a quest lodger,
/// or it is a prisoner of the colony (a prison break leaves it one); otherwise enemies when it is hostile
/// to the player; otherwise none. Read before death: HostileTo is false for anything destroyed.
/// </summary>
public static ForbidGroup GroupOf(Pawn p)
{
Faction player = Faction.OfPlayerSilentFail;
if (p == null || player == null)
return ForbidGroup.None;
if (p.Faction == player && !p.IsQuestLodger())
return ForbidGroup.Colony;
if (p.IsPrisonerOfColony)
return ForbidGroup.Colony;
if (p.HostileTo(player))
return ForbidGroup.Enemies;
return ForbidGroup.None;
}
/// <summary>
/// The group of a dead pawn, from its faction alone: your faction (not a lodger) is your colony, a faction
/// hostile to yours is enemies. A dead prisoner counts by the faction it came from.
/// </summary>
public static ForbidGroup GroupOfDead(Pawn p)
{
Faction player = Faction.OfPlayerSilentFail;
if (p == null || player == null || p.Faction == null)
return ForbidGroup.None;
if (p.Faction == player)
return p.IsQuestLodger() ? ForbidGroup.None : ForbidGroup.Colony;
return p.Faction.HostileTo(player) ? ForbidGroup.Enemies : ForbidGroup.None;
}
/// <summary>
/// The corpse switch a pawn's corpse falls under: animal (any RaceProps.Animal), then enemy (the group read
/// while it was alive), then other.
/// </summary>
public static CorpseKind CorpseKindOf(Pawn p, ForbidGroup group)
{
if (p?.RaceProps != null && p.RaceProps.Animal)
return CorpseKind.Animal;
return group == ForbidGroup.Enemies ? CorpseKind.Enemy : CorpseKind.Other;
}
/// <summary>The corpse switch for this kind is on (and the forbid rules).</summary>
public static bool CorpseSwitch(CorpseKind kind)
{
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
if (s == null || !On)
return false;
switch (kind)
{
case CorpseKind.Animal: return s.animalCorpsesAllowed;
case CorpseKind.Enemy: return s.enemyCorpsesAllowed;
default: return s.otherCorpsesAllowed;
}
}
/// <summary>
/// What a forbid filter may ever allow: every storable item (StorageSettings.EverStorableFixedSettings)
/// without the Corpses category, which the corpse switches cover. Built once.
/// </summary>
public static ThingFilter ParentFilter
{
get
{
if (parentFilter == null)
{
var f = new ThingFilter();
f.CopyAllowancesFrom(StorageSettings.EverStorableFixedSettings().filter);
if (ThingCategoryDefOf.Corpses != null)
f.SetAllow(ThingCategoryDefOf.Corpses, false);
f.RecalculateDisplayRootCategory();
parentFilter = f;
}
return parentFilter;
}
}
/// <summary>
/// A base the template goes on: every item of the parent filter, every special filter, full ranges. The
/// edit window's "game's default" for a forbid rule.
/// </summary>
public static StorageSettings BaseSettings()
{
var s = new StorageSettings();
s.filter.SetAllowAll(ParentFilter);
s.filter.AllowedHitPointsPercents = FloatRange.ZeroToOne;
s.filter.AllowedQualityLevels = QualityRange.All;
s.Priority = StoragePriority.Normal;
return s;
}
/// <summary>The ThingFilter a template stands for: the base with the template applied on top.</summary>
public static ThingFilter BuildFilter(StorageTemplate t)
{
StorageSettings s = BaseSettings();
t?.ApplyTo(s, ParentFilter);
return s.filter;
}
/// <summary>
/// What a rule's row says: "all items, hit points 50 to 100%, Normal or better", "allows 120 of 1,903 items,
/// refuses tainted apparel". Counts only names that resolve.
/// </summary>
public static string Summary(StorageTemplate t)
{
if (t == null)
return null;
ThingFilter f = BuildFilter(t);
List<ThingDef> storable = StorageKinds.StorableDefs(ParentFilter).ToList();
int allows = storable.Count(d => f.Allows(d));
var parts = new List<string>();
if (allows == storable.Count)
parts.Add("BlaxDefaults_ForbidSummaryAll".Translate());
else if (allows == 0)
parts.Add("BlaxDefaults_ForbidSummaryNone".Translate());
else
parts.Add("BlaxDefaults_ForbidSummarySome".Translate(allows.ToString("N0", System.Globalization.CultureInfo.InvariantCulture),
storable.Count.ToString("N0", System.Globalization.CultureInfo.InvariantCulture)));
if (t.hitPoints != FloatRange.ZeroToOne)
parts.Add("BlaxDefaults_ForbidSummaryHitPoints".Translate(Percent(t.hitPoints.min), Percent(t.hitPoints.max)));
string quality = QualityText(t.quality);
if (quality != null)
parts.Add(quality);
List<string> refusedSpecial = t.refusedSpecial
.Select(n => DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(n))
.Where(sf => sf != null && sf.configurable)
.Select(sf => sf.label)
.ToList();
if (refusedSpecial.Count > 0)
parts.Add("BlaxDefaults_ForbidSummaryRefuses".Translate(string.Join(", ", refusedSpecial)));
return string.Join(", ", parts);
}
private static string Percent(float f) => UnityEngine.Mathf.RoundToInt(f * 100f).ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>"Normal or better", "up to Normal", "Normal to Excellent", or null for every quality.</summary>
public static string QualityText(QualityRange q)
{
if (q == QualityRange.All)
return null;
if (q.max == QualityCategory.Legendary)
return "BlaxDefaults_ForbidSummaryQualityMin".Translate(q.min.GetLabel().CapitalizeFirst());
if (q.min == QualityCategory.Awful)
return "BlaxDefaults_ForbidSummaryQualityMax".Translate(q.max.GetLabel().CapitalizeFirst());
if (q.min == q.max)
return "BlaxDefaults_ForbidSummaryQualityOnly".Translate(q.min.GetLabel().CapitalizeFirst());
return "BlaxDefaults_ForbidSummaryQualityRange".Translate(q.min.GetLabel().CapitalizeFirst(), q.max.GetLabel().CapitalizeFirst());
}
/// <summary>The thing's forbidden flag, false for things that can't be forbidden.</summary>
public static bool IsForbiddenFlag(Thing t) => t is ThingWithComps twc && twc.GetComp<CompForbiddable>() is CompForbiddable c && c.Forbidden;
}
}