consolidate plugin loading code

This commit is contained in:
Az committed 2026-11-13 00:55:24 -05:00
1 parent 2805599d35
commit 94fbaac1ea
14 files changed
+140 -165

No files matched your search

+4 -6
View File
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
@@ -45,11 +46,8 @@ public static class PaletteManager
private static int originalLength;
internal static bool RegisterColors(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterColors(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var miraPlugin = context.MiraPlugin;
if (!type.TryGetCustomAttribute<RegisterCustomColorsAttribute>(out var attribute))
{
return false;
@@ -79,7 +77,7 @@ public static class PaletteManager
VariableColorNames.Add(color.Name);
}
if (!miraPlugin.DebugMode)
if (!context.MiraPlugin.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers)
+11 -17
View File
@@ -84,27 +84,24 @@ public static class MiraEventManager
return true;
}
internal static bool RegisterEventType(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterEventType(Type type, in MiraPluginManager.RegistrationContext context)
{
var eventType = context.Type;
var pluginInfo = context.PluginInfo;
if (eventType.IsAbstract || !eventType.IsSubclassOf(typeof(MiraEvent)))
if (type.IsAbstract || !type.IsSubclassOf(typeof(MiraEvent)))
{
return false;
}
AddTypeToTracked(eventType);
AddTypeToTracked(type);
// subtypes are added to their supertypes, regardless of which were added first
TrackedEventTypes[eventType].UnionWith(InternalEventTypes.Where(x => x.IsSubclassOfWithGeneric(eventType)));
foreach (var supertype in InternalEventTypes.Where(x => eventType.IsSubclassOfWithGeneric(x)))
TrackedEventTypes[type].UnionWith(InternalEventTypes.Where(x => x.IsSubclassOfWithGeneric(type)));
foreach (var supertype in InternalEventTypes.Where(x => type.IsSubclassOfWithGeneric(x)))
{
AddTypeToTracked(supertype, eventType);
AddTypeToTracked(supertype, type);
}
pluginInfo.InternalEventTypes.Add(eventType);
InternalEventTypes.Add(eventType);
context.PluginInfo.InternalEventTypes.Add(type);
InternalEventTypes.Add(type);
return true;
}
@@ -343,14 +340,11 @@ public static class MiraEventManager
EventHandlersToLoad.Clear();
}
internal static bool RegisterEvents(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterEvents(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var miraPlugin = context.MiraPlugin;
var hasContainerAttribute = type.IsDefined<RegisterEventContainerAttribute>();
if (!miraPlugin.ForceRegisterEvents && !hasContainerAttribute)
if (!context.MiraPlugin.ForceRegisterEvents && !hasContainerAttribute)
{
return false;
}
@@ -368,7 +362,7 @@ public static class MiraEventManager
continue;
}
RegisterEventHandler(method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
RegisterEventHandler(parameters[0].ParameterType, method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
}
return hasContainerAttribute;
+1 -3
View File
@@ -15,10 +15,8 @@ public static class GameOverManager
private static int nextId = Enum.GetNames<GameOverReason>().Length;
internal static bool RegisterGameOver(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterGameOver(Type type, in MiraPluginManager.RegistrationContext _)
{
var type = context.Type;
if (!typeof(CustomGameOver).IsAssignableFrom(type))
{
return false;
+2 -5
View File
@@ -19,11 +19,8 @@ public static class CustomGameModeManager
return ++lastId;
}
internal static bool RegisterGameMode(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterGameMode(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(AbstractGameMode).IsAssignableFrom(type))
{
return false;
@@ -41,7 +38,7 @@ public static class CustomGameModeManager
var id = GetNextId();
mode.ID = id;
IdToModeMap.Add(id, mode);
pluginInfo.GameModes.Add(id, mode);
context.PluginInfo.GameModes.Add(id, mode);
GameModeOption.AddOption(mode);
return true;
}
+16 -43
View File
@@ -67,15 +67,8 @@ public static class ModdedOptionsManager
notif.SettingsChangeMessageLogic(key, item, playSound);
}
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterGroup(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterGroup(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!type.IsAssignableTo(typeof(AbstractOptionGroup)))
{
return false;
@@ -104,40 +97,44 @@ public static class ModdedOptionsManager
}
}
var pluginInfo = context.PluginInfo;
pluginInfo.InternalOptionGroups.Add(group);
Groups.Add(group);
TypeToGroup.Add(type, group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, group);
Helpers.SetInstance(typeof(OptionGroupSingleton<>), type, group);
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers))
{
if (property.PropertyType.IsAssignableTo(typeof(IModdedOption)))
{
RegisterPropertyOption(type, property, pluginInfo);
RegisterPropertyOption(group, property, pluginInfo);
continue;
}
if (property.PropertyType.IsAssignableTo(typeof(IBaseModdedOptionList)))
{
RegisterPropertyOptionList(type, property, pluginInfo);
RegisterPropertyOptionList(group, property, pluginInfo);
continue;
}
if (property.TryGetCustomAttribute<ModdedOptionAttribute>(out var attribute))
{
RegisterAttributeOption(type, attribute, property, pluginInfo);
RegisterAttributeOption(group, attribute, property, pluginInfo);
continue;
}
if (property.TryGetCustomAttribute<ModdedOptionListAttribute>(out var listAttr))
{
RegisterAttributeOptionList(type, listAttr, property, pluginInfo);
RegisterAttributeOptionList(group, listAttr, property, pluginInfo);
}
}
if (!pluginInfo.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !f.IsAutoPropertyBackingField()
&& (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IBaseModdedOptionList)))))
@@ -148,14 +145,8 @@ public static class ModdedOptionsManager
return true;
}
private static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
private static void RegisterPropertyOption(AbstractOptionGroup group, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
return;
}
if (property.GetValue(group) is not IModdedOption option)
{
Error($"Failed to get option for {property.Name}");
@@ -166,7 +157,7 @@ public static class ModdedOptionsManager
}
private static void RegisterAttributeOption(
Type type,
AbstractOptionGroup group,
ModdedOptionAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo)
@@ -177,12 +168,6 @@ public static class ModdedOptionsManager
return;
}
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
return;
}
var option = attribute.CreateOption(property.GetValue(group), property);
if (option == null)
@@ -230,14 +215,8 @@ public static class ModdedOptionsManager
RegisterOption(option, group, property.Name, pluginInfo);
}
private static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo)
private static void RegisterPropertyOptionList(AbstractOptionGroup group, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
return;
}
if (property.GetValue(group) is not IBaseModdedOptionList optionList)
{
Error($"Failed to get option list for {property.Name}");
@@ -253,7 +232,7 @@ public static class ModdedOptionsManager
}
private static void RegisterAttributeOptionList(
Type type,
AbstractOptionGroup group,
ModdedOptionListAttribute attribute,
PropertyInfo property,
MiraPluginInfo pluginInfo)
@@ -264,12 +243,6 @@ public static class ModdedOptionsManager
return;
}
if (!TypeToGroup.TryGetValue(type, out var group))
{
Error($"Failed to get group for {type.Name}");
return;
}
var propertyVal = property.GetValue(group);
if (propertyVal == null)
+9 -19
View File
@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using MiraAPI.Events.Mira;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
namespace MiraAPI.Hud;
@@ -32,38 +31,29 @@ public static class CustomButtonManager
internal static readonly Dictionary<Type, Type> ButtonEventTypes = [];
internal static readonly Dictionary<Type, Type> ButtonCancelledEventTypes = [];
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterButton(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterButton(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!type.IsAssignableTo(typeof(CustomActionButton)) || Activator.CreateInstance(type) is not CustomActionButton button)
{
return false;
}
context.PluginInfo.InternalButtons.Add(button);
CustomButtons.Add(button);
pluginInfo.InternalButtons.Add(button);
typeof(CustomButtonSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this
.SetValue(null, button);
ButtonEventTypes.Add(type, typeof(MiraButtonClickEvent<>).MakeGenericType(type));
ButtonCancelledEventTypes.Add(type, typeof(MiraButtonCancelledEvent<>).MakeGenericType(type));
Helpers.SetInstance(typeof(CustomButtonSingleton<>), type, button);
return true;
}
internal static void RegisterAllButtons()
{
// Save all buttons into a read-only collection for easy access
Buttons = new ReadOnlyCollection<CustomActionButton>(CustomButtonManager.CustomButtons);
EventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonEventTypes);
CancelledEventTypes = new ReadOnlyDictionary<Type, Type>(CustomButtonManager.ButtonCancelledEventTypes);
Buttons = new ReadOnlyCollection<CustomActionButton>(CustomButtons);
EventTypes = new ReadOnlyDictionary<Type, Type>(ButtonEventTypes);
CancelledEventTypes = new ReadOnlyDictionary<Type, Type>(ButtonCancelledEventTypes);
}
}
+12 -4
View File
@@ -23,6 +23,15 @@ public static class KeybindManager
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
internal static readonly Dictionary<Type, VanillaKeybind> VanillaKeybinds = [];
internal static void SetKeybind<T>(int keybindId)
where T : ActionButton
{
var type = typeof(T);
var bind = new VanillaKeybind(keybindId);
VanillaKeybinds[type] = bind;
Helpers.SetInstance(typeof(VanillaKeybinding<>), type, bind);
}
internal static void RewiredInit()
{
try
@@ -78,16 +87,15 @@ public static class KeybindManager
}
}
internal static bool RegisterKeybinds(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterKeybinds(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var miraPlugin = context.MiraPlugin;
if (!type.IsDefined<RegisterCustomKeybindsAttribute>())
{
return false;
}
var miraPlugin = context.MiraPlugin;
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers))
{
if (!property.PropertyType.IsAssignableTo(typeof(MiraKeybind)))
+6 -14
View File
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using BepInEx.Configuration;
using MiraAPI.LocalSettings.Attributes;
using MiraAPI.PluginLoading;
@@ -19,15 +17,8 @@ public static class LocalSettingsManager
internal static readonly List<LocalSettingsTab> Tabs = [];
internal static readonly List<LocalSettingsTab> AvailableTabs = [];
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
internal static bool RegisterLocalTabs(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterLocalTabs(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var basePlugin = context.BasePlugin;
if (!type.IsAssignableTo(typeof(LocalSettingsTab)))
{
return false;
@@ -39,7 +30,7 @@ public static class LocalSettingsManager
return false;
}
if (Activator.CreateInstance(type, basePlugin.Config) is not LocalSettingsTab tabInstance)
if (Activator.CreateInstance(type, context.BasePlugin.Config) is not LocalSettingsTab tabInstance)
{
return false;
}
@@ -53,9 +44,7 @@ public static class LocalSettingsManager
TypeToTab.Add(type, tabInstance);
typeof(LocalSettingsTabSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this
.SetValue(null, tabInstance);
Helpers.SetInstance(typeof(LocalSettingsTabSingleton<>), type, tabInstance);
foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers))
{
@@ -91,6 +80,9 @@ public static class LocalSettingsManager
attribute.CreateSetting(type, configEntry);
}
if (!context.MiraPlugin.DebugMode)
return true;
foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers)
.Where(f => !f.IsAutoPropertyBackingField()
&& (f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) || f.FieldType.IsAssignableTo(typeof(LocalSettingsButton)))))
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Components;
using UnityEngine;
@@ -22,34 +23,30 @@ public static class MeetingButtonManager
/// </summary>
public static List<MeetingActionButton> UntargetedButtons { get; internal set; } = [];
internal static bool RegisterTargetedMeetingButton(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterTargetedMeetingButton(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(TargetedMeetingButton).IsAssignableFrom(type))
{
return false;
}
var button = (Activator.CreateInstance(type) as TargetedMeetingButton)!;
pluginInfo.InternalTargetedMeetingButtons.Add(button);
context.PluginInfo.InternalTargetedMeetingButtons.Add(button);
TargetedButtons.Add(button);
Helpers.SetInstance(typeof(TargetedMeetingButtonSingleton<>), type, button);
return true;
}
internal static bool RegisterMeetingButton(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterMeetingButton(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(MeetingActionButton).IsAssignableFrom(type))
{
return false;
}
var button = (Activator.CreateInstance(type) as MeetingActionButton)!;
pluginInfo.InternalMeetingButtons.Add(button);
context.PluginInfo.InternalMeetingButtons.Add(button);
UntargetedButtons.Add(button);
return true;
}
+2 -5
View File
@@ -67,11 +67,8 @@ public static class ModifierManager
Modifiers = new ReadOnlyCollection<BaseModifier>(InternalModifiers);
}
internal static bool RegisterModifier(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterModifier(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
if (!typeof(BaseModifier).IsAssignableFrom(type))
{
return false;
@@ -94,7 +91,7 @@ public static class ModifierManager
modifier = (BaseModifier)FormatterServices.GetUninitializedObject(type);
}
pluginInfo.InternalModifiers.Add(modifier);
context.PluginInfo.InternalModifiers.Add(modifier);
InternalModifiers.Add(modifier);
if (modifier is not GameModifier gameModifier)
+6 -6
View File
@@ -21,11 +21,11 @@ public static class KeybindMenuPatch
_registered = true;
// Set these here right after input manager initializes
KeybindManager.VanillaKeybinds[typeof(KillButton)] = new VanillaKeybind(8);
KeybindManager.VanillaKeybinds[typeof(UseButton)] = new VanillaKeybind(6);
KeybindManager.VanillaKeybinds[typeof(ReportButton)] = new VanillaKeybind(7);
KeybindManager.VanillaKeybinds[typeof(VentButton)] = new VanillaKeybind(50);
KeybindManager.VanillaKeybinds[typeof(SabotageButton)] = new VanillaKeybind(4);
KeybindManager.VanillaKeybinds[typeof(AbilityButton)] = new VanillaKeybind(49);
KeybindManager.SetKeybind<KillButton>(8);
KeybindManager.SetKeybind<UseButton>(6);
KeybindManager.SetKeybind<ReportButton>(7);
KeybindManager.SetKeybind<VentButton>(50);
KeybindManager.SetKeybind<SabotageButton>(4);
KeybindManager.SetKeybind<AbilityButton>(49);
}
}
+34 -15
View File
@@ -29,9 +29,9 @@ namespace MiraAPI.PluginLoading;
[SuppressMessage("Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Intended behaviour.")]
public sealed class MiraPluginManager
{
internal delegate bool TypeRegistrationHandler(in RegistrationContext context);
internal delegate bool TypeRegistrationHandler(Type type, in RegistrationContext context);
internal readonly record struct RegistrationContext(Type Type, MiraPluginInfo PluginInfo, IMiraPlugin MiraPlugin, BasePlugin BasePlugin, List<Type> Roles);
internal readonly record struct RegistrationContext(MiraPluginInfo PluginInfo, IMiraPlugin MiraPlugin, BasePlugin BasePlugin, List<Type> Roles);
private MiraPluginManager()
{
@@ -68,6 +68,15 @@ public sealed class MiraPluginManager
("targeted meeting ability", MeetingButtonManager.RegisterTargetedMeetingButton),
];
private static readonly (string LogContext, Action Handler)[] RegistrationFinalisers =
[
("color", PaletteManager.RegisterAllColors),
("button", CustomButtonManager.RegisterAllButtons),
("modifier", ModifierManager.RegisterAllModifiers),
("event", MiraEventManager.OnLoadFinalize),
("plugin", Instance.FinaliseLoading),
];
/// <summary>
/// Get a mira plugin by its GUID.
/// </summary>
@@ -110,18 +119,28 @@ public sealed class MiraPluginManager
IL2CPPChainloader.Instance.Finished += () =>
{
PaletteManager.RegisterAllColors();
CustomButtonManager.RegisterAllButtons();
ModifierManager.RegisterAllModifiers();
MiraEventManager.OnLoadFinalize();
// Cache all the registered plugins into an array for easy access
RegisteredPlugins = [.. _registeredPlugins.Values];
RegisteredPluginsWithOptions = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu)];
PluginsWithOptionsOrGameModes = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu || m.GameModes.Count > 0)];
foreach (var (logContext, handler) in RegistrationFinalisers)
{
try
{
handler();
}
catch (Exception e)
{
Error($"Failed to finalise {logContext} registry: {e}");
}
}
};
}
private void FinaliseLoading()
{
// Cache all the registered plugins into an array for easy access
RegisteredPlugins = [.. _registeredPlugins.Values];
RegisteredPluginsWithOptions = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu)];
PluginsWithOptionsOrGameModes = [.. RegisteredPlugins.Where(m => m.MiraPlugin.DisplayOnOptionsMenu || m.GameModes.Count > 0)];
}
private MiraPluginInfo RegisterPlugin(Assembly assembly, IMiraPlugin plugin, PluginInfo pluginInfo, BasePlugin basePlugin, bool isMira)
{
var info = new MiraPluginInfo(plugin, pluginInfo, assembly);
@@ -155,23 +174,23 @@ public sealed class MiraPluginManager
Warning("For optimisation reasons, MiraAPI no longer automatically searches every type for events. Please use RegisterEventContainerAttribute moving forward.");
}
var context = new RegistrationContext(info, plugin, basePlugin, roles);
foreach (var type in assembly.GetTypes())
{
if ((isMira && type.IsAbstract) || type.IsDefined<MiraIgnoreAttribute>())
continue;
var context = new RegistrationContext(type, info, plugin, basePlugin, roles);
foreach (var (logContext, handler) in RegistrationHandlers)
{
try
{
if (handler(in context))
if (handler(type, in context))
break;
}
catch (Exception e)
{
Error($"Failed to register {logContext} {type.Name}: {e}");
Error($"Failed to register {logContext} in {type.Name}: {e}");
}
}
}
+5 -7
View File
@@ -119,24 +119,20 @@ public static class CustomRoleManager
pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting;
}
internal static bool RegisterRole(in MiraPluginManager.RegistrationContext context)
internal static bool RegisterRole(Type type, in MiraPluginManager.RegistrationContext context)
{
var type = context.Type;
var pluginInfo = context.PluginInfo;
var roles = context.Roles;
if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type)))
{
return false;
}
if (!ModList.GetById(pluginInfo.PluginId).IsRequiredOnAllClients)
if (!ModList.GetById(context.PluginInfo.PluginId).IsRequiredOnAllClients)
{
Error("Custom roles are only supported on all clients.");
return false;
}
roles.Add(type);
context.Roles.Add(type);
return true;
}
@@ -216,6 +212,8 @@ public static class CustomRoleManager
CustomRoles.Add(roleId, roleBehaviour);
Helpers.SetInstance(typeof(CustomRoleSingleton<>), roleType, roleBehaviour);
if (customRole.Configuration.HideSettings)
{
return roleBehaviour;
+25 -11
View File
@@ -5,6 +5,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using HarmonyLib;
@@ -33,6 +34,12 @@ internal readonly record struct AdvancedSettingsRow(string Title, string Value,
/// </summary>
public static class Helpers
{
[SuppressMessage(
"Major Code Smell",
"S3011:Reflection should not be used to increase accessibility of classes, methods, or fields",
Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")]
private const BindingFlags StaticInstanceFlags = BindingFlags.Static | BindingFlags.NonPublic;
internal const float MatchInfoGuideBaseScale = 1.3f;
private static readonly Regex TrailingZeroRegex = new(@"\.0+(?!\d)", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
private static NumberOption? _advancedSettingsRowPrefab;
@@ -479,6 +486,17 @@ public static class Helpers
];
}
private static readonly Comparer<PlayerControl, Vector2> PlayerPosComparer = Comparer<PlayerControl, Vector2>.Create((a, b, source) =>
{
var magnitude2 = (a!.GetTruePosition() - source).sqrMagnitude;
var magnitude3 = (b!.GetTruePosition() - source).sqrMagnitude;
return magnitude2 > magnitude3
? 1
: magnitude2 < magnitude3
? -1
: 0;
});
/// <summary>
/// Gets the closest <see cref="PlayerControl"/>s to a specific <see cref="PlayerControl"/>.
/// </summary>
@@ -504,17 +522,6 @@ public static class Helpers
return ignoreSource ? [.. players.Where(plr => plr.PlayerId != source.PlayerId)] : players;
}
private static readonly Comparer<PlayerControl, Vector2> PlayerPosComparer = Comparer<PlayerControl, Vector2>.Create((a, b, source) =>
{
var magnitude2 = (a!.GetTruePosition() - source).sqrMagnitude;
var magnitude3 = (b!.GetTruePosition() - source).sqrMagnitude;
return magnitude2 > magnitude3
? 1
: magnitude2 < magnitude3
? -1
: 0;
});
/// <summary>
/// Gets the closest <see cref="PlayerControl"/>s to a specific point.
/// </summary>
@@ -1300,4 +1307,11 @@ public static class Helpers
panel.roleCount.fontMaterial.SetFloat(panel.STENCIL_NAME, 50f);
panel.roleIcon.transform.localScale = new Vector3(3.5f, 3.5f, 1f);
}
internal static void SetInstance(Type openGeneric, Type typeParam, object value)
{
openGeneric.MakeGenericType(typeParam)
.GetField("_instance", StaticInstanceFlags)! // Suppression message refers to this
.SetValue(null, value);
}
}