using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
namespace BlaxDefaults
{
/// Who a pawn that goes down, dies or is stripped belongs to, for the forbid rules.
public enum ForbidGroup
{
/// Neutral visitors, traders, quest lodgers and anyone else: the game's rules.
None,
/// Colonists, slaves, colony mechs, colony animals and prisoners, breaking out or rebelling included.
Colony,
/// Everyone else hostile to the player.
Enemies,
}
/// Which corpse switch a corpse falls under; the first kind that fits decides.
public enum CorpseKind
{
Animal,
Enemy,
Other,
}
///
/// 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.
///
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;
/// The rule's checkbox: colonyGearRule or enemyGearRule.
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;
}
}
/// "Where": true for anywhere (the default), false for only inside the home area.
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;
}
}
/// "Stripping forbids what doesn't match": colonyStripRule or enemyStripRule.
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;
}
}
/// The saved filter, or null.
public StorageTemplate Template => DefaultsLibrary.Get(Key);
public bool HasFilter => Template != null;
/// The gear rule acts: the forbid rules are on, the rule is ticked and it has a filter.
public bool Active => ForbidRules.On && Ticked && HasFilter;
/// The strip switch acts: the forbid rules are on, the switch is ticked and the rule has a filter.
public bool StripActive => ForbidRules.On && StripTicked && HasFilter;
/// "Gear your colony drops" or "Gear enemies drop".
public string Label => (Group == ForbidGroup.Colony ? "BlaxDefaults_ForbidColonyRule" : "BlaxDefaults_ForbidEnemyRule").Translate();
///
/// 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.
///
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;
}
}
/// The filter allows the thing (def, hit points, quality, special filters). False without a filter.
public bool Allows(Thing t)
{
ThingFilter f = Filter;
return f != null && t != null && f.Allows(t);
}
/// The thing's cell passes "Where": anywhere, or inside the home area of its map.
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];
}
///
/// 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.
///
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;
}
/// The strip switch the suggested setup sets.
public bool SuggestedStrip => Group == ForbidGroup.Enemies;
///
/// 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.
///
public bool UseSuggested()
{
bool ok = DefaultsLibrary.Set(Suggested());
Anywhere = true;
StripTicked = SuggestedStrip;
return ok;
}
///
/// 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").
///
public bool SetTicked(bool on)
{
bool usedSuggested = false;
if (on && !HasFilter)
{
UseSuggested();
usedSuggested = true;
}
Ticked = on;
return usedSuggested;
}
/// Forget: deletes the filter and turns the rule and its strip switch off.
public void Forget()
{
DefaultsLibrary.Forget(Key);
Ticked = false;
StripTicked = false;
}
public override string ToString() => Key;
}
///
/// 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).
///
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;
/// The forbid rules category is on (and the master switch).
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);
/// Anything a downing or a death could change: a gear rule acting or a corpse switch on.
public static bool AnyDropRuleOn =>
On && (Colony.Active || Enemies.Active || CorpseSwitch(CorpseKind.Animal) || CorpseSwitch(CorpseKind.Enemy) || CorpseSwitch(CorpseKind.Other));
///
/// 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.
///
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;
}
///
/// 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.
///
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;
}
///
/// The corpse switch a pawn's corpse falls under: animal (any RaceProps.Animal), then enemy (the group read
/// while it was alive), then other.
///
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;
}
/// The corpse switch for this kind is on (and the forbid rules).
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;
}
}
///
/// What a forbid filter may ever allow: every storable item (StorageSettings.EverStorableFixedSettings)
/// without the Corpses category, which the corpse switches cover. Built once.
///
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;
}
}
///
/// 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.
///
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;
}
/// The ThingFilter a template stands for: the base with the template applied on top.
public static ThingFilter BuildFilter(StorageTemplate t)
{
StorageSettings s = BaseSettings();
t?.ApplyTo(s, ParentFilter);
return s.filter;
}
///
/// 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.
///
public static string Summary(StorageTemplate t)
{
if (t == null)
return null;
ThingFilter f = BuildFilter(t);
List storable = StorageKinds.StorableDefs(ParentFilter).ToList();
int allows = storable.Count(d => f.Allows(d));
var parts = new List();
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 refusedSpecial = t.refusedSpecial
.Select(n => DefDatabase.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);
/// "Normal or better", "up to Normal", "Normal to Excellent", or null for every quality.
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());
}
/// The thing's forbidden flag, false for things that can't be forbidden.
public static bool IsForbiddenFlag(Thing t) => t is ThingWithComps twc && twc.GetComp() is CompForbiddable c && c.Forbidden;
}
}