From ed74458ba71836c39d9acba6d82b25653b7d35c2 Mon Sep 17 00:00:00 2001 From: Az <56699741+AlchlcDvl@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:35:21 -0500 Subject: [PATCH 1/3] make it an extension instead --- MiraAPI/Colors/PaletteManager.cs | 2 +- MiraAPI/GameOptions/ModdedOptionsManager.cs | 2 +- MiraAPI/Keybinds/KeybindManager.cs | 2 +- MiraAPI/LocalSettings/LocalSettingsManager.cs | 2 +- MiraAPI/PluginLoading/MiraPluginInfo.cs | 2 +- MiraAPI/PluginLoading/MiraPluginManager.cs | 8 +------- MiraAPI/Utilities/Extensions.cs | 12 ++++++++++++ 7 files changed, 18 insertions(+), 12 deletions(-) diff --git a/MiraAPI/Colors/PaletteManager.cs b/MiraAPI/Colors/PaletteManager.cs index c5cba43f..561d6ba7 100644 --- a/MiraAPI/Colors/PaletteManager.cs +++ b/MiraAPI/Colors/PaletteManager.cs @@ -83,7 +83,7 @@ public static class PaletteManager return true; foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers) - .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor)))) + .Where(f => !f.IsAutoPropertyBackingField() && f.FieldType.IsAssignableTo(typeof(CustomColor)))) { Error($"{field.Name} is a field, not a property. Use properties for colors."); } diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 8071299f..07d21c28 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -138,7 +138,7 @@ public static class ModdedOptionsManager } foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers) - .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) + .Where(f => !f.IsAutoPropertyBackingField() && (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IBaseModdedOptionList))))) { Error($"{field.Name} is a field, not a property. Use properties for options."); diff --git a/MiraAPI/Keybinds/KeybindManager.cs b/MiraAPI/Keybinds/KeybindManager.cs index cffe9b35..d541ee31 100644 --- a/MiraAPI/Keybinds/KeybindManager.cs +++ b/MiraAPI/Keybinds/KeybindManager.cs @@ -109,7 +109,7 @@ public static class KeybindManager return true; foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers) - .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) + .Where(f => !f.IsAutoPropertyBackingField() && f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) { Error($"{field.Name} is a field, not a property. Use properties for keybinds."); } diff --git a/MiraAPI/LocalSettings/LocalSettingsManager.cs b/MiraAPI/LocalSettings/LocalSettingsManager.cs index 646a2664..5f72c11d 100644 --- a/MiraAPI/LocalSettings/LocalSettingsManager.cs +++ b/MiraAPI/LocalSettings/LocalSettingsManager.cs @@ -92,7 +92,7 @@ public static class LocalSettingsManager } foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers) - .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) + .Where(f => !f.IsAutoPropertyBackingField() && (f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) || f.FieldType.IsAssignableTo(typeof(LocalSettingsButton))))) { Error($"{field.Name} is a field, not a property. Use properties for local settings or buttons."); diff --git a/MiraAPI/PluginLoading/MiraPluginInfo.cs b/MiraAPI/PluginLoading/MiraPluginInfo.cs index a8914df5..c6eee6f8 100644 --- a/MiraAPI/PluginLoading/MiraPluginInfo.cs +++ b/MiraAPI/PluginLoading/MiraPluginInfo.cs @@ -119,7 +119,7 @@ public class MiraPluginInfo Modifiers = [.. InternalModifiers]; OptionGroups = [.. InternalOptionGroups]; Options = [.. InternalOptions]; - Roles = new ReadOnlyDictionary(InternalRoles); + Roles = new(InternalRoles); Buttons = [.. InternalButtons]; MeetingButtons = [.. InternalMeetingButtons]; TargetedMeetingButtons = [.. InternalTargetedMeetingButtons]; diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index 526b96f1..bebdb109 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; -using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using BepInEx.Unity.IL2CPP; @@ -141,18 +140,13 @@ public sealed class MiraPluginManager _registeredPlugins.Add(pluginInfo.Metadata.GUID, info); info.SavePublicCollections(); + PresetManager.CreateDefaultPreset(info); PresetManager.LoadPresets(info); return info; } - internal static bool IsAutoPropertyBackingField(FieldInfo field) - { - return field.IsDefined(false) && - field.Name.Contains(">k__BackingField", StringComparison.Ordinal); - } - private static void ProcessAssemblyTypes(Assembly assembly, MiraPluginInfo info, BasePlugin basePlugin, IMiraPlugin plugin, List roles, bool isMira) { if (plugin.ForceRegisterEvents) diff --git a/MiraAPI/Utilities/Extensions.cs b/MiraAPI/Utilities/Extensions.cs index 29f8b623..acdd79e6 100644 --- a/MiraAPI/Utilities/Extensions.cs +++ b/MiraAPI/Utilities/Extensions.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using HarmonyLib; using MiraAPI.GameModes; @@ -916,4 +917,15 @@ public static class Extensions attribute = member.GetCustomAttribute(); return attribute != null; } + + /// + /// Checks if a field is auto-generated by the compiler. + /// + /// The to check. + /// true if the field was auto-generated; otherwise false. + public static bool IsAutoPropertyBackingField(this FieldInfo field) + { + return field.IsDefined(false) && + field.Name.Contains(">k__BackingField", StringComparison.Ordinal); + } } From 2805599d35575bbda311a55626b764bf478938b2 Mon Sep 17 00:00:00 2001 From: Az <56699741+AlchlcDvl@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:35:21 -0500 Subject: [PATCH 2/3] new comparer util + minor optimisations --- MiraAPI.Example/Roles/ChameleonRole.cs | 2 +- MiraAPI/GameOptions/ModdedOptionsManager.cs | 1 + .../Patches/Options/PlayerOptionPatches.cs | 7 +- MiraAPI/PluginLoading/MiraPluginManager.cs | 3 +- MiraAPI/Utilities/ContextualComparer.cs | 76 +++++++ .../Utilities/ContextualComparerExtensions.cs | 189 ++++++++++++++++++ MiraAPI/Utilities/Helpers.cs | 22 +- 7 files changed, 286 insertions(+), 14 deletions(-) create mode 100644 MiraAPI/Utilities/ContextualComparer.cs create mode 100644 MiraAPI/Utilities/ContextualComparerExtensions.cs diff --git a/MiraAPI.Example/Roles/ChameleonRole.cs b/MiraAPI.Example/Roles/ChameleonRole.cs index e6e3adf9..8d8151cb 100644 --- a/MiraAPI.Example/Roles/ChameleonRole.cs +++ b/MiraAPI.Example/Roles/ChameleonRole.cs @@ -40,7 +40,7 @@ public class ChameleonRole : CrewmateRole, ICustomRole return; } - if (Player.MyPhysics.Velocity.magnitude > 0) + if (Player.MyPhysics.Velocity.sqrMagnitude > 0) { var rend = Player.cosmetics.currentBodySprite.BodySprite; var tmp = Player.cosmetics.nameText; diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 07d21c28..76c0a0e1 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -39,6 +39,7 @@ public static class ModdedOptionsManager internal static readonly Dictionary> GameModeOptionGroups = []; internal static readonly Dictionary ModdedOptions = []; internal static readonly List Groups = []; + internal static readonly Comparer Comparer = Comparer.Create((x, y) => x.GroupPriority.CompareTo(y.GroupPriority)); internal static uint NextId => _nextId++; private static uint _nextId = 1; diff --git a/MiraAPI/Patches/Options/PlayerOptionPatches.cs b/MiraAPI/Patches/Options/PlayerOptionPatches.cs index ab19fced..596e73aa 100644 --- a/MiraAPI/Patches/Options/PlayerOptionPatches.cs +++ b/MiraAPI/Patches/Options/PlayerOptionPatches.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System.Collections.Generic; +using System.Linq; using HarmonyLib; using MiraAPI.GameOptions; using MiraAPI.Utilities; @@ -9,6 +10,8 @@ namespace MiraAPI.Patches.Options; [HarmonyPatch(typeof(PlayerOption))] public static class PlayerOptionPatches { + private static readonly Comparer Comparer = Comparer.Create((a, b) => a.PlayerId.CompareTo(b.PlayerId)); + // Updates the list of players according to the filter. [HarmonyPrefix] [HarmonyPatch(nameof(PlayerOption.FixedUpdate))] @@ -24,7 +27,7 @@ public static class PlayerOptionPatches var filteredPlayers = moddedPlrOpt.GetFilteredPlayers(); if (filteredPlayers.Count != __instance.Values.Count) { - filteredPlayers.Sort((a, b) => a.PlayerId.CompareTo(b.PlayerId)); + filteredPlayers.Sort(Comparer); moddedPlrOpt.Values = filteredPlayers; __instance.Values = filteredPlayers.ToIl2CppList(); diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index bebdb109..5fcf4c03 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -135,7 +135,8 @@ public sealed class MiraPluginManager info.PluginConfig.Save(); info.PluginConfig.SaveOnConfigSet = oldConfigSetting; - info.InternalOptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority)); + info.InternalOptionGroups.Sort(ModdedOptionsManager.Comparer); + QueuedRoleRegistrations.Add(info, roles); _registeredPlugins.Add(pluginInfo.Metadata.GUID, info); diff --git a/MiraAPI/Utilities/ContextualComparer.cs b/MiraAPI/Utilities/ContextualComparer.cs new file mode 100644 index 00000000..f6cf52b8 --- /dev/null +++ b/MiraAPI/Utilities/ContextualComparer.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace MiraAPI.Utilities; + +/// +/// Defines a method that a type implements to compare two objects using extra contextual information. +/// +/// The type of objects to compare. +/// The type of the context. +public interface IComparer +{ + /// + /// When overridden in a derived class, performs a comparison of two objects of the + /// same type using the provided context and returns a value indicating whether one + /// object is less than, equal or greater than the other. + /// + /// The first object to compare. + /// The second object to compare. + /// The extra information to aid in the comparison. + /// + /// A signed integer that indicates the relative values of x and y, as shown in the + /// following table.

+ /// Value – Meaning
+ /// Less than zero – x is less than y.
+ /// Zero – x equals y.
+ /// Greater than zero – x is greater than y.
+ ///
+ int Compare(TValue? x, TValue? y, TParam? context); +} + +/// +/// Provides a base class for implementations of the +/// generic interface. +/// +/// The type of objects to compare. +/// The type of the context. +[SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "Mimics Comparer design.")] +public abstract class Comparer : IComparer +{ + /// + /// Gets a default contextual comparer that ignores the parameter and falls back to standard comparison. + /// + public static Comparer Default { get; } = new DefaultComparer(); + + /// + /// Creates a contextual comparer by using the specified comparison delegate. + /// + /// The comparison to use. + /// The new comparer. + public static Comparer Create(Func? comparison) + { + ArgumentNullException.ThrowIfNull(comparison); + return new FuncComparer(comparison); + } + + /// + public abstract int Compare(TValue? x, TValue? y, TParam? context); + + private sealed class DefaultComparer : Comparer + { + public override int Compare(TValue? x, TValue? y, TParam? context) + { + return Comparer.Default.Compare(x, y); + } + } + + private sealed class FuncComparer(Func comparison) : Comparer + { + public override int Compare(TValue? x, TValue? y, TParam? context) + { + return comparison(x, y, context); + } + } +} diff --git a/MiraAPI/Utilities/ContextualComparerExtensions.cs b/MiraAPI/Utilities/ContextualComparerExtensions.cs new file mode 100644 index 00000000..254c9140 --- /dev/null +++ b/MiraAPI/Utilities/ContextualComparerExtensions.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MiraAPI.Utilities; + +/// +/// Provides extension methods to integrate with standard .NET collections and LINQ. +/// +public static class ContextualComparerExtensions +{ + private readonly struct BoundComparer(IComparer comparer, TParam? context) : IComparer + { + public int Compare(T? x, T? y) + { + return comparer.Compare(x, y, context); + } + } + + /// + /// Binds a context parameter to a contextual comparer, returning a standard . + /// + /// The type of objects to compare. + /// The type of the context. + /// The contextual comparer. + /// The context to bind to the comparer. + /// A standard comparer that implicitly uses the provided context. + /// is null. + public static IComparer Bind(this IComparer comparer, TParam? context) + { + ArgumentNullException.ThrowIfNull(comparer); + return new BoundComparer(comparer, context); + } + + /// + /// Sorts the elements in the entire using the specified contextual comparer and context. + /// + /// The type of elements in the list. + /// The type of the context. + /// The list to sort. + /// The contextual comparer to use when comparing elements. + /// The context to aid in the comparison. + /// or is null. + public static void Sort(this List list, IComparer comparer, TParam? context) + { + ArgumentNullException.ThrowIfNull(list); + list.Sort(comparer.Bind(context)); + } + + /// + /// Sorts the elements in an entire one-dimensional array using the specified contextual comparer and context. + /// + /// The type of elements in the array. + /// The type of the context. + /// The one-dimensional array to sort. + /// The contextual comparer to use when comparing elements. + /// The context to aid in the comparison. + /// or is null. + public static void Sort(this T[] array, IComparer comparer, TParam? context) + { + ArgumentNullException.ThrowIfNull(array); + Array.Sort(array, comparer.Bind(context)); + } + + /// + /// Searches the entire sorted for an element using the specified contextual comparer and context, + /// and returns the zero-based index of the element. + /// + /// The type of elements in the list. + /// The type of the context. + /// The sorted list to search. + /// The object to locate. The value can be null for reference types. + /// The contextual comparer to use when comparing elements. + /// The context to aid in the comparison. + /// + /// The zero-based index of item in the sorted list, if item is found; otherwise, a negative number that is the + /// bitwise complement of the index of the next element that is larger than item or, if there is no larger element, + /// the bitwise complement of Count. + /// + /// or is null. + public static int BinarySearch(this List list, T item, IComparer comparer, TParam? context) + { + ArgumentNullException.ThrowIfNull(list); + return list.BinarySearch(item, comparer.Bind(context)); + } + + /// + /// Searches an entire one-dimensional sorted array for a specific element using the specified contextual comparer and context. + /// + /// The type of elements in the array. + /// The type of the context. + /// The sorted one-dimensional array to search. + /// The object to locate. The value can be null for reference types. + /// The contextual comparer to use when comparing elements. + /// The context to aid in the comparison. + /// + /// The index of the specified value in the specified array, if value is found; otherwise, a negative number. + /// + /// or is null. + public static int BinarySearch(this T[] array, T item, IComparer comparer, TParam? context) + { + ArgumentNullException.ThrowIfNull(array); + return Array.BinarySearch(array, item, comparer.Bind(context)); + } + + /// + /// Sorts the elements of a sequence in ascending order according to a key and a contextual comparer. + /// + /// The type of the elements of source. + /// The type of the key returned by keySelector. + /// The type of the context. + /// A sequence of values to order. + /// A function to extract a key from an element. + /// The contextual comparer to compare keys. + /// The context to aid in the comparison. + /// An whose elements are sorted according to a key. + /// , , or is null. + public static IOrderedEnumerable OrderBy( + this IEnumerable source, + Func keySelector, + IComparer comparer, + TParam? context) + { + return source.OrderBy(keySelector, comparer.Bind(context)); + } + + /// + /// Sorts the elements of a sequence in descending order according to a key and a contextual comparer. + /// + /// The type of the elements of source. + /// The type of the key returned by keySelector. + /// The type of the context. + /// A sequence of values to order. + /// A function to extract a key from an element. + /// The contextual comparer to compare keys. + /// The context to aid in the comparison. + /// An whose elements are sorted in descending order according to a key. + /// , , or is null. + public static IOrderedEnumerable OrderByDescending( + this IEnumerable source, + Func keySelector, + IComparer comparer, + TParam? context) + { + return source.OrderByDescending(keySelector, comparer.Bind(context)); + } + + /// + /// Performs a subsequent ordering of the elements in a sequence in ascending order according to a key and a contextual comparer. + /// + /// The type of the elements of source. + /// The type of the key returned by keySelector. + /// The type of the context. + /// An that contains elements to sort. + /// A function to extract a key from an element. + /// The contextual comparer to compare keys. + /// The context to aid in the comparison. + /// An whose elements are sorted according to a key. + /// , , or is null. + public static IOrderedEnumerable ThenBy( + this IOrderedEnumerable source, + Func keySelector, + IComparer comparer, + TParam? context) + { + return source.ThenBy(keySelector, comparer.Bind(context)); + } + + /// + /// Performs a subsequent ordering of the elements in a sequence in descending order, according to a key and a contextual comparer. + /// + /// The type of the elements of source. + /// The type of the key returned by keySelector. + /// The type of the context. + /// An that contains elements to sort. + /// A function to extract a key from an element. + /// The contextual comparer to compare keys. + /// The context to aid in the comparison. + /// An whose elements are sorted in descending order according to a key. + /// , , or is null. + public static IOrderedEnumerable ThenByDescending( + this IOrderedEnumerable source, + Func keySelector, + IComparer comparer, + TParam? context) + { + return source.ThenByDescending(keySelector, comparer.Bind(context)); + } +} diff --git a/MiraAPI/Utilities/Helpers.cs b/MiraAPI/Utilities/Helpers.cs index d08a4a00..f4e7ce33 100644 --- a/MiraAPI/Utilities/Helpers.cs +++ b/MiraAPI/Utilities/Helpers.cs @@ -504,6 +504,17 @@ 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. /// @@ -537,16 +548,7 @@ public static class Helpers Constants.ShipAndObjectsMask)) select playerControl); - outputList.Sort((a, b) => - { - var magnitude2 = (a.GetTruePosition() - source).magnitude; - var magnitude3 = (b.GetTruePosition() - source).magnitude; - return magnitude2 > magnitude3 - ? 1 - : magnitude2 < magnitude3 - ? -1 - : 0; - }); + outputList.Sort(PlayerPosComparer, source); return outputList; } 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 3/3] 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); + } }