rimworld-blax-castes/Source/BlaxCastes/WeaponsTab.cs

219 lines
9.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HarmonyLib;
using Verse;
namespace BlaxCastes
{
/// <summary>
/// The weapon loadout slot's link to [1001] Weapons Tab Reborn (packageId papercrane1001.WeaponsTab).
/// Bound by reflection to the static API it publishes for Better Pawn Control, in
/// WeaponsTabReborn.LoadoutDictionary (read from its 1.6 assembly, which 1.7 loads):
/// - int BPC_GetLoadoutId(Pawn): the pawn's loadout id; a pawn without one gets the default loadout.
/// - void BPC_SetLoadoutId(Pawn, int): an id that does not exist clears the pawn's loadout, so Castes
/// checks the id first.
/// - int BPC_GetDefaultLoadoutId(): the first loadout.
/// - string BPC_GetLoadoutNamebyId(int): throws InvalidOperationException for an id that does not exist.
/// - Dictionary&lt;string, int&gt; BPC_GetWeaponsLoadoutsDatabase(): label to id. It only ever grows
/// (deleted and renamed loadouts stay in it, and a new loadout whose label is already a key is left
/// out), so every id in it is checked by name, and the ids just above the highest one are probed.
/// Loadout ids are the highest id plus one, so an id freed by deleting the newest loadout can come back.
/// A missing type or method turns the slot off for the session; a call that throws anything else turns
/// it off for the rest of the game. Either logs one warning and never throws.
/// </summary>
public static class WeaponsTab
{
public const string ApiTypeName = "WeaponsTabReborn.LoadoutDictionary";
/// <summary>How many ids above the highest known one Loadouts() checks.</summary>
private const int ProbeAhead = 16;
private static bool? modActive;
private static bool bound;
private static bool bindFailed;
private static bool callFailed;
private static Func<Pawn, int> getLoadoutId;
private static Action<Pawn, int> setLoadoutId;
private static Func<int> getDefaultLoadoutId;
private static Func<int, string> getLoadoutName;
private static Func<Dictionary<string, int>> getDatabase;
/// <summary>Weapons Tab Reborn is in the active mod list. The manager hides the loadout row without it.</summary>
public static bool ModActive => modActive ??= Compat.IsActive(Compat.WeaponsTab);
/// <summary>The mod is active and its API is bound and has not failed in this game.</summary>
public static bool Available => ModActive && Bind() && !callFailed;
public static bool SettingOn => BlaxCastesMod.Settings == null || BlaxCastesMod.Settings.manageWeaponLoadout;
/// <summary>The slot is written: the API works and the manageWeaponLoadout setting is on.</summary>
public static bool Active => SettingOn && Available;
/// <summary>Called when a game starts or loads, so a call that failed in an earlier game is tried again.</summary>
internal static void ResetForGame() => callFailed = false;
// ---- binding -----------------------------------------------------------------------------
private static bool Bind()
{
if (bound)
return !bindFailed;
bound = true;
try
{
Type api = AccessTools.TypeByName(ApiTypeName);
if (api == null)
return BindFailed("type " + ApiTypeName + " not found");
getLoadoutId = Make<Func<Pawn, int>>(api, "BPC_GetLoadoutId", typeof(int), typeof(Pawn));
setLoadoutId = Make<Action<Pawn, int>>(api, "BPC_SetLoadoutId", typeof(void), typeof(Pawn), typeof(int));
getDefaultLoadoutId = Make<Func<int>>(api, "BPC_GetDefaultLoadoutId", typeof(int));
getLoadoutName = Make<Func<int, string>>(api, "BPC_GetLoadoutNamebyId", typeof(string), typeof(int));
getDatabase = Make<Func<Dictionary<string, int>>>(api, "BPC_GetWeaponsLoadoutsDatabase", typeof(Dictionary<string, int>));
var missing = new List<string>();
if (getLoadoutId == null) missing.Add("BPC_GetLoadoutId");
if (setLoadoutId == null) missing.Add("BPC_SetLoadoutId");
if (getDefaultLoadoutId == null) missing.Add("BPC_GetDefaultLoadoutId");
if (getLoadoutName == null) missing.Add("BPC_GetLoadoutNamebyId");
if (getDatabase == null) missing.Add("BPC_GetWeaponsLoadoutsDatabase");
return missing.Count == 0 || BindFailed(string.Join(", ", missing) + " not found");
}
catch (Exception e)
{
return BindFailed(e.GetType().Name + ": " + e.Message);
}
}
private static TDelegate Make<TDelegate>(Type api, string name, Type returnType, params Type[] parameters) where TDelegate : Delegate
{
MethodInfo method = api.GetMethod(name, BindingFlags.Public | BindingFlags.Static, null, parameters, null);
if (method == null || method.ReturnType != returnType)
return null;
return (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), method, throwOnBindFailure: false);
}
private static bool BindFailed(string why)
{
bindFailed = true;
Log.Warning("[Blax Castes] Weapons Tab Reborn is active, but its loadout API could not be used (" + why + "). The weapon loadout slot is off.");
return false;
}
private static void CallFailed(string call, Exception e)
{
if (callFailed)
return;
callFailed = true;
Log.Warning("[Blax Castes] Weapons Tab Reborn's " + call + " failed (" + e.GetType().Name + ": " + e.Message
+ "). The weapon loadout slot is off until the next game is loaded.");
}
// ---- calls -------------------------------------------------------------------------------
/// <summary>The pawn's loadout id, or null when the API is not available.</summary>
public static int? LoadoutOf(Pawn pawn)
{
if (pawn == null || !Available)
return null;
try
{
return getLoadoutId(pawn);
}
catch (Exception e)
{
CallFailed("BPC_GetLoadoutId", e);
return null;
}
}
/// <summary>Sets the pawn's loadout. False when the API is not available or the id does not exist.</summary>
public static bool SetLoadout(Pawn pawn, int id)
{
if (pawn == null || !Exists(id))
return false;
try
{
setLoadoutId(pawn, id);
return true;
}
catch (Exception e)
{
CallFailed("BPC_SetLoadoutId", e);
return false;
}
}
/// <summary>The default loadout's id (what a pawn without one uses), or null.</summary>
public static int? DefaultLoadoutId()
{
if (!Available)
return null;
try
{
return getDefaultLoadoutId();
}
catch (Exception e)
{
CallFailed("BPC_GetDefaultLoadoutId", e);
return null;
}
}
/// <summary>The loadout's label, or null when it does not exist or the API is not available.</summary>
public static string NameOf(int id)
{
if (id < 0 || !Available)
return null;
try
{
return getLoadoutName(id);
}
catch (InvalidOperationException)
{
// Enumerable.First found no loadout with that id: it was deleted.
return null;
}
catch (Exception e)
{
CallFailed("BPC_GetLoadoutNamebyId", e);
return null;
}
}
public static bool Exists(int id) => NameOf(id) != null;
/// <summary>The loadouts that exist now, as (id, label), by id.</summary>
public static List<KeyValuePair<int, string>> Loadouts()
{
var result = new List<KeyValuePair<int, string>>();
if (!Available)
return result;
Dictionary<string, int> database;
try
{
database = getDatabase();
}
catch (Exception e)
{
CallFailed("BPC_GetWeaponsLoadoutsDatabase", e);
return result;
}
if (database == null)
return result;
// A loadout whose label an older entry already holds never gets into the database dictionary.
// New loadouts get the highest id plus one, so the ids just above the known ones are probed too.
int highest = database.Count == 0 ? 0 : database.Values.Max();
IEnumerable<int> ids = database.Values.Concat(Enumerable.Range(0, Math.Max(0, highest) + ProbeAhead + 1));
foreach (int id in ids.Where(i => i >= 0).Distinct().OrderBy(i => i))
{
string name = NameOf(id);
if (name != null)
result.Add(new KeyValuePair<int, string>(id, name));
}
return result;
}
}
}