diff --git a/MiraAPI.Example/ExampleColors.cs b/MiraAPI.Example/ExampleColors.cs index 297a370e..88710683 100644 --- a/MiraAPI.Example/ExampleColors.cs +++ b/MiraAPI.Example/ExampleColors.cs @@ -5,20 +5,14 @@ using UnityEngine; namespace MiraAPI.Example; -[RegisterCustomColors] +[RegisterCustomColors("color.")] public static class ExampleColors { - public static CustomColor Cerulean { get; } = new("color.cerulean", new Color(0.0f, 0.48f, 0.65f)) - { - ColorBrightness = CustomColorBrightness.Lighter, - }; + public static CustomColor Cerulean { get; } = new("cerulean", new Color(0.0f, 0.48f, 0.65f), CustomColorBrightness.Lighter); - public static CustomColor Rose { get; } = new("color.rose", new Color(0.98f, 0.26f, 0.62f)); + public static CustomColor Rose { get; } = new("rose", new Color(0.98f, 0.26f, 0.62f), CustomColorBrightness.Lighter); - public static CustomColor Gold { get; } = new("color.gold", new Color(1.0f, 0.84f, 0.0f)); + public static CustomColor Gold { get; } = new("gold", new Color(1.0f, 0.84f, 0.0f), CustomColorBrightness.Lighter); - public static VariableColor Rainbow { get; } = new("color.rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f)) - { - ColorBrightness = CustomColorBrightness.Lighter, - }; + public static VariableColor Rainbow { get; } = new("rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f), CustomColorBrightness.Lighter); } diff --git a/MiraAPI/Colors/CustomColor.cs b/MiraAPI/Colors/CustomColor.cs index f3c38395..156bb3b5 100644 --- a/MiraAPI/Colors/CustomColor.cs +++ b/MiraAPI/Colors/CustomColor.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.CodeAnalysis; +using System; +using System.Diagnostics.CodeAnalysis; using MiraAPI.Translation; using MiraAPI.Utilities; using UnityEngine; @@ -8,45 +9,44 @@ namespace MiraAPI.Colors; /// /// Represents a custom color with a main color and a shadow color. /// -/// The name of the option. +/// The name of the option as a value. +/// The name of the option as a value. /// The main color. /// The shadow color. +/// The brightness type of the color. [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Internal code.")] -[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1513:Closing brace should be followed by blank line", Justification = "Looks weird.")] -public class CustomColor(StringNames name, Color32 mainColor, Color32 shadowColor) +public class CustomColor(StringNames? nameId, string? rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness) { - /// - /// Gets or sets the main color. - /// - public Color32 MainColor - { - get; - set - { - field = value; - InternalMainColor = value; - } - } - = mainColor; + private StringNames? name = nameId; + private CustomColorBrightness colorBrightness = brightness; /// - /// Gets or sets the shadow color. + /// Gets the main color. /// - public Color32 ShadowColor - { - get; - set - { - field = value; - InternalShadowColor = value; - } - } - = shadowColor; + public Color32 MainColor => mainColor; /// - /// Gets or sets the name of the color. + /// Gets the shadow color. /// - public StringNames Name { get; set; } = name; + public Color32 ShadowColor => shadowColor; + + /// + /// Gets the name of the color. + /// + public StringNames Name + { + get + { + if (!name.HasValue && !string.IsNullOrEmpty(RawId)) + name = MiraLocaleManager.GetOrCreateLocaleString(RawId); + + return name.GetValueOrDefault(); + } + internal set + { + name = value; + } + } /// /// Gets the id of the color. @@ -54,28 +54,68 @@ public class CustomColor(StringNames name, Color32 mainColor, Color32 shadowColo public int ColorId { get; internal set; } = -1; /// - /// Gets or sets whether the color is lighter or darker. Can be used to help with colorblind stuff. + /// Gets or sets whether the color is lighter or darker. /// - public CustomColorBrightness ColorBrightness { get; set; } = CustomColorBrightness.Darker; + public CustomColorBrightness ColorBrightness + { + get => colorBrightness; + [Obsolete("Use the constructor to set ColorBrightness instead. This will be removed in a future version.")] + set => colorBrightness = value; + } + internal string? RawId = rawId; internal Color InternalMainColor = mainColor; internal Color InternalShadowColor = shadowColor; - /// - public CustomColor(StringNames name, Color32 mainColor) - : this(name, mainColor, mainColor.DarkenAbsolute(60)) + /// + public CustomColor(StringNames nameId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness) + : this(nameId, null, mainColor, shadowColor, brightness) { } - /// - public CustomColor(string name, Color32 mainColor) - : this(name, mainColor, mainColor.DarkenAbsolute(60)) + /// + public CustomColor(StringNames nameId, Color32 mainColor, CustomColorBrightness brightness) + : this(nameId, null, mainColor, mainColor.DarkenAbsolute(60), brightness) { } - /// - public CustomColor(string name, Color32 mainColor, Color32 shadowColor) - : this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor) + /// + public CustomColor(string rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness) + : this(null, rawId, mainColor, shadowColor, brightness) + { + } + + /// + public CustomColor(string rawId, Color32 mainColor, CustomColorBrightness brightness) + : this(null, rawId, mainColor, mainColor.DarkenAbsolute(60), brightness) + { + } + + /// + [Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")] + public CustomColor(StringNames nameId, Color32 mainColor, Color32 shadowColor) + : this(nameId, null, mainColor, shadowColor, CustomColorBrightness.Darker) + { + } + + /// + [Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")] + public CustomColor(StringNames nameId, Color32 mainColor) + : this(nameId, null, mainColor, mainColor.DarkenAbsolute(60), CustomColorBrightness.Darker) + { + } + + /// + [Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")] + public CustomColor(string rawId, Color32 mainColor, Color32 shadowColor) + : this(null, rawId, mainColor, shadowColor, CustomColorBrightness.Darker) + { + } + + /// + [Obsolete("Use the constructor that takes in a CustomColorBrightness parameter. This will be removed in a future version.")] + public CustomColor(string rawId, Color32 mainColor) + : this(null, rawId, mainColor, mainColor.DarkenAbsolute(60), CustomColorBrightness.Darker) { } } diff --git a/MiraAPI/Colors/PaletteManager.cs b/MiraAPI/Colors/PaletteManager.cs index 760822fc..fb0106a8 100644 --- a/MiraAPI/Colors/PaletteManager.cs +++ b/MiraAPI/Colors/PaletteManager.cs @@ -1,7 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using HarmonyLib; +using MiraAPI.PluginLoading; +using MiraAPI.Translation; +using MiraAPI.Utilities; using UnityEngine; namespace MiraAPI.Colors; @@ -16,9 +20,8 @@ public static class PaletteManager /// public static CustomColor[] RegisteredColors => [.. CustomColors]; - internal static readonly List CustomColors = []; - internal static readonly HashSet VariableColorNames = []; - + private static readonly List CustomColors = []; + private static readonly HashSet VariableColorNames = []; private static readonly CustomColorBrightness[] ColorBrightnessMap = [ CustomColorBrightness.Darker, // Red @@ -43,6 +46,55 @@ public static class PaletteManager private static int originalLength; + internal static bool RegisterColors(Type type, MiraPluginInfo miraPlugin) + { + if (!type.TryGetCustomAttribute(out var attribute)) + { + return false; + } + + if (!type.IsStatic()) + { + Error($"Color class {type.Name} must be static."); + return false; + } + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers)) + { + if (!property.PropertyType.IsAssignableTo(typeof(CustomColor))) + { + continue; + } + + if (property.GetValue(null) is not CustomColor color) + { + Error($"Color property {property.Name} in {type.Name} is not a CustomColor."); + continue; + } + + if (!string.IsNullOrEmpty(color.RawId) && !string.IsNullOrEmpty(attribute.IdPrefix)) + { + color.Name = MiraLocaleManager.GetOrCreateLocaleString(attribute.IdPrefix + color.RawId); + } + + CustomColors.Add(color); + + if (color is VariableColor) + VariableColorNames.Add(color.Name); + } + + if (!miraPlugin.DebugMode) + return true; + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor)))) + { + Error($"{field.Name} is a field, not a property. Use properties for colors."); + } + + return true; + } + internal static void RegisterAllColors() { originalLength = Palette.PlayerColors.Length; @@ -50,7 +102,9 @@ public static class PaletteManager var colors = CustomColors.Select(x => x.MainColor).ToArray(); var shadowColors = CustomColors.Select(x => x.ShadowColor).ToArray(); var stringNames = CustomColors.Select(x => x.Name).ToArray(); + var newColorId = originalLength; + foreach (var color in CustomColors) { color.ColorId = newColorId++; diff --git a/MiraAPI/Colors/RegisterCustomColorsAttribute.cs b/MiraAPI/Colors/RegisterCustomColorsAttribute.cs index 63565829..eecba2b5 100644 --- a/MiraAPI/Colors/RegisterCustomColorsAttribute.cs +++ b/MiraAPI/Colors/RegisterCustomColorsAttribute.cs @@ -5,5 +5,20 @@ namespace MiraAPI.Colors; /// /// Used to mark a class for registration. /// +/// The group translation ID prefix to attach to color names before registration. [AttributeUsage(AttributeTargets.Class)] -public class RegisterCustomColorsAttribute : Attribute; +public class RegisterCustomColorsAttribute(string idPrefix) : Attribute +{ + /// + /// Gets the translation ID prefix for all of the colors within the container type. + /// + public string IdPrefix => idPrefix; + + /// + /// Initializes a new instance of the class. + /// + public RegisterCustomColorsAttribute() + : this(string.Empty) + { + } +} diff --git a/MiraAPI/Colors/VariableColor.cs b/MiraAPI/Colors/VariableColor.cs index 84a38358..6a6eae1c 100644 --- a/MiraAPI/Colors/VariableColor.cs +++ b/MiraAPI/Colors/VariableColor.cs @@ -1,6 +1,5 @@ using System; using MiraAPI.LocalSettings; -using MiraAPI.Translation; using MiraAPI.Utilities; using UnityEngine; @@ -9,40 +8,129 @@ namespace MiraAPI.Colors; /// /// Represents a dynamic custom color that changes over time. /// -/// The name of the color. +/// The name of the option as a value. +/// The name of the option as a value. /// The function to evaluate the dynamic main color. /// The function to evaluate the dynamic shadow color. /// The static main color used when dynamic colors are disabled. /// The static shadow color used when dynamic colors are disabled. /// The default time that is used to automatically fill in the static colors when the latter is not provided. -public sealed class VariableColor(StringNames name, Func mainEvaluator, Func? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f) - : CustomColor(name, mainColor ?? mainEvaluator(defaultTime), shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).DarkenAbsolute(60)) +/// The brightness type of the color. +public sealed class VariableColor( + StringNames? nameId, + string? rawId, + Func mainEvaluator, + Func? shadowEvaluator, + Color32? mainColor, + Color32? shadowColor, + float defaultTime, + CustomColorBrightness brightness) + : CustomColor( + nameId, + rawId, + mainColor ?? mainEvaluator(defaultTime), + shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).DarkenAbsolute(60), + brightness) { /// - /// Gets or sets a delegate that takes in a time value and returns the dynamic main color. + /// Gets a delegate that takes in a time value and returns the dynamic main color. /// - public Func MainEvaluator { get; set; } = mainEvaluator; + public Func MainEvaluator => mainEvaluator; /// - /// Gets or sets a delegate that takes in a time value and returns the dynamic shadow color. + /// Gets a delegate that takes in a time value and returns the dynamic shadow color. /// - public Func ShadowEvaluator { get; set; } = shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f)); + public Func ShadowEvaluator => shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f)); - /// - public VariableColor(StringNames name, Func mainEvaluator, Color32? mainColor = null, float defaultTime = 0f) - : this(name, mainEvaluator, null, mainColor, null, defaultTime) + /// + public VariableColor( + StringNames nameId, + Func mainEvaluator, + Func? shadowEvaluator, + CustomColorBrightness brightness, + Color32? mainColor = null, + Color32? shadowColor = null, + float defaultTime = 0f) + : this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness) { } - /// - public VariableColor(string name, Func mainEvaluator, Color32? mainColor = null, float defaultTime = 0f) - : this(name, mainEvaluator, null, mainColor, null, defaultTime) + /// + public VariableColor( + StringNames nameId, + Func mainEvaluator, + CustomColorBrightness brightness, + Color32? mainColor = null, + float defaultTime = 0f) + : this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, brightness) { } - /// - public VariableColor(string name, Func mainEvaluator, Func? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f) - : this(MiraLocaleManager.GetOrCreateLocaleString(name), mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime) + /// + public VariableColor( + string rawId, + Func mainEvaluator, + Func? shadowEvaluator, + CustomColorBrightness brightness, + Color32? mainColor = null, + Color32? shadowColor = null, + float defaultTime = 0f) + : this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness) + { + } + + /// + public VariableColor( + string rawId, + Func mainEvaluator, + CustomColorBrightness brightness, + Color32? mainColor = null, + float defaultTime = 0f) + : this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, brightness) + { + } + + /// + public VariableColor( + StringNames nameId, + Func mainEvaluator, + Func? shadowEvaluator, + Color32? mainColor = null, + Color32? shadowColor = null, + float defaultTime = 0f) + : this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker) + { + } + + /// + public VariableColor( + StringNames nameId, + Func mainEvaluator, + Color32? mainColor = null, + float defaultTime = 0f) + : this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker) + { + } + + /// + public VariableColor( + string rawId, + Func mainEvaluator, + Func? shadowEvaluator, + Color32? mainColor = null, + Color32? shadowColor = null, + float defaultTime = 0f) + : this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker) + { + } + + /// + public VariableColor( + string rawId, + Func mainEvaluator, + Color32? mainColor = null, + float defaultTime = 0f) + : this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker) { } diff --git a/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs b/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs index 6973c4f0..5ac4e910 100644 --- a/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs +++ b/MiraAPI/Events/Mira/MiraButtonCancelledEvent.cs @@ -13,7 +13,7 @@ public sealed class MiraButtonCancelledEvent(T button) : MiraEvent /// /// Gets the whose click was cancelled. /// - public T Button { get; } = button; + public T Button => button; } /// @@ -25,5 +25,5 @@ public sealed class MiraButtonCancelledEvent(CustomActionButton button) : MiraEv /// /// Gets the whose click was cancelled. /// - public CustomActionButton Button { get; } = button; + public CustomActionButton Button => button; } diff --git a/MiraAPI/Events/Mira/MiraButtonClickEvent.cs b/MiraAPI/Events/Mira/MiraButtonClickEvent.cs index 72237d24..9105aa0a 100644 --- a/MiraAPI/Events/Mira/MiraButtonClickEvent.cs +++ b/MiraAPI/Events/Mira/MiraButtonClickEvent.cs @@ -14,12 +14,12 @@ public class MiraButtonClickEvent(T button, MiraButtonClickEvent genericClick /// /// Gets the that was clicked. /// - public T Button { get; } = button; + public T Button => button; /// /// Gets the generic that is invoked before this button-specific event. /// - public MiraButtonClickEvent GenericClickEvent { get; } = genericClickEvent; + public MiraButtonClickEvent GenericClickEvent => genericClickEvent; } /// @@ -31,5 +31,5 @@ public class MiraButtonClickEvent(CustomActionButton button) : MiraCancelableEve /// /// Gets the that was clicked. /// - public CustomActionButton Button { get; } = button; + public CustomActionButton Button => button; } diff --git a/MiraAPI/Events/Mira/UiButtonPostResetEvent.cs b/MiraAPI/Events/Mira/UiButtonPostResetEvent.cs index 38c17555..0e5f2c0b 100644 --- a/MiraAPI/Events/Mira/UiButtonPostResetEvent.cs +++ b/MiraAPI/Events/Mira/UiButtonPostResetEvent.cs @@ -12,10 +12,10 @@ public class UiButtonPostResetEvent(GameObject topUiRow, GameObject secondUiRow) /// /// Gets the parent for the very top UI row. /// - public GameObject MainTopUiRow { get; } = topUiRow; + public GameObject MainTopUiRow => topUiRow; /// /// Gets the parent for the second top UI row. /// - public GameObject SecondTopUiRow { get; } = secondUiRow; + public GameObject SecondTopUiRow => secondUiRow; } diff --git a/MiraAPI/Events/MiraEventManager.cs b/MiraAPI/Events/MiraEventManager.cs index a8b34f16..1f4cf74c 100644 --- a/MiraAPI/Events/MiraEventManager.cs +++ b/MiraAPI/Events/MiraEventManager.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Reflection; +using MiraAPI.PluginLoading; +using MiraAPI.Utilities; namespace MiraAPI.Events; @@ -153,4 +155,24 @@ public static class MiraEventManager return true; } + + internal static void RegisterEvents(Type type) + { + foreach (var method in type.GetMethods(MiraPluginManager.DeclaredStaticMembers)) + { + if (!method.TryGetCustomAttribute(out var eventAttribute)) + continue; + + var parameters = method.GetParameters(); + + if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent))) + { + Error($"Invalid event registration method {method.Name} in {type.Name}"); + continue; + } + + var paramType = parameters[0].ParameterType; + RegisterEventHandler(paramType, method, eventAttribute.Priority); + } + } } diff --git a/MiraAPI/Events/MiraEventWrapper.cs b/MiraAPI/Events/MiraEventWrapper.cs index 2a2c410a..469a98d3 100644 --- a/MiraAPI/Events/MiraEventWrapper.cs +++ b/MiraAPI/Events/MiraEventWrapper.cs @@ -12,10 +12,10 @@ public class MiraEventWrapper(Delegate eventHandler, int priority) /// /// Gets the event handler delegate. /// - public Delegate EventHandler { get; } = eventHandler; + public Delegate EventHandler => eventHandler; /// /// Gets the priority of the handler. Lower values are called first. /// - public int Priority { get; } = priority; + public int Priority => priority; } diff --git a/MiraAPI/Events/RegisterEventAttribute.cs b/MiraAPI/Events/RegisterEventAttribute.cs index 062f30ec..494d7689 100644 --- a/MiraAPI/Events/RegisterEventAttribute.cs +++ b/MiraAPI/Events/RegisterEventAttribute.cs @@ -12,5 +12,5 @@ public class RegisterEventAttribute(int priority = 0) : Attribute /// /// Gets the priority of the event. Lower values are called first. /// - public int Priority { get; } = priority; + public int Priority => priority; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs index 1ca09d67..640f4ce3 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/AfterMurderEvent.cs @@ -14,33 +14,33 @@ public class AfterMurderEvent(PlayerControl source, PlayerControl target, Player /// /// Gets the that killed the . /// - public PlayerControl Source { get; } = source; + public PlayerControl Source => source; /// /// Gets the that was killed. /// - public PlayerControl Target { get; } = target; + public PlayerControl Target => target; /// /// Gets the that was framed, if any. /// - public PlayerControl? Framed { get; } = framed; + public PlayerControl? Framed => framed; /// /// Gets a value indicating whether the murder was done indirectly. /// This is commonly used to prevent the from being killed. /// - public bool IsIndirectAttack { get; } = isIndirect; + public bool IsIndirectAttack => isIndirect; /// /// Gets a value indicating whether the murder was able to bypass protective roles or general defense, such as . /// - public bool IgnoreDefense { get; } = ignoreDefense; + public bool IgnoreDefense => ignoreDefense; /// /// Gets the 's , if it exists. /// - public DeadBody? DeadBody { get; } = deadBody; + public DeadBody? DeadBody => deadBody; /// /// Initializes a new instance of the class. diff --git a/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs index 0b96741f..603f35d3 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/BeforeGameEndEvent.cs @@ -9,5 +9,5 @@ public class BeforeGameEndEvent(GameOverReason reason) : MiraCancelableEvent /// /// Gets the reason for the game end. /// - public GameOverReason Reason { get; } = reason; + public GameOverReason Reason => reason; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs index 61dd2648..c2bdf0dd 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/BeforeMurderEvent.cs @@ -17,22 +17,22 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target /// /// Gets the that is killing the . /// - public PlayerControl Source { get; } = source; + public PlayerControl Source => source; /// /// Gets the that is being killed. /// - public PlayerControl Target { get; } = target; + public PlayerControl Target => target; /// /// Gets the that is being framed, if any. /// - public PlayerControl? Framed { get; } = framed; + public PlayerControl? Framed => framed; /// /// Gets whether the murder was meant to be done in a meeting, via an enum. /// - public MeetingCheck InMeeting { get; } = inMeeting; + public MeetingCheck InMeeting => inMeeting; /// /// Gets or sets a value indicating whether the murder is done indirectly. diff --git a/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs index 841f24dc..80067b74 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/BeforeRoundStartEvent.cs @@ -9,5 +9,5 @@ public class BeforeRoundStartEvent(bool triggeredByIntro) : MiraCancelableEvent /// /// Gets a value indicating whether the event was triggered by the or . /// - public bool TriggeredByIntro { get; } = triggeredByIntro; + public bool TriggeredByIntro => triggeredByIntro; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs index 5d94b4b0..783f7bcd 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/GameEndEvent.cs @@ -9,5 +9,5 @@ public class GameEndEvent(EndGameManager manager) : MiraEvent /// /// Gets the instance. /// - public EndGameManager EndGameManager { get; } = manager; + public EndGameManager EndGameManager => manager; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs index b381390a..72215e21 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/IntroBeginEvent.cs @@ -9,5 +9,5 @@ public class IntroBeginEvent(IntroCutscene introCutscene) : MiraEvent /// /// Gets the instance. /// - public IntroCutscene IntroCutscene { get; } = introCutscene; + public IntroCutscene IntroCutscene => introCutscene; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs index bdd64bd8..246e232c 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/IntroEndEvent.cs @@ -9,5 +9,5 @@ public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent /// /// Gets the instance. /// - public IntroCutscene IntroCutscene { get; } = introCutscene; + public IntroCutscene IntroCutscene => introCutscene; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs index 417e96b2..37ec4853 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/IntroRoleRevealEvent.cs @@ -9,5 +9,5 @@ public class IntroRoleRevealEvent(IntroCutscene introCutscene) : MiraEvent /// /// Gets the instance. /// - public IntroCutscene IntroCutscene { get; } = introCutscene; + public IntroCutscene IntroCutscene => introCutscene; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs index e9356ed7..7a6db14a 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/RoundStartEvent.cs @@ -10,5 +10,5 @@ public class RoundStartEvent(bool triggeredByIntro) : MiraEvent /// /// Gets a value indicating whether the event was triggered by the or . /// - public bool TriggeredByIntro { get; } = triggeredByIntro; + public bool TriggeredByIntro => triggeredByIntro; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs index f20996ac..a1bea90d 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/SetRoleEvent.cs @@ -12,10 +12,10 @@ public class SetRoleEvent(PlayerControl player, RoleTypes role) : MiraEvent /// /// Gets the whose role was changed. /// - public PlayerControl Player { get; } = player; + public PlayerControl Player => player; /// /// Gets the role that the player was set to. /// - public RoleTypes Role { get; } = role; + public RoleTypes Role => role; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs index 73200808..e4826a01 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonCancelledEvent.cs @@ -13,7 +13,7 @@ public sealed class VanillaButtonCancelledEvent(T button) : MiraEvent /// /// Gets the Vanilla whose click was cancelled. /// - public T Button { get; } = button; + public T Button => button; } /// @@ -25,5 +25,5 @@ public sealed class VanillaButtonCancelledEvent(AbilityButton button) : MiraEven /// /// Gets the Vanilla whose click was cancelled. /// - public AbilityButton Button { get; } = button; + public AbilityButton Button => button; } diff --git a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs index cd7028ae..4e87c87b 100644 --- a/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs +++ b/MiraAPI/Events/Vanilla/Gameplay/VanillaButtonClickEvent.cs @@ -14,12 +14,12 @@ public sealed class VanillaButtonClickEvent(T button, VanillaButtonClickEvent /// /// Gets the vanilla that was clicked. /// - public T Button { get; } = button; + public T Button => button; /// /// Gets the generic that is invoked before this button-specific event. /// - public VanillaButtonClickEvent GenericClickEvent { get; } = genericClickEvent; + public VanillaButtonClickEvent GenericClickEvent => genericClickEvent; } /// @@ -33,15 +33,15 @@ public sealed class VanillaButtonClickEvent(AbilityButton button, PlayerControl? /// /// Gets the Vanilla that was clicked. /// - public AbilityButton Button { get; } = button; + public AbilityButton Button => button; /// /// Gets the target , if any, of the Vanilla that was clicked. /// - public PlayerControl? PlayerTarget { get; } = playerTarget; + public PlayerControl? PlayerTarget => playerTarget; /// /// Gets the target , if any, of the Vanilla that was clicked. /// - public Vent? VentTarget { get; } = ventTarget; + public Vent? VentTarget => ventTarget; } diff --git a/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs b/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs index d0ce1ccc..86241e97 100644 --- a/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs +++ b/MiraAPI/Events/Vanilla/Map/CloseDoorsEvent.cs @@ -9,5 +9,5 @@ public class CloseDoorsEvent(SystemTypes room) : MiraCancelableEvent /// /// Gets the room that the doors were closed in. /// - public SystemTypes Room { get; } = room; + public SystemTypes Room => room; } diff --git a/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs b/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs index 4e9327ff..d342b321 100644 --- a/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs +++ b/MiraAPI/Events/Vanilla/Map/PlayerOpenSabotageEvent.cs @@ -9,5 +9,5 @@ public class PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) : MiraCancelable /// /// Gets the . /// - public MapBehaviour MapBehaviour { get; } = mapBehaviour; + public MapBehaviour MapBehaviour => mapBehaviour; } diff --git a/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs b/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs index b1382e56..e39b29d7 100644 --- a/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs +++ b/MiraAPI/Events/Vanilla/Map/UpdateSystemEvent.cs @@ -11,15 +11,15 @@ public class UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byt /// /// Gets the type of system that will be updated. /// - public SystemTypes SystemType { get; } = systemType; + public SystemTypes SystemType => systemType; /// /// Gets the that is updating the system. /// - public PlayerControl Player { get; } = player; + public PlayerControl Player => player; /// /// Gets the byte amount the system is being updated by. /// - public byte Amount { get; } = amount; + public byte Amount => amount; } diff --git a/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs b/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs index 5c0eaeff..e2203ca9 100644 --- a/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/EjectionEvent.cs @@ -9,5 +9,5 @@ public class EjectionEvent(ExileController controller) : MiraEvent /// /// Gets the instance. /// - public ExileController ExileController { get; } = controller; + public ExileController ExileController => controller; } diff --git a/MiraAPI/Events/Vanilla/Meeting/EndMeetingEvent.cs b/MiraAPI/Events/Vanilla/Meeting/EndMeetingEvent.cs index da6642fc..ad958ede 100644 --- a/MiraAPI/Events/Vanilla/Meeting/EndMeetingEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/EndMeetingEvent.cs @@ -9,5 +9,5 @@ public class EndMeetingEvent(MeetingHud meetingHud) : MiraEvent /// /// Gets the instance. /// - public MeetingHud MeetingHud { get; } = meetingHud; + public MeetingHud MeetingHud => meetingHud; } diff --git a/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs b/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs index 139aa77d..891d61b4 100644 --- a/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs @@ -12,15 +12,15 @@ public class ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target /// /// Gets the player that is reporting the body. /// - public PlayerControl Reporter { get; } = reporter; + public PlayerControl Reporter => reporter; /// /// Gets the player that is being reported. Will be for emergency meeting. /// - public NetworkedPlayerInfo? Target { get; } = target; + public NetworkedPlayerInfo? Target => target; /// /// Gets the that is being reported. Will be for emergency meeting. /// - public DeadBody? Body { get; } = body; + public DeadBody? Body => body; } diff --git a/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs b/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs index a38b3c6c..ce373eb7 100644 --- a/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/StartMeetingEvent.cs @@ -10,5 +10,5 @@ public class StartMeetingEvent(MeetingHud meetingHud) : MiraEvent /// /// Gets the instance. /// - public MeetingHud MeetingHud { get; } = meetingHud; + public MeetingHud MeetingHud => meetingHud; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs index 34df3f9d..c6610f79 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/AfterVoteEvent.cs @@ -10,10 +10,10 @@ public class AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) /// /// Gets the instance of the voter's . /// - public PlayerVoteArea VoteArea { get; } = playerVoteArea; + public PlayerVoteArea VoteArea => playerVoteArea; /// /// Gets the player who voted. /// - public PlayerControl Player { get; } = voter; + public PlayerControl Player => voter; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs index 9d21b716..b666d490 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/BeforeVoteEvent.cs @@ -10,10 +10,10 @@ public class BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) /// /// Gets the instance of the voter's . /// - public PlayerVoteArea VoteArea { get; } = playerVoteArea; + public PlayerVoteArea VoteArea => playerVoteArea; /// /// Gets the player who voted. /// - public PlayerControl Player { get; } = voter; + public PlayerControl Player => voter; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs index 656ef44f..c6212dcc 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/CheckForEndVotingEvent.cs @@ -9,7 +9,7 @@ public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent /// /// Gets a value indicating whether default voting logic determines that voting is complete. /// - public bool IsVotingComplete { get; } = isVotingComplete; + public bool IsVotingComplete => isVotingComplete; /// /// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic. diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs index 1bb0bc84..febf84cc 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/DummyVoteEvent.cs @@ -13,12 +13,12 @@ public class DummyVoteEvent(DummyBehaviour dummy) : MiraCancelableEvent /// /// Gets the dummy that needs to vote. /// - public DummyBehaviour Dummy { get; } = dummy; + public DummyBehaviour Dummy => dummy; /// /// Gets the instance of the dummy's . /// - public PlayerVoteData VoteData { get; } = dummy.myPlayer.GetVoteData(); + public PlayerVoteData VoteData => dummy.myPlayer.GetVoteData(); /// /// Gets or sets a value indicating whether the dummy can vote to skip the meeting. diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs index 5d3008d6..f9592cb5 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/HandleVoteEvent.cs @@ -17,18 +17,18 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool /// /// Gets the instance of the voter's . /// - public PlayerVoteData VoteData { get; } = playerVoteData; + public PlayerVoteData VoteData => playerVoteData; + + /// + /// Gets the player id of the target. + /// + public byte TargetId => targetId; /// /// Gets the player who voted. /// public PlayerControl Player { get; } = playerVoteData.Owner; - /// - /// Gets the player id of the target. - /// - public byte TargetId { get; } = targetId; - /// /// Gets the of the target. /// diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs index aff24f7f..3042a1a2 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/MeetingSelectEvent.cs @@ -13,12 +13,12 @@ public class MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, boo /// /// Gets the instance of the voter's . /// - public PlayerVoteData VoteData { get; } = playerVoteData; + public PlayerVoteData VoteData => playerVoteData; /// /// Gets the player id of the target. /// - public int TargetId { get; } = targetId; + public int TargetId => targetId; /// /// Gets the of the target. diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs index 3914722f..bc49cb4a 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/PopulateResultsEvent.cs @@ -15,5 +15,5 @@ public class PopulateResultsEvent(List votes) : MiraCancelableEvent /// /// Gets a list of networked s. /// - public List Votes { get; } = votes; + public List Votes => votes; } diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs index 40a7f1a5..0c0abdbf 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/ProcessVotesEvent.cs @@ -27,7 +27,7 @@ public class ProcessVotesEvent(List votes, NetworkedPlayerInfo? exil /// /// Gets the list of s that are being processed. /// - public List Votes { get; } = votes; + public List Votes => votes; /// /// Gets or sets a value indicating whether an overruling was done. Normally set by judge but can be overwritten. diff --git a/MiraAPI/Events/Vanilla/Meeting/Voting/VotingCompleteEvent.cs b/MiraAPI/Events/Vanilla/Meeting/Voting/VotingCompleteEvent.cs index 52d4c369..b601fbdc 100644 --- a/MiraAPI/Events/Vanilla/Meeting/Voting/VotingCompleteEvent.cs +++ b/MiraAPI/Events/Vanilla/Meeting/Voting/VotingCompleteEvent.cs @@ -9,5 +9,5 @@ public class VotingCompleteEvent(MeetingHud meetingHud) : MiraEvent /// /// Gets the instance. /// - public MeetingHud MeetingHud { get; } = meetingHud; + public MeetingHud MeetingHud => meetingHud; } diff --git a/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs b/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs index 7528fc15..c21f6a49 100644 --- a/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/CompleteHnsTaskEvent.cs @@ -11,15 +11,15 @@ public class CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl p /// /// Gets the instance of the . /// - public PlayerControl Player { get; } = player; + public PlayerControl Player => player; /// /// Gets the instance of the that the player completed. /// - public PlayerTask Task { get; } = task; + public PlayerTask Task => task; /// /// Gets the instance of the attached to the game. /// - public HideAndSeekManager HnsManager { get; } = hnsManager; + public HideAndSeekManager HnsManager => hnsManager; } diff --git a/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs b/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs index 95b24304..642e04d2 100644 --- a/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/CompleteTaskEvent.cs @@ -10,10 +10,10 @@ public class CompleteTaskEvent(PlayerControl player, PlayerTask task) : MiraEven /// /// Gets the instance of the . /// - public PlayerControl Player { get; } = player; + public PlayerControl Player => player; /// /// Gets the instance of the that the player completed. /// - public PlayerTask Task { get; } = task; + public PlayerTask Task => task; } diff --git a/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs b/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs index b03d2aa1..4a3e2869 100644 --- a/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/PlayerDeathEvent.cs @@ -11,15 +11,15 @@ public class PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody /// /// Gets the player who died. /// - public PlayerControl Player { get; } = player; + public PlayerControl Player => player; /// /// Gets the reason the player died. /// - public DeathReason DeathReason { get; } = reason; + public DeathReason DeathReason => reason; /// /// Gets the associated with the player, if any. /// - public DeadBody? DeadBody { get; } = deadBody; + public DeadBody? DeadBody => deadBody; } diff --git a/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs b/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs index 5f664723..18229e9e 100644 --- a/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/PlayerJoinEvent.cs @@ -11,5 +11,5 @@ public class PlayerJoinEvent(ClientData data) : MiraEvent /// /// Gets the player who joined. /// - public ClientData ClientData { get; } = data; + public ClientData ClientData => data; } diff --git a/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs b/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs index 1af8bdea..63446cb8 100644 --- a/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs +++ b/MiraAPI/Events/Vanilla/Player/PlayerLeaveEvent.cs @@ -12,10 +12,10 @@ public class PlayerLeaveEvent(ClientData data, DisconnectReasons reason) : MiraE /// /// Gets the player who left. /// - public ClientData ClientData { get; } = data; + public ClientData ClientData => data; /// /// Gets the reason why the player left. /// - public DisconnectReasons Reason { get; } = reason; + public DisconnectReasons Reason => reason; } diff --git a/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs b/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs index 4d6eaaa0..85af54a9 100644 --- a/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs +++ b/MiraAPI/Events/Vanilla/Usables/EnterVentEvent.cs @@ -10,10 +10,10 @@ public class EnterVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEv /// /// Gets the that is entering the . /// - public PlayerControl Player { get; } = player; + public PlayerControl Player => player; /// /// Gets the that the is entering. /// - public Vent? Vent { get; } = vent; + public Vent? Vent => vent; } diff --git a/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs b/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs index 3c0782e0..4612bf6a 100644 --- a/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs +++ b/MiraAPI/Events/Vanilla/Usables/ExitVentEvent.cs @@ -10,10 +10,10 @@ public class ExitVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEve /// /// Gets the that is exiting the . /// - public PlayerControl Player { get; } = player; + public PlayerControl Player => player; /// /// Gets the that the is exiting. /// - public Vent? Vent { get; } = vent; + public Vent? Vent => vent; } diff --git a/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs b/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs index a23ce0e8..b2893a59 100644 --- a/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs +++ b/MiraAPI/Events/Vanilla/Usables/PlayerUseEvent.cs @@ -9,7 +9,7 @@ public class PlayerUseEvent(IUsable usable) : MiraCancelableEvent /// /// Gets the instance of that was used. /// - public IUsable Usable { get; } = usable; + public IUsable Usable => usable; /// /// Gets a value indicating whether the is a , , or . diff --git a/MiraAPI/GameModes/CustomGameModeManager.cs b/MiraAPI/GameModes/CustomGameModeManager.cs index acb0f51b..8a74f4f1 100644 --- a/MiraAPI/GameModes/CustomGameModeManager.cs +++ b/MiraAPI/GameModes/CustomGameModeManager.cs @@ -29,13 +29,10 @@ public static class CustomGameModeManager { if (!typeof(AbstractGameMode).IsAssignableFrom(gameModeType)) { - Warning($"{gameModeType.Name} does not inherit CustomGameMode!"); return false; } - var instance = Activator.CreateInstance(gameModeType); - - if (instance is not AbstractGameMode mode) + if (Activator.CreateInstance(gameModeType) is not AbstractGameMode mode) { Error($"Failed to create instance of {gameModeType.Name}"); return false; diff --git a/MiraAPI/GameOptions/CollectionBuilder.cs b/MiraAPI/GameOptions/CollectionBuilder.cs index 99d42d9e..103030b3 100644 --- a/MiraAPI/GameOptions/CollectionBuilder.cs +++ b/MiraAPI/GameOptions/CollectionBuilder.cs @@ -3,6 +3,6 @@ namespace System.Runtime.CompilerServices; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] internal sealed class CollectionBuilderAttribute(Type builderType, string methodName) : Attribute { - public Type BuilderType { get; } = builderType; - public string MethodName { get; } = methodName; + public Type BuilderType => builderType; + public string MethodName => methodName; } diff --git a/MiraAPI/GameOptions/ModdedOptionsManager.cs b/MiraAPI/GameOptions/ModdedOptionsManager.cs index 44a684b7..98d07606 100644 --- a/MiraAPI/GameOptions/ModdedOptionsManager.cs +++ b/MiraAPI/GameOptions/ModdedOptionsManager.cs @@ -69,25 +69,17 @@ public static class ModdedOptionsManager notif.SettingsChangeMessageLogic(key, item, playSound); } - internal static bool RegisterGroup(Type type) - { - if (TypeToGroup.ContainsKey(type)) - { - Error($"Group {type.Name} already exists."); - return false; - } - - if (Activator.CreateInstance(type) is not AbstractOptionGroup group) - { - return false; - } - - RegisterGroupInternal(group, type); - return true; - } - + [SuppressMessage( + "Major Code Smell", + "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", + Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")] internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo) { + if (!type.IsAssignableTo(typeof(AbstractOptionGroup))) + { + return false; + } + if (TypeToGroup.ContainsKey(type)) { Error($"Group {type.Name} already exists."); @@ -113,24 +105,49 @@ public static class ModdedOptionsManager pluginInfo.InternalOptionGroups.Add(group); - RegisterGroupInternal(group, type); - return true; - } - - [SuppressMessage( - "Major Code Smell", - "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", - Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")] - private static void RegisterGroupInternal(AbstractOptionGroup group, Type type) - { Groups.Add(group); TypeToGroup.Add(type, group); typeof(OptionGroupSingleton<>).MakeGenericType(type) .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! .SetValue(null, group); + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers)) + { + if (property.PropertyType.IsAssignableTo(typeof(IModdedOption))) + { + RegisterPropertyOption(type, property, pluginInfo); + continue; + } + + if (property.PropertyType.IsAssignableTo(typeof(IModdedOptionList))) + { + RegisterPropertyOptionList(type, property, pluginInfo); + continue; + } + + if (property.TryGetCustomAttribute(out var attribute)) + { + RegisterAttributeOption(type, attribute, property, pluginInfo); + continue; + } + + if (property.TryGetCustomAttribute(out var listAttr)) + { + RegisterAttributeOptionList(type, listAttr, property, pluginInfo); + } + } + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) + && (f.FieldType.IsAssignableTo(typeof(IModdedOption)) || f.FieldType.IsAssignableTo(typeof(IModdedOptionList))))) + { + Error($"{field.Name} is a field, not a property. Use properties for options."); + } + + return true; } - internal static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) + private static void RegisterPropertyOption(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) { if (!TypeToGroup.TryGetValue(type, out var group)) { @@ -147,7 +164,7 @@ public static class ModdedOptionsManager RegisterOption(option, group, property.Name, pluginInfo); } - internal static void RegisterAttributeOption( + private static void RegisterAttributeOption( Type type, ModdedOptionAttribute attribute, PropertyInfo property, @@ -224,7 +241,7 @@ public static class ModdedOptionsManager RegisterOption(option, group, property.Name, pluginInfo); } - internal static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) + private static void RegisterPropertyOptionList(Type type, PropertyInfo property, MiraPluginInfo pluginInfo) { if (!TypeToGroup.TryGetValue(type, out var group)) { @@ -246,7 +263,7 @@ public static class ModdedOptionsManager } } - internal static void RegisterAttributeOptionList( + private static void RegisterAttributeOptionList( Type type, ModdedOptionListAttribute attribute, PropertyInfo property, @@ -372,7 +389,7 @@ public static class ModdedOptionsManager } } - internal static void RegisterOption( + private static void RegisterOption( IModdedOption option, AbstractOptionGroup group, string propertyName, @@ -393,9 +410,9 @@ public static class ModdedOptionsManager { var chunks = ModdedOptions.Values.Select(option => option.GetNetData()).ChunkNetData(1000); - while (chunks.Count > 0) + while (chunks.TryDequeue(out var netData)) { - Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, chunks.Dequeue())); + Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData)); } } diff --git a/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs b/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs index b9dd3d82..260b8895 100644 --- a/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs +++ b/MiraAPI/GameOptions/OptionTypes/ModdedOption.cs @@ -162,7 +162,7 @@ public abstract class ModdedOption(string groupPrefix, string title, T defaul entry.Value = _value; } - Rpc.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true); + Rpc.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true); } if (ShowNotification) diff --git a/MiraAPI/Hud/CustomButtonManager.cs b/MiraAPI/Hud/CustomButtonManager.cs index a532f8e0..1e8656ed 100644 --- a/MiraAPI/Hud/CustomButtonManager.cs +++ b/MiraAPI/Hud/CustomButtonManager.cs @@ -45,6 +45,7 @@ public static class CustomButtonManager CustomButtons.Add(button); pluginInfo.InternalButtons.Add(button); + typeof(CustomButtonSingleton<>).MakeGenericType(buttonType) .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this .SetValue(null, button); diff --git a/MiraAPI/Hud/CustomPaginableMenu.cs b/MiraAPI/Hud/CustomPaginableMenu.cs index aca20b53..c8ef1cef 100644 --- a/MiraAPI/Hud/CustomPaginableMenu.cs +++ b/MiraAPI/Hud/CustomPaginableMenu.cs @@ -72,18 +72,18 @@ public abstract class CustomPaginableMenu : CustomPhoneMenu().sprite = MiraAssets.NextButton.LoadAsset(); - nextButton.gameObject.GetComponent().DestroyImmediate(); + nextButton.GetComponent().DestroyImmediate(); - var passiveButton = nextButton.gameObject.GetComponent(); + var passiveButton = nextButton.GetComponent(); passiveButton.OnClick = new Button.ButtonClickedEvent(); passiveButton.OnClick.AddListener((UnityAction)customMenu.NextPage); var backButton = Object.Instantiate(nextButton, customMenu.transform).gameObject; backButton.transform.localPosition = new Vector3(-1.85f, -2.185f, customMenu.MenuDepth); backButton.name = "LeftArrowButton"; - backButton.gameObject.GetComponent().Destroy(); + backButton.GetComponent().Destroy(); backButton.GetComponent().flipX = true; - var prevPassive = backButton.gameObject.GetComponent(); + var prevPassive = backButton.GetComponent(); prevPassive.OnClick.AddListener((UnityAction)customMenu.PreviousPage); customMenu.PhoneUI.GetChild(0).GetComponent().material = diff --git a/MiraAPI/Hud/CustomPhoneMenu.cs b/MiraAPI/Hud/CustomPhoneMenu.cs index 1f636f73..55af740f 100644 --- a/MiraAPI/Hud/CustomPhoneMenu.cs +++ b/MiraAPI/Hud/CustomPhoneMenu.cs @@ -260,7 +260,7 @@ public abstract class CustomPhoneMenu : ICustomMenu MenuEntries.Add(menuEntry); var button = shapeshifterPanel.Button; - var nameplate = shapeshifterPanel.gameObject.transform.FindChild("Nameplate"); + var nameplate = shapeshifterPanel.transform.FindChild("Nameplate"); var highlight = nameplate.FindChild("Highlight").GetComponent(); var icon = highlight.transform.GetChild(0).GetComponent(); @@ -317,7 +317,7 @@ public abstract class CustomPhoneMenu : ICustomMenu { ShapeshifterPanel panel = menuEntry.Panel; - var nameplate = panel.gameObject.transform.FindChild("Nameplate"); + var nameplate = panel.transform.FindChild("Nameplate"); var highlight = nameplate.FindChild("Highlight").GetComponent(); var icon = highlight.transform.GetChild(0).GetComponent(); if (sprite != null) diff --git a/MiraAPI/Hud/CustomPlayerMenu.cs b/MiraAPI/Hud/CustomPlayerMenu.cs index 26c3b94b..e0c0a777 100644 --- a/MiraAPI/Hud/CustomPlayerMenu.cs +++ b/MiraAPI/Hud/CustomPlayerMenu.cs @@ -89,6 +89,22 @@ public class CustomPlayerMenu : CustomMultiSelectMenu { var flag = PlayerControl.LocalPlayer.Data.Role.NameColor == entry.Data.Role.NameColor; panel.SetPlayer(i, entry.Data, (Il2CppSystem.Action)onClick); + var outfit = entry.Data.DefaultOutfit; + + if (entry.Data.IsDead) + { + var currentOutfit = entry.CurrentOutfit; + + if (!string.IsNullOrEmpty(currentOutfit.SkinId)) + { + outfit = currentOutfit; + } + } + + panel.PlayerIcon.cosmetics.SetSkin(outfit.SkinId, outfit.ColorId); + panel.PlayerIcon.cosmetics.SetHat(outfit.HatId, outfit.ColorId); + panel.PlayerIcon.cosmetics.SetVisor(outfit.VisorId, outfit.ColorId); + panel.NameText.color = flag ? entry.Data.Role.NameColor : Color.white; } } diff --git a/MiraAPI/Hud/MultiTargetButton.cs b/MiraAPI/Hud/MultiTargetButton.cs index 6f931e7e..ec12a346 100644 --- a/MiraAPI/Hud/MultiTargetButton.cs +++ b/MiraAPI/Hud/MultiTargetButton.cs @@ -22,7 +22,7 @@ public abstract class MultiTargetButton : CustomActionButton /// /// Gets the maximum amount of targets the button can have. /// - public virtual int MaxTargets { get; } = int.MaxValue; + public virtual int MaxTargets => int.MaxValue; /// public virtual bool IsTargetValid(T target) diff --git a/MiraAPI/Keybinds/KeybindManager.cs b/MiraAPI/Keybinds/KeybindManager.cs index b3097e14..057b3243 100644 --- a/MiraAPI/Keybinds/KeybindManager.cs +++ b/MiraAPI/Keybinds/KeybindManager.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using MiraAPI.PluginLoading; +using MiraAPI.Translation; using MiraAPI.Utilities; using Rewired; @@ -76,6 +78,48 @@ public static class KeybindManager } } + internal static bool RegisterKeybinds(Type type, IMiraPlugin plugin) + { + if (!type.IsDefined()) + { + return false; + } + + if (!type.IsStatic()) + { + Error($"Keybinds class {type.Name} must be static."); + return false; + } + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredStaticMembers)) + { + if (property.PropertyType != typeof(MiraKeybind)) + { + continue; + } + + if (property.GetValue(null) is not MiraKeybind keybind) + { + Error($"Keybind property {property.Name} in {type.Name} is not a MiraKeybind."); + continue; + } + + Keybinds.Add(keybind); + keybind.SourcePluginName = plugin.OptionsTitleText.Translate(); + } + + if (!plugin.DebugMode) + return true; + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredStaticMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) + { + Error($"{field.Name} is a field, not a property. Use properties for keybinds."); + } + + return true; + } + /// /// Returns all conflicts where s use the same key. /// @@ -89,16 +133,18 @@ public static class KeybindManager if (key == KeyboardKeyCode.None) continue; var all = GetKeybindsForKey(key, true); - if (all.Length > 1) + if (all.Length <= 1) { - if (!conflicts.TryGetValue(key, out var group)) - { - group = []; - conflicts.Add(key, group); - } - - if (!group.Contains(keybind)) group.Add(keybind); + continue; } + + if (!conflicts.TryGetValue(key, out var group)) + { + group = []; + conflicts.Add(key, group); + } + + if (!group.Contains(keybind)) group.Add(keybind); } return conflicts; diff --git a/MiraAPI/Keybinds/MiraKeybind.cs b/MiraAPI/Keybinds/MiraKeybind.cs index ef466b52..3153f37c 100644 --- a/MiraAPI/Keybinds/MiraKeybind.cs +++ b/MiraAPI/Keybinds/MiraKeybind.cs @@ -15,7 +15,7 @@ public class MiraKeybind(string name, KeyboardKeyCode? defaultKeycode, ModifierK /// /// Gets name of the keybind. /// - public string Name { get; } = name; + public string Name => name; /// /// Gets the default keycode of this keybind. @@ -37,7 +37,7 @@ public class MiraKeybind(string name, KeyboardKeyCode? defaultKeycode, ModifierK /// Gets a value indicating whether this keybind should be checked for conflicts with other exclusive keybinds using the same key. /// Active exclusive controller bindings take priority over vanilla actions during gameplay. /// - public bool Exclusive { get; } = exclusive; + public bool Exclusive => exclusive; internal string? SourcePluginName { get; set; } diff --git a/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs b/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs index 83a39556..8c0eb3d4 100644 --- a/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs +++ b/MiraAPI/LocalSettings/Attributes/LocalSettingsButtonAttribute.cs @@ -6,6 +6,4 @@ namespace MiraAPI.LocalSettings.Attributes; /// Attribute for local setting buttons. /// [AttributeUsage(AttributeTargets.Property)] -public class LocalSettingsButtonAttribute : Attribute -{ -} +public class LocalSettingsButtonAttribute : Attribute; diff --git a/MiraAPI/LocalSettings/LocalSettingsManager.cs b/MiraAPI/LocalSettings/LocalSettingsManager.cs index 4907d8c1..44d77681 100644 --- a/MiraAPI/LocalSettings/LocalSettingsManager.cs +++ b/MiraAPI/LocalSettings/LocalSettingsManager.cs @@ -1,8 +1,13 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Reflection; +using BepInEx.Configuration; using BepInEx.Unity.IL2CPP; +using MiraAPI.LocalSettings.Attributes; +using MiraAPI.PluginLoading; +using MiraAPI.Utilities; namespace MiraAPI.LocalSettings; @@ -19,9 +24,9 @@ public static class LocalSettingsManager "Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Dynamic singleton initialization requires reflection to bypass the private field access modifier because the type is only known at runtime.")] - internal static bool RegisterTab(Type type, BasePlugin pluginInfo) + internal static bool RegisterLocalTabs(Type type, BasePlugin pluginInfo) { - if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tab) + if (!type.IsAssignableTo(typeof(LocalSettingsTab))) { return false; } @@ -32,17 +37,64 @@ public static class LocalSettingsManager return false; } - Tabs.Add(tab); - if (tab.ShouldCreateButton) + if (Activator.CreateInstance(type, pluginInfo.Config) is not LocalSettingsTab tabInstance) { - AvailableTabs.Add(tab); + return false; } - TypeToTab.Add(type, tab); + Tabs.Add(tabInstance); + + if (tabInstance.ShouldCreateButton) + { + AvailableTabs.Add(tabInstance); + } + + TypeToTab.Add(type, tabInstance); typeof(LocalSettingsTabSingleton<>).MakeGenericType(type) .GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)! // Suppression message refers to this - .SetValue(null, tab); + .SetValue(null, tabInstance); + + foreach (var property in type.GetProperties(MiraPluginManager.DeclaredInstanceMembers)) + { + if (property.IsDefined()) + { + if (property.GetValue(tabInstance) is not LocalSettingsButton button) + { + Error($"Option property {property.Name} in {type.Name} has to be a settings button."); + continue; + } + + button.Tab = tabInstance; + tabInstance.Buttons.Add(button); + continue; + } + + if (!property.TryGetCustomAttribute(out var attribute)) + { + continue; + } + + if (!typeof(ConfigEntryBase).IsAssignableFrom(property.PropertyType)) + { + continue; + } + + if (property.GetValue(tabInstance) is not ConfigEntryBase configEntry) + { + Error($"Option property {property.Name} in {type.Name} has to be a config entry."); + continue; + } + + attribute.CreateSetting(type, configEntry); + } + + foreach (var field in type.GetFields(MiraPluginManager.DeclaredInstanceMembers) + .Where(f => !MiraPluginManager.IsAutoPropertyBackingField(f) + && (f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) || f.FieldType.IsAssignableTo(typeof(LocalSettingsButton))))) + { + Error($"{field.Name} is a field, not a property. Use properties for local settings or buttons."); + } return true; } diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs index 5fcbb081..61d995cc 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalEnumSetting.cs @@ -31,7 +31,7 @@ public class LocalEnumSetting( /// /// Gets the type of the setting. /// - public Type EnumType { get; } = enumType; + public Type EnumType => enumType; /// /// Gets the values. diff --git a/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs b/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs index 14f1ffe9..2c813bbe 100644 --- a/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs +++ b/MiraAPI/LocalSettings/SettingTypes/LocalSliderSetting.cs @@ -41,7 +41,7 @@ public class LocalSliderSetting( /// /// Gets a value indicating whether the value should be displayed next to name. /// - public bool DisplayValue { get; } = displayValue; + public bool DisplayValue => displayValue; /// /// Gets a format for the text to use to format the number. @@ -51,7 +51,7 @@ public class LocalSliderSetting( /// /// Gets a value indicating whether the value should be rounded. /// - public bool RoundValue { get; } = roundValue; + public bool RoundValue => roundValue; /// /// Gets the suffix for the number value. diff --git a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs index 5ca75d85..92348f5d 100644 --- a/MiraAPI/MeetingAbilities/MeetingButtonManager.cs +++ b/MiraAPI/MeetingAbilities/MeetingButtonManager.cs @@ -13,12 +13,12 @@ namespace MiraAPI.MeetingAbilities; public static class MeetingButtonManager { /// - /// Gets a list if==of all registered . + /// Gets a list of all registered . /// public static List TargetedButtons { get; internal set; } = []; /// - /// Gets a list if==of all registered . + /// Gets a list of all registered . /// public static List UntargetedButtons { get; internal set; } = []; diff --git a/MiraAPI/MeetingAbilities/TargetedMeetingButton.cs b/MiraAPI/MeetingAbilities/TargetedMeetingButton.cs index 2d4766e4..0a05c5a0 100644 --- a/MiraAPI/MeetingAbilities/TargetedMeetingButton.cs +++ b/MiraAPI/MeetingAbilities/TargetedMeetingButton.cs @@ -64,7 +64,7 @@ public abstract class TargetedMeetingButton /// /// Gets the for this button. /// - public virtual MeetingButtonUsesMode UsesMode { get; } = MeetingButtonUsesMode.PerGame; + public virtual MeetingButtonUsesMode UsesMode => MeetingButtonUsesMode.PerGame; /// /// Determines if the button is enabled. @@ -89,7 +89,7 @@ public abstract class TargetedMeetingButton if (MeetingHud.Instance == null) return null!; var btn = Object.Instantiate(MeetingHud.Instance.PlayerButtonPrefab.ConfirmButton).GetComponent(); - btn.gameObject.name = Name + "Button"; + btn.name = Name + "Button"; var spriteRenderer = btn.GetComponent(); spriteRenderer.sprite = Sprite.LoadAsset(); diff --git a/MiraAPI/MiraAPI.csproj b/MiraAPI/MiraAPI.csproj index b6bcb5d2..2d47477a 100644 --- a/MiraAPI/MiraAPI.csproj +++ b/MiraAPI/MiraAPI.csproj @@ -5,7 +5,6 @@ AllOfUs.MiraAPI true true - IDE0031;IDE0032 @@ -16,11 +15,5 @@ - - - - - - diff --git a/MiraAPI/MiraApiPlugin.cs b/MiraAPI/MiraApiPlugin.cs index dc926b2e..7e744781 100644 --- a/MiraAPI/MiraApiPlugin.cs +++ b/MiraAPI/MiraApiPlugin.cs @@ -41,6 +41,9 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin /// public bool DisplayOnOptionsMenu => false; + /// + public bool DebugMode => IsDevBuild; + /// /// Gets a value indicating whether the current device is running Starlight (on mobile). /// diff --git a/MiraAPI/MiraApiSettings.cs b/MiraAPI/MiraApiSettings.cs index 2240d0c1..ce722351 100644 --- a/MiraAPI/MiraApiSettings.cs +++ b/MiraAPI/MiraApiSettings.cs @@ -144,15 +144,15 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config) if (button.transform.name.Contains("Friends List Button")) { - button.gameObject.transform.localScale = new Vector3(0.2675f * actualScaleVal, 0.2675f * actualScaleVal, 1); + button.transform.localScale = new Vector3(0.2675f * actualScaleVal, 0.2675f * actualScaleVal, 1); continue; } - button.gameObject.transform.localScale = actualScale; + button.transform.localScale = actualScale; } baseGrid.CellSize = new Vector2(alteredScale, alteredScale); - if (baseGrid.gameObject.transform.childCount != 0) + if (baseGrid.transform.childCount != 0) { baseGrid.ArrangeChilds(); } @@ -175,15 +175,15 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config) if (button.transform.name.Contains("Modifiers")) { - button.gameObject.transform.localScale = new Vector3(0.65f * scaleFactor, 0.65f * scaleFactor, 1); + button.transform.localScale = new Vector3(0.65f * scaleFactor, 0.65f * scaleFactor, 1); continue; } - button.gameObject.transform.localScale = actualScale; + button.transform.localScale = actualScale; } extraGrid.CellSize = new Vector2(alteredScale, alteredScale); - if (extraGrid.gameObject.transform.childCount != 0) + if (extraGrid.transform.childCount != 0) { extraGrid.ArrangeChilds(); } diff --git a/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs b/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs index 3c66358b..8638f75e 100644 --- a/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs +++ b/MiraAPI/Modifiers/ModifierDisplay/ModifierUiComponent.cs @@ -37,7 +37,7 @@ public class ModifierUiComponent(nint cppPtr) : MonoBehaviour(cppPtr) icon = modBg.transform.GetChild(1).GetComponent(); var nameBg = transform.GetChild(1); nameText = nameBg.GetChild(0).GetComponent(); - descRect = desc.gameObject.GetComponent(); + descRect = desc.GetComponent(); nameText.font = desc.font = HudManager.Instance.TaskPanel.taskText.font; nameText.fontMaterial = desc.fontMaterial = HudManager.Instance.TaskPanel.taskText.fontMaterial; diff --git a/MiraAPI/Modifiers/ModifierManager.cs b/MiraAPI/Modifiers/ModifierManager.cs index 935c82e5..f12d2172 100644 --- a/MiraAPI/Modifiers/ModifierManager.cs +++ b/MiraAPI/Modifiers/ModifierManager.cs @@ -72,7 +72,9 @@ public static class ModifierManager TypeToIdModifierMap.Add(modifierType, _nextTypeId); BaseModifier modifier; - if (modifierType.GetConstructor(Type.EmptyTypes) != null) + var ctor = modifierType.GetConstructor(Type.EmptyTypes); + + if (ctor != null) { modifier = (BaseModifier)Activator.CreateInstance(modifierType)!; } @@ -90,7 +92,7 @@ public static class ModifierManager return true; } - if (modifierType.GetConstructor(Type.EmptyTypes) == null) + if (ctor == null) { Error($"Game Modifier {modifierType.FullName} does not have a parameterless constructor!"); return false; diff --git a/MiraAPI/Networking/NetData.cs b/MiraAPI/Networking/NetData.cs index aa9a52ee..db8c91c4 100644 --- a/MiraAPI/Networking/NetData.cs +++ b/MiraAPI/Networking/NetData.cs @@ -10,12 +10,12 @@ public readonly struct NetData(uint id, byte[] data) /// /// Gets the ID of the data. /// - public uint Id { get; } = id; + public uint Id => id; /// /// Gets the byte[] data. /// - public byte[] Data { get; } = data; + public byte[] Data => data; /// /// Gets the length of the data in bytes. diff --git a/MiraAPI/Networking/SyncOptionsRpc.cs b/MiraAPI/Networking/SyncOptionsRpc.cs index 9cf83a3d..2c6ee922 100644 --- a/MiraAPI/Networking/SyncOptionsRpc.cs +++ b/MiraAPI/Networking/SyncOptionsRpc.cs @@ -1,27 +1,24 @@ using Hazel; using MiraAPI.GameOptions; +using MiraAPI.Roles; using Reactor.Networking.Attributes; using Reactor.Networking.Rpc; namespace MiraAPI.Networking; +internal readonly struct MiraOptionNetData(bool showNotif, NetData[] data) +{ + public bool ShouldShowNotifications => showNotif; + public NetData[] Data => data; +} + // METHOD RPC DOESN'T WORK WITH THE ARRAYS AND STUFF SO THIS IS HOW WE WILL DO IT FOR NOW -[RegisterCustomRpc((uint)MiraRpc.SyncGameOptions)] -#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.) -// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.) -internal sealed class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) -#pragma warning restore SA1515 // Single-line comment should be preceded by blank line +internal abstract class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) { public override RpcLocalHandling LocalHandling => RpcLocalHandling.None; public override void Write(MessageWriter writer, MiraOptionNetData data) { - /*if (data == null) - { - writer.WritePacked(0U); - return; - }*/ - var info = data.Data; writer.Write(data.ShouldShowNotifications); writer.WritePacked((uint)info.Length); @@ -46,14 +43,34 @@ internal sealed class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCust return new MiraOptionNetData(shouldShowNotif, data); } +} +[RegisterCustomRpc((uint)MiraRpc.SyncGameOptions)] +#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.) +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.) +internal sealed class SyncGameOptionsRpc(MiraApiPlugin plugin, uint id) : SyncOptionsRpc(plugin, id) +#pragma warning restore SA1515 // Single-line comment should be preceded by blank line +{ public override void Handle(PlayerControl innerNetObject, MiraOptionNetData data) { - if (AmongUsClient.Instance.HostId != innerNetObject.OwnerId) + if (AmongUsClient.Instance.HostId == innerNetObject.OwnerId) { - return; + ModdedOptionsManager.HandleSyncOptions(data.ShouldShowNotifications, data.Data ?? []); + } + } +} + +[RegisterCustomRpc((uint)MiraRpc.SyncRoleOptions)] +#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.) +// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.) +internal sealed class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : SyncOptionsRpc(plugin, id) +#pragma warning restore SA1515 // Single-line comment should be preceded by blank line +{ + public override void Handle(PlayerControl innerNetObject, MiraOptionNetData data) + { + if (AmongUsClient.Instance.HostId == innerNetObject.OwnerId) + { + CustomRoleManager.HandleSyncRoleOptions(data.ShouldShowNotifications, data.Data ?? []); } - - ModdedOptionsManager.HandleSyncOptions(data.ShouldShowNotifications, data.Data ?? []); } } diff --git a/MiraAPI/Networking/SyncRoleOptionsRpc.cs b/MiraAPI/Networking/SyncRoleOptionsRpc.cs deleted file mode 100644 index eb632ed4..00000000 --- a/MiraAPI/Networking/SyncRoleOptionsRpc.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Hazel; -using MiraAPI.Roles; -using Reactor.Networking.Attributes; -using Reactor.Networking.Rpc; - -namespace MiraAPI.Networking; - -internal readonly struct MiraOptionNetData(bool showNotif, NetData[] data) -{ - public bool ShouldShowNotifications { get; } = showNotif; - public NetData[] Data { get; } = data; -} - -[RegisterCustomRpc((uint)MiraRpc.SyncRoleOptions)] -#pragma warning disable SA1515 // Single-line comment should be preceded by blank line (Justification: ReSharper suppression.) -// ReSharper disable once ClassNeverInstantiated.Global (Justification: Instantiated by Reactor.) -internal sealed class SyncRoleOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc(plugin, id) -#pragma warning restore SA1515 // Single-line comment should be preceded by blank line -{ - public override RpcLocalHandling LocalHandling => RpcLocalHandling.None; - - public override void Write(MessageWriter writer, MiraOptionNetData data) - { - /*if (data == null) - { - writer.WritePacked(0U); - return; - }*/ - - var info = data.Data; - writer.Write(data.ShouldShowNotifications); - writer.WritePacked((uint)info.Length); - foreach (var netData in info) - { - writer.WritePacked(netData.Id); - writer.WriteBytesAndSize(netData.Data); - } - } - - public override MiraOptionNetData Read(MessageReader reader) - { - var shouldShowNotif = reader.ReadBoolean(); - var length = reader.ReadPackedUInt32(); - var data = new NetData[length]; - for (var i = 0; i < length; i++) - { - var dataId = reader.ReadPackedUInt32(); - var bytes = reader.ReadBytesAndSize(); - data[i] = new NetData(dataId, bytes); - } - - return new MiraOptionNetData(shouldShowNotif, data); - } - - public override void Handle(PlayerControl innerNetObject, MiraOptionNetData data) - { - if (AmongUsClient.Instance.HostId != innerNetObject.OwnerId) - { - return; - } - - CustomRoleManager.HandleSyncRoleOptions(data.ShouldShowNotifications, data.Data ?? []); - } -} diff --git a/MiraAPI/Patches/AmongUsClientSyncPatch.cs b/MiraAPI/Patches/AmongUsClientSyncPatch.cs index 926004d6..9fb6cbb6 100644 --- a/MiraAPI/Patches/AmongUsClientSyncPatch.cs +++ b/MiraAPI/Patches/AmongUsClientSyncPatch.cs @@ -1,23 +1,35 @@ -using HarmonyLib; +using System.Reflection; +using HarmonyLib; +using Il2CppInterop.Runtime.InteropTypes; using InnerNet; using MiraAPI.Events; using MiraAPI.Events.Vanilla.Player; using MiraAPI.GameModes; using MiraAPI.GameOptions; using MiraAPI.Roles; +using MiraAPI.Utilities; namespace MiraAPI.Patches; /// /// Sync all settings to the player when they join the game. /// -[HarmonyPatch(typeof(AmongUsClient))] +[HarmonyPatch] internal static class AmongUsClientSyncPatch { - [HarmonyPostfix] - [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CreatePlayer))] - public static void CreatePlayerPatch(ClientData clientData) + public static MethodBase TargetMethod() { + return Helpers.GetStateMachineMoveNext(nameof(AmongUsClient.CreatePlayer))!; + } + + [HarmonyPostfix] + public static void CreatePlayerPatch(Il2CppObjectBase __instance, bool __result) + { + if (__result) + return; + + var wrapper = new StateMachineWrapper(__instance); + var clientData = wrapper.GetParameter("clientData"); var joinEvent = new PlayerJoinEvent(clientData); MiraEventManager.InvokeEvent(joinEvent); @@ -35,9 +47,12 @@ internal static class AmongUsClientSyncPatch CustomRoleManager.SyncAllRoleSettings(clientData.Id); GameModeOption.RpcSyncGamemode(PlayerControl.LocalPlayer, GameModeOption.Value); } +} +[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerLeft))] +internal static class AmongUsClientSyncPatch2 +{ [HarmonyPrefix] - [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerLeft))] public static void PlayerLeftPatch(ClientData data, DisconnectReasons reason) { var leftEvent = new PlayerLeaveEvent(data, reason); diff --git a/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs b/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs index 6a97687f..a4ba9cbd 100644 --- a/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs +++ b/MiraAPI/Patches/Freeplay/TaskAdderPatches.cs @@ -111,8 +111,7 @@ public static class TaskAdderPatches if (plugin.InternalModifiers.Exists(x => x.ShowInFreeplay)) { - __instance.CreateFolder(plugin.PluginInfo.Metadata.Name, modifiersFolder) - .gameObject.name = plugin.PluginId; + __instance.CreateFolder(plugin.PluginInfo.Metadata.Name, modifiersFolder).name = plugin.PluginId; } } diff --git a/MiraAPI/Patches/GameModes/HudPatches.cs b/MiraAPI/Patches/GameModes/HudPatches.cs index 3c2d815d..325d193d 100644 --- a/MiraAPI/Patches/GameModes/HudPatches.cs +++ b/MiraAPI/Patches/GameModes/HudPatches.cs @@ -34,8 +34,8 @@ internal static class HudPatches yield return new WaitUntil((Il2CppSystem.Func)(() => GameManager.Instance != null)); if (GameManager.Instance.IsHideAndSeek()) yield return null; - var infoPane = instance.gameObject.transform.FindChild("LobbyInfoPane"); - var aspect = infoPane.gameObject.transform.Find("AspectSize"); + var infoPane = instance.transform.FindChild("LobbyInfoPane"); + var aspect = infoPane.transform.Find("AspectSize"); var modeLabel = aspect!.Find("ModeLabel"); var modeValue = aspect.Find("ModeValue"); var modelText = modeLabel!.Find("Text_TMP").gameObject; diff --git a/MiraAPI/Patches/HudManagerPatches.cs b/MiraAPI/Patches/HudManagerPatches.cs index 75b0e5e7..a6959ead 100644 --- a/MiraAPI/Patches/HudManagerPatches.cs +++ b/MiraAPI/Patches/HudManagerPatches.cs @@ -47,9 +47,9 @@ public static class HudManagerPatches { if (!aspect.gameObject) continue; - if (aspect.gameObject.transform.parent.name == "TopRight") continue; + if (aspect.transform.parent.name == "TopRight") continue; - if (aspect.gameObject.name.Contains("TopRight")) continue; + if (aspect.name.Contains("TopRight")) continue; aspect.gameObject.SetActive(!aspect.isActiveAndEnabled); aspect.DistanceFromEdge *= new Vector2(scaleFactor, scaleFactor); @@ -62,7 +62,7 @@ public static class HudManagerPatches if (!button.gameObject) continue; button.gameObject.SetActive(!button.isActiveAndEnabled); - button.gameObject.transform.localScale *= scaleFactor; + button.transform.localScale *= scaleFactor; button.gameObject.SetActive(!button.isActiveAndEnabled); } @@ -71,12 +71,12 @@ public static class HudManagerPatches { if (!arrange.gameObject || !arrange.transform) continue; - if (arrange.gameObject.name.Contains("TopRight")) continue; + if (arrange.name.Contains("TopRight")) continue; arrange.gameObject.SetActive(!arrange.isActiveAndEnabled); arrange.CellSize = new Vector2(scaleFactor, scaleFactor); arrange.gameObject.SetActive(!arrange.isActiveAndEnabled); - if (!arrange.isActiveAndEnabled || arrange.gameObject.transform.childCount == 0) continue; + if (!arrange.isActiveAndEnabled || arrange.transform.childCount == 0) continue; try { arrange.ArrangeChilds(); diff --git a/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs b/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs index 0799bf2f..3d19f0f6 100644 --- a/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs +++ b/MiraAPI/Patches/Options/GameOptionsMenuPatch.cs @@ -313,7 +313,7 @@ internal static class GameOptionsMenuPatch }; _modIcon = modIconObj.AddComponent(); _modIcon.sprite = MiraAssets.BlankSprite.LoadAsset(); - _modIcon.material = gamemodeBg.gameObject.GetComponent().material; + _modIcon.material = gamemodeBg.GetComponent().material; var gamemodeTextObj = Object.Instantiate(GameModeOption.OptionBehaviour.transform.GetChild(1).gameObject, modeInfoHolder); gamemodeTextObj.transform.localPosition = new Vector3(0.3f, 0, -0.01f); @@ -739,7 +739,7 @@ internal static class GameOptionsMenuPatch var newText = Object.Instantiate(categoryHeaderMasked.Title, categoryHeaderMasked.transform); newText.text = $"({"MiraApi.GameSetting.Global.ClickToClose".Translate()})"; newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f); - newText.gameObject.GetComponent().Destroy(); + newText.GetComponent().Destroy(); var boxCol = categoryHeaderMasked.gameObject.AddComponent(); boxCol.size = new Vector2(7, 0.7f); diff --git a/MiraAPI/Patches/Options/GamePresetsTabPatches.cs b/MiraAPI/Patches/Options/GamePresetsTabPatches.cs index 4bf0cf83..fe6ac117 100644 --- a/MiraAPI/Patches/Options/GamePresetsTabPatches.cs +++ b/MiraAPI/Patches/Options/GamePresetsTabPatches.cs @@ -164,7 +164,7 @@ internal static class GamePresetsTabPatches return; } - var tmpTranslator = presetTab.PresetDescriptionText.gameObject.GetComponent(); + var tmpTranslator = presetTab.PresetDescriptionText.GetComponent(); if (tmpTranslator) { tmpTranslator.Destroy(); @@ -184,7 +184,7 @@ internal static class GamePresetsTabPatches { saveButton = Object.Instantiate(prefab, presetTab.transform); _saveButton = saveButton.gameObject; - _saveButton.gameObject.name = "SaveButton"; + _saveButton.name = "SaveButton"; _saveButton.transform.localPosition = new Vector3(3.2f, 1.7f, -2); // set the button text and alignment @@ -282,7 +282,7 @@ internal static class GamePresetsTabPatches _folderButton.name = "OpenFolderButton"; _folderButton.transform.localPosition = new Vector3(3.55f, 1.1f, -2); - var folderRend = openFolderButton.transform.FindChild("Sprite").gameObject.GetComponent(); + var folderRend = openFolderButton.transform.FindChild("Sprite").GetComponent(); folderRend.sprite = MiraAssets.FolderIcon.LoadAsset(); folderRend.transform.localScale = new Vector3(0.4f, 0.4f, 1); diff --git a/MiraAPI/Patches/Options/GameSettingMenuPatches.cs b/MiraAPI/Patches/Options/GameSettingMenuPatches.cs index 6c1ede7a..47c45a06 100644 --- a/MiraAPI/Patches/Options/GameSettingMenuPatches.cs +++ b/MiraAPI/Patches/Options/GameSettingMenuPatches.cs @@ -20,9 +20,10 @@ internal static class GameSettingMenuPatches } // Add Menu State object - if (!__instance.gameObject.GetComponent()) + __instance.gameObject.GetOrAddComponent(out var existed); + + if (!existed) { - __instance.gameObject.AddComponent(); Info("MenuState component added to GameSettingMenu."); } else diff --git a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs index c77f93d1..79315f3a 100644 --- a/MiraAPI/Patches/Options/LobbyViewPanePatches.cs +++ b/MiraAPI/Patches/Options/LobbyViewPanePatches.cs @@ -72,7 +72,7 @@ public static class LobbyViewPanePatches // create modifiers button modifiersTabButton = Object.Instantiate(__instance.rolesTabButton, __instance.rolesTabButton.transform.parent); - modifiersTabButton.buttonText.gameObject.GetComponent().Destroy(); + modifiersTabButton.buttonText.GetComponent().Destroy(); modifiersTabButton.name = "ModifiersTabButton"; var pos = modifiersTabButton.transform.localPosition; pos.x = 2.1f; @@ -101,7 +101,7 @@ public static class LobbyViewPanePatches hover.transform.localPosition = new Vector3(0, 0f, 0.3f); hover.sprite = MiraAssets.NextButtonActive.LoadAsset(); - var passiveButton = nextButton.gameObject.GetComponent(); + var passiveButton = nextButton.GetComponent(); passiveButton.OnClick = new Button.ButtonClickedEvent(); passiveButton.OnClick.AddListener( (UnityAction)(() => @@ -123,7 +123,7 @@ public static class LobbyViewPanePatches = backButton.transform.FindChild("Hover").gameObject.GetComponentInChildren().flipX = true; - var passiveButton2 = backButton.gameObject.GetComponent(); + var passiveButton2 = backButton.GetComponent(); passiveButton2.OnClick = new Button.ButtonClickedEvent(); passiveButton2.OnClick.AddListener( (UnityAction)(() => diff --git a/MiraAPI/Patches/Options/MenuState.cs b/MiraAPI/Patches/Options/MenuState.cs index 66876991..9d3a38ab 100644 --- a/MiraAPI/Patches/Options/MenuState.cs +++ b/MiraAPI/Patches/Options/MenuState.cs @@ -50,7 +50,8 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) private readonly Dictionary _smallButtons = []; private readonly Dictionary _largeButtons = []; - + private Vector3 _gameSettingsButtonOrig; + private Vector3 _roleSettingsButtonOrig; [HideFromIl2Cpp] public Dictionary> Containers { get; } = new() { @@ -121,35 +122,39 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) var nextButton = Instantiate(Gsm.BackButton, Gsm.BackButton.transform.parent).gameObject; nextButton.transform.localPosition = new Vector3(-2.2663f, 1.5272f, -25f); nextButton.name = "RightArrowButton"; - nextButton.transform.FindChild("Inactive").gameObject.GetComponent().sprite = + nextButton.transform.FindChild("Inactive").GetComponent().sprite = MiraAssets.NextButton.LoadAsset(); - nextButton.transform.FindChild("Active").gameObject.GetComponent().sprite = + nextButton.transform.FindChild("Active").GetComponent().sprite = MiraAssets.NextButtonActive.LoadAsset(); - nextButton.gameObject.GetComponent().DestroyImmediate(); + nextButton.GetComponent().DestroyImmediate(); - var nextPassiveButton = nextButton.gameObject.GetComponent(); + var nextPassiveButton = nextButton.GetComponent(); nextPassiveButton.OnClick = new Button.ButtonClickedEvent(); nextPassiveButton.OnClick.AddListener((UnityAction)NextMod); var previousButton = Instantiate(nextButton, Gsm.BackButton.transform.parent).gameObject; previousButton.transform.localPosition = new Vector3(-4.4209f, 1.5272f, -25f); previousButton.name = "LeftArrowButton"; - previousButton.gameObject.GetComponent().Destroy(); - previousButton.transform.FindChild("Active").gameObject.GetComponent().flipX = - previousButton.transform.FindChild("Inactive").gameObject.GetComponent().flipX = true; + previousButton.GetComponent().Destroy(); + previousButton.transform.FindChild("Active").GetComponent().flipX = + previousButton.transform.FindChild("Inactive").GetComponent().flipX = true; - var prevPassiveButton = previousButton.gameObject.GetComponent(); + var prevPassiveButton = previousButton.GetComponent(); prevPassiveButton.OnClick = new Button.ButtonClickedEvent(); prevPassiveButton.OnClick.AddListener((UnityAction)PreviousMod); // Create menu buttons _largeButtons[(int)MenuButton.Roles] = Gsm.RoleSettingsButton; + // cache + _gameSettingsButtonOrig = Gsm.GameSettingsButton.transform.localPosition; + _roleSettingsButtonOrig = Gsm.RoleSettingsButton.transform.localPosition; + // modifiers button var mBtn = Instantiate(Gsm.RoleSettingsButton, Gsm.RoleSettingsButton.transform.parent); _largeButtons[MenuButton.Modifiers] = mBtn; mBtn.name = "ModifiersButton"; - mBtn.buttonText.gameObject.GetComponent().Destroy(); + mBtn.buttonText.GetComponent().Destroy(); mBtn.buttonText.text = "Modifiers".Translate(); mBtn.OnClick = new Button.ButtonClickedEvent(); mBtn.OnClick.AddListener( @@ -168,7 +173,7 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) var c1Btn = Instantiate(mBtn, mBtn.transform.parent); _largeButtons[MenuButton.CustomOne] = c1Btn; c1Btn.name = "CustomOneButton"; - c1Btn.buttonText.gameObject.GetComponent().Destroy(); + c1Btn.buttonText.GetComponent().Destroy(); c1Btn.OnClick = new Button.ButtonClickedEvent(); c1Btn.OnClick.AddListener( (UnityAction)(() => @@ -322,7 +327,7 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) // Create game options container var gameContainer = Containers[MenuCategory.Game][idx + 1] = Instantiate( Gsm.GameSettingsTab.settingsContainer.gameObject, - Gsm.GameSettingsTab.settingsContainer.gameObject.transform.parent); + Gsm.GameSettingsTab.settingsContainer.transform.parent); gameContainer.name = $"GameSettings_{mod.PluginInfo.Metadata.Name}"; gameContainer.transform.DestroyChildren(); gameContainer.SetActive(false); @@ -340,7 +345,7 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) { var cont = Containers[i][idx + 1] = Instantiate( Gsm.GameSettingsTab.settingsContainer.gameObject, - Gsm.GameSettingsTab.settingsContainer.gameObject.transform.parent); + Gsm.GameSettingsTab.settingsContainer.transform.parent); cont.name = $"{i}_{mod.PluginInfo.Metadata.Name}"; cont.transform.DestroyChildren(); cont.SetActive(false); @@ -409,6 +414,11 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) btn.gameObject.SetActive(false); } + // The mod options page moves RoleSettingsButton as needed. + // But when hasOptions == false, it leaves the button at the GameSettingsButton spot. + // So before each re-layout, always put the original button back into the prefab slot first. + RestoreButtonLayout(); + if (CurrentModIdx == 0) { Gsm.GameSettingsButton.gameObject.SetActive(true); @@ -532,6 +542,12 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr) } } + private void RestoreButtonLayout() + { + Gsm.GameSettingsButton.transform.localPosition = _gameSettingsButtonOrig; + Gsm.RoleSettingsButton.transform.localPosition = _roleSettingsButtonOrig; + } + internal void ChangeTabPatch(GameSettingMenu menu, int tabNum, bool previewOnly) { Info($"Changed tab to {(MenuCategory)tabNum} (previewOnly: {previewOnly}) for mod {CurrentModIdx}"); diff --git a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs index aa6396df..b6372387 100644 --- a/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs +++ b/MiraAPI/Patches/Options/RoleSettingMenuPatches.cs @@ -309,7 +309,7 @@ public static class RoleSettingMenuPatches var newText = Object.Instantiate(categoryHeaderMasked.Title, categoryHeaderMasked.transform); newText.text = $"{label}"; newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f); - newText.gameObject.GetComponent().Destroy(); + newText.GetComponent().Destroy(); scrollerNum -= 0.422f; @@ -604,14 +604,14 @@ public static class RoleSettingMenuPatches var categoryHeaderMasked = __instance.AdvancedRolesSettings.transform.Find("CategoryHeaderMasked").GetComponent(); - if (categoryHeaderMasked.Title.gameObject.TryGetComponent(out var comp)) + if (categoryHeaderMasked.Title.TryGetComponent(out var comp)) { comp.Destroy(); } categoryHeaderMasked.Title.text = "MiraApi.ReturnToRoleSettings".Translate(); - if (!categoryHeaderMasked.gameObject.TryGetComponent(out _)) + if (!categoryHeaderMasked.TryGetComponent(out _)) { var boxCol = categoryHeaderMasked.gameObject.AddComponent(); boxCol.size = new Vector2(7, 0.7f); diff --git a/MiraAPI/Patches/Options/SettingPatches.cs b/MiraAPI/Patches/Options/SettingPatches.cs index 1ef854b5..df2a31c7 100644 --- a/MiraAPI/Patches/Options/SettingPatches.cs +++ b/MiraAPI/Patches/Options/SettingPatches.cs @@ -52,7 +52,7 @@ public static class SettingPatches MiraNumberSuffixes.None => part, MiraNumberSuffixes.Multiplier => part + "x", MiraNumberSuffixes.Percent => part + "%", - MiraNumberSuffixes.Distance => string.Concat(part, " ", MiraApiPlugin.DistanceSuffix.Value), + MiraNumberSuffixes.Distance => part + MiraApiPlugin.DistanceSuffix.Value, _ => TranslationController.Instance.GetString(StringNames.GameSecondsAbbrev, part), }; } @@ -69,7 +69,7 @@ public static class SettingPatches MiraNumberSuffixes.None => part, MiraNumberSuffixes.Multiplier => part + "x", MiraNumberSuffixes.Percent => part + "%", - MiraNumberSuffixes.Distance => string.Concat(part, " ", MiraApiPlugin.DistanceSuffix.Value), + MiraNumberSuffixes.Distance => part + MiraApiPlugin.DistanceSuffix.Value, _ => TranslationController.Instance.GetString(StringNames.GameSecondsAbbrev, part), }; } diff --git a/MiraAPI/Patches/PlayerControlPatches.cs b/MiraAPI/Patches/PlayerControlPatches.cs index 791334d8..89c78e36 100644 --- a/MiraAPI/Patches/PlayerControlPatches.cs +++ b/MiraAPI/Patches/PlayerControlPatches.cs @@ -22,12 +22,12 @@ internal static class PlayerControlPatches [HarmonyPatch(nameof(PlayerControl.Start))] public static void PlayerControlStartPostfix(PlayerControl __instance) { - if (__instance.gameObject.TryGetComponent(out var modifierComp)) + if (__instance.TryGetComponent(out var modifierComp)) { modifierComp.DestroyImmediate(); } - if (__instance.gameObject.TryGetComponent(out var voteComp)) + if (__instance.TryGetComponent(out var voteComp)) { voteComp.DestroyImmediate(); } diff --git a/MiraAPI/Patches/RoleGuidePatches.cs b/MiraAPI/Patches/RoleGuidePatches.cs index c1fa5314..ee3cda49 100644 --- a/MiraAPI/Patches/RoleGuidePatches.cs +++ b/MiraAPI/Patches/RoleGuidePatches.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; +using System.Reflection; using AmongUs.GameOptions; using HarmonyLib; using Innersloth.Assets; @@ -296,7 +297,7 @@ public static class RoleGuidePatches if (_titleText) { _titleText.transform.localPosition += new Vector3(0.5f, 0); - _titleText.transform.GetComponent().Destroy(); + _titleText.GetComponent().Destroy(); } } @@ -656,7 +657,7 @@ public static class RoleGuidePatches _searchBoxTmp.Pipe.transform.localPosition = new Vector3( outputText.transform.localPosition.x - (outputText.rectTransform.sizeDelta.x * outputText.rectTransform.pivot.x), - outputText.transform.localPosition.y + _searchBoxTmp.caretYOffset, + outputText.transform.localPosition.y + GetCaretYOffset(_searchBoxTmp), -0.3f); } @@ -831,6 +832,25 @@ public static class RoleGuidePatches button.gameObject.AddComponent(); } + private static float GetCaretYOffset(TextBoxTMP box) + { + try + { + var prop = typeof(TextBoxTMP).GetProperty("caretYOffset", BindingFlags.Instance | BindingFlags.Public); + + if (prop == null) + { + return 0f; + } + + return Convert.ToSingle(prop.GetValue(box), CultureInfo.InvariantCulture); + } + catch + { + return 0f; + } + } + private static void SetupSearchButton(PassiveButton button, string objName, Action onClick, Sprite inactive, Sprite hover, Vector3 pos, out SpriteRenderer inactiveSprite, out SpriteRenderer hoverSprite) { button.name = objName; @@ -942,13 +962,13 @@ public static class RoleGuidePatches private sealed class DetailedPanel(string title, string category, string modId, RoleBehaviour? role, GameModifier? modifier, uint typeId) { + public string Title => title; + public string Category => category; + public string ModId => modId; + public RoleBehaviour? Role => role; + public GameModifier? Modifier => modifier; + public uint TypeId => typeId; public MatchInfoRolePanel? Panel { get; set; } - public string Title { get; } = title; - public string Category { get; } = category; - public string ModId { get; } = modId; - public RoleBehaviour? Role { get; } = role; - public GameModifier? Modifier { get; } = modifier; - public uint TypeId { get; } = typeId; public int Amount { get; set; } public int Chance { get; set; } public float Likelihood { get; set; } @@ -1565,20 +1585,13 @@ public static class RoleGuidePatches private static void SetupPanelButton(MatchInfoRolePanel panel, Action onClick) { - var collider = panel.roleIcon.gameObject.GetComponent(); - if (!collider) - { - collider = panel.roleIcon.gameObject.AddComponent(); - } + var collider = panel.roleIcon.gameObject.GetOrAddComponent(); collider.size = new Vector2(0.13f, 0.13f); collider.offset = new Vector2(0, 0); collider.enabled = true; - var passiveButton = panel.roleIcon.gameObject.GetComponent(); - if (!passiveButton) - { - passiveButton = panel.roleIcon.gameObject.AddComponent(); - } + + var passiveButton = panel.roleIcon.gameObject.GetOrAddComponent(); passiveButton.enabled = true; passiveButton.ClickSound = HudManager.Instance.MapButton.ClickSound; diff --git a/MiraAPI/Patches/Roles/RoleManagerPatches.cs b/MiraAPI/Patches/Roles/RoleManagerPatches.cs index 82e937fc..82cf9911 100644 --- a/MiraAPI/Patches/Roles/RoleManagerPatches.cs +++ b/MiraAPI/Patches/Roles/RoleManagerPatches.cs @@ -37,7 +37,7 @@ public static class RoleManagerPatches Object.Destroy(data.Role.gameObject); } - var roleBehaviour = Object.Instantiate(__instance.AllRoles.ToArray().First(r => r.Role == roleType), data.gameObject.transform); + var roleBehaviour = Object.Instantiate(__instance.AllRoles.ToArray().First(r => r.Role == roleType), data.transform); roleBehaviour.Initialize(targetPlayer); targetPlayer.Data.Role = roleBehaviour; targetPlayer.Data.RoleType = roleType; diff --git a/MiraAPI/Patches/Roles/TaskPanelPatch.cs b/MiraAPI/Patches/Roles/TaskPanelPatch.cs index c858d9f0..e97646da 100644 --- a/MiraAPI/Patches/Roles/TaskPanelPatch.cs +++ b/MiraAPI/Patches/Roles/TaskPanelPatch.cs @@ -15,7 +15,7 @@ internal static class TaskPanelPatch [HarmonyPatch(nameof(TaskPanelBehaviour.Update))] public static bool UpdatePrefix(TaskPanelBehaviour __instance) { - if (__instance.gameObject.name != "RolePanel") + if (__instance.name != "RolePanel") { return true; } diff --git a/MiraAPI/PluginLoading/IMiraPlugin.cs b/MiraAPI/PluginLoading/IMiraPlugin.cs index c77a97e0..f1f9fc30 100644 --- a/MiraAPI/PluginLoading/IMiraPlugin.cs +++ b/MiraAPI/PluginLoading/IMiraPlugin.cs @@ -58,6 +58,11 @@ public interface IMiraPlugin /// string CustomOptionMenuTwoDescription => "Apply game settings for this mod!"; + /// + /// Gets a value indicating whether the plugin is in debug mode. + /// + bool DebugMode => false; + /// /// Gets the for the plugin. /// diff --git a/MiraAPI/PluginLoading/MiraPluginInfo.cs b/MiraAPI/PluginLoading/MiraPluginInfo.cs index ca7812cd..4bbfe363 100644 --- a/MiraAPI/PluginLoading/MiraPluginInfo.cs +++ b/MiraAPI/PluginLoading/MiraPluginInfo.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Reflection; using BepInEx; using BepInEx.Configuration; using MiraAPI.GameModes; @@ -17,12 +18,13 @@ namespace MiraAPI.PluginLoading; /// public class MiraPluginInfo { - internal MiraPluginInfo(IMiraPlugin miraPlugin, PluginInfo info) + internal MiraPluginInfo(IMiraPlugin miraPlugin, PluginInfo info, Assembly assembly) { MiraPlugin = miraPlugin; PluginConfig = miraPlugin.GetConfigFile(); PluginInfo = info; PluginId = info.Metadata.GUID; + PluginAssembly = assembly; } /// @@ -45,6 +47,16 @@ public class MiraPluginInfo /// public ConfigFile PluginConfig { get; } + /// + /// Gets the plugin's . + /// + public Assembly PluginAssembly { get; } + + /// + /// Gets a value indicating whether the plugin is in debug mode. + /// + public bool DebugMode => MiraPlugin.DebugMode; + /// /// Gets a of this 's s. This is not safe for s with constructors. /// diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs index 596a4975..d0bcaa14 100644 --- a/MiraAPI/PluginLoading/MiraPluginManager.cs +++ b/MiraAPI/PluginLoading/MiraPluginManager.cs @@ -9,24 +9,19 @@ using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using BepInEx.Unity.IL2CPP; -using HarmonyLib; using MiraAPI.Colors; using MiraAPI.Events; using MiraAPI.GameEnd; using MiraAPI.GameModes; using MiraAPI.GameOptions; -using MiraAPI.GameOptions.Attributes; using MiraAPI.Hud; using MiraAPI.Keybinds; using MiraAPI.LocalSettings; -using MiraAPI.LocalSettings.Attributes; using MiraAPI.MeetingAbilities; using MiraAPI.Modifiers; using MiraAPI.Presets; using MiraAPI.Roles; -using MiraAPI.Translation; using MiraAPI.Utilities; -using Reactor.Networking; namespace MiraAPI.PluginLoading; @@ -40,10 +35,10 @@ public sealed class MiraPluginManager { } - private const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - private const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + internal const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + internal const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - private readonly Dictionary _registeredPlugins = []; + private readonly Dictionary _registeredPlugins = []; internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = []; internal MiraPluginInfo[] RegisteredPluginsWithOptions { get; private set; } = []; @@ -104,7 +99,7 @@ public sealed class MiraPluginManager private MiraPluginInfo RegisterPlugin(Assembly assembly, IMiraPlugin plugin, PluginInfo pluginInfo, BasePlugin basePlugin, bool isMira) { - var info = new MiraPluginInfo(plugin, pluginInfo); + var info = new MiraPluginInfo(plugin, pluginInfo, assembly); var roles = new List(); var oldConfigSetting = info.PluginConfig.SaveOnConfigSet; @@ -117,7 +112,7 @@ public sealed class MiraPluginManager info.InternalOptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority)); QueuedRoleRegistrations.Add(info, roles); - _registeredPlugins.Add(assembly, info); + _registeredPlugins.Add(pluginInfo.Metadata.GUID, info); info.SavePublicCollections(); PresetManager.CreateDefaultPreset(info); @@ -126,12 +121,13 @@ public sealed class MiraPluginManager return info; } - private static bool IsAutoPropertyBackingField(FieldInfo field) + internal static bool IsAutoPropertyBackingField(FieldInfo field) { return field.IsDefined(false) && - field.Name.Contains(">k__BackingField", StringComparison.Ordinal); + field.Name.Contains(">k__BackingField", StringComparison.Ordinal); } + [SuppressMessage("Minor Code Smell", "S3626:Jump statements should not be redundant", Justification = "Code consistency.")] private static void ProcessAssemblyTypes(Assembly assembly, MiraPluginInfo info, BasePlugin basePlugin, IMiraPlugin plugin, List roles, bool isMira) { foreach (var type in assembly.GetTypes()) @@ -141,21 +137,30 @@ public sealed class MiraPluginManager RegisterEvents(type); - if (RegisterModifier(type, info)) - continue; - if (RegisterOptions(type, info)) continue; if (RegisterLocalTabs(type, basePlugin)) continue; + if (RegisterColors(type, info)) + continue; + if (RegisterRole(type, info, roles)) continue; + if (RegisterModifier(type, info)) + continue; + if (RegisterButton(type, info)) continue; + if (RegisterKeybinds(type, plugin)) + continue; + + if (RegisterGameModeAttribute(type, info)) + continue; + if (RegisterGameOver(type)) continue; @@ -164,37 +169,18 @@ public sealed class MiraPluginManager if (RegisterTargetedMeetingAbility(type, info)) continue; - - if (RegisterGameModeAttribute(type, info)) - continue; - - if (!RegisterColorClasses(type)) - RegisterKeybinds(type, plugin); } } private static void RegisterEvents(Type type) { - foreach (var method in AccessTools.GetDeclaredMethods(type)) + try { - if (!method.TryGetCustomAttribute(out var eventAttribute)) - continue; - - if (!method.IsStatic) - { - Error($"Event method {method.Name} in {type.Name} must be static."); - continue; - } - - var parameters = method.GetParameters(); - if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent))) - { - Error($"Invalid event registration method {method.Name} in {type.Name}"); - continue; - } - - var paramType = parameters[0].ParameterType; - MiraEventManager.RegisterEventHandler(paramType, method, eventAttribute.Priority); + MiraEventManager.RegisterEvents(type); + } + catch (Exception e) + { + Error($"Failed to register events in {type.Name}: {e}"); } } @@ -205,7 +191,7 @@ public sealed class MiraPluginManager /// A . public static MiraPluginInfo? GetPluginByGuid(string pluginId) { - return Instance._registeredPlugins.Values.FirstOrDefault(plugin => plugin.PluginId == pluginId); + return Instance._registeredPlugins.GetValueOrDefault(pluginId); } private static bool RegisterGameOver(Type type) @@ -221,73 +207,11 @@ public sealed class MiraPluginManager } } - private static readonly Type OptionType = typeof(IModdedOption); - private static readonly Type OptionListType = typeof(IModdedOptionList); - private static bool RegisterOptions(Type type, MiraPluginInfo pluginInfo) { try { - if (!type.IsAssignableTo(typeof(AbstractOptionGroup))) - { - return false; - } - - if (!ModdedOptionsManager.RegisterGroup(type, pluginInfo)) - { - return false; - } - - foreach (var property in type.GetProperties(DeclaredInstanceMembers)) - { - if (property.IsDefined()) - continue; - - if (property.GetMethod == null) - { - Error($"Non-ignored option property {property.Name} in {type.Name} must at least have a getter."); - continue; - } - - var propType = property.PropertyType; - - if (propType.IsAssignableTo(OptionType)) - { - ModdedOptionsManager.RegisterPropertyOption(type, property, pluginInfo); - continue; - } - - if (propType.IsAssignableTo(OptionListType)) - { - ModdedOptionsManager.RegisterPropertyOptionList(type, property, pluginInfo); - continue; - } - - var attributes = property.GetCustomAttributes(false); - - foreach (var attr in attributes) - { - if (attr is ModdedOptionAttribute moddedAttr) - { - ModdedOptionsManager.RegisterAttributeOption(type, moddedAttr, property, pluginInfo, propType, attributes); - break; - } - - if (attr is ModdedOptionListAttribute listAttr) - { - ModdedOptionsManager.RegisterAttributeOptionList(type, listAttr, property, pluginInfo, propType, attributes); - break; - } - } - } - - foreach (var field in type.GetFields(DeclaredInstanceMembers) - .Where(f => !IsAutoPropertyBackingField(f) && (f.FieldType.IsAssignableTo(OptionType) || f.FieldType.IsAssignableTo(OptionListType)))) - { - Error($"{field.Name} is a field, not a property. Use properties for options."); - } - - return true; + return ModdedOptionsManager.RegisterGroup(type, pluginInfo); } catch (Exception e) { @@ -301,19 +225,7 @@ public sealed class MiraPluginManager { try { - if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type))) - { - return false; - } - - if (!ModList.GetById(pluginInfo.PluginId).IsRequiredOnAllClients) - { - Error("Custom roles are only supported on all clients."); - return false; - } - - roles.Add(type); - return true; + return CustomRoleManager.RegisterRole(type, pluginInfo, roles); } catch (Exception e) { @@ -323,46 +235,11 @@ public sealed class MiraPluginManager return false; } - private static bool RegisterColorClasses(Type type) + private static bool RegisterColors(Type type, MiraPluginInfo miraPlugin) { try { - if (type.GetCustomAttribute() == null) - { - return false; - } - - if (!type.IsStatic()) - { - Error($"Color class {type.Name} must be static."); - return false; - } - - foreach (var property in type.GetProperties(DeclaredStaticMembers)) - { - if (!property.PropertyType.IsAssignableTo(typeof(CustomColor))) - { - continue; - } - - if (property.GetValue(null) is not CustomColor color) - { - Error($"Color property {property.Name} in {type.Name} is not a CustomColor."); - continue; - } - - PaletteManager.CustomColors.Add(color); - - if (color is VariableColor) - PaletteManager.VariableColorNames.Add(color.Name); - } - - foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor)))) - { - Error($"{field.Name} is a field, not a property. Use properties for colors."); - } - - return true; + return PaletteManager.RegisterColors(type, miraPlugin); } catch (Exception e) { @@ -381,8 +258,9 @@ public sealed class MiraPluginManager catch (Exception e) { Error($"Failed to register modifier {type.Name}: {e}"); - return false; } + + return false; } private static bool RegisterButton(Type type, MiraPluginInfo pluginInfo) @@ -403,8 +281,7 @@ public sealed class MiraPluginManager { try { - if (typeof(AbstractGameMode).IsAssignableFrom(type)) - return CustomGameModeManager.RegisterGameMode(type, pluginInfo); + return CustomGameModeManager.RegisterGameMode(type, pluginInfo); } catch (Exception e) { @@ -418,55 +295,7 @@ public sealed class MiraPluginManager { try { - if (!type.IsAssignableTo(typeof(LocalSettingsTab))) - { - return false; - } - - if (!LocalSettingsManager.RegisterTab(type, pluginInfo)) - { - return false; - } - - if (!LocalSettingsManager.TypeToTab.TryGetValue(type, out var tabInstance)) - { - return false; - } - - foreach (var property in type.GetProperties(DeclaredInstanceMembers)) - { - if (property.IsDefined() && - property.PropertyType.IsAssignableTo(typeof(LocalSettingsButton))) - { - var button = property.GetValue(tabInstance) as LocalSettingsButton; - button!.Tab = tabInstance; - tabInstance.Buttons.Add(button); - continue; - } - - if (!typeof(ConfigEntryBase).IsAssignableFrom(property.PropertyType)) - { - continue; - } - - if (property.GetValue(tabInstance) is not ConfigEntryBase configEntry) - { - Error($"Option property {property.Name} in {type.Name} has to be a config entry."); - continue; - } - - if (property.TryGetCustomAttribute(out var attribute)) - { - attribute.CreateSetting(type, configEntry); - } - } - - foreach (var field in type.GetFields(DeclaredInstanceMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.IsDefined())) - { - Error($"{field.Name} is a field, not a property. Use properties for local settings."); - } - - return true; + return LocalSettingsManager.RegisterLocalTabs(type, pluginInfo); } catch (Exception e) { @@ -476,47 +305,18 @@ public sealed class MiraPluginManager return false; } - private static void RegisterKeybinds(Type type, IMiraPlugin plugin) + private static bool RegisterKeybinds(Type type, IMiraPlugin plugin) { try { - if (!type.IsDefined()) - { - return; - } - - if (!type.IsStatic()) - { - Error($"Keybinds class {type.Name} must be static."); - return; - } - - foreach (var property in type.GetProperties(DeclaredStaticMembers)) - { - if (property.PropertyType != typeof(MiraKeybind)) - { - continue; - } - - if (property.GetValue(null) is not MiraKeybind keybind) - { - Error($"Keybind property {property.Name} in {type.Name} is not a MiraKeybind."); - continue; - } - - KeybindManager.Keybinds.Add(keybind); - keybind.SourcePluginName = plugin.OptionsTitleText.Translate(); - } - - foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind)))) - { - Error($"{field.Name} is a field, not a property. Use properties for keybinds."); - } + return KeybindManager.RegisterKeybinds(type, plugin); } catch (Exception e) { Error($"Failed to register keybind class {type.Name}: {e}"); } + + return false; } private static bool RegisterMeetingAbility(Type type, MiraPluginInfo info) @@ -528,8 +328,9 @@ public sealed class MiraPluginManager catch (Exception e) { Error($"Failed to register meeting ability {type.Name}: {e}"); - return false; } + + return false; } private static bool RegisterTargetedMeetingAbility(Type type, MiraPluginInfo info) @@ -541,7 +342,8 @@ public sealed class MiraPluginManager catch (Exception e) { Error($"Failed to register targeted meeting ability {type.Name}: {e}"); - return false; } + + return false; } } diff --git a/MiraAPI/Presets/OptionPreset.cs b/MiraAPI/Presets/OptionPreset.cs index 6ecab1fd..90eb3894 100644 --- a/MiraAPI/Presets/OptionPreset.cs +++ b/MiraAPI/Presets/OptionPreset.cs @@ -18,22 +18,22 @@ public class OptionPreset(string name, MiraPluginInfo plugin, ConfigFile presetC /// /// Gets the name of the preset. /// - public string Name { get; } = name; + public string Name => name; /// /// Gets the plugin associated with the preset. /// - public MiraPluginInfo Plugin { get; } = plugin; + public MiraPluginInfo Plugin => plugin; /// /// Gets the of the plugin associated with the preset. /// - public ConfigFile PluginConfig { get; } = plugin.PluginConfig; + public ConfigFile PluginConfig => plugin.PluginConfig; /// /// Gets the for the preset. /// - public ConfigFile PresetConfig { get; } = presetConfig; + public ConfigFile PresetConfig => presetConfig; /// /// Gets or sets the button associated with the preset in the UI. diff --git a/MiraAPI/Presets/SavePresetPopup.cs b/MiraAPI/Presets/SavePresetPopup.cs index 9405e83b..d2db31ba 100644 --- a/MiraAPI/Presets/SavePresetPopup.cs +++ b/MiraAPI/Presets/SavePresetPopup.cs @@ -70,7 +70,7 @@ public class SavePresetPopup(nint cppPtr) : Minigame(cppPtr) foreach (var tmp in gameObject.GetComponentsInChildren()) { - if (tmp.gameObject.transform.parent.name == "Textbox") + if (tmp.transform.parent.name == "Textbox") { continue; } diff --git a/MiraAPI/Roles/CustomRoleManager.cs b/MiraAPI/Roles/CustomRoleManager.cs index d89e40a9..a2a0164f 100644 --- a/MiraAPI/Roles/CustomRoleManager.cs +++ b/MiraAPI/Roles/CustomRoleManager.cs @@ -10,6 +10,7 @@ using MiraAPI.PluginLoading; using MiraAPI.Translation; using MiraAPI.Utilities; using MiraAPI.Utilities.Assets; +using Reactor.Networking; using Reactor.Networking.Rpc; using Reactor.Utilities.Extensions; using TMPro; @@ -118,6 +119,23 @@ public static class CustomRoleManager pluginInfo.PluginConfig.SaveOnConfigSet = oldConfigSetting; } + internal static bool RegisterRole(Type type, MiraPluginInfo miraPlugin, List roles) + { + if (!(typeof(RoleBehaviour).IsAssignableFrom(type) && typeof(ICustomRole).IsAssignableFrom(type))) + { + return false; + } + + if (!ModList.GetById(miraPlugin.PluginId).IsRequiredOnAllClients) + { + Error("Custom roles are only supported on all clients."); + return false; + } + + roles.Add(type); + return true; + } + private static RoleBehaviour? RegisterRole(Type roleType, MiraPluginInfo parentMod) { if (!(typeof(RoleBehaviour).IsAssignableFrom(roleType) && typeof(ICustomRole).IsAssignableFrom(roleType))) @@ -239,7 +257,7 @@ public static class CustomRoleManager internal static TaskPanelBehaviour CreateRoleTab(ICustomRole role) { - var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").gameObject.GetComponent(); + var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").GetComponent(); var clonePanel = Object.Instantiate(ogPanel.gameObject, ogPanel.transform.parent); clonePanel.name = "RolePanel"; @@ -257,8 +275,8 @@ public static class CustomRoleManager internal static void UpdateRoleTab(TaskPanelBehaviour panel, ICustomRole role) { - var tabText = panel.tab.gameObject.GetComponentInChildren(); - var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").gameObject.GetComponent(); + var tabText = panel.tab.GetComponentInChildren(); + var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").GetComponent(); if (tabText.text != role.RoleName) { tabText.text = role.RoleName; @@ -278,9 +296,9 @@ public static class CustomRoleManager .Select(x => ((ICustomRole)x).GetNetData()) .ChunkNetData(1000); - while (data.Count > 0) + while (data.TryDequeue(out var netData)) { - Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, data.Dequeue())); + Rpc.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData)); } } diff --git a/MiraAPI/Utilities/Extensions.cs b/MiraAPI/Utilities/Extensions.cs index 0446e84f..d3a0fbae 100644 --- a/MiraAPI/Utilities/Extensions.cs +++ b/MiraAPI/Utilities/Extensions.cs @@ -843,6 +843,21 @@ public static class Extensions return comp ? comp : go.AddComponent(); } + /// + /// Gets a component that is attached to the provided , attaching and returning the component if it wasn't found, and returns a bool that indicates if the component already existed before. + /// + /// The component type. + /// The to get the component from. + /// When this method returns true if the component already existed; otherwise false. + /// The component. + public static T GetOrAddComponent(this GameObject go, out bool exists) + where T : Component + { + var comp = go.GetComponent(); + exists = comp; + return exists ? comp : go.AddComponent(); + } + /// /// The type of the attribute. /// true if a custom attribute of type is applied to element; otherwise, false. diff --git a/MiraAPI/Utilities/GuideOptionsPatches.cs b/MiraAPI/Utilities/GuideOptionsPatches.cs index 1c0b57ea..f9bc6988 100644 --- a/MiraAPI/Utilities/GuideOptionsPatches.cs +++ b/MiraAPI/Utilities/GuideOptionsPatches.cs @@ -29,13 +29,13 @@ internal sealed class GuideOptionPage( IReadOnlyList modSearchTerms, List entries) { - public AbstractOptionGroup Group { get; } = group; + public AbstractOptionGroup Group => group; public List Groups { get; } = [group]; - public string Title { get; } = title; + public string Title => title; - public LoadableAsset Sprite { get; } = group.Sprite; + public LoadableAsset Sprite => group.Sprite; public int Order { get; set; } = order; @@ -43,13 +43,13 @@ internal sealed class GuideOptionPage( public uint GroupPriority { get; set; } = groupPriority; - public int Columns { get; } = columns; + public int Columns => columns; - public string ModAbbreviation { get; } = modAbbreviation; + public string ModAbbreviation => modAbbreviation; public HashSet ModSearchTerms { get; } = new(modSearchTerms, StringComparer.OrdinalIgnoreCase); - public List Entries { get; } = entries; + public List Entries => entries; } internal static class GuideOptionPages diff --git a/MiraAPI/Utilities/Helpers.cs b/MiraAPI/Utilities/Helpers.cs index 613c8457..0c24c972 100644 --- a/MiraAPI/Utilities/Helpers.cs +++ b/MiraAPI/Utilities/Helpers.cs @@ -117,7 +117,7 @@ public static class Helpers { var keybindIcon = Object.Instantiate(HudManager.Instance.AbilityButton.usesRemainingSprite.gameObject, button.transform); keybindIcon.GetComponent().sprite = MiraAssets.KeybindButton.LoadAsset(); - keybindIcon.transform.GetComponentInChildren().text = keyCode.ToString(); + keybindIcon.GetComponentInChildren().text = keyCode.ToString(); keybindIcon.name = "KeybindIcon"; keybindIcon.transform.localPosition = localPos; return keybindIcon; @@ -131,26 +131,21 @@ public static class Helpers /// THe corresponding method to patch. public static MethodBase? GetStateMachineMoveNext(string methodName) { - var typeName = typeof(T).FullName; - var showRoleStateMachine = - typeof(T) - .GetNestedTypes() - .FirstOrDefault(x => x.Name.Contains(methodName)); + var stateMachine = typeof(T).GetNestedTypes().FirstOrDefault(x => x.Name.Contains(methodName, StringComparison.Ordinal)); - if (showRoleStateMachine == null) + if (stateMachine == null) { - Error($"Failed to find {methodName} state machine for {typeName}"); + Error($"Failed to find {methodName} state machine for {typeof(T).FullName}"); return null; } - var moveNext = AccessTools.Method(showRoleStateMachine, "MoveNext"); + var moveNext = AccessTools.Method(stateMachine, "MoveNext"); + if (moveNext == null) - { - Error($"Failed to find MoveNext method for {typeName}.{methodName}"); - return null; - } + Error($"Failed to find MoveNext method for {typeof(T).FullName}.{methodName}"); + else + Info($"Found {methodName}.MoveNext"); - Info($"Found {methodName}.MoveNext"); return moveNext; } @@ -249,7 +244,7 @@ public static class Helpers { var prefab = Object.FindObjectOfType(true); var arrow = Object.Instantiate(prefab, parent); - arrow.image = arrow.gameObject.GetComponent(); + arrow.image = arrow.GetComponent(); arrow.image.color = color; arrow.gameObject.layer = 5; arrow.gameObject.SetActive(true); @@ -559,6 +554,7 @@ public static class Helpers MiraNumberSuffixes.Multiplier => "x", MiraNumberSuffixes.Seconds => "s", MiraNumberSuffixes.Percent => "%", + MiraNumberSuffixes.Distance => MiraApiPlugin.DistanceSuffix.Value, _ => string.Empty, }; } @@ -593,14 +589,14 @@ public static class Helpers /// The formatted value. public static string FormatValue(float value, MiraNumberSuffixes suffix = MiraNumberSuffixes.None, string formatString = "0.0") { + var part = value.ToString(formatString, NumberFormatInfo.InvariantInfo); return suffix switch { - MiraNumberSuffixes.None => value.ToString(formatString, NumberFormatInfo.InvariantInfo), - MiraNumberSuffixes.Multiplier => value.ToString(formatString, NumberFormatInfo.InvariantInfo) + "x", - MiraNumberSuffixes.Percent => value.ToString(formatString, NumberFormatInfo.InvariantInfo) + "%", - _ => TranslationController.Instance.GetString( - StringNames.GameSecondsAbbrev, - (Il2CppSystem.Object[])[value.ToString(formatString, CultureInfo.InvariantCulture)]), + MiraNumberSuffixes.None => part, + MiraNumberSuffixes.Percent => part + "%", + MiraNumberSuffixes.Multiplier => part + "x", + MiraNumberSuffixes.Distance => part + MiraApiPlugin.DistanceSuffix.Value, + _ => TranslationController.Instance.GetString(StringNames.GameSecondsAbbrev, part), }; } diff --git a/MiraAPI/Utilities/StateMachineWrapper.cs b/MiraAPI/Utilities/StateMachineWrapper.cs index 6b9d683d..cfe5d8a1 100644 --- a/MiraAPI/Utilities/StateMachineWrapper.cs +++ b/MiraAPI/Utilities/StateMachineWrapper.cs @@ -21,6 +21,7 @@ public class StateMachineWrapper private readonly PropertyInfo _stateProperty; private readonly PropertyInfo _currentProperty; private readonly Dictionary _propertyCache; + private readonly Type _type; private T? _parentInstance; @@ -37,14 +38,14 @@ public class StateMachineWrapper { _stateMachine = stateMachine; - var type = _stateMachine.GetType(); - _thisProperty = AccessTools.Property(type, "__4__this"); - _stateProperty = AccessTools.Property(type, "__1__state"); - _currentProperty = AccessTools.Property(type, "__2__current"); + _type = _stateMachine.GetType(); + _thisProperty = AccessTools.Property(_type, "__4__this"); + _stateProperty = AccessTools.Property(_type, "__1__state"); + _currentProperty = AccessTools.Property(_type, "__2__current"); if (_thisProperty == null || _stateProperty == null || _currentProperty == null) { - throw new MissingMemberException($"Could not find required properties in type '{type}'."); + throw new MissingMemberException($"Could not find required properties in type '{_type}'."); } _propertyCache = []; @@ -91,8 +92,8 @@ public class StateMachineWrapper return (TField)property.GetValue(_stateMachine)!; } - property = AccessTools.Property(_stateMachine.GetType(), parameterName) - ?? throw new MissingFieldException($"Could not find parameter '{parameterName}' in state machine of type '{_stateMachine.GetType()}'."); + property = AccessTools.Property(_type, parameterName) + ?? throw new MissingFieldException($"Could not find parameter '{parameterName}' in state machine of type '{_type.Name}'."); _propertyCache[parameterName] = property; return (TField)property.GetValue(_stateMachine)!;