Merge branch 'dev' into pr/115

This commit is contained in:
Az committed 2026-11-05 03:10:05 -05:00
commit b277a86f2b
24 files changed
+235 -262

No files matched your search

+2
View File
@@ -77,6 +77,8 @@ public abstract class AbstractGameMode : IOptionable
/// </summary>
public virtual float DefaultImpostorKillCooldown => GameOptionsManager.Instance.CurrentGameOptions.GetFloat(FloatOptionNames.KillCooldown);
internal StringNames StringName { get; set; }
/// <summary>
/// Called on GameManager.GetBodyType().
/// </summary>
+11 -13
View File
@@ -44,9 +44,10 @@ public static class CustomGameModeManager
if (mode.HideMode)
return true;
IdToModeMap.Add(GetNextId(), mode);
pluginInfo.GameModes.Add(lastId, mode);
mode.ID = lastId;
var id = GetNextId();
mode.ID = id;
IdToModeMap.Add(id, mode);
pluginInfo.GameModes.Add(id, mode);
GameModeOption.AddOption(mode);
return true;
}
@@ -107,34 +108,31 @@ public static class CustomGameModeManager
internal static void RegisterDefaultMode()
{
var defaultMode = new ClassicMode();
var defaultMode = new ClassicMode { ID = 0 };
IdToModeMap.Add(0, defaultMode);
GameModeOption.AddOption(defaultMode);
// no need to add to game mode option as it already contains it
// because we cannot have the option be created with no values
defaultMode.ID = 0;
var hnsMode = new HideAndSeekMode();
var hnsMode = new HideAndSeekMode() { ID = 1 };
if (hnsMode.HideMode)
return;
IdToModeMap.Add(1, hnsMode);
hnsMode.ID = 1;
GameModeOption.AddOption(hnsMode);
lastId++;
}
internal static void GetAndSetGameMode()
{
var id = (uint)GameModeOption.Value;
var index = GameModeOption.Value;
if (IdToModeMap.TryGetValue(id, out var mode))
if ((uint)index < (uint)GameModeOption.Values.Count)
{
ActiveMode = mode;
ActiveMode = GameModeOption.Values[index];
return;
}
ActiveMode = IdToModeMap[0];
Warning($"Unable to find game mode of id {id}!");
Warning($"Unable to find game mode at index {index}!");
}
}
+29 -81
View File
@@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
@@ -18,7 +17,7 @@ namespace MiraAPI.GameModes;
/// </summary>
[HarmonyPatch]
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] // why so many warnings???
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public static class GameModeOption
{
/// <summary>
@@ -27,113 +26,63 @@ public static class GameModeOption
/// </summary>
public static int Value
{
get =>
OptionBehaviour != null
? OptionBehaviour.GetInt()
: LastValue;
get => OptionBehaviour != null
? OptionBehaviour.GetInt()
: LastValue;
private set
{
LastValue = value;
if (OptionBehaviour == null)
return;
OptionBehaviour.Value = value;
OptionBehaviour.UpdateValue();
LastValue = value;
}
}
internal static readonly StringNames GamemodeName = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.Gamemode");
internal static readonly StringNames CustomName = MiraLocaleManager.GetOrCreateLocaleString("Custom");
internal static readonly Dictionary<uint, StringNames> Values = new()
{
[0] = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.Gamemode.Classic"),
};
internal static readonly List<AbstractGameMode> Values = [];
internal static StringOption OptionBehaviour = null!;
internal static int LastValue;
internal static void AddOption(AbstractGameMode mode)
{
if (!Values.ContainsKey(mode.ID))
Values.Add(mode.ID, MiraLocaleManager.GetOrCreateLocaleString(mode.Name));
mode.StringName = MiraLocaleManager.GetOrCreateLocaleString(mode.Name);
Values.Add(mode);
}
/*[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.CreateSettings))]
[HarmonyPostfix]
private static void CreateSettingsPatch(GameOptionsMenu __instance)
{
if (MenuState.Instance.CurrentModIdx != 0 || GameManager.Instance.IsHideAndSeek() || CustomGameModeManager.ActiveMode == null)
{
return;
}
var num = 0.713f;
foreach (var category in __instance.settingsContainer.GetComponentsInChildren<CategoryHeaderMasked>())
{
if (category)
category.gameObject.transform.localPosition -= new Vector3(0, 1.3f, 0);
}
CategoryHeaderMasked categoryHeaderMasked = Object.Instantiate(__instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, __instance.settingsContainer);
categoryHeaderMasked.SetHeader(CustomName, 20);
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num, -2f);
OptionBehaviour = Object.Instantiate(
__instance.stringOptionOrigin,
Vector3.zero,
Quaternion.identity,
__instance.settingsContainer);
num -= 0.63f;
OptionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
OptionBehaviour.SetClickMask(__instance.ButtonClickMask);
StringGameSetting setting = ScriptableObject.CreateInstance<StringGameSetting>();
setting.Type = OptionTypes.MultipleChoice;
setting.Title = GamemodeName;
setting.Index = _lastValue;
setting.Values = new Il2CppStructArray<StringNames>([Values[0]]);
OptionBehaviour.SetUpFromData(setting, 20);
Set(_lastValue);
OptionBehaviour.TitleText.fontSize = 3;
foreach (var optionBehaviour in __instance.Children.ToArray().Skip(1))
{
optionBehaviour.gameObject.transform.localPosition -= new Vector3(0, 1.3f, 0);
}
__instance.Children.Add(OptionBehaviour);
for (var i = 1; i < Values.Count; i++)
OptionBehaviour.Values = (Il2CppStructArray<StringNames>)OptionBehaviour.Values.Add(Values.ElementAt(i).Value);
__instance.scrollBar.SetYBoundsMax(__instance.scrollBar.GetYBounds().max + 1);
}*/
internal static void Set(int val)
{
Value = val;
var previousMode = CustomGameModeManager.ActiveMode;
CustomGameModeManager.GetAndSetGameMode();
HudPatches.SetGameModeText(CustomGameModeManager.GetMode(Values.ElementAt(LastValue).Key).ColoredName);
HudPatches.SetGameModeText(Values[LastValue].ColoredName);
var gm = CustomGameModeManager.ActiveMode!;
if (gm != previousMode)
{
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon);
if (MenuState.Instance)
{
// should force reset roles for gamemodes properly
foreach (var roleMenu in MenuState.Instance.QueuedRoleMenuRefresh)
{
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = true;
}
}
if (gm == previousMode)
return;
GameOptionsMenuPatch.RefreshForGameMode();
RoleGuidePatches.RefreshSettingsForGameMode();
ModdedOptionsManager.AddSettingsChangeMessage(
HudManager.Instance.Notifier,
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon);
if (MenuState.Instance)
{
// should force reset roles for gamemodes properly
foreach (var roleMenu in MenuState.Instance.QueuedRoleMenuRefresh)
{
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = true;
}
}
// TODO: could make Values a dict of AbstractGameMode too
GameOptionsMenuPatch.RefreshForGameMode();
RoleGuidePatches.RefreshSettingsForGameMode();
}
[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.ValueChanged))]
@@ -150,8 +99,7 @@ public static class GameModeOption
}
[MethodRpc((uint)MiraRpc.SyncGamemodeOption)]
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Intentionally unused because the main intent is for it to be used by dependent mods to add to a blacklist.")]
internal static void RpcSyncGamemode(PlayerControl host, int data)
internal static void RpcSyncGamemode(PlayerControl _, int data)
{
Set(data);
}
+2 -2
View File
@@ -92,9 +92,9 @@ public class HideAndSeekMode : AbstractGameMode
runOriginal = false;
CppCollections.List<ClientData> list = new();
AmongUsClient.Instance.GetAllClients(list);
List<NetworkedPlayerInfo> list2 = [.. list.ToArray()
var list2 = list.ToArray()
.Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected &&
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data),];
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data).ToList();
foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers)
{
@@ -12,7 +12,7 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="modeType">Optional parameter to specify a game mode Type.</param>
[AttributeUsage(AttributeTargets.Property)]
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] // why so many warnings???
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public abstract class ModdedOptionAttribute(string title, Type? roleType = null, Type? modeType = null) : PropertyOptionAttribute
{
internal IModdedOption? HolderOption;
@@ -26,12 +26,12 @@ public abstract class ModdedOptionAttribute(string title, Type? roleType = null,
/// <summary>
/// Gets the role type of the option.
/// </summary>
protected Type? RoleType { get; private set; } = roleType;
protected Type? RoleType => roleType;
/// <summary>
/// Gets the game mode type of the option.
/// </summary>
protected Type? ModeType { get; private set; } = modeType;
protected Type? ModeType => modeType;
internal abstract IModdedOption? CreateOption(object? value, PropertyInfo property);
}
@@ -13,7 +13,7 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="title">The title of the options.</param>
[AttributeUsage(AttributeTargets.Property)]
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] // why so many warnings???
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAttribute
{
internal IModdedOptionList? HolderOptionList;
+1 -6
View File
@@ -30,12 +30,7 @@ public abstract class CustomMultiSelectMenu<TEntry> : CustomPhoneMenu<CustomMult
private Color? activeColor;
private Color? hoverSelectColor;
private Color? hoverDeselectColor;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
[SuppressMessage("Minor Code Smell", "S1104:Fields should not have public accessibility", Justification = "Unity convention.")]
public UiElement confirmButton;
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
private UiElement confirmButton;
private Action<List<TEntry>>? onSelection;
/// <summary>
+9 -6
View File
@@ -108,12 +108,15 @@ public abstract class CustomPaginableMenu : CustomPhoneMenu<CustomPaginableMenu.
if (string.IsNullOrEmpty(query))
return MenuEntries;
return [.. MenuEntries
.Where(e => e.SortKey.Contains(query, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(e => e.SortKey.Equals(query, StringComparison.OrdinalIgnoreCase))
.ThenByDescending(e => e.SortKey.StartsWith(query, StringComparison.OrdinalIgnoreCase))
.ThenByDescending(e => e.SortKey.Contains(query, StringComparison.OrdinalIgnoreCase))
.ThenBy(e => e.SortKey, StringComparer.OrdinalIgnoreCase),];
return
[
.. MenuEntries
.Where(e => e.SortKey.Contains(query, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(e => e.SortKey.Equals(query, StringComparison.OrdinalIgnoreCase))
.ThenByDescending(e => e.SortKey.StartsWith(query, StringComparison.OrdinalIgnoreCase))
.ThenByDescending(e => e.SortKey.Contains(query, StringComparison.OrdinalIgnoreCase))
.ThenBy(e => e.SortKey, StringComparer.OrdinalIgnoreCase),
];
}
private static int GetTotalPages(int itemCount)
+6 -3
View File
@@ -55,9 +55,12 @@ public abstract class MultiTargetButton<T> : CustomActionButton
}
}
Targets = [.. newTargets
.Where(IsTargetValid)
.Take(MaxTargets),];
Targets =
[
.. newTargets
.Where(IsTargetValid)
.Take(MaxTargets),
];
Targets.Do(t => SetOutline(t, true));
return base.CanUse() && Targets.Length > 0;
@@ -36,10 +36,13 @@ public class LocalEnumSetting(
/// <summary>
/// Gets the <see langword="enum"/> values.
/// </summary>
public string[] Values { get; } = values ?? [.. Enum
.GetValues(configEntry.SettingType)
.Cast<Enum>()
.Select(x => x.ToDisplayString()),];
public string[] Values { get; } = values ??
[
.. Enum
.GetValues(configEntry.SettingType)
.Cast<Enum>()
.Select(x => x.ToDisplayString()),
];
private SpriteRenderer _highlight;
private TextMeshPro _btnText;
@@ -1,19 +0,0 @@
using HarmonyLib;
using GameModesEnum = AmongUs.GameOptions.GameModes;
namespace MiraAPI.Patches.GameModes;
[HarmonyPatch(typeof(CreateOptionsPicker), nameof(CreateOptionsPicker.SetGameMode))]
internal static class CreateOptionsPatch
{
public static bool Prefix(CreateOptionsPicker __instance, GameModesEnum mode)
{
if (mode <= GameModesEnum.SeekFools)
{
return true;
}
// TODO: finish this
return false;
}
}
@@ -1,4 +1,5 @@
using System.Collections;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -14,21 +15,14 @@ using UnityEngine.UI;
namespace MiraAPI.Patches.LocalSettings;
[HarmonyPatch(typeof(OptionsMenuBehaviour))]
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public static class OptionsMenuPatches
{
private static readonly Dictionary<int, List<GameObject>> TabButtons = [];
private static int _currentPage = 1;
internal static OptionsMenuBehaviour? Instance { get; private set; }
[SuppressMessage(
"Critical Code Smell",
"S2223:Non-constant static fields should not be visible",
Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage(
"StyleCop.CSharp.MaintainabilityRules",
"SA1401:Fields should be private",
Justification = "Read above.")]
internal static OptionsMenuBehaviour? Instance;
internal static BoxCollider2D MaskCollider = null!;
private static SpriteRenderer? background;
@@ -79,7 +73,7 @@ public static class OptionsMenuPatches
_currentPage = 1;
TabButtons.Clear();
float yOffset = 0;
var yOffset = 0f;
var i = 0;
var tabIdx = 0;
var page = 1;
@@ -153,9 +147,9 @@ public static class OptionsMenuPatches
UpdatePages();
}));
button.OnMouseOver = new UnityEvent();
button.OnMouseOver.AddListener((UnityAction)(() => rollover.DoMouseOver()));
button.OnMouseOver.AddListener((Action)rollover.DoMouseOver);
button.OnMouseOut = new UnityEvent();
button.OnMouseOut.AddListener((UnityAction)(() => rollover.DoMouseOut()));
button.OnMouseOut.AddListener((Action)rollover.DoMouseOut);
}
private static void ChangePage(int increase)
@@ -183,15 +177,15 @@ public static class OptionsMenuPatches
LocalSettingsManager.AvailableTabs.ForEach(CustomClose); // Close all mod tabs
// Tabs with index 10 and above are the mod settings tabs
if (index >= 10)
if (index < 10)
{
var tab = LocalSettingsManager.AvailableTabs[index - 10];
CustomOpen(tab);
__instance.StartCoroutine(RefreshScrollBoundsAfterOpen(__instance, tab).WrapToIl2Cpp());
return false;
return true;
}
return true;
var tab = LocalSettingsManager.AvailableTabs[index - 10];
CustomOpen(tab);
__instance.StartCoroutine(RefreshScrollBoundsAfterOpen(__instance, tab).WrapToIl2Cpp());
return false;
}
/// <summary>
@@ -218,14 +212,17 @@ public static class OptionsMenuPatches
private static void CustomOpen(LocalSettingsTab tab)
{
if (tab.TabButton?.Button)
tab.TabButton!.Button.color = tab.TabAppearance.TabButtonHoverColor;
if (tab.TabButton)
{
if (tab.TabButton!.Button)
tab.TabButton.Button.color = tab.TabAppearance.TabButtonHoverColor;
if (tab.TabButton?.Rollover)
tab.TabButton!.Rollover.OutColor = tab.TabAppearance.TabButtonHoverColor;
if (tab.TabButton.Rollover)
tab.TabButton.Rollover.OutColor = tab.TabAppearance.TabButtonHoverColor;
if (tab.TabButton?.Content)
tab.TabButton!.Content.SetActive(true);
if (tab.TabButton.Content)
tab.TabButton.Content.SetActive(true);
}
if (background != null)
background.color = tab.TabAppearance.TabColor;
@@ -245,14 +242,17 @@ public static class OptionsMenuPatches
private static void CustomClose(LocalSettingsTab tab)
{
if (tab.TabButton?.Button)
tab.TabButton!.Button.color = tab.TabAppearance.TabButtonColor;
if (tab.TabButton)
{
if (tab.TabButton!.Button)
tab.TabButton.Button.color = tab.TabAppearance.TabButtonColor;
if (tab.TabButton?.Rollover)
tab.TabButton!.Rollover.OutColor = tab.TabAppearance.TabButtonColor;
if (tab.TabButton.Rollover)
tab.TabButton.Rollover.OutColor = tab.TabAppearance.TabButtonColor;
if (tab.TabButton?.Content)
tab.TabButton!.Content.SetActive(false);
if (tab.TabButton.Content)
tab.TabButton.Content.SetActive(false);
}
if (background != null)
background.color = Color.white;
@@ -1,5 +1,6 @@
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using HarmonyLib;
using MiraAPI.LocalSettings;
using Reactor.Utilities;
@@ -13,7 +14,9 @@ namespace MiraAPI.Patches.Menu;
[HarmonyPatch(typeof(MainMenuManager))]
public static class MainMenuManagerPatches
{
internal static bool NeedsDeepDestroy { get; private set; }
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
internal static bool NeedsDeepDestroy;
/// <summary>
/// A postfix on <see cref="MainMenuManager.Awake"/> to load all the addressables registered.
+18 -22
View File
@@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.Linq;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
@@ -16,7 +15,6 @@ using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.ProBuilder;
using UnityEngine.UI;
using Object = UnityEngine.Object;
@@ -218,7 +216,7 @@ internal static class GameOptionsMenuPatch
{
if (!option || !option.gameObject.activeInHierarchy ||
option == menu.MapPicker ||
(GameModeOption.OptionBehaviour && option == GameModeOption.OptionBehaviour) ||
option == GameModeOption.OptionBehaviour ||
!option.Data)
{
continue;
@@ -250,7 +248,6 @@ internal static class GameOptionsMenuPatch
private static void CreateSettings(GameOptionsMenu instance, Transform container)
{
var num = 0.713f;
VanillaHeaders.Clear();
VanillaOptions.Clear();
MainOptions.Clear();
@@ -258,35 +255,36 @@ internal static class GameOptionsMenuPatch
GameModeOptions.Clear();
GameModeGroups.Clear();
var gmCategory = Object.Instantiate(instance.categoryHeaderOrigin, Vector3.zero, Quaternion.identity, container);
var num = 0.713f;
var gmCategory = Object.Instantiate(instance.categoryHeaderOrigin, container);
gmCategory.SetHeader(GameModeOption.CustomName, 20);
gmCategory.transform.localScale = Vector3.one * 0.63f;
gmCategory.transform.localPosition = new Vector3(-0.903f, num, -2f);
GameModeOption.OptionBehaviour = Object.Instantiate(instance.stringOptionOrigin, container);
num -= 0.63f;
GameModeOption.OptionBehaviour = Object.Instantiate(instance.stringOptionOrigin, container);
GameModeOption.OptionBehaviour.transform.localPosition = new Vector3(0.952f, num, -2f);
GameModeOption.OptionBehaviour.SetClickMask(instance.ButtonClickMask);
var setting = ScriptableObject.CreateInstance<StringGameSetting>();
setting.Type = OptionTypes.MultipleChoice;
setting.Title = GameModeOption.GamemodeName;
setting.Index = GameModeOption.LastValue;
setting.Values = new Il2CppStructArray<StringNames>([GameModeOption.Values[0]]);
setting.Values = GameModeOption.Values.Select(x => x.StringName).ToArray();
GameModeOption.OptionBehaviour.SetUpFromData(setting, 20);
GameModeOption.Set(GameModeOption.LastValue);
GameModeOption.OptionBehaviour.TitleText.fontSize = 3;
instance.Children.Add(GameModeOption.OptionBehaviour);
foreach (var optionBehaviour in instance.Children)
{
MainOptions.Add(optionBehaviour);
}
for (var i = 1; i < GameModeOption.Values.Count; i++)
{
GameModeOption.OptionBehaviour.Values =
(Il2CppStructArray<StringNames>)GameModeOption.OptionBehaviour.Values.Add(
GameModeOption.Values.ElementAt(i).Value);
}
var modeInfoHolder = new GameObject("GamemodeInfo")
{
transform =
@@ -298,7 +296,7 @@ internal static class GameOptionsMenuPatch
layer = container.gameObject.layer,
}.transform;
var gamemodeBg = Object.Instantiate(GameModeOption.OptionBehaviour.transform.GetChild(0).gameObject, Vector3.zero, Quaternion.identity, modeInfoHolder);
var gamemodeBg = Object.Instantiate(GameModeOption.OptionBehaviour.transform.GetChild(0).gameObject, modeInfoHolder);
gamemodeBg.transform.localPosition = Vector3.zero;
gamemodeBg.transform.localScale = new Vector3(1.35f, 0.85f, 1);
gamemodeBg.name = "Background";
@@ -317,7 +315,7 @@ internal static class GameOptionsMenuPatch
_modIcon.sprite = MiraAssets.BlankSprite.LoadAsset();
_modIcon.material = gamemodeBg.gameObject.GetComponent<SpriteRenderer>().material;
var gamemodeTextObj = Object.Instantiate(GameModeOption.OptionBehaviour.transform.GetChild(1).gameObject, Vector3.zero, Quaternion.identity, modeInfoHolder);
var gamemodeTextObj = Object.Instantiate(GameModeOption.OptionBehaviour.transform.GetChild(1).gameObject, modeInfoHolder);
gamemodeTextObj.transform.localPosition = new Vector3(0.3f, 0, -0.01f);
gamemodeTextObj.transform.localScale = new Vector3(2.12f, 2.12f, 1);
_gamemodeDescription = gamemodeTextObj.GetComponentInChildren<TextMeshPro>();
@@ -469,11 +467,7 @@ internal static class GameOptionsMenuPatch
private static void CreateGroup(GameOptionsMenu menu, AbstractOptionGroup group, Transform container, ref float num, ref List<OptionBehaviour> optionBehaviours, ref List<CategoryHeaderMasked> categoryHeaders)
{
var categoryHeaderMasked = Object.Instantiate(
menu.categoryHeaderOrigin,
Vector3.zero,
Quaternion.identity,
container);
var categoryHeaderMasked = Object.Instantiate(menu.categoryHeaderOrigin, container);
categoryHeaderMasked.transform.localPosition = new Vector3(-0.903f, num + 1, -2f);
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaders.Add(categoryHeaderMasked);
@@ -510,12 +504,14 @@ internal static class GameOptionsMenuPatch
foreach (var newOpt in options)
{
newOpt.SetClickMask(menu.ButtonClickMask);
SpriteRenderer[] componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
var componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
foreach (var renderer in componentsInChildren)
{
if (group.GroupColor != MiraApiPlugin.DefaultHeaderColor)
{
renderer.color = group.GroupColor.FindAlternateColor();
if (renderer.transform.parent.TryGetComponent<GameOptionButton>(out var btn))
{
btn.interactableColor = group.GroupColor.FindAlternateColor();
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using AmongUs.GameOptions;
using BepInEx.Unity.IL2CPP.Utils.Collections;
@@ -12,6 +13,7 @@ using MiraAPI.Roles;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using MiraAPI.Utilities.Components;
using Reactor.Networking.Rpc;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -23,15 +25,24 @@ using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(RolesSettingsMenu))]
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Is internal code. Property-level protections are not required.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public static class RoleSettingMenuPatches
{
private static readonly Dictionary<RoleOptionsGroup, bool> RoleGroupHidden = [];
private static RoleBehaviour? currentRole;
private static List<IModdedOption>? currentRoleOptions;
internal static RoleBehaviour? CurrentRole;
internal static IModdedOption[]? CurrentRoleOptions;
private static float scrollerNum = 0.522f;
[HarmonyPostfix]
[HarmonyPatch(nameof(RolesSettingsMenu.Awake))]
public static void OnAwake(RolesSettingsMenu __instance)
{
__instance.gameObject.AddComponent<RoleSettingsMenuUpdater>();
}
[HarmonyPostfix]
[HarmonyPatch(nameof(RolesSettingsMenu.OnEnable))]
public static void OpenPatch()
@@ -41,8 +52,8 @@ public static class RoleSettingMenuPatches
private static IEnumerator CoQuotaTabPatch(RolesSettingsMenu roleMenu)
{
currentRole = null;
currentRoleOptions = null;
CurrentRole = null;
CurrentRoleOptions = null;
roleMenu.QuotaTabSelectables.Clear();
roleMenu.roleChances.Clear();
@@ -91,7 +102,7 @@ public static class RoleSettingMenuPatches
Object.Destroy(child.gameObject);
}
yield return new WaitForEndOfFrame();
yield return null;
MenuState.Instance.QueuedRoleMenuRefresh[MenuState.Instance.CurrentModIdx] = false;
}
@@ -186,7 +197,7 @@ public static class RoleSettingMenuPatches
Object.Destroy(child.gameObject);
}
yield return new WaitForEndOfFrame();
yield return null;
var roleGroups = MenuState.Instance.CurrentMod.InternalRoles.Values.OfType<ICustomRole>()
.ToLookup(x => x.RoleOptionsGroup);
@@ -432,32 +443,12 @@ public static class RoleSettingMenuPatches
scroller.SetYBoundsMax(-scrollerNum - 2);
}
// TODO: turn this into a fixed update
// Completed: turn this into a fixed update
[HarmonyPrefix]
[HarmonyPatch(nameof(RolesSettingsMenu.Update))]
public static bool UpdatePatch(RolesSettingsMenu __instance)
{
if (MenuState.Instance.CurrentModIdx == 0) return true;
if (currentRole == null || currentRoleOptions == null) return false;
var hasImage = currentRole.RoleScreenshot != null;
var num = hasImage ? -0.872f : -1;
foreach (var opt in currentRoleOptions)
{
if (opt.OptionBehaviour == null) continue;
if (!opt.Visible.Invoke())
{
opt.OptionBehaviour.gameObject.SetActive(false);
continue;
}
opt.OptionBehaviour.transform.localPosition = new Vector3(hasImage ? 2.17f : 1.1f, num, -2f);
opt.OptionBehaviour.gameObject.SetActive(true);
num += -0.45f;
}
__instance.scrollBar.SetYBoundsMax(-num - 3);
// See RoleSettingsMenuUpdater.FixedUpdate in Utilities/Components/RoleSettingsMenuUpdater.cs
return false;
}
@@ -509,14 +500,15 @@ public static class RoleSettingMenuPatches
optBehaviour.gameObject.Destroy();
}
currentRole = role;
CurrentRole = role;
__instance.advancedSettingChildren.Clear();
// TODO: create sub groups under the role settings.
var type = role.GetType();
var filteredOptions = MenuState.Instance.CurrentMod.InternalOptionGroups
.Where(x => x.GroupVisible() && x.OptionableType == role.GetType())
.Where(x => x.OptionableType == type && x.GroupVisible())
.SelectMany(x => x.Options)
.ToList();
.ToArray();
foreach (var option in filteredOptions)
{
@@ -548,7 +540,7 @@ public static class RoleSettingMenuPatches
newOpt.Initialize();
}
currentRoleOptions = filteredOptions;
CurrentRoleOptions = filteredOptions;
}
[HarmonyPrefix]
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AmongUs.GameOptions;
using HarmonyLib;
using MiraAPI.Roles;
@@ -12,24 +12,14 @@ namespace MiraAPI.Patches.Roles;
/// </summary>
public static class RoleOptionsCollectionPatch
{
internal static Assembly BaseAssembly { get; private set; }
internal static Type[] BaseTypes { get; private set; }
internal static Type CollectionsType { get; private set; }
public static void PatchRoleMethods(Harmony harmony)
{
var assembly = Array.Find(
AppDomain.CurrentDomain.GetAssemblies(),
ass => ass.GetName().Name == "Assembly-CSharp");
if (assembly == null)
return;
var compatType = typeof(RoleOptionsCollectionPatch);
BaseAssembly = assembly;
BaseTypes = AccessTools.GetTypesFromAssembly(assembly);
var collections = BaseTypes.Where(x => x.Name.Contains("RoleOptionsCollectionV")).ToArray();
var pairings = new System.Collections.Generic.Dictionary<int, Type>();
var baseAssembly = typeof(RoleBehaviour).Assembly;
var baseTypes = AccessTools.GetTypesFromAssembly(baseAssembly);
var collections = baseTypes.Where(x => x.Name.Contains("RoleOptionsCollectionV")).ToArray();
var pairings = new Dictionary<int, Type>();
var newestId = 0;
foreach (var collection in collections)
{
var remainder = collection.Name.Replace("RoleOptionsCollectionV", string.Empty);
@@ -45,22 +35,26 @@ public static class RoleOptionsCollectionPatch
}
}
Type? collectionsType = null;
if (pairings.TryGetValue(newestId, out var typeToGet))
{
CollectionsType = typeToGet;
collectionsType = typeToGet;
}
var anyRolesEnabledMethod = AccessTools.Method(CollectionsType, "AnyRolesEnabled");
var compatType = typeof(RoleOptionsCollectionPatch);
var anyRolesEnabledMethod = AccessTools.Method(collectionsType, "AnyRolesEnabled");
harmony.Patch(
anyRolesEnabledMethod,
new HarmonyMethod(AccessTools.Method(compatType, nameof(AnyRolesEnabledPrefix))));
var chancePerGameMethod = AccessTools.Method(CollectionsType, "GetChancePerGame");
var chancePerGameMethod = AccessTools.Method(collectionsType, "GetChancePerGame");
harmony.Patch(
chancePerGameMethod,
new HarmonyMethod(AccessTools.Method(compatType, nameof(GetChancePrefix))));
var numPerGameMethod = AccessTools.Method(CollectionsType, "GetNumPerGame");
var numPerGameMethod = AccessTools.Method(collectionsType, "GetNumPerGame");
harmony.Patch(
numPerGameMethod,
new HarmonyMethod(AccessTools.Method(compatType, nameof(GetNumPrefix))));
+2 -2
View File
@@ -45,9 +45,9 @@ public static class SelectRolesPatch
CppCollections.List<ClientData> list = new();
AmongUsClient.Instance.GetAllClients(list);
List<NetworkedPlayerInfo> list2 = [.. list.ToArray()
var list2 = list.ToArray()
.Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected &&
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data),];
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data).ToList();
foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers)
{
+1 -1
View File
@@ -271,7 +271,7 @@ internal static class MeetingHudPatches
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.PopulateResults))]
public static bool PopulateResultsPatch(ref Il2CppStructArray<MeetingHud.VoterState> states)
public static bool PopulateResultsPatch(Il2CppStructArray<MeetingHud.VoterState> states)
{
var votes = states.Select(x => new CustomVote(x.VoterId, x.VotedForId)).ToList();
+2 -2
View File
@@ -68,7 +68,7 @@ public sealed class MiraPluginManager
MiraApiPluginInfo = info;
registrationTimer.Stop();
Info($"Registering Mira API as mod in {registrationTimer.ElapsedMilliseconds}ms.");
Info($"Registered Mira API as mod in {registrationTimer.ElapsedMilliseconds}ms.");
}
IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, assembly, plugin) =>
@@ -81,7 +81,7 @@ public sealed class MiraPluginManager
var registrationTimer = Stopwatch.StartNew();
RegisterPlugin(assembly, miraPlugin, pluginInfo, plugin, false);
registrationTimer.Stop();
Info($"Registering mod {pluginInfo.Metadata.Name} with Mira API in {registrationTimer.ElapsedMilliseconds}ms.");
Info($"Registered mod {pluginInfo.Metadata.Name} with Mira API in {registrationTimer.ElapsedMilliseconds}ms.");
};
IL2CPPChainloader.Instance.Finished += () =>
@@ -0,0 +1,49 @@
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Patches.Options;
using Reactor.Utilities.Attributes;
using UnityEngine;
namespace MiraAPI.Utilities.Components;
/// <summary>
/// Updates the visuals of the <see cref="RolesSettingsMenu"/> in a fixed update loop.
/// </summary>
/// <param name="cppPtr">The C++ pointer to the object.</param>
[RegisterInIl2Cpp]
[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity convention.")]
public sealed class RoleSettingsMenuUpdater(nint cppPtr) : MonoBehaviour(cppPtr)
{
private RolesSettingsMenu menu;
private void Awake()
{
menu = GetComponent<RolesSettingsMenu>();
}
private void FixedUpdate()
{
if (MenuState.Instance.CurrentModIdx == 0) return;
if (menu == null || RoleSettingMenuPatches.CurrentRole == null || RoleSettingMenuPatches.CurrentRoleOptions == null) return;
var hasImage = RoleSettingMenuPatches.CurrentRole.RoleScreenshot != null;
var num = hasImage ? -0.872f : -1;
foreach (var opt in RoleSettingMenuPatches.CurrentRoleOptions)
{
var behaviour = opt.OptionBehaviour;
if (behaviour == null) continue;
if (!opt.Visible())
{
behaviour.gameObject.SetActive(false);
continue;
}
behaviour.transform.localPosition = new Vector3(hasImage ? 2.17f : 1.1f, num, -2f);
behaviour.gameObject.SetActive(true);
num += -0.45f;
}
menu.scrollBar.SetYBoundsMax(-num - 3);
}
}
+1 -1
View File
@@ -682,7 +682,7 @@ public static class Extensions
/// <returns><see langword="true"/> if the <see cref="OptionBehaviour"/> is for a custom options, <see langword="false"/> otherwise.</returns>
public static bool IsCustom(this OptionBehaviour optionBehaviour)
{
return ModdedOptionsManager.ModdedOptions.Values.Any(opt => opt.OptionBehaviour && opt.OptionBehaviour == optionBehaviour) || optionBehaviour.Equals(GameModeOption.OptionBehaviour);
return ModdedOptionsManager.ModdedOptions.Values.Any(opt => opt.OptionBehaviour == optionBehaviour) || optionBehaviour.Equals(GameModeOption.OptionBehaviour);
}
/// <summary>
+15 -9
View File
@@ -142,12 +142,15 @@ internal static class GuideOptionPages
}
}
return [.. pages
.OrderBy(page => page.MenuOrder)
.ThenBy(page => page.GroupPriority)
.ThenBy(page => page.Order)
.ThenBy(page => page.Group.GroupName, StringComparer.OrdinalIgnoreCase)
.ThenBy(page => page.ModAbbreviation, StringComparer.OrdinalIgnoreCase),];
return
[
.. pages
.OrderBy(page => page.MenuOrder)
.ThenBy(page => page.GroupPriority)
.ThenBy(page => page.Order)
.ThenBy(page => page.Group.GroupName, StringComparer.OrdinalIgnoreCase)
.ThenBy(page => page.ModAbbreviation, StringComparer.OrdinalIgnoreCase),
];
}
private static int GetMenuOrder(MenuCategory menu)
@@ -184,12 +187,15 @@ internal static class GuideOptionPages
return [.. matchingModPages.SelectMany(page => page.Entries)];
}
return [.. pageList
.SelectMany(page => page.Entries
return
[
.. pageList
.SelectMany(page => page.Entries
.Select(entry => (Entry: entry, Rank: Rank(entry, query, cmp)))
.Where(result => result.Rank < int.MaxValue)
.OrderBy(result => result.Rank)
.Select(result => result.Entry)),];
.Select(result => result.Entry)),
];
}
private static string[] GetModSearchTerms(MiraPluginInfo plugin, AbstractOptionGroup group)
+1 -1
View File
@@ -370,7 +370,7 @@ public static class Helpers
public static LobbyNotificationMessage CreateAndShowNotification(string text, Color color, Vector3 localPos, AudioClip? clip = null, Sprite? spr = null)
{
var popper = HudManager.Instance.Notifier;
var newMessage = Object.Instantiate(popper.notificationMessageOrigin, Vector3.zero, Quaternion.identity, popper.transform);
var newMessage = Object.Instantiate(popper.notificationMessageOrigin, popper.transform);
newMessage.transform.localPosition = localPos;
newMessage.SetUp(text, spr ?? null, color, new Action(() => popper.OnMessageDestroy(newMessage)));
popper.lastMessageKey = -1;
+1 -1
View File
@@ -23,7 +23,7 @@ public class PlayerVoteData(nint cppPtr) : MonoBehaviour(cppPtr)
/// Gets the list of <see cref="CustomVote"/>s the owner has.
/// </summary>
[HideFromIl2Cpp]
public List<CustomVote> Votes { get; private set; } = [];
public List<CustomVote> Votes { get; } = [];
/// <summary>
/// Gets or sets the amount of votes the owner has left.