rimworld-blax-laws/Source/BlaxLaws/Detection/Hook_C_Ingested.cs

87 lines
3.2 KiB
C#

using System;
using System.Runtime.CompilerServices;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxLaws
{
/// <summary>
/// Hook C: a pawn eats or drinks (category Ate) and every dose of a drug binge, which reaches
/// CompDrug.PostIngested through this method (Verse/Thing.cs:2180; Verse/ThingWithComps.cs:767-774). Prefix
/// and postfix on Thing.Ingested (Verse/Thing.cs:2005). Toils_Ingest calls it once per meal with the job's
/// target as the eaten thing (RimWorld/Toils_Ingest.cs:402, 428). The prefix reads the facts while the
/// stack still exists (it may be destroyed at :2176-2179) and checks that the eater acts on its own job;
/// the postfix files, so an ingestion vanilla refuses (destroyed, not ingestible now, :2007-2016) files
/// nothing.
/// </summary>
[HarmonyPatch(typeof(Thing), nameof(Thing.Ingested))]
public static class Patch_Thing_Ingested
{
public const string Where = "hook C, Thing.Ingested";
/// <summary>What the prefix hands to the postfix. A struct: an empty book allocates nothing.</summary>
public struct State
{
public bool file;
public ActFacts facts;
public ChemicalDef chemical;
public DrugCategory drugCategory;
}
public static void Prefix(Thing __instance, Pawn ingester, out State __state)
{
__state = default;
if (!Watch.Ate)
return;
__state = Read(__instance, ingester);
}
// The work, off the hot path: a method with a try block is never inlined, so the flag check above
// stays a static field read the patched method can inline.
[MethodImpl(MethodImplOptions.NoInlining)]
private static State Read(Thing __instance, Pawn ingester)
{
State __state = default;
try
{
ThingDef def = __instance?.def;
if (def == null || ingester == null || __instance.Destroyed || !Watch.MayMatch(ActCategories.Ate, def))
return default;
if (!Offenders.IsCovered(ingester) || !DetectionHooks.OnOwnJob(ingester, __instance))
return default;
__state.facts = FoodFacts.Of(__instance);
__state.chemical = DrugInfo.ChemicalOf(def);
__state.drugCategory = DrugInfo.CategoryOf(def);
__state.file = true;
}
catch (Exception e)
{
__state = default;
HookGuard.Fail(Where, e);
}
return __state;
}
public static void Postfix(Thing __instance, Pawn ingester, State __state)
{
if (!__state.file)
return;
try
{
CaseFiler.Report(new ActEvent(ActCategories.Ate, __instance.def, ingester)
{
thing = __instance,
facts = __state.facts,
chemical = __state.chemical,
drugCategory = __state.drugCategory,
});
}
catch (Exception e)
{
HookGuard.Fail(Where, e);
}
}
}
}