Merge branch 'dev' into no-boxing

This commit is contained in:
Az committed 2026-11-07 04:00:37 -05:00
commit 79f54f87ff
97 files changed
+862 -678

No files matched your search

+5 -11
View File
@@ -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);
}
+81 -41
View File
@@ -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;
/// <summary>
/// Represents a custom color with a main color and a shadow color.
/// </summary>
/// <param name="name">The name of the option.</param>
/// <param name="nameId">The name of the option as a <see cref="StringNames"/> value.</param>
/// <param name="rawId">The name of the option as a <see cref="string"/> value.</param>
/// <param name="mainColor">The main color.</param>
/// <param name="shadowColor">The shadow color.</param>
/// <param name="brightness">The brightness type of the color.</param>
[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)
{
/// <summary>
/// Gets or sets the main color.
/// </summary>
public Color32 MainColor
{
get;
set
{
field = value;
InternalMainColor = value;
}
}
= mainColor;
private StringNames? name = nameId;
private CustomColorBrightness colorBrightness = brightness;
/// <summary>
/// Gets or sets the shadow color.
/// Gets the main color.
/// </summary>
public Color32 ShadowColor
{
get;
set
{
field = value;
InternalShadowColor = value;
}
}
= shadowColor;
public Color32 MainColor => mainColor;
/// <summary>
/// Gets or sets the name of the color.
/// Gets the shadow color.
/// </summary>
public StringNames Name { get; set; } = name;
public Color32 ShadowColor => shadowColor;
/// <summary>
/// Gets the name of the color.
/// </summary>
public StringNames Name
{
get
{
if (!name.HasValue && !string.IsNullOrEmpty(RawId))
name = MiraLocaleManager.GetOrCreateLocaleString(RawId);
return name.GetValueOrDefault();
}
internal set
{
name = value;
}
}
/// <summary>
/// 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;
/// <summary>
/// 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.
/// </summary>
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;
/// <inheritdoc cref="CustomColor"/>
public CustomColor(StringNames name, Color32 mainColor)
: this(name, mainColor, mainColor.DarkenAbsolute(60))
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(StringNames nameId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
: this(nameId, null, mainColor, shadowColor, brightness)
{
}
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor)
: this(name, mainColor, mainColor.DarkenAbsolute(60))
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(StringNames nameId, Color32 mainColor, CustomColorBrightness brightness)
: this(nameId, null, mainColor, mainColor.DarkenAbsolute(60), brightness)
{
}
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor, Color32 shadowColor)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor)
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(string rawId, Color32 mainColor, Color32 shadowColor, CustomColorBrightness brightness)
: this(null, rawId, mainColor, shadowColor, brightness)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
public CustomColor(string rawId, Color32 mainColor, CustomColorBrightness brightness)
: this(null, rawId, mainColor, mainColor.DarkenAbsolute(60), brightness)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[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)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[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)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[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)
{
}
/// <inheritdoc cref="CustomColor(StringNames?, string?, Color32, Color32, CustomColorBrightness)"/>
[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)
{
}
}
+58 -4
View File
@@ -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
/// </summary>
public static CustomColor[] RegisteredColors => [.. CustomColors];
internal static readonly List<CustomColor> CustomColors = [];
internal static readonly HashSet<StringNames> VariableColorNames = [];
private static readonly List<CustomColor> CustomColors = [];
private static readonly HashSet<StringNames> 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<RegisterCustomColorsAttribute>(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++;
@@ -5,5 +5,20 @@ namespace MiraAPI.Colors;
/// <summary>
/// Used to mark a class for <see cref="CustomColor"/> registration.
/// </summary>
/// <param name="idPrefix">The group translation ID prefix to attach to color names before registration.</param>
[AttributeUsage(AttributeTargets.Class)]
public class RegisterCustomColorsAttribute : Attribute;
public class RegisterCustomColorsAttribute(string idPrefix) : Attribute
{
/// <summary>
/// Gets the translation ID prefix for all of the colors within the container type.
/// </summary>
public string IdPrefix => idPrefix;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterCustomColorsAttribute"/> class.
/// </summary>
public RegisterCustomColorsAttribute()
: this(string.Empty)
{
}
}
+105 -17
View File
@@ -1,6 +1,5 @@
using System;
using MiraAPI.LocalSettings;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -9,40 +8,129 @@ namespace MiraAPI.Colors;
/// <summary>
/// Represents a dynamic custom color that changes over time.
/// </summary>
/// <param name="name">The name of the color.</param>
/// <param name="nameId">The name of the option as a <see cref="StringNames"/> value.</param>
/// <param name="rawId">The name of the option as a <see cref="string"/> value.</param>
/// <param name="mainEvaluator">The function to evaluate the dynamic main color.</param>
/// <param name="shadowEvaluator">The function to evaluate the dynamic shadow color.</param>
/// <param name="mainColor">The static main color used when dynamic colors are disabled.</param>
/// <param name="shadowColor">The static shadow color used when dynamic colors are disabled.</param>
/// <param name="defaultTime">The default time that is used to automatically fill in the static colors when the latter is not provided.</param>
public sealed class VariableColor(StringNames name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: CustomColor(name, mainColor ?? mainEvaluator(defaultTime), shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).DarkenAbsolute(60))
/// <param name="brightness">The brightness type of the color.</param>
public sealed class VariableColor(
StringNames? nameId,
string? rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? 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)
{
/// <summary>
/// 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.
/// </summary>
public Func<float, Color> MainEvaluator { get; set; } = mainEvaluator;
public Func<float, Color> MainEvaluator => mainEvaluator;
/// <summary>
/// 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.
/// </summary>
public Func<float, Color> ShadowEvaluator { get; set; } = shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f));
public Func<float, Color> ShadowEvaluator => shadowEvaluator ?? (t => mainEvaluator(t).DarkenAbsolute(0.24f));
/// <inheritdoc cref="VariableColor"/>
public VariableColor(StringNames name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime)
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
CustomColorBrightness brightness,
Color32? mainColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, brightness)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
StringNames nameId,
Func<float, Color> mainEvaluator,
Color32? mainColor = null,
float defaultTime = 0f)
: this(nameId, null, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Func<float, Color>? shadowEvaluator,
Color32? mainColor = null,
Color32? shadowColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime, CustomColorBrightness.Darker)
{
}
/// <inheritdoc cref="VariableColor(StringNames?, string?, Func{float, Color}, Func{float, Color}?, Color32?, Color32?, float, CustomColorBrightness)"/>
public VariableColor(
string rawId,
Func<float, Color> mainEvaluator,
Color32? mainColor = null,
float defaultTime = 0f)
: this(null, rawId, mainEvaluator, null, mainColor, null, defaultTime, CustomColorBrightness.Darker)
{
}
@@ -13,7 +13,7 @@ public sealed class MiraButtonCancelledEvent<T>(T button) : MiraEvent
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public T Button { get; } = button;
public T Button => button;
}
/// <summary>
@@ -25,5 +25,5 @@ public sealed class MiraButtonCancelledEvent(CustomActionButton button) : MiraEv
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public CustomActionButton Button { get; } = button;
public CustomActionButton Button => button;
}
+3 -3
View File
@@ -14,12 +14,12 @@ public class MiraButtonClickEvent<T>(T button, MiraButtonClickEvent genericClick
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public T Button { get; } = button;
public T Button => button;
/// <summary>
/// Gets the generic <see cref="MiraButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public MiraButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
public MiraButtonClickEvent GenericClickEvent => genericClickEvent;
}
/// <summary>
@@ -31,5 +31,5 @@ public class MiraButtonClickEvent(CustomActionButton button) : MiraCancelableEve
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public CustomActionButton Button { get; } = button;
public CustomActionButton Button => button;
}
@@ -12,10 +12,10 @@ public class UiButtonPostResetEvent(GameObject topUiRow, GameObject secondUiRow)
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the very top UI row.
/// </summary>
public GameObject MainTopUiRow { get; } = topUiRow;
public GameObject MainTopUiRow => topUiRow;
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the second top UI row.
/// </summary>
public GameObject SecondTopUiRow { get; } = secondUiRow;
public GameObject SecondTopUiRow => secondUiRow;
}
+22
View File
@@ -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<RegisterEventAttribute>(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);
}
}
}
+2 -2
View File
@@ -12,10 +12,10 @@ public class MiraEventWrapper(Delegate eventHandler, int priority)
/// <summary>
/// Gets the event handler delegate.
/// </summary>
public Delegate EventHandler { get; } = eventHandler;
public Delegate EventHandler => eventHandler;
/// <summary>
/// Gets the priority of the handler. Lower values are called first.
/// </summary>
public int Priority { get; } = priority;
public int Priority => priority;
}
+1 -1
View File
@@ -12,5 +12,5 @@ public class RegisterEventAttribute(int priority = 0) : Attribute
/// <summary>
/// Gets the priority of the event. Lower values are called first.
/// </summary>
public int Priority { get; } = priority;
public int Priority => priority;
}
@@ -14,33 +14,33 @@ public class AfterMurderEvent(PlayerControl source, PlayerControl target, Player
/// <summary>
/// Gets the <see cref="PlayerControl"/> that killed the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; } = source;
public PlayerControl Source => source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was killed.
/// </summary>
public PlayerControl Target { get; } = target;
public PlayerControl Target => target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was framed, if any.
/// </summary>
public PlayerControl? Framed { get; } = framed;
public PlayerControl? Framed => framed;
/// <summary>
/// Gets a value indicating whether the murder was done indirectly.
/// This is commonly used to prevent the <see cref="Source"/> <see cref="PlayerControl"/> from being killed.
/// </summary>
public bool IsIndirectAttack { get; } = isIndirect;
public bool IsIndirectAttack => isIndirect;
/// <summary>
/// Gets a value indicating whether the murder was able to bypass protective roles or general defense, such as <see cref="GuardianAngelRole"/>.
/// </summary>
public bool IgnoreDefense { get; } = ignoreDefense;
public bool IgnoreDefense => ignoreDefense;
/// <summary>
/// Gets the <see cref="Target"/>'s <see cref="DeadBody"/>, if it exists.
/// </summary>
public DeadBody? DeadBody { get; } = deadBody;
public DeadBody? DeadBody => deadBody;
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
@@ -9,5 +9,5 @@ public class BeforeGameEndEvent(GameOverReason reason) : MiraCancelableEvent
/// <summary>
/// Gets the reason for the game end.
/// </summary>
public GameOverReason Reason { get; } = reason;
public GameOverReason Reason => reason;
}
@@ -17,22 +17,22 @@ public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is killing the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; } = source;
public PlayerControl Source => source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being killed.
/// </summary>
public PlayerControl Target { get; } = target;
public PlayerControl Target => target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being framed, if any.
/// </summary>
public PlayerControl? Framed { get; } = framed;
public PlayerControl? Framed => framed;
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting { get; } = inMeeting;
public MeetingCheck InMeeting => inMeeting;
/// <summary>
/// Gets or sets a value indicating whether the murder is done indirectly.
@@ -9,5 +9,5 @@ public class BeforeRoundStartEvent(bool triggeredByIntro) : MiraCancelableEvent
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; } = triggeredByIntro;
public bool TriggeredByIntro => triggeredByIntro;
}
@@ -9,5 +9,5 @@ public class GameEndEvent(EndGameManager manager) : MiraEvent
/// <summary>
/// Gets the <see cref="global::EndGameManager"/> instance.
/// </summary>
public EndGameManager EndGameManager { get; } = manager;
public EndGameManager EndGameManager => manager;
}
@@ -9,5 +9,5 @@ public class IntroBeginEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -9,5 +9,5 @@ public class IntroRoleRevealEvent(IntroCutscene introCutscene) : MiraEvent
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; } = introCutscene;
public IntroCutscene IntroCutscene => introCutscene;
}
@@ -10,5 +10,5 @@ public class RoundStartEvent(bool triggeredByIntro) : MiraEvent
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; } = triggeredByIntro;
public bool TriggeredByIntro => triggeredByIntro;
}
@@ -12,10 +12,10 @@ public class SetRoleEvent(PlayerControl player, RoleTypes role) : MiraEvent
/// <summary>
/// Gets the <see cref="PlayerControl"/> whose role was changed.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the role that the player was set to.
/// </summary>
public RoleTypes Role { get; } = role;
public RoleTypes Role => role;
}
@@ -13,7 +13,7 @@ public sealed class VanillaButtonCancelledEvent<T>(T button) : MiraEvent
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public T Button { get; } = button;
public T Button => button;
}
/// <summary>
@@ -25,5 +25,5 @@ public sealed class VanillaButtonCancelledEvent(AbilityButton button) : MiraEven
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public AbilityButton Button { get; } = button;
public AbilityButton Button => button;
}
@@ -14,12 +14,12 @@ public sealed class VanillaButtonClickEvent<T>(T button, VanillaButtonClickEvent
/// <summary>
/// Gets the vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public T Button { get; } = button;
public T Button => button;
/// <summary>
/// Gets the generic <see cref="VanillaButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public VanillaButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
public VanillaButtonClickEvent GenericClickEvent => genericClickEvent;
}
/// <summary>
@@ -33,15 +33,15 @@ public sealed class VanillaButtonClickEvent(AbilityButton button, PlayerControl?
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public AbilityButton Button { get; } = button;
public AbilityButton Button => button;
/// <summary>
/// Gets the target <see cref="PlayerControl"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public PlayerControl? PlayerTarget { get; } = playerTarget;
public PlayerControl? PlayerTarget => playerTarget;
/// <summary>
/// Gets the target <see cref="Vent"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public Vent? VentTarget { get; } = ventTarget;
public Vent? VentTarget => ventTarget;
}
@@ -9,5 +9,5 @@ public class CloseDoorsEvent(SystemTypes room) : MiraCancelableEvent
/// <summary>
/// Gets the room that the doors were closed in.
/// </summary>
public SystemTypes Room { get; } = room;
public SystemTypes Room => room;
}
@@ -9,5 +9,5 @@ public class PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) : MiraCancelable
/// <summary>
/// Gets the <see cref="global::MapBehaviour"/>.
/// </summary>
public MapBehaviour MapBehaviour { get; } = mapBehaviour;
public MapBehaviour MapBehaviour => mapBehaviour;
}
@@ -11,15 +11,15 @@ public class UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byt
/// <summary>
/// Gets the type of system that will be updated.
/// </summary>
public SystemTypes SystemType { get; } = systemType;
public SystemTypes SystemType => systemType;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is updating the system.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the byte amount the system is being updated by.
/// </summary>
public byte Amount { get; } = amount;
public byte Amount => amount;
}
@@ -9,5 +9,5 @@ public class EjectionEvent(ExileController controller) : MiraEvent
/// <summary>
/// Gets the <see cref="global::ExileController"/> instance.
/// </summary>
public ExileController ExileController { get; } = controller;
public ExileController ExileController => controller;
}
@@ -9,5 +9,5 @@ public class EndMeetingEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -12,15 +12,15 @@ public class ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target
/// <summary>
/// Gets the player that is reporting the body.
/// </summary>
public PlayerControl Reporter { get; } = reporter;
public PlayerControl Reporter => reporter;
/// <summary>
/// Gets the player that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target { get; } = target;
public NetworkedPlayerInfo? Target => target;
/// <summary>
/// Gets the <see cref="DeadBody"/> that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public DeadBody? Body { get; } = body;
public DeadBody? Body => body;
}
@@ -10,5 +10,5 @@ public class StartMeetingEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -10,10 +10,10 @@ public class AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
public PlayerVoteArea VoteArea => playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = voter;
public PlayerControl Player => voter;
}
@@ -10,10 +10,10 @@ public class BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
public PlayerVoteArea VoteArea => playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = voter;
public PlayerControl Player => voter;
}
@@ -9,7 +9,7 @@ public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent
/// <summary>
/// Gets a value indicating whether default voting logic determines that voting is complete.
/// </summary>
public bool IsVotingComplete { get; } = isVotingComplete;
public bool IsVotingComplete => isVotingComplete;
/// <summary>
/// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic.
@@ -13,12 +13,12 @@ public class DummyVoteEvent(DummyBehaviour dummy) : MiraCancelableEvent
/// <summary>
/// Gets the dummy that needs to vote.
/// </summary>
public DummyBehaviour Dummy { get; } = dummy;
public DummyBehaviour Dummy => dummy;
/// <summary>
/// Gets the instance of the dummy's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = dummy.myPlayer.GetVoteData();
public PlayerVoteData VoteData => dummy.myPlayer.GetVoteData();
/// <summary>
/// Gets or sets a value indicating whether the dummy can vote to skip the meeting.
@@ -17,18 +17,18 @@ public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = playerVoteData;
public PlayerVoteData VoteData => playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId => targetId;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; } = playerVoteData.Owner;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId { get; } = targetId;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
/// </summary>
@@ -13,12 +13,12 @@ public class MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, boo
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; } = playerVoteData;
public PlayerVoteData VoteData => playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public int TargetId { get; } = targetId;
public int TargetId => targetId;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
@@ -15,5 +15,5 @@ public class PopulateResultsEvent(List<CustomVote> votes) : MiraCancelableEvent
/// <summary>
/// Gets a list of networked <see cref="CustomVote"/>s.
/// </summary>
public List<CustomVote> Votes { get; } = votes;
public List<CustomVote> Votes => votes;
}
@@ -27,7 +27,7 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
/// <summary>
/// Gets the list of <see cref="CustomVote"/>s that are being processed.
/// </summary>
public List<CustomVote> Votes { get; } = votes;
public List<CustomVote> Votes => votes;
/// <summary>
/// Gets or sets a value indicating whether an overruling was done. Normally set by judge but can be overwritten.
@@ -9,5 +9,5 @@ public class VotingCompleteEvent(MeetingHud meetingHud) : MiraEvent
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; } = meetingHud;
public MeetingHud MeetingHud => meetingHud;
}
@@ -11,15 +11,15 @@ public class CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl p
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; } = task;
public PlayerTask Task => task;
/// <summary>
/// Gets the instance of the <see cref="HideAndSeekManager"/> attached to the game.
/// </summary>
public HideAndSeekManager HnsManager { get; } = hnsManager;
public HideAndSeekManager HnsManager => hnsManager;
}
@@ -10,10 +10,10 @@ public class CompleteTaskEvent(PlayerControl player, PlayerTask task) : MiraEven
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; } = task;
public PlayerTask Task => task;
}
@@ -11,15 +11,15 @@ public class PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody
/// <summary>
/// Gets the player who died.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the reason the player died.
/// </summary>
public DeathReason DeathReason { get; } = reason;
public DeathReason DeathReason => reason;
/// <summary>
/// Gets the <see cref="global::DeadBody"/> associated with the player, if any.
/// </summary>
public DeadBody? DeadBody { get; } = deadBody;
public DeadBody? DeadBody => deadBody;
}
@@ -11,5 +11,5 @@ public class PlayerJoinEvent(ClientData data) : MiraEvent
/// <summary>
/// Gets the player who joined.
/// </summary>
public ClientData ClientData { get; } = data;
public ClientData ClientData => data;
}
@@ -12,10 +12,10 @@ public class PlayerLeaveEvent(ClientData data, DisconnectReasons reason) : MiraE
/// <summary>
/// Gets the player who left.
/// </summary>
public ClientData ClientData { get; } = data;
public ClientData ClientData => data;
/// <summary>
/// Gets the reason why the player left.
/// </summary>
public DisconnectReasons Reason { get; } = reason;
public DisconnectReasons Reason => reason;
}
@@ -10,10 +10,10 @@ public class EnterVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEv
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is entering the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is entering.
/// </summary>
public Vent? Vent { get; } = vent;
public Vent? Vent => vent;
}
@@ -10,10 +10,10 @@ public class ExitVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEve
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is exiting the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; } = player;
public PlayerControl Player => player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is exiting.
/// </summary>
public Vent? Vent { get; } = vent;
public Vent? Vent => vent;
}
@@ -9,7 +9,7 @@ public class PlayerUseEvent(IUsable usable) : MiraCancelableEvent
/// <summary>
/// Gets the instance of <see cref="IUsable"/> that was used.
/// </summary>
public IUsable Usable { get; } = usable;
public IUsable Usable => usable;
/// <summary>
/// Gets a value indicating whether the <see cref="Usable"/> is a <see cref="Console"/>, <see cref="MapConsole"/>, or <see cref="SystemConsole"/>.
+1 -4
View File
@@ -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;
+2 -2
View File
@@ -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;
}
+51 -34
View File
@@ -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<ModdedOptionAttribute>(out var attribute))
{
RegisterAttributeOption(type, attribute, property, pluginInfo);
continue;
}
if (property.TryGetCustomAttribute<ModdedOptionListAttribute>(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<SyncOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, chunks.Dequeue()));
Rpc<SyncGameOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData));
}
}
@@ -162,7 +162,7 @@ public abstract class ModdedOption<T>(string groupPrefix, string title, T defaul
entry.Value = _value;
}
Rpc<SyncOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true);
Rpc<SyncGameOptionsRpc>.Instance.Send(PlayerControl.LocalPlayer, new MiraOptionNetData(true, [GetNetData()]), true);
}
if (ShowNotification)
+1
View File
@@ -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);
+4 -4
View File
@@ -72,18 +72,18 @@ public abstract class CustomPaginableMenu : CustomPhoneMenu<CustomPaginableMenu.
nextButton.transform.localScale = new Vector3(0.65f, 0.65f, 1);
nextButton.name = "RightArrowButton";
nextButton.GetComponent<SpriteRenderer>().sprite = MiraAssets.NextButton.LoadAsset();
nextButton.gameObject.GetComponent<CloseButtonConsoleBehaviour>().DestroyImmediate();
nextButton.GetComponent<CloseButtonConsoleBehaviour>().DestroyImmediate();
var passiveButton = nextButton.gameObject.GetComponent<PassiveButton>();
var passiveButton = nextButton.GetComponent<PassiveButton>();
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<CloseButtonConsoleBehaviour>().Destroy();
backButton.GetComponent<CloseButtonConsoleBehaviour>().Destroy();
backButton.GetComponent<SpriteRenderer>().flipX = true;
var prevPassive = backButton.gameObject.GetComponent<PassiveButton>();
var prevPassive = backButton.GetComponent<PassiveButton>();
prevPassive.OnClick.AddListener((UnityAction)customMenu.PreviousPage);
customMenu.PhoneUI.GetChild(0).GetComponent<SpriteRenderer>().material =
+2 -2
View File
@@ -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<SpriteRenderer>();
var icon = highlight.transform.GetChild(0).GetComponent<SpriteRenderer>();
@@ -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<SpriteRenderer>();
var icon = highlight.transform.GetChild(0).GetComponent<SpriteRenderer>();
if (sprite != null)
+16
View File
@@ -89,6 +89,22 @@ public class CustomPlayerMenu : CustomMultiSelectMenu<PlayerControl>
{
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;
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ public abstract class MultiTargetButton<T> : CustomActionButton
/// <summary>
/// Gets the maximum amount of targets the button can have.
/// </summary>
public virtual int MaxTargets { get; } = int.MaxValue;
public virtual int MaxTargets => int.MaxValue;
/// <inheritdoc cref="CustomActionButton{T}.IsTargetValid"/>
public virtual bool IsTargetValid(T target)
+54 -8
View File
@@ -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<RegisterCustomKeybindsAttribute>())
{
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;
}
/// <summary>
/// Returns all conflicts where <see cref="MiraKeybind"/>s use the same key.
/// </summary>
@@ -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;
+2 -2
View File
@@ -15,7 +15,7 @@ public class MiraKeybind(string name, KeyboardKeyCode? defaultKeycode, ModifierK
/// <summary>
/// Gets name of the keybind.
/// </summary>
public string Name { get; } = name;
public string Name => name;
/// <summary>
/// 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.
/// </summary>
public bool Exclusive { get; } = exclusive;
public bool Exclusive => exclusive;
internal string? SourcePluginName { get; set; }
@@ -6,6 +6,4 @@ namespace MiraAPI.LocalSettings.Attributes;
/// Attribute for local setting buttons.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class LocalSettingsButtonAttribute : Attribute
{
}
public class LocalSettingsButtonAttribute : Attribute;
+59 -7
View File
@@ -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<LocalSettingsButtonAttribute>())
{
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<LocalSettingAttribute>(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;
}
@@ -31,7 +31,7 @@ public class LocalEnumSetting(
/// <summary>
/// Gets the <see cref="Enum"/> type of the setting.
/// </summary>
public Type EnumType { get; } = enumType;
public Type EnumType => enumType;
/// <summary>
/// Gets the <see langword="enum"/> values.
@@ -41,7 +41,7 @@ public class LocalSliderSetting(
/// <summary>
/// Gets a value indicating whether the value should be displayed next to name.
/// </summary>
public bool DisplayValue { get; } = displayValue;
public bool DisplayValue => displayValue;
/// <summary>
/// Gets a format for the text to use to format the number.
@@ -51,7 +51,7 @@ public class LocalSliderSetting(
/// <summary>
/// Gets a value indicating whether the value should be rounded.
/// </summary>
public bool RoundValue { get; } = roundValue;
public bool RoundValue => roundValue;
/// <summary>
/// Gets the suffix for the number value.
@@ -13,12 +13,12 @@ namespace MiraAPI.MeetingAbilities;
public static class MeetingButtonManager
{
/// <summary>
/// Gets a list if==of all registered <see cref="TargetedMeetingButton"/>.
/// Gets a list of all registered <see cref="TargetedMeetingButton"/>.
/// </summary>
public static List<TargetedMeetingButton> TargetedButtons { get; internal set; } = [];
/// <summary>
/// Gets a list if==of all registered <see cref="MeetingActionButton"/>.
/// Gets a list of all registered <see cref="MeetingActionButton"/>.
/// </summary>
public static List<MeetingActionButton> UntargetedButtons { get; internal set; } = [];
@@ -64,7 +64,7 @@ public abstract class TargetedMeetingButton
/// <summary>
/// Gets the <see cref="MeetingButtonUsesMode"/> for this button.
/// </summary>
public virtual MeetingButtonUsesMode UsesMode { get; } = MeetingButtonUsesMode.PerGame;
public virtual MeetingButtonUsesMode UsesMode => MeetingButtonUsesMode.PerGame;
/// <summary>
/// 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<PassiveButton>();
btn.gameObject.name = Name + "Button";
btn.name = Name + "Button";
var spriteRenderer = btn.GetComponent<SpriteRenderer>();
spriteRenderer.sprite = Sprite.LoadAsset();
-7
View File
@@ -5,7 +5,6 @@
<PackageId>AllOfUs.MiraAPI</PackageId>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>IDE0031;IDE0032</NoWarn>
</PropertyGroup>
<ItemGroup>
@@ -16,11 +15,5 @@
<EmbeddedResource Include="Resources\**\*.*" />
</ItemGroup>
<ItemGroup>
<EditorConfigFiles Remove="GameModes\.editorconfig" />
<EditorConfigFiles Remove="Patches\GameModes\.editorconfig" />
<EditorConfigFiles Remove="Patches\.editorconfig" />
</ItemGroup>
<Import Project="../AmongUs.props" />
</Project>
+3
View File
@@ -41,6 +41,9 @@ public partial class MiraApiPlugin : BasePlugin, IMiraPlugin
/// <inheritdoc />
public bool DisplayOnOptionsMenu => false;
/// <inheritdoc />
public bool DebugMode => IsDevBuild;
/// <summary>
/// Gets a value indicating whether the current device is running Starlight (on mobile).
/// </summary>
+6 -6
View File
@@ -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();
}
@@ -37,7 +37,7 @@ public class ModifierUiComponent(nint cppPtr) : MonoBehaviour(cppPtr)
icon = modBg.transform.GetChild(1).GetComponent<SpriteRenderer>();
var nameBg = transform.GetChild(1);
nameText = nameBg.GetChild(0).GetComponent<TextMeshPro>();
descRect = desc.gameObject.GetComponent<RectTransform>();
descRect = desc.GetComponent<RectTransform>();
nameText.font = desc.font = HudManager.Instance.TaskPanel.taskText.font;
nameText.fontMaterial = desc.fontMaterial = HudManager.Instance.TaskPanel.taskText.fontMaterial;
+4 -2
View File
@@ -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;
+2 -2
View File
@@ -10,12 +10,12 @@ public readonly struct NetData(uint id, byte[] data)
/// <summary>
/// Gets the ID of the data.
/// </summary>
public uint Id { get; } = id;
public uint Id => id;
/// <summary>
/// Gets the byte[] data.
/// </summary>
public byte[] Data { get; } = data;
public byte[] Data => data;
/// <summary>
/// Gets the length of the data in bytes.
+32 -15
View File
@@ -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<MiraApiPlugin, MiraOptionNetData>(plugin, id)
#pragma warning restore SA1515 // Single-line comment should be preceded by blank line
internal abstract class SyncOptionsRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, MiraOptionNetData>(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 ?? []);
}
}
-64
View File
@@ -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<MiraApiPlugin, MiraOptionNetData>(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 ?? []);
}
}
+21 -6
View File
@@ -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;
/// <summary>
/// Sync all settings to the player when they join the game.
/// </summary>
[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<AmongUsClient>(nameof(AmongUsClient.CreatePlayer))!;
}
[HarmonyPostfix]
public static void CreatePlayerPatch(Il2CppObjectBase __instance, bool __result)
{
if (__result)
return;
var wrapper = new StateMachineWrapper<AmongUsClient>(__instance);
var clientData = wrapper.GetParameter<ClientData>("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);
+1 -2
View File
@@ -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;
}
}
+2 -2
View File
@@ -34,8 +34,8 @@ internal static class HudPatches
yield return new WaitUntil((Il2CppSystem.Func<bool>)(() => 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;
+5 -5
View File
@@ -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();
@@ -313,7 +313,7 @@ internal static class GameOptionsMenuPatch
};
_modIcon = modIconObj.AddComponent<SpriteRenderer>();
_modIcon.sprite = MiraAssets.BlankSprite.LoadAsset();
_modIcon.material = gamemodeBg.gameObject.GetComponent<SpriteRenderer>().material;
_modIcon.material = gamemodeBg.GetComponent<SpriteRenderer>().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 = $"<size=70%>({"MiraApi.GameSetting.Global.ClickToClose".Translate()})</size>";
newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f);
newText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
newText.GetComponent<TextTranslatorTMP>().Destroy();
var boxCol = categoryHeaderMasked.gameObject.AddComponent<BoxCollider2D>();
boxCol.size = new Vector2(7, 0.7f);
@@ -164,7 +164,7 @@ internal static class GamePresetsTabPatches
return;
}
var tmpTranslator = presetTab.PresetDescriptionText.gameObject.GetComponent<TextTranslatorTMP>();
var tmpTranslator = presetTab.PresetDescriptionText.GetComponent<TextTranslatorTMP>();
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<SpriteRenderer>();
var folderRend = openFolderButton.transform.FindChild("Sprite").GetComponent<SpriteRenderer>();
folderRend.sprite = MiraAssets.FolderIcon.LoadAsset();
folderRend.transform.localScale = new Vector3(0.4f, 0.4f, 1);
@@ -20,9 +20,10 @@ internal static class GameSettingMenuPatches
}
// Add Menu State object
if (!__instance.gameObject.GetComponent<MenuState>())
__instance.gameObject.GetOrAddComponent<MenuState>(out var existed);
if (!existed)
{
__instance.gameObject.AddComponent<MenuState>();
Info("MenuState component added to GameSettingMenu.");
}
else
@@ -72,7 +72,7 @@ public static class LobbyViewPanePatches
// create modifiers button
modifiersTabButton = Object.Instantiate(__instance.rolesTabButton, __instance.rolesTabButton.transform.parent);
modifiersTabButton.buttonText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
modifiersTabButton.buttonText.GetComponent<TextTranslatorTMP>().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<PassiveButton>();
var passiveButton = nextButton.GetComponent<PassiveButton>();
passiveButton.OnClick = new Button.ButtonClickedEvent();
passiveButton.OnClick.AddListener(
(UnityAction)(() =>
@@ -123,7 +123,7 @@ public static class LobbyViewPanePatches
= backButton.transform.FindChild("Hover").gameObject.GetComponentInChildren<SpriteRenderer>().flipX
= true;
var passiveButton2 = backButton.gameObject.GetComponent<PassiveButton>();
var passiveButton2 = backButton.GetComponent<PassiveButton>();
passiveButton2.OnClick = new Button.ButtonClickedEvent();
passiveButton2.OnClick.AddListener(
(UnityAction)(() =>
+29 -13
View File
@@ -50,7 +50,8 @@ public class MenuState(IntPtr cppPtr) : MonoBehaviour(cppPtr)
private readonly Dictionary<MenuButton, PassiveButton> _smallButtons = [];
private readonly Dictionary<MenuButton, PassiveButton> _largeButtons = [];
private Vector3 _gameSettingsButtonOrig;
private Vector3 _roleSettingsButtonOrig;
[HideFromIl2Cpp]
public Dictionary<MenuCategory, Dictionary<int, GameObject>> 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<SpriteRenderer>().sprite =
nextButton.transform.FindChild("Inactive").GetComponent<SpriteRenderer>().sprite =
MiraAssets.NextButton.LoadAsset();
nextButton.transform.FindChild("Active").gameObject.GetComponent<SpriteRenderer>().sprite =
nextButton.transform.FindChild("Active").GetComponent<SpriteRenderer>().sprite =
MiraAssets.NextButtonActive.LoadAsset();
nextButton.gameObject.GetComponent<CloseButtonConsoleBehaviour>().DestroyImmediate();
nextButton.GetComponent<CloseButtonConsoleBehaviour>().DestroyImmediate();
var nextPassiveButton = nextButton.gameObject.GetComponent<PassiveButton>();
var nextPassiveButton = nextButton.GetComponent<PassiveButton>();
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<CloseButtonConsoleBehaviour>().Destroy();
previousButton.transform.FindChild("Active").gameObject.GetComponent<SpriteRenderer>().flipX =
previousButton.transform.FindChild("Inactive").gameObject.GetComponent<SpriteRenderer>().flipX = true;
previousButton.GetComponent<CloseButtonConsoleBehaviour>().Destroy();
previousButton.transform.FindChild("Active").GetComponent<SpriteRenderer>().flipX =
previousButton.transform.FindChild("Inactive").GetComponent<SpriteRenderer>().flipX = true;
var prevPassiveButton = previousButton.gameObject.GetComponent<PassiveButton>();
var prevPassiveButton = previousButton.GetComponent<PassiveButton>();
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<TextTranslatorTMP>().Destroy();
mBtn.buttonText.GetComponent<TextTranslatorTMP>().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<TextTranslatorTMP>().Destroy();
c1Btn.buttonText.GetComponent<TextTranslatorTMP>().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}");
@@ -309,7 +309,7 @@ public static class RoleSettingMenuPatches
var newText = Object.Instantiate(categoryHeaderMasked.Title, categoryHeaderMasked.transform);
newText.text = $"<size=70%>{label}</size>";
newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f);
newText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
newText.GetComponent<TextTranslatorTMP>().Destroy();
scrollerNum -= 0.422f;
@@ -604,14 +604,14 @@ public static class RoleSettingMenuPatches
var categoryHeaderMasked = __instance.AdvancedRolesSettings.transform.Find("CategoryHeaderMasked").GetComponent<CategoryHeaderMasked>();
if (categoryHeaderMasked.Title.gameObject.TryGetComponent<TextTranslatorTMP>(out var comp))
if (categoryHeaderMasked.Title.TryGetComponent<TextTranslatorTMP>(out var comp))
{
comp.Destroy();
}
categoryHeaderMasked.Title.text = "MiraApi.ReturnToRoleSettings".Translate();
if (!categoryHeaderMasked.gameObject.TryGetComponent<PassiveButton>(out _))
if (!categoryHeaderMasked.TryGetComponent<PassiveButton>(out _))
{
var boxCol = categoryHeaderMasked.gameObject.AddComponent<BoxCollider2D>();
boxCol.size = new Vector2(7, 0.7f);
+2 -2
View File
@@ -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),
};
}
+2 -2
View File
@@ -22,12 +22,12 @@ internal static class PlayerControlPatches
[HarmonyPatch(nameof(PlayerControl.Start))]
public static void PlayerControlStartPostfix(PlayerControl __instance)
{
if (__instance.gameObject.TryGetComponent<ModifierComponent>(out var modifierComp))
if (__instance.TryGetComponent<ModifierComponent>(out var modifierComp))
{
modifierComp.DestroyImmediate();
}
if (__instance.gameObject.TryGetComponent<PlayerVoteData>(out var voteComp))
if (__instance.TryGetComponent<PlayerVoteData>(out var voteComp))
{
voteComp.DestroyImmediate();
}
+31 -18
View File
@@ -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<TextTranslatorTMP>().Destroy();
_titleText.GetComponent<TextTranslatorTMP>().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<RectTransform>();
}
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<BoxCollider2D>();
if (!collider)
{
collider = panel.roleIcon.gameObject.AddComponent<BoxCollider2D>();
}
var collider = panel.roleIcon.gameObject.GetOrAddComponent<BoxCollider2D>();
collider.size = new Vector2(0.13f, 0.13f);
collider.offset = new Vector2(0, 0);
collider.enabled = true;
var passiveButton = panel.roleIcon.gameObject.GetComponent<PassiveButton>();
if (!passiveButton)
{
passiveButton = panel.roleIcon.gameObject.AddComponent<PassiveButton>();
}
var passiveButton = panel.roleIcon.gameObject.GetOrAddComponent<PassiveButton>();
passiveButton.enabled = true;
passiveButton.ClickSound = HudManager.Instance.MapButton.ClickSound;
+1 -1
View File
@@ -37,7 +37,7 @@ public static class RoleManagerPatches
Object.Destroy(data.Role.gameObject);
}
var roleBehaviour = Object.Instantiate<RoleBehaviour>(__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;
+1 -1
View File
@@ -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;
}
+5
View File
@@ -58,6 +58,11 @@ public interface IMiraPlugin
/// </summary>
string CustomOptionMenuTwoDescription => "Apply game settings for this mod!";
/// <summary>
/// Gets a value indicating whether the plugin is in debug mode.
/// </summary>
bool DebugMode => false;
/// <summary>
/// Gets the <see cref="ConfigFile"/> for the plugin.
/// </summary>
+13 -1
View File
@@ -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;
/// </summary>
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;
}
/// <summary>
@@ -45,6 +47,16 @@ public class MiraPluginInfo
/// </summary>
public ConfigFile PluginConfig { get; }
/// <summary>
/// Gets the plugin's <see cref="Assembly"/>.
/// </summary>
public Assembly PluginAssembly { get; }
/// <summary>
/// Gets a value indicating whether the plugin is in debug mode.
/// </summary>
public bool DebugMode => MiraPlugin.DebugMode;
/// <summary>
/// Gets a <see cref="IReadOnlyCollection{T}"/> of this <see cref="IMiraPlugin"/>'s <see cref="BaseModifier"/>s. This is not safe for <see cref="BaseModifier"/>s with constructors.
/// </summary>
+43 -241
View File
@@ -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<Assembly, MiraPluginInfo> _registeredPlugins = [];
private readonly Dictionary<string, MiraPluginInfo> _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<Type>();
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<CompilerGeneratedAttribute>(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<Type> 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<RegisterEventAttribute>(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
/// <returns>A <see cref="MiraPluginInfo"/>.</returns>
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<MiraIgnoreAttribute>())
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<RegisterCustomColorsAttribute>() == 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<LocalSettingsButtonAttribute>() &&
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<LocalSettingAttribute>(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<LocalSettingAttribute>()))
{
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<RegisterCustomKeybindsAttribute>())
{
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;
}
}
+4 -4
View File
@@ -18,22 +18,22 @@ public class OptionPreset(string name, MiraPluginInfo plugin, ConfigFile presetC
/// <summary>
/// Gets the name of the preset.
/// </summary>
public string Name { get; } = name;
public string Name => name;
/// <summary>
/// Gets the plugin associated with the preset.
/// </summary>
public MiraPluginInfo Plugin { get; } = plugin;
public MiraPluginInfo Plugin => plugin;
/// <summary>
/// Gets the <see cref="ConfigFile"/> of the plugin associated with the preset.
/// </summary>
public ConfigFile PluginConfig { get; } = plugin.PluginConfig;
public ConfigFile PluginConfig => plugin.PluginConfig;
/// <summary>
/// Gets the <see cref="ConfigFile"/> for the preset.
/// </summary>
public ConfigFile PresetConfig { get; } = presetConfig;
public ConfigFile PresetConfig => presetConfig;
/// <summary>
/// Gets or sets the button associated with the preset in the UI.
+1 -1
View File
@@ -70,7 +70,7 @@ public class SavePresetPopup(nint cppPtr) : Minigame(cppPtr)
foreach (var tmp in gameObject.GetComponentsInChildren<TextMeshPro>())
{
if (tmp.gameObject.transform.parent.name == "Textbox")
if (tmp.transform.parent.name == "Textbox")
{
continue;
}
+23 -5
View File
@@ -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<Type> 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<TaskPanelBehaviour>();
var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").GetComponent<TaskPanelBehaviour>();
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<TextMeshPro>();
var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").gameObject.GetComponent<TaskPanelBehaviour>();
var tabText = panel.tab.GetComponentInChildren<TextMeshPro>();
var ogPanel = HudManager.Instance.TaskStuff.transform.FindChild("TaskPanel").GetComponent<TaskPanelBehaviour>();
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<SyncRoleOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, data.Dequeue()));
Rpc<SyncRoleOptionsRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, new MiraOptionNetData(false, netData));
}
}
+15
View File
@@ -843,6 +843,21 @@ public static class Extensions
return comp ? comp : go.AddComponent<T>();
}
/// <summary>
/// Gets a component that is attached to the provided <see cref="GameObject"/>, attaching and returning the component if it wasn't found, and returns a bool that indicates if the component already existed before.
/// </summary>
/// <typeparam name="T">The component type.</typeparam>
/// <param name="go">The <see cref="GameObject"/> to get the component from.</param>
/// <param name="exists">When this method returns true if the component already existed; otherwise false.</param>
/// <returns>The component.</returns>
public static T GetOrAddComponent<T>(this GameObject go, out bool exists)
where T : Component
{
var comp = go.GetComponent<T>();
exists = comp;
return exists ? comp : go.AddComponent<T>();
}
/// <inheritdoc cref="Attribute.IsDefined(MemberInfo, Type, bool)"/>
/// <typeparam name="T">The type of the attribute.</typeparam>
/// <returns>true if a custom attribute of type <typeparamref name="T"/> is applied to element; otherwise, false.</returns>
+6 -6
View File
@@ -29,13 +29,13 @@ internal sealed class GuideOptionPage(
IReadOnlyList<string> modSearchTerms,
List<GuideOptionEntry> entries)
{
public AbstractOptionGroup Group { get; } = group;
public AbstractOptionGroup Group => group;
public List<AbstractOptionGroup> Groups { get; } = [group];
public string Title { get; } = title;
public string Title => title;
public LoadableAsset<Sprite> Sprite { get; } = group.Sprite;
public LoadableAsset<Sprite> 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<string> ModSearchTerms { get; } = new(modSearchTerms, StringComparer.OrdinalIgnoreCase);
public List<GuideOptionEntry> Entries { get; } = entries;
public List<GuideOptionEntry> Entries => entries;
}
internal static class GuideOptionPages
+17 -21
View File
@@ -117,7 +117,7 @@ public static class Helpers
{
var keybindIcon = Object.Instantiate(HudManager.Instance.AbilityButton.usesRemainingSprite.gameObject, button.transform);
keybindIcon.GetComponent<SpriteRenderer>().sprite = MiraAssets.KeybindButton.LoadAsset();
keybindIcon.transform.GetComponentInChildren<TextMeshPro>().text = keyCode.ToString();
keybindIcon.GetComponentInChildren<TextMeshPro>().text = keyCode.ToString();
keybindIcon.name = "KeybindIcon";
keybindIcon.transform.localPosition = localPos;
return keybindIcon;
@@ -131,26 +131,21 @@ public static class Helpers
/// <returns>THe corresponding method to patch.</returns>
public static MethodBase? GetStateMachineMoveNext<T>(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<ArrowBehaviour>(true);
var arrow = Object.Instantiate(prefab, parent);
arrow.image = arrow.gameObject.GetComponent<SpriteRenderer>();
arrow.image = arrow.GetComponent<SpriteRenderer>();
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
/// <returns>The formatted value.</returns>
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),
};
}
+8 -7
View File
@@ -21,6 +21,7 @@ public class StateMachineWrapper<T>
private readonly PropertyInfo _stateProperty;
private readonly PropertyInfo _currentProperty;
private readonly Dictionary<string, PropertyInfo> _propertyCache;
private readonly Type _type;
private T? _parentInstance;
@@ -37,14 +38,14 @@ public class StateMachineWrapper<T>
{
_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<T>
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)!;