From 6f94e4ed213f369dc001eb4c7563a4cf363e84a6 Mon Sep 17 00:00:00 2001 From: Az <56699741+AlchlcDvl@users.noreply.github.com> Date: Mon, 26 Oct 2026 03:35:11 -0400 Subject: [PATCH] reduce value boxing --- MiraAPI.Example/Options/ExampleOptions.cs | 8 +- MiraAPI.Example/Resources/Locale/en_US.xml | 1 - .../GameOptions/Attributes/ITypedOption.cs | 20 ++++ .../Attributes/ModdedEnumOptionAttribute.cs | 22 ++++- .../Attributes/ModdedNumberOptionAttribute.cs | 28 +++++- .../Attributes/ModdedPlayerOptionAttribute.cs | 43 ++++++++- .../Attributes/ModdedStringOptionAttribute.cs | 17 +++- .../Attributes/ModdedToggleOptionAttribute.cs | 17 +++- .../Attributes/OptionList/ITypedOptionList.cs | 22 +++++ .../ModdedEnumOptionListAttribute.cs | 22 ++++- .../ModdedNumberOptionListAttribute.cs | 28 +++++- .../OptionList/ModdedOptionListAttribute.cs | 8 +- .../ModdedPlayerOptionListAttribute.cs | 43 ++++++++- .../ModdedStringOptionListAttribute.cs | 17 +++- .../ModdedToggleOptionListAttribute.cs | 17 +++- MiraAPI/GameOptions/ModdedArray.cs | 22 ++++- MiraAPI/GameOptions/ModdedOptionsManager.cs | 94 +++++++++++++++++-- .../OptionTypes/ModdedEnumOption.cs | 1 + 18 files changed, 378 insertions(+), 52 deletions(-) create mode 100644 MiraAPI/GameOptions/Attributes/ITypedOption.cs create mode 100644 MiraAPI/GameOptions/Attributes/OptionList/ITypedOptionList.cs diff --git a/MiraAPI.Example/Options/ExampleOptions.cs b/MiraAPI.Example/Options/ExampleOptions.cs index 9b424c0b..935cc504 100644 --- a/MiraAPI.Example/Options/ExampleOptions.cs +++ b/MiraAPI.Example/Options/ExampleOptions.cs @@ -30,16 +30,12 @@ public class ExampleOptions : AbstractOptionGroup [ModdedNumberOption("options.exampleOptions1.numberOpt", min: 0, max: 10, suffixType: MiraNumberSuffixes.Distance)] public int NumberOpt2 { get; set; } = 4; // Can also be int! - [ModdedEnumOption("options.exampleOptions1.bestApi", typeof(Api), ["Mira API", "Mitochondria", "Reactor"])] - public Api BestApi { get; set; } = Api.MiraAPI; - - [ModdedEnumOption("options.exampleOptions1.worstApi", ["Mira API", "Mitochondria", "Reactor"])] - // These three can target both instance and static methods [ModdedOptionGetter(nameof(GetApi))] // Can also automatically resolve to {Option Name}Getter [ModdedOptionSetter(nameof(SetApi))] // Can also automatically resolve to {Option Name}Setter [ModdedOptionChanged(nameof(ApiChanged))] // Can also automatically resolve to {Option Name}Changed - public Api WorstApi { get; set; } = Api.MiraAPI; + [ModdedEnumOption("options.exampleOptions1.bestApi", ["Mira API", "Mitochondria", "Reactor"])] + public Api BestApi { get; set; } = Api.MiraAPI; [ModdedEnumOptionList("Value State {0}", ["None", "Primary", "Secondary"])] public ModdedArray ValueStates { get; set; } = [ValueState.Primary, ValueState.Secondary, ValueState.None, ValueState.None, ValueState.None]; diff --git a/MiraAPI.Example/Resources/Locale/en_US.xml b/MiraAPI.Example/Resources/Locale/en_US.xml index b37cad6b..fb7e9696 100644 --- a/MiraAPI.Example/Resources/Locale/en_US.xml +++ b/MiraAPI.Example/Resources/Locale/en_US.xml @@ -47,7 +47,6 @@ Eliminate every other faction. Toggle Opt 2 Number Opt Best API - Worst API Choose A Player Example Options 2 YOU MUST CHOSE A PLAYER diff --git a/MiraAPI/GameOptions/Attributes/ITypedOption.cs b/MiraAPI/GameOptions/Attributes/ITypedOption.cs new file mode 100644 index 00000000..44dfd02c --- /dev/null +++ b/MiraAPI/GameOptions/Attributes/ITypedOption.cs @@ -0,0 +1,20 @@ +namespace MiraAPI.GameOptions.Attributes; + +/// +/// Provides unboxed access to option values to prevent memory allocations. +/// +/// The type of the value that the option carries. +public interface ITypedOption +{ + /// + /// Gets the unboxed value of the option. + /// + /// The unboxed option value. + T GetValueUnboxed(); + + /// + /// Sets the unboxed value of the option. + /// + /// The new value to set. + void SetValueUnboxed(T value); +} diff --git a/MiraAPI/GameOptions/Attributes/ModdedEnumOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedEnumOptionAttribute.cs index 2754920a..ece868d7 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedEnumOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedEnumOptionAttribute.cs @@ -11,6 +11,7 @@ namespace MiraAPI.GameOptions.Attributes; /// The type. /// An option list of string values to use in place of the name. [AttributeUsage(AttributeTargets.Property)] +[Obsolete("Use ModdedEnumOptionAttribute instead.")] public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? values = null) : ModdedOptionAttribute(title) { @@ -32,7 +33,7 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va { return HolderOption is ModdedEnumOption opt ? Enum.ToObject(enumType, opt.Value) - : throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {enumType.FullName} is not a ModdedEnumOption"); + : throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption with enum type {enumType.FullName}"); } } @@ -44,7 +45,7 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va /// An option list of string values to use in place of the name. [AttributeUsage(AttributeTargets.Property)] public class ModdedEnumOptionAttribute(string title, string[]? values = null) - : ModdedOptionAttribute(title) + : ModdedOptionAttribute(title), ITypedOption where T : struct, Enum { internal override IModdedOption CreateOption(object? value, PropertyInfo property) @@ -56,15 +57,26 @@ public class ModdedEnumOptionAttribute(string title, string[]? values = null) /// public override void SetValue(object value) { - var opt = HolderOption as ModdedEnumOption; - opt?.SetValue((T)value); + SetValueUnboxed((T)value); + } + + /// + public void SetValueUnboxed(T value) + { + (HolderOption as ModdedEnumOption)?.SetValue(value); } /// public override object GetValue() + { + return GetValueUnboxed(); + } + + /// + public T GetValueUnboxed() { return HolderOption is ModdedEnumOption opt ? opt.Value - : throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).Name}>"); + : throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedEnumOption<{typeof(T).Name}>"); } } diff --git a/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs index f43773e1..6a678538 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedNumberOptionAttribute.cs @@ -28,7 +28,7 @@ public class ModdedNumberOptionAttribute( MiraNumberSuffixes suffixType = MiraNumberSuffixes.None, string? formatString = null, bool halfIncrements = false) - : ModdedOptionAttribute(title) + : ModdedOptionAttribute(title), ITypedOption, ITypedOption { /// /// Initializes a new instance of the class. @@ -88,6 +88,18 @@ public class ModdedNumberOptionAttribute( opt.SetValue(final); } + /// + public void SetValueUnboxed(float value) + { + (HolderOption as ModdedNumberOption)?.SetValue(value); + } + + /// + void ITypedOption.SetValueUnboxed(int value) + { + (HolderOption as ModdedNumberOption)?.SetValue(value); + } + /// public override object GetValue() { @@ -101,4 +113,18 @@ public class ModdedNumberOptionAttribute( return value; } + + /// + public float GetValueUnboxed() + { + return HolderOption is ModdedNumberOption opt + ? opt.Value + : throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedNumberOption"); + } + + /// + int ITypedOption.GetValueUnboxed() + { + return (int)Math.Round(GetValueUnboxed()); + } } diff --git a/MiraAPI/GameOptions/Attributes/ModdedPlayerOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedPlayerOptionAttribute.cs index 610d0c81..b4d296e3 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedPlayerOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedPlayerOptionAttribute.cs @@ -13,7 +13,7 @@ namespace MiraAPI.GameOptions.Attributes; public class ModdedPlayerOptionAttribute( string title, bool allowNone = true) - : ModdedOptionAttribute(title) + : ModdedOptionAttribute(title), ITypedOption, ITypedOption { internal override IModdedOption? CreateOption(object? value, PropertyInfo property) { @@ -33,6 +33,22 @@ public class ModdedPlayerOptionAttribute( return opt.SelectedPlayer!; } + /// + public NetworkedPlayerInfo? GetValueUnboxed() + { + return HolderOption is ModdedPlayerOption opt + ? opt.SelectedPlayer + : throw new InvalidOperationException($"Holder option for {Title} is not a ModdedPlayerOption."); + } + + /// + int ITypedOption.GetValueUnboxed() + { + return HolderOption is ModdedPlayerOption opt + ? opt.Value + : throw new InvalidOperationException($"Holder option for {Title} is not a ModdedPlayerOption."); + } + /// public override void SetValue(object value) { @@ -41,9 +57,32 @@ public class ModdedPlayerOptionAttribute( var final = value switch { - NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0), + NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1, _ => (int)value, }; + + if (final == -1 && !allowNone) + throw new ArgumentException("Cannot assign -1 or null to a ModdedPlayerOption that does not allow none as an option."); + opt?.SetValue(final); } + + /// + public void SetValueUnboxed(NetworkedPlayerInfo? value) + { + if (!value && !allowNone) + throw new ArgumentException("Cannot assign null to a ModdedPlayerOption that does not allow none as an option."); + + if (HolderOption is ModdedPlayerOption opt) + opt.SetValue(value ? opt.Values.IndexOf(value!) : -1); + } + + /// + void ITypedOption.SetValueUnboxed(int value) + { + if (value == -1 && !allowNone) + throw new ArgumentException("Cannot assign -1 to a ModdedPlayerOption that does not allow none as an option."); + + (HolderOption as ModdedPlayerOption)?.SetValue(value); + } } diff --git a/MiraAPI/GameOptions/Attributes/ModdedStringOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedStringOptionAttribute.cs index 9086b1f1..379c820f 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedStringOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedStringOptionAttribute.cs @@ -13,7 +13,7 @@ namespace MiraAPI.GameOptions.Attributes; public class ModdedStringOptionAttribute( string title, string[] values) - : ModdedOptionAttribute(title) + : ModdedOptionAttribute(title), ITypedOption { internal override IModdedOption? CreateOption(object? value, PropertyInfo property) { @@ -23,6 +23,12 @@ public class ModdedStringOptionAttribute( /// public override object GetValue() + { + return GetValueUnboxed(); + } + + /// + public string GetValueUnboxed() { return HolderOption is ModdedStringOption opt ? opt.Value @@ -32,7 +38,12 @@ public class ModdedStringOptionAttribute( /// public override void SetValue(object value) { - var opt = HolderOption as ModdedStringOption; - opt?.SetValue((string)value); + SetValueUnboxed((string)value); + } + + /// + public void SetValueUnboxed(string value) + { + (HolderOption as ModdedStringOption)?.SetValue(value); } } diff --git a/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs b/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs index 042c1f39..e94d8e49 100644 --- a/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/ModdedToggleOptionAttribute.cs @@ -15,7 +15,7 @@ public class ModdedToggleOptionAttribute( string title, string on, string off) - : ModdedOptionAttribute(title) + : ModdedOptionAttribute(title), ITypedOption { /// /// Initializes a new instance of the class. @@ -35,12 +35,23 @@ public class ModdedToggleOptionAttribute( /// public override void SetValue(object value) { - var opt = HolderOption as ModdedToggleOption; - opt?.SetValue((bool)value); + SetValueUnboxed((bool)value); + } + + /// + public void SetValueUnboxed(bool value) + { + (HolderOption as ModdedToggleOption)?.SetValue(value); } /// public override object GetValue() + { + return GetValueUnboxed(); + } + + /// + public bool GetValueUnboxed() { return HolderOption is ModdedToggleOption opt ? opt.Value diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ITypedOptionList.cs b/MiraAPI/GameOptions/Attributes/OptionList/ITypedOptionList.cs new file mode 100644 index 00000000..6c584085 --- /dev/null +++ b/MiraAPI/GameOptions/Attributes/OptionList/ITypedOptionList.cs @@ -0,0 +1,22 @@ +namespace MiraAPI.GameOptions.Attributes; + +/// +/// Provides unboxed access to option list values to prevent memory allocations. +/// +/// The type of the value that the option list carries. +public interface ITypedOptionList +{ + /// + /// Gets the unboxed value of the option at the specified index. + /// + /// The index of the option. + /// The option at the provided index. + T GetValueUnboxed(int idx); + + /// + /// Sets the unboxed value of the option at the specified index. + /// + /// The index of the option. + /// The new value of the option to set. + void SetValueUnboxed(int idx, T value); +} diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs index bf2fdf07..8a6a237c 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedEnumOptionListAttribute.cs @@ -12,6 +12,7 @@ namespace MiraAPI.GameOptions.Attributes; /// The type. /// An option list of string values to use in place of the name. [AttributeUsage(AttributeTargets.Property)] +[Obsolete("Use ModdedEnumOptionListAttribute instead.")] public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]? values = null) : ModdedOptionListAttribute(title) { @@ -34,7 +35,7 @@ public class ModdedEnumOptionListAttribute(string title, Type enumType, string[] { return HolderOptionList?[idx] is ModdedEnumOption opt ? Enum.ToObject(enumType, opt.Value) - : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {enumType.FullName} is not a ModdedEnumOption"); + : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedEnumOption with enum type {enumType.FullName}"); } } @@ -46,7 +47,7 @@ public class ModdedEnumOptionListAttribute(string title, Type enumType, string[] /// The option's possible values. [AttributeUsage(AttributeTargets.Property)] public class ModdedEnumOptionListAttribute(string title, string[]? values = null) - : ModdedOptionListAttribute(title) + : ModdedOptionListAttribute(title), ITypedOptionList where T : struct, Enum { internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) @@ -59,15 +60,26 @@ public class ModdedEnumOptionListAttribute(string title, string[]? values = n /// public override void SetValue(int idx, object value) { - var opt = HolderOptionList?[idx] as ModdedEnumOption; - opt?.SetValue((T)value); + SetValueUnboxed(idx, (T)value); + } + + /// + public void SetValueUnboxed(int idx, T value) + { + (HolderOptionList?[idx] as ModdedEnumOption)?.SetValue(value); } /// public override object GetValue(int idx) + { + return GetValueUnboxed(idx); + } + + /// + public T GetValueUnboxed(int idx) { return HolderOptionList?[idx] is ModdedEnumOption opt ? opt.Value - : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).FullName}>"); + : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedEnumOption<{typeof(T).FullName}>"); } } diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs index c393db3e..8b8745d3 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedNumberOptionListAttribute.cs @@ -29,7 +29,7 @@ public class ModdedNumberOptionListAttribute( MiraNumberSuffixes suffixType = MiraNumberSuffixes.None, string? formatString = null, bool halfIncrements = false) - : ModdedOptionListAttribute(title) + : ModdedOptionListAttribute(title), ITypedOptionList, ITypedOptionList { /// /// Initializes a new instance of the class. @@ -92,6 +92,18 @@ public class ModdedNumberOptionListAttribute( opt.SetValue(final); } + /// + public void SetValueUnboxed(int idx, float value) + { + (HolderOptionList?[idx] as ModdedNumberOption)?.SetValue(value); + } + + /// + void ITypedOptionList.SetValueUnboxed(int idx, int value) + { + (HolderOptionList?[idx] as ModdedNumberOption)?.SetValue(value); + } + /// public override object GetValue(int idx) { @@ -105,4 +117,18 @@ public class ModdedNumberOptionListAttribute( return value; } + + /// + public float GetValueUnboxed(int idx) + { + return HolderOptionList?[idx] is ModdedNumberOption opt + ? opt.Value + : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedNumberOption"); + } + + /// + int ITypedOptionList.GetValueUnboxed(int idx) + { + return (int)Math.Round(GetValueUnboxed(idx)); + } } diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs index d7ef6e6a..17d2b492 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedOptionListAttribute.cs @@ -1,9 +1,8 @@ using System; using System.Collections; -using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Reflection; using System.Text.RegularExpressions; -using MiraAPI.Translation; namespace MiraAPI.GameOptions.Attributes; @@ -75,10 +74,9 @@ public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAt /// /// The option's index. /// The formatted option's title. - [SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "I don't even know if this is worth it.")] protected string GetFormattedTitle(int index) { - var match = Regex.Match(Title.Translate(), @"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout); + var match = Regex.Match(Title, @"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout); if (!match.Success) { @@ -87,7 +85,7 @@ public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAt if (match.Value == "{0}" && !match.NextMatch().Success) { - return string.Format(Title, index); + return string.Format(CultureInfo.InvariantCulture, Title, index); } Error($"ModdedOptionList Title of {Title} cannot contain more than the first parameter for formatting."); diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs index 533492bb..ec98aea0 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedPlayerOptionListAttribute.cs @@ -14,7 +14,7 @@ namespace MiraAPI.GameOptions.Attributes; public class ModdedPlayerOptionListAttribute( string title, bool allowNone = true) - : ModdedOptionListAttribute(title) + : ModdedOptionListAttribute(title), ITypedOptionList, ITypedOptionList { internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) { @@ -32,12 +32,35 @@ public class ModdedPlayerOptionListAttribute( var final = value switch { - NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0), + NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : -1, _ => (int)value, }; + + if (final == -1 && !allowNone) + throw new ArgumentException("Cannot assign -1 or null to a ModdedPlayerOption that does not allow none as an option."); + opt?.SetValue(final); } + /// + public void SetValueUnboxed(int idx, NetworkedPlayerInfo? value) + { + if (!value && !allowNone) + throw new ArgumentException("Cannot assign null to a ModdedPlayerOption that does not allow none as an option."); + + if (HolderOptionList?[idx] is ModdedPlayerOption opt) + opt.SetValue(value ? opt.Values.IndexOf(value!) : -1); + } + + /// + public void SetValueUnboxed(int idx, int value) + { + if (value == -1 && !allowNone) + throw new ArgumentException("Cannot assign -1 to a ModdedPlayerOption that does not allow none as an option."); + + (HolderOptionList?[idx] as ModdedPlayerOption)?.SetValue(value); + } + /// public override object GetValue(int idx) { @@ -49,4 +72,20 @@ public class ModdedPlayerOptionListAttribute( return opt.SelectedPlayer!; } + + /// + public NetworkedPlayerInfo? GetValueUnboxed(int idx) + { + return HolderOptionList?[idx] is ModdedPlayerOption opt + ? opt.SelectedPlayer + : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption"); + } + + /// + int ITypedOptionList.GetValueUnboxed(int idx) + { + return HolderOptionList?[idx] is ModdedPlayerOption opt + ? opt.Value + : throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption"); + } } diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs index 78c4b66d..3613c98a 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedStringOptionListAttribute.cs @@ -15,7 +15,7 @@ namespace MiraAPI.GameOptions.Attributes; public class ModdedStringOptionListAttribute( string title, string[] values) - : ModdedOptionListAttribute(title) + : ModdedOptionListAttribute(title), ITypedOptionList { internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property) { @@ -28,12 +28,23 @@ public class ModdedStringOptionListAttribute( /// public override void SetValue(int idx, object value) { - var opt = HolderOptionList?[idx] as ModdedStringOption; - opt?.SetValue((string)value); + SetValueUnboxed(idx, (string)value); + } + + /// + public void SetValueUnboxed(int idx, string value) + { + (HolderOptionList?[idx] as ModdedStringOption)?.SetValue(value); } /// public override object GetValue(int idx) + { + return GetValueUnboxed(idx); + } + + /// + public string GetValueUnboxed(int idx) { return HolderOptionList?[idx] is ModdedStringOption opt ? opt.Value diff --git a/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs b/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs index 9dab9a43..decc51f2 100644 --- a/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs +++ b/MiraAPI/GameOptions/Attributes/OptionList/ModdedToggleOptionListAttribute.cs @@ -16,7 +16,7 @@ public class ModdedToggleOptionListAttribute( string title, string on, string off) - : ModdedOptionListAttribute(title) + : ModdedOptionListAttribute(title), ITypedOptionList { /// /// Initializes a new instance of the class. @@ -37,12 +37,23 @@ public class ModdedToggleOptionListAttribute( /// public override void SetValue(int idx, object value) { - var opt = HolderOptionList?[idx] as ModdedToggleOption; - opt?.SetValue((bool)value); + SetValueUnboxed(idx, (bool)value); + } + + /// + public void SetValueUnboxed(int idx, bool value) + { + (HolderOptionList?[idx] as ModdedToggleOption)?.SetValue(value); } /// public override object GetValue(int idx) + { + return GetValueUnboxed(idx); + } + + /// + public bool GetValueUnboxed(int idx) { return HolderOptionList?[idx] is ModdedToggleOption opt ? opt.Value diff --git a/MiraAPI/GameOptions/ModdedArray.cs b/MiraAPI/GameOptions/ModdedArray.cs index 65f60efd..4914a787 100644 --- a/MiraAPI/GameOptions/ModdedArray.cs +++ b/MiraAPI/GameOptions/ModdedArray.cs @@ -2,6 +2,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; +using MiraAPI.GameOptions.Attributes; namespace MiraAPI.GameOptions; @@ -72,15 +73,28 @@ public sealed class ModdedArray : IList, IReadOnlyList, IList /// The index of the value. public T this[int index] { - get => ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute) - ? (T)attribute.GetValue(index) - : items[index]; + get + { + if (!ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute)) + return items[index]; + + return attribute is ITypedOptionList typedAttr + ? typedAttr.GetValueUnboxed(index) + : (T)attribute.GetValue(index); + } set { if (ModdedOptionsManager.ListInstanceCache.TryGetValue(this, out var attribute)) - attribute.SetValue(index, value!); + { + if (attribute is ITypedOptionList typedAttr) + typedAttr.SetValueUnboxed(index, value); + else + attribute.SetValue(index, value!); + } else + { items[index] = value; + } version++; } diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 0fb10bb3..4bacd115 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -30,8 +30,14 @@ public static class ModdedOptionsManager private static readonly Dictionary TypeToGroup = []; private static readonly HashSet OptionAttributes = []; - private static readonly HarmonyMethod CachedGetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertyGetterPatch)); - private static readonly HarmonyMethod CachedSetterPatch = new(typeof(ModdedOptionsManager), nameof(PropertySetterPatch)); + private static readonly MethodInfo OpenGetterPatch = typeof(ModdedOptionsManager) + .GetMethods(BindingFlags.Public | BindingFlags.Static) + .First(m => m.Name == nameof(PropertyGetterPatch) && m.IsGenericMethodDefinition); + private static readonly MethodInfo OpenSetterPatch = typeof(ModdedOptionsManager) + .GetMethods(BindingFlags.Public | BindingFlags.Static) + .First(m => m.Name == nameof(PropertySetterPatch) && m.IsGenericMethodDefinition); + private static readonly Dictionary ConcretisedGetters = []; + private static readonly Dictionary ConcretisedSetters = []; internal static readonly ConditionalWeakTable ListInstanceCache = []; internal static readonly Dictionary CreatedPlayerOptions = []; @@ -170,20 +176,34 @@ public static class ModdedOptionsManager return; } + var propType = property.PropertyType; + + if (!ConcretisedGetters.TryGetValue(propType, out var concreteGetter)) + { + concreteGetter = OpenGetterPatch.MakeGenericMethod(propType); + ConcretisedGetters[propType] = concreteGetter; + } + var getterOriginal = property.GetGetMethod(true)!; - PluginSingleton.Instance.Harmony.Patch(getterOriginal, prefix: CachedGetterPatch); + PluginSingleton.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(concreteGetter)); GetterLookups[getterOriginal] = attribute; var setterOriginal = property.GetSetMethod(true); if (setterOriginal != null) { - PluginSingleton.Instance.Harmony.Patch(setterOriginal, postfix: CachedSetterPatch); + if (!ConcretisedSetters.TryGetValue(propType, out var concreteSetter)) + { + concreteSetter = OpenSetterPatch.MakeGenericMethod(propType); + ConcretisedSetters[propType] = concreteSetter; + } + + PluginSingleton.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(concreteSetter)); SetterLookups[setterOriginal] = attribute; } attribute.HolderOption = option; - attribute.ValueType = property.PropertyType; + attribute.ValueType = propType; var customAttributes = property.GetCustomAttributes(false); @@ -281,15 +301,27 @@ public static class ModdedOptionsManager return; } + if (!ConcretisedGetters.TryGetValue(listType, out var concreteGetter)) + { + concreteGetter = OpenGetterPatch.MakeGenericMethod(listType); + ConcretisedGetters[listType] = concreteGetter; + } + var getterOriginal = property.GetGetMethod(true)!; - PluginSingleton.Instance.Harmony.Patch(getterOriginal, prefix: CachedGetterPatch); + PluginSingleton.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(concreteGetter)); GetterLookups[getterOriginal] = attribute; var setterOriginal = property.GetSetMethod(true); if (setterOriginal != null) { - PluginSingleton.Instance.Harmony.Patch(setterOriginal, postfix: CachedSetterPatch); + if (!ConcretisedSetters.TryGetValue(listType, out var concreteSetter)) + { + concreteSetter = OpenSetterPatch.MakeGenericMethod(listType); + ConcretisedSetters[listType] = concreteSetter; + } + + PluginSingleton.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(concreteSetter)); SetterLookups[setterOriginal] = attribute; } @@ -327,7 +359,7 @@ public static class ModdedOptionsManager var option = optionList[i]; if (visibilityFactory != null) - option.Visible = (Func)(visibilityFactory(i) ?? DelegateUtilities.AlwaysTrue); + option.Visible = visibilityFactory(i) as Func ?? DelegateUtilities.AlwaysTrue; if (getterFactory != null) option.Getter = getterFactory(i); @@ -411,6 +443,7 @@ public static class ModdedOptionsManager /// The new object value. [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention.")] [SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")] + [Obsolete("Use PropertySetterPatch instead.")] public static void PropertySetterPatch(MethodBase __originalMethod, object value) { if (!SetterLookups.TryGetValue(__originalMethod, out var attribute)) @@ -422,6 +455,28 @@ public static class ModdedOptionsManager ListInstanceCache.AddOrUpdate(value, listAttribute); } + /// + /// Patches the setter of a property to update the value of the option. + /// + /// The type of the option value. + /// The original setter method. + /// The new object value. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention.")] + [SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")] + public static void PropertySetterPatch(MethodBase __originalMethod, T value) + { + if (!SetterLookups.TryGetValue(__originalMethod, out var attribute)) + return; + + if (attribute is ITypedOption typedAttribute) + typedAttribute.SetValueUnboxed(value); + else + attribute.SetValue(value!); + + if (attribute is ModdedOptionListAttribute listAttribute && value is not null) + ListInstanceCache.AddOrUpdate(value, listAttribute); + } + /// /// Patches the getter of a property to return the value of the option. /// @@ -430,6 +485,7 @@ public static class ModdedOptionsManager /// so the original getter gets skipped. [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")] [SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")] + [Obsolete("Use PropertyGetterPatch instead.")] public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result) { if (!GetterLookups.TryGetValue(__originalMethod, out var attribute)) @@ -438,4 +494,26 @@ public static class ModdedOptionsManager __result = attribute.GetValue(); return false; } + + /// + /// Patches the getter of a property to return the value of the option. + /// + /// The type of the option value. + /// The original getter method. + /// The result of the property getter. + /// so the original getter gets skipped. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")] + [SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Read above.")] + public static bool PropertyGetterPatch(MethodBase __originalMethod, ref T __result) + { + if (!GetterLookups.TryGetValue(__originalMethod, out var attribute)) + return true; + + if (attribute is ITypedOption typedAttribute) + __result = typedAttribute.GetValueUnboxed(); + else + __result = (T)attribute.GetValue(); + + return false; + } } diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs index 1fa3245c..c23fc76f 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedEnumOption.cs @@ -13,6 +13,7 @@ namespace MiraAPI.GameOptions.OptionTypes; /// /// An option for selecting an value. /// +[Obsolete("Use ModdedEnum instead.")] public class ModdedEnumOption : ModdedOption { ///