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

175 lines
6.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using Verse;
namespace BlaxSlaves
{
/// <summary>
/// Optional links to the other Blax mods (Blax Castes, Blax Zones). No assembly reference and no
/// hard dependency: their static APIs are bound by reflection at startup. A missing mod or method
/// leaves the delegate null and every call a silent no-op. The APIs only ever grow.
/// </summary>
public static class Siblings
{
public const string CastesId = "blax.castes";
public const string ZonesId = "blax.zones";
public const string ReasonRunawayReturned = "blax.slaves.runawayReturned";
public static int CastesVersion { get; private set; }
public static int ZonesVersion { get; private set; }
private static Action<Verse.Pawn, string> castesNotifyJoined;
private static Action<Verse.Pawn, string> castesHintJoinReason;
public delegate bool TryFindDropSpotFn(Map map, Thing thing, out IntVec3 cell);
private static TryFindDropSpotFn zonesTryFindDropSpot;
private static readonly List<(Verse.Pawn pawn, string reason, int tick)> notifyQueue = new List<(Verse.Pawn, string, int)>();
private static bool warned;
public static bool CastesBound => castesNotifyJoined != null || castesHintJoinReason != null;
public static bool ZonesBound => zonesTryFindDropSpot != null;
public static void Init()
{
castesNotifyJoined = null;
castesHintJoinReason = null;
zonesTryFindDropSpot = null;
CastesVersion = 0;
ZonesVersion = 0;
try
{
if (Compat.IsActive(CastesId))
{
Type api = AccessTools.TypeByName("BlaxCastes.CastesApi");
if (api != null)
{
CastesVersion = ReadVersion(api);
castesNotifyJoined = Bind<Action<Verse.Pawn, string>>(api, "NotifyJoined", typeof(Verse.Pawn), typeof(string));
castesHintJoinReason = Bind<Action<Verse.Pawn, string>>(api, "HintJoinReason", typeof(Verse.Pawn), typeof(string));
}
}
if (Compat.IsActive(ZonesId))
{
Type api = AccessTools.TypeByName("BlaxZones.ZonesApi");
if (api != null)
{
ZonesVersion = ReadVersion(api);
zonesTryFindDropSpot = Bind<TryFindDropSpotFn>(api, "TryFindDropSpot", typeof(Map), typeof(Thing), typeof(IntVec3).MakeByRefType());
}
}
}
catch (Exception e)
{
Log.Warning("[Blax Slaves] Binding the other Blax mods failed, they stay unlinked: " + e.Message);
}
}
public static string Describe()
{
string castes = Compat.IsActive(CastesId) ? (CastesBound ? "Blax Castes v" + CastesVersion : "Blax Castes (no API yet)") : null;
string zones = Compat.IsActive(ZonesId) ? (ZonesBound ? "Blax Zones v" + ZonesVersion : "Blax Zones (no API yet)") : null;
if (castes == null && zones == null)
return "BlaxSlaves_CompatNoSiblings".Translate();
return castes != null && zones != null ? castes + ", " + zones : castes ?? zones;
}
/// <summary>Tell Blax Castes about a join it can't see itself. Called one tick after the status is final.</summary>
public static void CastesNotifyJoined(Verse.Pawn pawn, string reason) => Call(castesNotifyJoined, pawn, reason);
/// <summary>Tell Blax Castes why the next join of this pawn (this tick) happens.</summary>
public static void CastesHintJoinReason(Verse.Pawn pawn, string reason) => Call(castesHintJoinReason, pawn, reason);
/// <summary>Queue a NotifyJoined for the next tick, after vanilla's status-change resets have run.</summary>
public static void CastesNotifyJoinedNextTick(Verse.Pawn pawn, string reason)
{
if (castesNotifyJoined == null || pawn == null || Find.TickManager == null)
return;
notifyQueue.Add((pawn, reason, Find.TickManager.TicksGame));
}
/// <summary>Drains the NotifyJoined queue. Called every tick from GameComponent_BlaxRunaways.</summary>
public static void Tick()
{
if (notifyQueue.Count == 0)
return;
int now = Find.TickManager.TicksGame;
for (int i = 0; i < notifyQueue.Count; i++)
{
var (pawn, reason, tick) = notifyQueue[i];
if (tick >= now)
continue;
notifyQueue.RemoveAt(i--);
if (pawn != null && !pawn.Destroyed && !pawn.Dead)
CastesNotifyJoined(pawn, reason);
}
}
public static void ClearQueue() => notifyQueue.Clear();
/// <summary>A delivery zone cell for this thing from Blax Zones, if it has one.</summary>
public static bool ZonesTryFindDropSpot(Map map, Thing thing, out IntVec3 cell)
{
cell = IntVec3.Invalid;
if (zonesTryFindDropSpot == null || map == null || thing == null)
return false;
try
{
return zonesTryFindDropSpot(map, thing, out cell) && cell.IsValid;
}
catch (Exception e)
{
WarnOnce(e);
cell = IntVec3.Invalid;
return false;
}
}
private static void Call(Action<Verse.Pawn, string> fn, Verse.Pawn pawn, string reason)
{
if (fn == null || pawn == null)
return;
try
{
fn(pawn, reason);
}
catch (Exception e)
{
WarnOnce(e);
}
}
private static void WarnOnce(Exception e)
{
if (warned)
return;
warned = true;
Log.Warning("[Blax Slaves] A call into another Blax mod failed (shown once): " + e);
}
private static int ReadVersion(Type api)
{
object v = AccessTools.Property(api, "Version")?.GetValue(null) ?? AccessTools.Field(api, "Version")?.GetValue(null);
return v is int i ? i : 0;
}
private static T Bind<T>(Type api, string name, params Type[] args) where T : Delegate
{
MethodInfo m = AccessTools.Method(api, name, args);
if (m == null || !m.IsStatic)
return null;
try
{
return (T)Delegate.CreateDelegate(typeof(T), m);
}
catch (ArgumentException)
{
return null;
}
}
}
}