rimworld-blax-slaves/Source/BlaxSlaves/Brand.cs

266 lines
12 KiB
C#

using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxSlaves
{
public class HediffCompProperties_BrandOwner : HediffCompProperties
{
public HediffCompProperties_BrandOwner()
{
compClass = typeof(HediffComp_BrandOwner);
}
}
/// <summary>Remembers whose mark the brand is. The name is cached in case the faction is removed.</summary>
public class HediffComp_BrandOwner : HediffComp
{
public Faction owner;
public string ownerName;
public string OwnerName => owner?.Name ?? ownerName;
public void SetOwner(Faction faction)
{
owner = faction;
ownerName = faction?.Name;
}
public override string CompLabelInBracketsExtra => OwnerName;
public override string CompTipStringExtra =>
OwnerName.NullOrEmpty() ? null : (string)"BlaxSlaves_BrandOwnerTip".Translate(OwnerName);
public override void CompExposeData()
{
base.CompExposeData();
if (Scribe.mode == LoadSaveMode.Saving && owner != null && !Find.FactionManager.AllFactionsListForReading.Contains(owner))
owner = null;
Scribe_References.Look(ref owner, "owner");
Scribe_Values.Look(ref ownerName, "ownerName");
}
public override void CopyFrom(HediffComp other)
{
base.CopyFrom(other);
if (other is HediffComp_BrandOwner o)
{
owner = o.owner;
ownerName = o.ownerName;
}
}
}
public static class BrandUtility
{
public const float FreshBurnSeverity = 10f;
public static bool IsBranded(Pawn pawn) =>
pawn?.health?.hediffSet != null && pawn.health.hediffSet.HasHediff(BlaxDefOf.BlaxSlaves_SlaveBrand);
public static HediffComp_BrandOwner BrandOf(Pawn pawn) =>
pawn?.health?.hediffSet?.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand)?.TryGetComp<HediffComp_BrandOwner>();
/// <summary>The brand stage's SlaveSuppressionFallRate factor (from the def), 1 without a brand.</summary>
public static float SuppressionFallFactor(Pawn pawn, out Hediff brand)
{
brand = pawn?.health?.hediffSet?.GetFirstHediffOfDef(BlaxDefOf.BlaxSlaves_SlaveBrand);
List<StatModifier> factors = brand?.CurStage?.statFactors;
if (factors == null || StatDefOf.SlaveSuppressionFallRate == null)
return 1f;
float f = 1f;
foreach (StatModifier m in factors)
if (m.stat == StatDefOf.SlaveSuppressionFallRate)
f *= m.value;
return f;
}
public static bool IsBrandedByPlayer(Pawn pawn)
{
HediffComp_BrandOwner brand = BrandOf(pawn);
return brand != null && brand.owner != null && brand.owner == Faction.OfPlayer;
}
public static void Brand(Pawn pawn, Faction owner)
{
if (IsBranded(pawn))
{
BrandOf(pawn)?.SetOwner(owner);
return;
}
Hediff brand = HediffMaker.MakeHediff(BlaxDefOf.BlaxSlaves_SlaveBrand, pawn);
brand.TryGetComp<HediffComp_BrandOwner>()?.SetOwner(owner);
pawn.health.AddHediff(brand);
}
/// <summary>A fresh burn on the core part (torso for humans): about a day of pain.</summary>
public static void AddFreshBurn(Pawn pawn, float severity = FreshBurnSeverity)
{
HediffDef burnDef = DamageDefOf.Burn?.hediff;
BodyPartRecord part = pawn.RaceProps?.body?.corePart;
if (burnDef == null || part == null || pawn.health.hediffSet.PartIsMissing(part))
return;
if (pawn.health.WouldDieAfterAddingHediff(burnDef, part, severity))
return;
Hediff burn = HediffMaker.MakeHediff(burnDef, pawn, part);
burn.Severity = severity;
// A deliberate mark, like scarification: no infection roll. After a reload the recreated
// comp starts inert (ticksUntilInfect defaults to "will not infect").
(burn as HediffWithComps)?.comps?.RemoveAll(c => c is HediffComp_Infecter);
pawn.health.AddHediff(burn, part);
}
}
/// <summary>"Branded" mood only while they're someone's slave; a freed pawn keeps the scar, not the shame.</summary>
public class ThoughtWorker_Branded : ThoughtWorker_Hediff
{
protected override ThoughtState CurrentStateInternal(Pawn p) =>
p.IsSlave ? base.CurrentStateInternal(p) : ThoughtState.Inactive;
}
/// <summary>Branding surgery: colony slaves only. Never fails, marks them as the player's.</summary>
public class Recipe_BrandSlave : Recipe_AddHediff
{
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null) =>
thing is Pawn pawn && pawn.IsSlaveOfColony && base.AvailableOnNow(thing, part);
// A bill queued before the slave got branded (bought back, handed over) must not stack a second
// brand on top; taking over someone else's brand is the rebrand surgery.
public override bool CompletableEver(Pawn surgeryTarget) =>
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony && !BrandUtility.IsBranded(surgeryTarget);
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
if (BrandUtility.IsBranded(pawn))
return;
base.ApplyOnPawn(pawn, part, billDoer, ingredients, bill);
}
protected override void OnSurgerySuccess(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
base.OnSurgerySuccess(pawn, part, billDoer, ingredients, bill);
BrandUtility.BrandOf(pawn)?.SetOwner(Faction.OfPlayer);
BrandUtility.AddFreshBurn(pawn);
if (billDoer != null)
Messages.Message("BlaxSlaves_BrandedMessage".Translate(billDoer.Named("DOCTOR"), pawn.Named("PAWN")), pawn, MessageTypeDefOf.NeutralEvent);
}
}
/// <summary>Burns the colony's mark over another owner's brand.</summary>
public class Recipe_RebrandSlave : Recipe_Surgery
{
public override bool AvailableOnNow(Thing thing, BodyPartRecord part = null)
{
if (!(thing is Pawn pawn) || !pawn.IsSlaveOfColony)
return false;
HediffComp_BrandOwner brand = BrandUtility.BrandOf(pawn);
return brand != null && brand.owner != Faction.OfPlayer
&& !pawn.BillStack.Bills.Any(b => b.recipe == recipe)
&& base.AvailableOnNow(thing, part);
}
public override bool CompletableEver(Pawn surgeryTarget) =>
base.CompletableEver(surgeryTarget) && surgeryTarget.IsSlaveOfColony
&& BrandUtility.BrandOf(surgeryTarget) is HediffComp_BrandOwner brand && brand.owner != Faction.OfPlayer;
public override void ApplyOnPawn(Pawn pawn, BodyPartRecord part, Pawn billDoer, List<Thing> ingredients, Bill bill)
{
HediffComp_BrandOwner brand = BrandUtility.BrandOf(pawn);
if (brand == null || brand.owner == Faction.OfPlayer)
return;
brand.SetOwner(Faction.OfPlayer);
BrandUtility.AddFreshBurn(pawn);
if (billDoer != null)
Messages.Message("BlaxSlaves_RebrandedMessage".Translate(billDoer.Named("DOCTOR"), pawn.Named("PAWN")), pawn, MessageTypeDefOf.NeutralEvent);
}
}
/// <summary>
/// Some slaves in trader stock already carry an owner's brand: the trader's faction, or another one.
/// First applies the default purchase mode (buy as slave or colonist), before any early return, so
/// children, non-slave stock and pre-branded pawns get it too and the brand roll sees the final joinStatus.
/// </summary>
[HarmonyPatch(typeof(ThingWithComps), nameof(ThingWithComps.PostGeneratedForTrader))]
public static class Patch_TraderSlaveBrand
{
public static void Postfix(ThingWithComps __instance, TraderKindDef trader, Faction forFaction)
{
BuyMode.ApplyDefaultPurchaseMode(__instance, trader);
if (!(__instance is Pawn pawn) || pawn.Dead || pawn.RaceProps == null || !pawn.RaceProps.Humanlike)
return;
if (pawn.ageTracker == null || !pawn.ageTracker.Adult || BrandUtility.IsBranded(pawn))
return;
if (!IsSlaveStock(pawn, trader))
return;
if (pawn.guest != null && pawn.guest.joinStatus == JoinStatus.JoinAsColonist)
return;
if (!Rand.Chance(BlaxSlavesMod.Settings.traderBrandChance))
return;
Faction owner = forFaction;
if (owner == null || owner.IsPlayer)
{
owner = Find.FactionManager.AllFactionsVisible
.Where(f => !f.IsPlayer && !f.temporary && f.def.humanlikeFaction && f != pawn.Faction)
.RandomElementWithFallback();
}
if (owner != null)
BrandUtility.Brand(pawn, owner);
}
/// <summary>
/// Only pawns a slave generator made: the Slave kind (vanilla, and More Slaves' own generator),
/// or a trader's custom slave kind (Royalty's Slave_Empire). Not hired pawns from mods like Rimdeed.
/// </summary>
private static bool IsSlaveStock(Pawn pawn, TraderKindDef trader)
{
if (trader != null && trader.defName == "RD_PawnTrader")
return false;
if (pawn.kindDef == PawnKindDefOf.Slave)
return true;
return trader?.stockGenerators != null
&& trader.stockGenerators.Any(g => g is StockGenerator_Slaves s && s.slaveKindDef != null && s.slaveKindDef == pawn.kindDef);
}
}
}
namespace BlaxSlaves
{
/// <summary>
/// StatWorker_SuppressionFallRate overrides GetValueUnfinalized without the hediff stat factors the
/// base worker applies, so the brand stage's SlaveSuppressionFallRate factor would do nothing.
/// Applies the brand's factor (and only that one, so other mods' hediffs keep vanilla behaviour).
/// </summary>
[HarmonyPatch(typeof(StatWorker_SuppressionFallRate), nameof(StatWorker_SuppressionFallRate.GetValueUnfinalized))]
public static class Patch_BrandSuppressionFallRate
{
public static void Postfix(StatRequest req, ref float __result)
{
float f = BrandUtility.SuppressionFallFactor(req.Thing as Pawn, out _);
if (f != 1f)
__result *= f;
}
}
/// <summary>Shows the brand's factor in the stat breakdown and the suppression tooltip.</summary>
[HarmonyPatch]
public static class Patch_BrandSuppressionFallRateExplanation
{
public static IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(StatWorker_SuppressionFallRate), nameof(StatWorker_SuppressionFallRate.GetExplanationUnfinalized));
yield return AccessTools.Method(typeof(StatWorker_SuppressionFallRate), nameof(StatWorker_SuppressionFallRate.GetExplanationForTooltip));
}
public static void Postfix(StatRequest req, ref string __result)
{
float f = BrandUtility.SuppressionFallFactor(req.Thing as Pawn, out Hediff brand);
if (f != 1f && brand != null)
__result = __result.TrimEnd() + "\n " + brand.LabelBaseCap + ": x" + f.ToStringPercent();
}
}
}