From 94fbaac1ead87d008be65e2d4239d995b219411a Mon Sep 17 00:00:00 2001 From: Az <56699741+AlchlcDvl@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:55:24 -0500 Subject: [PATCH] consolidate plugin loading code --- MiraAPI/Colors/PaletteManager.cs | 10 ++-- MiraAPI/Events/MiraEventManager.cs | 28 ++++----- MiraAPI/GameEnd/GameOverManager.cs | 4 +- MiraAPI/GameModes/CustomGameModeManager.cs | 7 +-- MiraAPI/GameOptions/ModdedOptionsManager.cs | 59 +++++-------------- MiraAPI/Hud/CustomButtonManager.cs | 28 +++------ MiraAPI/Keybinds/KeybindManager.cs | 16 +++-- MiraAPI/LocalSettings/LocalSettingsManager.cs | 20 ++----- .../MeetingAbilities/MeetingButtonManager.cs | 17 +++--- MiraAPI/Modifiers/ModifierManager.cs | 7 +-- MiraAPI/Patches/Keybinds/KeybindsPatch.cs | 12 ++-- MiraAPI/PluginLoading/MiraPluginManager.cs | 49 ++++++++++----- MiraAPI/Roles/CustomRoleManager.cs | 12 ++-- MiraAPI/Utilities/Helpers.cs | 36 +++++++---- 14 files changed, 140 insertions(+), 165 deletions(-) diff --git a/MiraAPI/Colors/PaletteManager.cs b/MiraAPI/Colors/PaletteManager.cs index 561d6ba7..af6454e9 100644 --- a/MiraAPI/Colors/PaletteManager.cs +++ b/MiraAPI/Colors/PaletteManager.cs @@ -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(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) diff --git a/MiraAPI/Events/MiraEventManager.cs b/MiraAPI/Events/MiraEventManager.cs index a3cd0e7f..8dfec5d5 100644 --- a/MiraAPI/Events/MiraEventManager.cs +++ b/MiraAPI/Events/MiraEventManager.cs @@ -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(); - 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; diff --git a/MiraAPI/GameEnd/GameOverManager.cs b/MiraAPI/GameEnd/GameOverManager.cs index e86c2c7a..668bbdc2 100644 --- a/MiraAPI/GameEnd/GameOverManager.cs +++ b/MiraAPI/GameEnd/GameOverManager.cs @@ -15,10 +15,8 @@ public static class GameOverManager private static int nextId = Enum.GetNames().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; diff --git a/MiraAPI/GameModes/CustomGameModeManager.cs b/MiraAPI/GameModes/CustomGameModeManager.cs index 11f8fd6c..5cebc594 100644 --- a/MiraAPI/GameModes/CustomGameModeManager.cs +++ b/MiraAPI/GameModes/CustomGameModeManager.cs @@ -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; } diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 76c0a0e1..636cf4b9 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -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(out var attribute)) { - RegisterAttributeOption(type, attribute, property, pluginInfo); + RegisterAttributeOption(group, attribute, property, pluginInfo); continue; } if (property.TryGetCustomAttribute(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) diff --git a/MiraAPI/Hud/CustomButtonManager.cs b/MiraAPI/Hud/CustomButtonManager.cs index 36e4da66..751d67c4 100644 --- a/MiraAPI/Hud/CustomButtonManager.cs +++ b/MiraAPI/Hud/CustomButtonManager.cs @@ -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 ButtonEventTypes = []; internal static readonly Dictionary 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(CustomButtonManager.CustomButtons); - EventTypes = new ReadOnlyDictionary(CustomButtonManager.ButtonEventTypes); - CancelledEventTypes = new ReadOnlyDictionary(CustomButtonManager.ButtonCancelledEventTypes); + Buttons = new ReadOnlyCollection(CustomButtons); + EventTypes = new ReadOnlyDictionary(ButtonEventTypes); + CancelledEventTypes = new ReadOnlyDictionary(ButtonCancelledEventTypes); } } diff --git a/MiraAPI/Keybinds/KeybindManager.cs b/MiraAPI/Keybinds/KeybindManager.cs index d541ee31..91414311 100644 --- a/MiraAPI/Keybinds/KeybindManager.cs +++ b/MiraAPI/Keybinds/KeybindManager.cs @@ -23,6 +23,15 @@ public static class KeybindManager [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] internal static readonly Dictionary VanillaKeybinds = []; + internal static void SetKeybind(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()) { return false; } + var miraPlugin = context.MiraPlugin; + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers)) { if (!property.PropertyType.IsAssignableTo(typeof(MiraKeybind))) diff --git a/MiraAPI/LocalSettings/LocalSettingsManager.cs b/MiraAPI/LocalSettings/LocalSettingsManager.cs index 5f72c11d..0daa822c 100644 --- a/MiraAPI/LocalSettings/LocalSettingsManager.cs +++ b/MiraAPI/LocalSettings/LocalSettingsManager.cs @@ -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 Tabs = []; internal static readonly List 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))))) diff --git a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs index f93aa7c6..a1282d91 100644 --- a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs +++ b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs @@ -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 /// public static List 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; } diff --git a/MiraAPI/Modifiers/ModifierManager.cs b/MiraAPI/Modifiers/ModifierManager.cs index d22edb67..af21bea3 100644 --- a/MiraAPI/Modifiers/ModifierManager.cs +++ b/MiraAPI/Modifiers/ModifierManager.cs @@ -67,11 +67,8 @@ public static class ModifierManager Modifiers = new ReadOnlyCollection(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) diff --git a/MiraAPI/Patches/Keybinds/KeybindsPatch.cs b/MiraAPI/Patches/Keybinds/KeybindsPatch.cs index 0fea5793..355d3a35 100644 --- a/MiraAPI/Patches/Keybinds/KeybindsPatch.cs +++ b/MiraAPI/Patches/Keybinds/KeybindsPatch.cs @@ -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(8); + KeybindManager.SetKeybind(6); + KeybindManager.SetKeybind(7); + KeybindManager.SetKeybind(50); + KeybindManager.SetKeybind(4); + KeybindManager.SetKeybind(49); } } diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index 5fcf4c03..d79404de 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -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 Roles); + internal readonly record struct RegistrationContext(MiraPluginInfo PluginInfo, IMiraPlugin MiraPlugin, BasePlugin BasePlugin, List 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), + ]; + /// /// Get a mira plugin by its GUID. /// @@ -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()) 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}"); } } } diff --git a/MiraAPI/Roles/CustomRoleManager.cs b/MiraAPI/Roles/CustomRoleManager.cs index e836d23e..19ce191e 100644 --- a/MiraAPI/Roles/CustomRoleManager.cs +++ b/MiraAPI/Roles/CustomRoleManager.cs @@ -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; diff --git a/MiraAPI/Utilities/Helpers.cs b/MiraAPI/Utilities/Helpers.cs index f4e7ce33..9516cf37 100644 --- a/MiraAPI/Utilities/Helpers.cs +++ b/MiraAPI/Utilities/Helpers.cs @@ -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, /// 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 PlayerPosComparer = Comparer.Create((a, b, source) => + { + var magnitude2 = (a!.GetTruePosition() - source).sqrMagnitude; + var magnitude3 = (b!.GetTruePosition() - source).sqrMagnitude; + return magnitude2 > magnitude3 + ? 1 + : magnitude2 < magnitude3 + ? -1 + : 0; + }); + /// /// Gets the closest s to a specific . /// @@ -504,17 +522,6 @@ public static class Helpers return ignoreSource ? [.. players.Where(plr => plr.PlayerId != source.PlayerId)] : players; } - private static readonly Comparer PlayerPosComparer = Comparer.Create((a, b, source) => - { - var magnitude2 = (a!.GetTruePosition() - source).sqrMagnitude; - var magnitude3 = (b!.GetTruePosition() - source).sqrMagnitude; - return magnitude2 > magnitude3 - ? 1 - : magnitude2 < magnitude3 - ? -1 - : 0; - }); - /// /// Gets the closest s to a specific point. /// @@ -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); + } }