Compare commits

..
4 Commits
Author SHA1 Message Date
Az 9548225991 Update ModdedOptionVisibilityAttribute.cs 2026-11-19 18:15:02 -05:00
Az 32a7dab31c some fixes and improvements 2026-11-19 18:13:22 -05:00
Az cc8d1ae878 some multi-select progress + code improvements 2026-11-19 17:32:08 -05:00
Az 8340ebba4e WIP multi select options 2026-11-19 02:53:28 -05:00
16 changed files with 699 additions and 30 deletions

No files matched your search

@@ -17,7 +17,7 @@ namespace MiraAPI.GameOptions.Attributes;
[AttributeUsage(AttributeTargets.Property)] [AttributeUsage(AttributeTargets.Property)]
public abstract class ModdedOptionMemberAttribute(string? memberName, Type? holderType, string defaultSuffix) : Attribute public abstract class ModdedOptionMemberAttribute(string? memberName, Type? holderType, string defaultSuffix) : Attribute
{ {
private static readonly Dictionary<MethodInfo, Delegate> DelegateCache = []; private static readonly Dictionary<(MethodInfo, Type), Delegate> DelegateCache = [];
/// <summary> /// <summary>
/// A helper class to bind a specific list index to a dynamically compiled delegate. /// A helper class to bind a specific list index to a dynamically compiled delegate.
@@ -218,7 +218,10 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
flags |= BindingFlags.NonPublic; flags |= BindingFlags.NonPublic;
} }
var member = type.GetMember(MemberName, flags).OrderBy(GetGenericArgsLength).FirstOrDefault(); var member = type.GetMember(MemberName, flags)
.OrderBy(GetGenericArgsLength)
.ThenBy(GetArgsLength)
.FirstOrDefault();
notFound = true; notFound = true;
if (member == null) if (member == null)
@@ -290,6 +293,14 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
return method.IsGenericMethodDefinition ? method.GetGenericArguments().Length : 0; return method.IsGenericMethodDefinition ? method.GetGenericArguments().Length : 0;
} }
private static int GetArgsLength(MemberInfo member)
{
if (member is not MethodInfo method)
return -1;
return method.GetParameters().Length;
}
/// <summary> /// <summary>
/// Compiles a <see cref="DynamicMethod"/> using IL generation to invoke the resolved static or instance <paramref name="method"/>. /// Compiles a <see cref="DynamicMethod"/> using IL generation to invoke the resolved static or instance <paramref name="method"/>.
/// </summary> /// </summary>
@@ -317,7 +328,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
bool forwardParameters = true, bool forwardParameters = true,
Action<ILGenerator>? postProcessCall = null) Action<ILGenerator>? postProcessCall = null)
{ {
if (postProcessCall == null && DelegateCache.TryGetValue(method, out var cachedDelegate)) if (postProcessCall == null && DelegateCache.TryGetValue((method, delegateType), out var cachedDelegate))
return cachedDelegate; return cachedDelegate;
var dm = new DynamicMethod($"{ownerType.Name}_{method.Name}_{suffix}", returnType, paramTypes, ownerType, true); var dm = new DynamicMethod($"{ownerType.Name}_{method.Name}_{suffix}", returnType, paramTypes, ownerType, true);
@@ -356,7 +367,7 @@ public abstract class ModdedOptionMemberAttribute(string? memberName, Type? hold
var compiledDelegate = dm.CreateDelegate(delegateType); var compiledDelegate = dm.CreateDelegate(delegateType);
if (postProcessCall == null) if (postProcessCall == null)
DelegateCache[method] = compiledDelegate; DelegateCache[(method, delegateType)] = compiledDelegate;
return compiledDelegate; return compiledDelegate;
} }
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using MiraAPI.GameOptions.OptionTypes; using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.Attributes; namespace MiraAPI.GameOptions.Attributes;
@@ -81,12 +82,14 @@ public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, T
return null; return null;
} }
if (field.IsLiteral)
return (bool)field.GetRawConstantValue()! ? DelegateUtilities.AlwaysTrue : DelegateUtilities.AlwaysFalse;
var dynamicMethod = new DynamicMethod($"GetVisibility_{type.Name}_{field.Name}", typeof(bool), Type.EmptyTypes, type, true); var dynamicMethod = new DynamicMethod($"GetVisibility_{type.Name}_{field.Name}", typeof(bool), Type.EmptyTypes, type, true);
var il = dynamicMethod.GetILGenerator(); var il = dynamicMethod.GetILGenerator();
if (instanceGetter != null) if (instanceGetter != null)
{ {
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, instanceGetter); il.Emit(OpCodes.Call, instanceGetter);
il.Emit(OpCodes.Ldfld, field); il.Emit(OpCodes.Ldfld, field);
} }
@@ -109,7 +112,7 @@ public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, T
internal Func<int, Delegate?>? GetListVisibility(AbstractOptionGroup group, PropertyInfo property) internal Func<int, Delegate?>? GetListVisibility(AbstractOptionGroup group, PropertyInfo property)
{ {
if (ResolveMember(group, property, out Type type, out var instanceGetter, out var notFound) is not { } member) if (ResolveMember(group, property, out var type, out var instanceGetter, out var notFound) is not { } member)
{ {
if (notFound) if (notFound)
Error($"Member {MemberName} does not exist in {type.FullName}"); Error($"Member {MemberName} does not exist in {type.FullName}");
@@ -225,12 +228,17 @@ public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, T
return null; return null;
} }
if (field.IsLiteral)
{
var constant = (bool)field.GetRawConstantValue()! ? DelegateUtilities.AlwaysTrue : DelegateUtilities.AlwaysFalse;
return _ => constant;
}
var dynamicMethod = new DynamicMethod($"GetListVisibility_{type.Name}_{field.Name}", typeof(bool), [typeof(int)], type, true); var dynamicMethod = new DynamicMethod($"GetListVisibility_{type.Name}_{field.Name}", typeof(bool), [typeof(int)], type, true);
var il = dynamicMethod.GetILGenerator(); var il = dynamicMethod.GetILGenerator();
if (instanceGetter != null) if (instanceGetter != null)
{ {
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, instanceGetter); il.Emit(OpCodes.Call, instanceGetter);
il.Emit(OpCodes.Ldfld, field); il.Emit(OpCodes.Ldfld, field);
} }
@@ -0,0 +1,101 @@
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Translation;
using Reactor.Utilities.Attributes;
namespace MiraAPI.GameOptions.Components;
/// <summary>
/// A <see cref="BaseGameSetting"/> implementation that supports multi-select options.
/// </summary>
/// <param name="cppPtr">The C++ pointer to the object.</param>
[RegisterInIl2Cpp]
public class FlagsGameSetting(nint cppPtr) : BaseGameSetting(cppPtr)
{
/// <summary>
/// Gets or sets the value currently held by the setting.
/// </summary>
public int Value { get; set; }
/// <summary>
/// Gets or sets the integer value used to denote that all flags have been selected.
/// </summary>
public int All { get; set; }
/// <summary>
/// Gets or sets every defined flag within the enum.
/// </summary>
public Il2CppStructArray<int> Flags { get; set; }
/// <summary>
/// Gets or sets the string names associated with every flag.
/// </summary>
public Il2CppStructArray<StringNames> Values { get; set; }
/// <summary>
/// Gets or sets the string name for when no value is selected.
/// </summary>
public StringNames NoneName { get; set; }
/// <summary>
/// Gets or sets the string name for when all values are selected.
/// </summary>
public StringNames AllName { get; set; }
/// <inheritdoc/>
public override string GetValueString(float value)
{
return GetValueString((int)value);
}
/// <summary>
/// Gets a value display string.
/// </summary>
/// <param name="value">The enum value as an int.</param>
/// <returns>A value string.</returns>
public string GetValueString(int value)
{
if (value == 0)
{
return TranslationController.Instance.GetString(NoneName).Translate();
}
if (value == All)
{
return TranslationController.Instance.GetString(AllName).Translate();
}
var activeCount = 0;
var firstActiveName = StringNames.None;
var foundFirst = false;
for (var i = 0; i < Flags.Length; i++)
{
var flag = Flags[i];
if (flag == 0 || (value & flag) != flag)
continue;
if (!foundFirst)
{
firstActiveName = Values[i];
foundFirst = true;
}
activeCount++;
}
if (activeCount == 0)
{
return TranslationController.Instance.GetString(NoneName).Translate();
}
var firstNameString = TranslationController.Instance.GetString(firstActiveName).Translate();
if (activeCount == 1)
{
return firstNameString;
}
return MiraLocaleManager.GetParsed("MiraApi.Compound", string.Empty, firstNameString, activeCount - 1);
}
}
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
using Reactor.Utilities.Attributes;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace MiraAPI.GameOptions.Components;
// TODO: Add documentation once completed
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
/// <summary>
/// An option behaviour that acts as a container for dynamically generated flag toggles.
/// </summary>
/// <param name="cppPtr">The pointer to the C++ object.</param>
[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity convention.")]
[RegisterInIl2Cpp]
public class FlagsOption(nint cppPtr) : OptionBehaviour(cppPtr)
{
public TextMeshPro TitleText;
public TextMeshPro ValueText;
public GameOptionButton Button;
public bool Expanded;
public int Value;
public Il2CppStructArray<int> Flags;
public Il2CppStructArray<StringNames> Values;
public IFlagsOption Option;
private int oldValue;
private void Start()
{
Initialize();
}
public override int GetInt()
{
return Value;
}
public override void SetUpFromData(BaseGameSetting data, int maskLayer)
{
base.SetUpFromData(data, maskLayer);
var flagsGameSetting = data.TryCast<FlagsGameSetting>();
if (flagsGameSetting == null)
{
return;
}
Title = flagsGameSetting.Title;
Value = flagsGameSetting.Value;
Flags = flagsGameSetting.Flags;
Values = flagsGameSetting.Values;
}
public override void Initialize()
{
Value = Option.Value;
ValueText.text = Option.GetDisplayValue();
TitleText.text = TranslationController.Instance.GetString(Title);
Button.AddOnClickListeners((Action)UpdateList);
AdjustButtonState();
}
private void UpdateList()
{
}
private void AdjustButtonState()
{
Button.ChangeButtonText(Expanded ? "⏶" : "⏷");
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ using System.Collections.Generic;
namespace MiraAPI.GameOptions; namespace MiraAPI.GameOptions;
/// <summary> /// <summary>
/// A holder option for a summary and option string names that are hidden behind it. /// A grouped data container that holds the options that need to be hidden and the summary produced from hiding them.
/// </summary> /// </summary>
/// <param name="hiddenKeys">The <see cref="StringNames"/> of the options being hidden.</param> /// <param name="hiddenKeys">The <see cref="StringNames"/> of the options being hidden.</param>
/// <param name="summaryLines">A delegate that produces the summary to replace the default text of the options being hidden.</param> /// <param name="summaryLines">A delegate that produces the summary to replace the default text of the options being hidden.</param>
+46 -4
View File
@@ -23,6 +23,7 @@ namespace MiraAPI.GameOptions;
/// </summary> /// </summary>
public static class ModdedOptionsManager public static class ModdedOptionsManager
{ {
private static readonly Dictionary<(Type Holder, string Property), IBaseModdedOptionList> PropertyToOptionListMap = [];
private static readonly Dictionary<(Type Holder, string Property), IModdedOption> PropertyToOptionMap = []; private static readonly Dictionary<(Type Holder, string Property), IModdedOption> PropertyToOptionMap = [];
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> GetterLookup = []; private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> GetterLookup = [];
private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> SetterLookup = []; private static readonly Dictionary<RuntimeMethodHandle, PropertyOptionAttribute> SetterLookup = [];
@@ -257,6 +258,8 @@ public static class ModdedOptionsManager
{ {
RegisterOption(type, optionList.ElementAt(i), group, configName(i), pluginInfo); RegisterOption(type, optionList.ElementAt(i), group, configName(i), pluginInfo);
} }
PropertyToOptionListMap.Add((type, property.Name), optionList);
} }
private static void RegisterAttributeOptionList( private static void RegisterAttributeOptionList(
@@ -350,6 +353,8 @@ public static class ModdedOptionsManager
RegisterOption(type, option, group, property.Name + (i + 1), pluginInfo); RegisterOption(type, option, group, property.Name + (i + 1), pluginInfo);
} }
PropertyToOptionListMap.Add((type, property.Name), optionList);
} }
private static void RegisterOption( private static void RegisterOption(
@@ -424,7 +429,8 @@ public static class ModdedOptionsManager
} }
/// <summary> /// <summary>
/// Gets a <see cref="StringNames"/> value associated to the option of the provided property name that is found in <typeparamref name="T"/>. /// Gets a <see cref="StringNames"/> value associated to the option of the provided property name that is found in <typeparamref name="T"/>.<br/>
/// Use only for attribute options. Explicitly defined options should be used as they are.
/// </summary> /// </summary>
/// <typeparam name="T">The container option type.</typeparam> /// <typeparam name="T">The container option type.</typeparam>
/// <param name="propertyName">The name of the property that defines the option.</param> /// <param name="propertyName">The name of the property that defines the option.</param>
@@ -432,13 +438,49 @@ public static class ModdedOptionsManager
public static StringNames GetStringName<T>(string propertyName) public static StringNames GetStringName<T>(string propertyName)
where T : AbstractOptionGroup where T : AbstractOptionGroup
{ {
var type = typeof(T); return GetOption<T, IModdedOption>(propertyName)?.StringName ?? StringNames.None;
}
/// <summary>
/// Gets a <see cref="IModdedOption"/> associated to the provided property name that is found in <typeparamref name="TGroup"/>.<br/>
/// Use only for attribute options. Explicitly defined options should be used as they are.
/// </summary>
/// <typeparam name="TGroup">The container option type.</typeparam>
/// <typeparam name="TOption">The option type.</typeparam>
/// <param name="propertyName">The name of the property that defines the option.</param>
/// <returns>The option, if found.</returns>
public static TOption? GetOption<TGroup, TOption>(string propertyName)
where TGroup : AbstractOptionGroup
where TOption : IModdedOption
{
var type = typeof(TGroup);
if (PropertyToOptionMap.TryGetValue((type, propertyName), out var option)) if (PropertyToOptionMap.TryGetValue((type, propertyName), out var option))
return option.StringName; return (TOption)option;
Error($"Could not find an option with the property name {propertyName} in {type.Name}"); Error($"Could not find an option with the property name {propertyName} in {type.Name}");
return StringNames.None; return default;
}
/// <summary>
/// Gets a <see cref="IBaseModdedOptionList"/> associated to the provided property name that is found in <typeparamref name="TGroup"/>.<br/>
/// Use only for attribute lists. Explicitly defined lists should be used as they are.
/// </summary>
/// <typeparam name="TGroup">The container option type.</typeparam>
/// <typeparam name="TList">The option list type.</typeparam>
/// <param name="propertyName">The name of the property that defines the option list.</param>
/// <returns>The option list, if found.</returns>
public static TList? GetOptionList<TGroup, TList>(string propertyName)
where TGroup : AbstractOptionGroup
where TList : IBaseModdedOptionList
{
var type = typeof(TGroup);
if (PropertyToOptionListMap.TryGetValue((type, propertyName), out var optionList))
return (TList)optionList;
Error($"Could not find an option list with the property name {propertyName} in {type.Name}");
return default;
} }
/// <summary> /// <summary>
@@ -1,4 +1,6 @@
using System; using System;
using System.Linq;
using MiraAPI.Translation;
using UnityEngine; using UnityEngine;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
@@ -41,6 +43,8 @@ public abstract class ModdedBaseStringOption<T>(string groupPrefix, string title
/// <param name="defaultIndex">The default index to assign.</param> /// <param name="defaultIndex">The default index to assign.</param>
protected void InitializeData(int defaultIndex) protected void InitializeData(int defaultIndex)
{ {
StringNameValues = [.. Values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
var data = ScriptableObject.CreateInstance<StringGameSetting>(); var data = ScriptableObject.CreateInstance<StringGameSetting>();
data.Title = StringName; data.Title = StringName;
data.Type = global::OptionTypes.String; data.Type = global::OptionTypes.String;
@@ -4,7 +4,6 @@ using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using BepInEx.Configuration; using BepInEx.Configuration;
using MiraAPI.Networking; using MiraAPI.Networking;
using MiraAPI.Translation;
using MiraAPI.Utilities; using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.OptionTypes; namespace MiraAPI.GameOptions.OptionTypes;
@@ -46,21 +45,27 @@ public class ModdedEnumOption : ModdedBaseEnumOption<int>
if (!enumType.IsEnum) if (!enumType.IsEnum)
throw new ArgumentException($"The type {enumType.Name} is not an Enum.", nameof(enumType)); throw new ArgumentException($"The type {enumType.Name} is not an Enum.", nameof(enumType));
idPrefix = idPrefix.Replace("%type%", enumType.Name);
var rawValues = Enum.GetValues(enumType); var rawValues = Enum.GetValues(enumType);
UnderlyingValues = new int[rawValues.Length]; var underlyingValues = new int[rawValues.Length];
for (var i = 0; i < rawValues.Length; i++) for (var i = 0; i < rawValues.Length; i++)
UnderlyingValues[i] = Convert.ToInt32(rawValues.GetValue(i), NumberFormatInfo.InvariantInfo); underlyingValues[i] = Convert.ToInt32(rawValues.GetValue(i), NumberFormatInfo.InvariantInfo);
UnderlyingValues = [.. underlyingValues.Distinct()];
if (values != null && values.Length != UnderlyingValues.Length) if (values != null && values.Length != UnderlyingValues.Length)
{ {
throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of enum values ({UnderlyingValues.Length}) in {enumType.Name}.", nameof(values)); throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of enum values ({UnderlyingValues.Length}) in {enumType.Name}.", nameof(values));
} }
Values = values ?? Enum.GetNames(enumType); if (Array.IndexOf(UnderlyingValues, defaultValue) == -1)
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString($"{idPrefix}{x}"))]; {
throw new ArgumentException($"The defaultValue '{defaultValue}' is not present in the allowed enum values.", nameof(defaultValue));
}
idPrefix = idPrefix.Replace("%type%", enumType.Name);
Values = [.. (values ?? rawValues.Cast<object>()).Select(x => idPrefix + x)];
InitializeData(GetIndex(defaultValue)); InitializeData(GetIndex(defaultValue));
} }
@@ -147,22 +152,21 @@ public class ModdedEnumOption<T> : ModdedBaseEnumOption<T>
public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, bool includeInPreset = true) public ModdedEnumOption(string groupPrefix, string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset) : base(groupPrefix, title, defaultValue, includeInPreset)
{ {
idPrefix = idPrefix.Replace("%type%", typeof(T).Name); UnderlyingValues = [.. (allowedValues ?? Enum.GetValues<T>()).Distinct()];
UnderlyingValues = allowedValues ?? Enum.GetValues<T>(); if (values != null && values.Length != UnderlyingValues.Length)
{
throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of enum values ({UnderlyingValues.Length}) in {typeof(T).Name}.", nameof(values));
}
if (Array.IndexOf(UnderlyingValues, defaultValue) == -1) if (Array.IndexOf(UnderlyingValues, defaultValue) == -1)
{ {
throw new ArgumentException($"The defaultValue '{defaultValue}' is not present in the allowed enum values.", nameof(defaultValue)); throw new ArgumentException($"The defaultValue '{defaultValue}' is not present in the allowed enum values.", nameof(defaultValue));
} }
if (values != null && values.Length != UnderlyingValues.Length) idPrefix = idPrefix.Replace("%type%", typeof(T).Name);
{
throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of allowed enum values ({UnderlyingValues.Length}).", nameof(values));
}
Values = values ?? [.. UnderlyingValues.Select(v => v.ToString())]; Values = [.. (values ?? UnderlyingValues.Cast<object>()).Select(x => idPrefix + x)];
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString($"{idPrefix}{x}"))];
InitializeData(GetIndex(defaultValue)); InitializeData(GetIndex(defaultValue));
} }
@@ -0,0 +1,290 @@
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using MiraAPI.GameOptions.Components;
using MiraAPI.Networking;
using MiraAPI.Patches.Options;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.GameOptions.OptionTypes;
/// <summary>
/// An interface used to mark an option class as a flags option.
/// </summary>
public interface IFlagsOption
{
/// <summary>
/// Gets the combined bits value of the option's selected flags.
/// </summary>
int Value { get; }
/// <inheritdoc cref="IModdedOption.GetDisplayValue"/>
string GetDisplayValue();
}
/// <summary>
/// An option for selecting multiple <typeparamref name="T"/> values.
/// </summary>
/// <typeparam name="T">The type of the flag enum used as the backing value.</typeparam>
public class ModdedFlagsOption<T> : ModdedOption<T>, IFlagsOption
where T : struct, Enum
{
/// <summary>
/// Gets an array of int values where only a bit is turned on to denote each flag contained within <typeparamref name="T"/>.
/// </summary>
public int[] Flags { get; }
/// <summary>
/// Gets the string values of the option.
/// </summary>
public string[] Values { get; } = [];
/// <summary>
/// Gets the String Name values of the option.
/// </summary>
public StringNames[] StringNameValues { get; } = [];
/// <summary>
/// Gets the <see cref="StringNames"/> ID of the translation that corresponds to when no options are selected.
/// </summary>
public StringNames NoneName { get; }
/// <summary>
/// Gets the <see cref="StringNames"/> ID of the translation that corresponds to when all options are selected.
/// </summary>
public StringNames AllName { get; }
/// <summary>
/// Gets the "maximum" value of the flag option, which is where all defined flags are turned on.
/// </summary>
public int All { get; }
/// <summary>
/// Gets a (possibly) filtered array of strongly typed values that are allowed to be used by the option.
/// </summary>
public T[] AllowedValues { get; }
private readonly string allTranslationId;
private readonly string noneTranslationId;
private int value;
int IFlagsOption.Value => value;
/// <summary>
/// Initializes a new instance of the <see cref="ModdedFlagsOption{T}"/> class.
/// </summary>
/// <param name="groupPrefix">The translation ID prefix of the group containing this option.</param>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an <see langword="int"/>.</param>
/// <param name="idPrefix">The common translation ID prefix of all enum values.</param>
/// <param name="allowedValues">An option array of enum values to filter down what values can actually be used.</param>
/// <param name="values">An optional array of string values to use in place of the <see langword="enum"/> name.</param>
/// <param name="noneId">The core part of the translation ID corresponding to when no options are selected.</param>
/// <param name="allId">The core part of the translation ID corresponding to when all options are selected.</param>
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
public ModdedFlagsOption(string groupPrefix, string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: base(groupPrefix, title, defaultValue, includeInPreset)
{
var enumType = typeof(T);
if (!enumType.IsDefined<FlagsAttribute>(false))
throw new ArgumentException($"{enumType.Name} does not have [Flags], and therefore cannot be used for multi-select options.");
if (allowedValues == null)
allowedValues = Enum.GetValues<T>();
allowedValues = [.. allowedValues.Distinct()];
var tuples = allowedValues
.Select(x => (Val: x, Bit: Convert.ToInt32(x, NumberFormatInfo.InvariantInfo)))
.Where(val => val.Bit > 0 && (val.Bit & (val.Bit - 1)) == 0)
.ToArray();
if (values != null && values.Length != tuples.Length)
{
throw new ArgumentException($"The number of custom values ({values.Length}) must exactly match the number of allowed single-bit flags ({tuples.Length}).", nameof(values));
}
var all = 0;
foreach (var (_, bit) in tuples)
{
all |= bit;
}
var defaultBits = Convert.ToInt32(defaultValue, NumberFormatInfo.InvariantInfo);
if ((defaultBits & ~all) != 0)
{
throw new ArgumentException($"The defaultValue contains flags that are not present in the allowed subset.", nameof(defaultValue));
}
idPrefix = idPrefix.Replace("%type%", enumType.Name);
value = defaultBits;
allTranslationId = idPrefix + (allId ?? "All");
noneTranslationId = idPrefix + (noneId ?? "None");
All = all;
Flags = [.. tuples.Select(x => x.Bit)];
AllowedValues = [.. tuples.Select(x => x.Val)];
Values = values ?? [.. tuples.Select(x => x.Val.ToString())];
AllName = MiraLocaleManager.GetOrCreateLocaleString(allTranslationId);
NoneName = MiraLocaleManager.GetOrCreateLocaleString(noneTranslationId);
StringNameValues = [.. Values.Select(x => MiraLocaleManager.GetOrCreateLocaleString(idPrefix + x))];
var data = ScriptableObject.CreateInstance<FlagsGameSetting>();
data.Type = global::OptionTypes.MultipleChoice; // How nice of Innersloth to provide us with a pre-defined enum value
data.Value = defaultBits;
data.All = All;
data.Flags = Flags;
data.Values = StringNameValues;
Data = data;
}
/// <inheritdoc cref="ModdedFlagsOption(string, string, T, string, T[], string[], string, string, bool)"/>
public ModdedFlagsOption(string groupPrefix, string title, T defaultValue, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: this(groupPrefix, title, defaultValue, string.Empty, allowedValues, values, noneId, allId, includeInPreset)
{
}
/// <inheritdoc cref="ModdedFlagsOption(string, string, T, string, T[], string[], string, string, bool)"/>
public ModdedFlagsOption(string title, T defaultValue, string idPrefix, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, idPrefix, allowedValues, values, noneId, allId, includeInPreset)
{
}
/// <inheritdoc cref="ModdedFlagsOption(string, string, T, string, T[], string[], string, string, bool)"/>
public ModdedFlagsOption(string title, T defaultValue, T[]? allowedValues = null, string[]? values = null, string? noneId = null, string? allId = null, bool includeInPreset = true)
: this(string.Empty, title, defaultValue, string.Empty, allowedValues, values, noneId, allId, includeInPreset)
{
}
/// <inheritdoc />
public override OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, PlayerOption playerOpt, Transform container)
{
var multiSelectOption = GameOptionsMenuPatch.CreateOption(stringOpt, container);
multiSelectOption.name = $"{ParentMod!.OptionsTitleText}.FlagsOption.{Title}";
multiSelectOption.SetUpFromData(Data, 20);
multiSelectOption.Option = this;
multiSelectOption.OnValueChanged = (Action<OptionBehaviour>)ValueChanged;
OptionBehaviour = multiSelectOption;
return multiSelectOption;
}
/// <inheritdoc />
public override float GetFloatData()
{
return value;
}
/// <inheritdoc />
public override NetData GetNetData()
{
var buffer = new byte[Unsafe.SizeOf<T>()];
Unsafe.WriteUnaligned(ref buffer[0], _value);
return new(Id, buffer);
}
/// <inheritdoc />
public override void HandleNetData(byte[] data)
{
SetValue(Unsafe.ReadUnaligned<T>(ref data[0]));
}
/// <inheritdoc />
public override string GetDisplayValue()
{
if (value == 0)
{
return noneTranslationId.Translate();
}
if (value == All)
{
return allTranslationId.Translate();
}
var activeCount = 0;
var firstActiveName = string.Empty;
var foundFirst = false;
for (var i = 0; i < Flags.Length; i++)
{
var flag = Flags[i];
if (flag == 0 || (value & flag) != flag)
continue;
if (!foundFirst)
{
firstActiveName = Values[i];
foundFirst = true;
}
activeCount++;
}
if (activeCount == 0)
{
return noneTranslationId.Translate();
}
var firstNameString = firstActiveName.Translate();
if (activeCount == 1)
{
return firstNameString;
}
return "MiraApi.Compound".Translate(firstNameString, activeCount - 1);
}
/// <inheritdoc />
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return (T)Enum.ToObject(typeof(T), optionBehaviour.GetInt());
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
if (OptionBehaviour && OptionBehaviour is FlagsOption opt)
{
opt.Value = value;
}
}
/// <inheritdoc />
protected override ConfigDescription? CreateDescription()
{
return new(string.Empty, new AcceptableFlagValues<T>(AllowedValues));
}
/// <inheritdoc />
protected override T ModifyValue(T newValue, T oldValue)
{
value = Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo) & All;
return (T)Enum.ToObject(typeof(T), value);
}
/// <summary>
/// Implicitly converts the option to an <see langword="int"/>.
/// </summary>
/// <param name="option">The option.</param>
/// <returns>Integer value.</returns>
public static implicit operator int(ModdedFlagsOption<T> option)
{
return option.value;
}
}
@@ -27,7 +27,6 @@ public class ModdedStringOption : ModdedBaseStringOption<string>
{ {
Values = values; Values = values;
UnderlyingValues = values; UnderlyingValues = values;
StringNameValues = [.. values.Select(MiraLocaleManager.GetOrCreateLocaleString)];
InitializeData(GetIndex(defaultValue)); InitializeData(GetIndex(defaultValue));
} }
@@ -6,6 +6,7 @@ using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib; using HarmonyLib;
using MiraAPI.GameModes; using MiraAPI.GameModes;
using MiraAPI.GameOptions; using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Components;
using MiraAPI.Modifiers; using MiraAPI.Modifiers;
using MiraAPI.Presets; using MiraAPI.Presets;
using MiraAPI.Translation; using MiraAPI.Translation;
@@ -32,6 +33,29 @@ internal static class GameOptionsMenuPatch
private static TextMeshPro _gamemodeDescription = null!; private static TextMeshPro _gamemodeDescription = null!;
private static SpriteRenderer _modIcon = null!; private static SpriteRenderer _modIcon = null!;
public static FlagsOption CreateOption(StringOption stringOption, Transform container)
{
var baseOption = Object.Instantiate(stringOption, container).DontUnload().DontDestroy();
var optionGO = baseOption.gameObject;
var titleText = baseOption.TitleText;
var valueText = baseOption.ValueText;
var button = baseOption.PlusBtn;
baseOption.MinusBtn.gameObject.Destroy();
baseOption.Destroy();
var flagsOption = optionGO.AddComponent<FlagsOption>();
flagsOption.TitleText = titleText;
flagsOption.ValueText = valueText;
flagsOption.Button = button;
flagsOption.buttons = new PassiveButton[] { button };
button.OnClick = new();
return flagsOption;
}
[HarmonyPrefix] [HarmonyPrefix]
[HarmonyPatch(nameof(GameOptionsMenu.Initialize))] [HarmonyPatch(nameof(GameOptionsMenu.Initialize))]
public static bool InitPatch(GameOptionsMenu __instance) public static bool InitPatch(GameOptionsMenu __instance)
@@ -590,7 +614,7 @@ internal static class GameOptionsMenuPatch
continue; continue;
} }
if (!opt.Visible.Invoke()) if (!opt.Visible())
{ {
newOpt.gameObject.SetActive(false); newOpt.gameObject.SetActive(false);
continue; continue;
+3
View File
@@ -76,6 +76,9 @@
<string name="Activated">Activated</string> <string name="Activated">Activated</string>
<string name="Deactivated">Deactivated</string> <string name="Deactivated">Deactivated</string>
<string name="MiraApi.AbbreviatedDistance">unit(s)</string> <string name="MiraApi.AbbreviatedDistance">unit(s)</string>
<string name="All">All</string>
<string name="None">None</string>
<string name="MiraApi.Compound">{0} + {1}</string>
<string name="MiraApi.Option.Group.HnsCrewmate">Crewmates</string> <string name="MiraApi.Option.Group.HnsCrewmate">Crewmates</string>
<string name="MiraApi.HnsCrewmate.Option.PlayerSpeed">Player Speed</string> <string name="MiraApi.HnsCrewmate.Option.PlayerSpeed">Player Speed</string>
+17
View File
@@ -249,6 +249,23 @@ public static class MiraLocaleManager
return GetParsed(language, key, string.Empty, parseList); return GetParsed(language, key, string.Empty, parseList);
} }
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
string key,
string fallback,
params object[] parseList)
{
return GetParsed(CurrentLanguage, key, fallback, parseList);
}
/// <inheritdoc cref="GetParsed(MiraLanguage, string, ValueTuple{string, string}[], string)"/>
public static string GetParsed(
string key,
params object[] parseList)
{
return GetParsed(CurrentLanguage, key, string.Empty, parseList);
}
/// <summary> /// <summary>
/// Builds a formatted translation ID string using a mod ID, a specific ID part, and a suffix. /// Builds a formatted translation ID string using a mod ID, a specific ID part, and a suffix.
/// </summary> /// </summary>
@@ -14,4 +14,15 @@ public static class TranslationExtensions
{ {
return MiraLocaleManager.Get(key); return MiraLocaleManager.Get(key);
} }
/// <summary>
/// Translates a key to the current language.
/// </summary>
/// <param name="key">The translation key.</param>
/// <param name="args">The values to format the string with.</param>
/// <returns>The corresponding translation.</returns>
public static string Translate(this string key, params object[] args)
{
return MiraLocaleManager.GetParsed(key, string.Empty, args);
}
} }
+1 -1
View File
@@ -61,6 +61,6 @@ public sealed class AcceptableEnumValues<T> : AcceptableValueBase
/// <inheritdoc/> /// <inheritdoc/>
public override string ToDescriptionString() public override string ToDescriptionString()
{ {
return "# Acceptable values: " + string.Join(", ", AcceptableValues.Select(x => x.ToString())); return "# Acceptable values: " + string.Join(", ", AcceptableValues);
} }
} }
+73
View File
@@ -0,0 +1,73 @@
using System;
using System.Globalization;
using BepInEx.Configuration;
namespace MiraAPI.Utilities;
/// <summary>
/// Specify the list of acceptable individual flag values for a setting.<br/>
/// Any bitwise combination of these provided flags is considered valid.
/// </summary>
/// <typeparam name="T">The type of the flag enum.</typeparam>
public sealed class AcceptableFlagValues<T> : AcceptableValueBase
where T : struct, Enum
{
/// <summary>
/// Gets a list of single-bit values that a setting can include.
/// </summary>
public T[] AcceptableValues { get; }
private readonly int allMask;
/// <summary>
/// Initializes a new instance of the <see cref="AcceptableFlagValues{T}"/> class.
/// </summary>
/// <param name="acceptableValues">The acceptable individual flags.</param>
/// <exception cref="ArgumentNullException">Thrown when the given values are null.</exception>
/// <exception cref="ArgumentException">Thrown when no values are given.</exception>
public AcceptableFlagValues(params T[] acceptableValues)
: base(typeof(T))
{
ArgumentNullException.ThrowIfNull(acceptableValues);
if (acceptableValues.Length == 0)
throw new ArgumentException("At least one acceptable value is needed", nameof(acceptableValues));
AcceptableValues = acceptableValues;
allMask = 0;
foreach (var val in acceptableValues)
allMask |= Convert.ToInt32(val, NumberFormatInfo.InvariantInfo);
}
/// <inheritdoc/>
public override object Clamp(object value)
{
if (IsValid(value))
return value;
if (value is not T)
return Enum.ToObject(typeof(T), 0);
var intVal = Convert.ToInt32(value, NumberFormatInfo.InvariantInfo);
var clampedVal = intVal & allMask;
return Enum.ToObject(typeof(T), clampedVal);
}
/// <inheritdoc/>
public override bool IsValid(object value)
{
if (value is not T)
return false;
var intVal = Convert.ToInt32(value, NumberFormatInfo.InvariantInfo);
return (intVal & ~allMask) == 0;
}
/// <inheritdoc/>
public override string ToDescriptionString()
{
return "# Acceptable Flags: " + string.Join(", ", AcceptableValues);
}
}