Compare commits

...
Author SHA1 Message Date
XtraCube 3387564f2d Merge pull request #29 from All-Of-Us-Mods/custom-game-over
Custom game over
2025-02-27 20:20:11 -05:00
XtraCube 9e2787b781 fix intro cutscene bug 2025-02-27 20:19:34 -05:00
XtraCube 90ed9b2a98 finalize custom gameover 2025-02-27 20:11:24 -05:00
XtraCube 530cb79981 custom game over 2025-02-27 19:33:14 -05:00
XtraCube 6f4eff7b38 Merge pull request #19 from All-Of-Us-Mods/rpc-modifier-arguments
Modifier Rework
2025-02-27 18:33:35 -05:00
XtraCube 2159b6aa89 Merge pull request #28 from Zeo666/IntroTeam
Custom Intro Team Screen
2025-02-27 18:33:24 -05:00
XtraCube 9ec270bd68 use precomputed shader ID 2025-02-27 18:22:42 -05:00
XtraCube c9ff839f12 improve flexibility of setup team intro 2025-02-27 18:21:04 -05:00
XtraCube d1116b3fce comment on miraapiplugin 2025-02-27 15:15:21 -05:00
XtraCube 65a81d0fb4 fix broken wav audio resource loader 2025-02-26 21:34:31 -05:00
XtraCube 26b94b0127 fix ordering of properties in BaseModifier.cs 2025-02-26 17:29:46 -05:00
XtraCube 6443b5932b modifier converter + cleanup 2025-02-26 17:24:41 -05:00
XtraCube a619a975d7 fix modifier factory issue 2025-02-26 17:24:05 -05:00
XtraCube 81834a7f1a allow modifier in lobby with error 2025-02-26 15:38:25 -05:00
Zeo 3015c6dd6a Added method to override the intro team screen to be based on custom role 2025-02-26 18:26:07 +00:00
XtraCube 0e2eeea069 add check to prevent adding modifiers before a game has started 2025-02-25 22:01:52 -05:00
XtraCube 7e4a71739c better modifier unique IDs 2025-02-25 21:57:38 -05:00
XtraCube caa27642db further modifier improvements (massive changes) 2025-02-25 17:22:00 -05:00
XtraCube 4a8fb38380 improvements to timed modifier 2025-02-25 17:17:40 -05:00
XtraCube 66375e884f use invariant info to shut up warnings 2025-02-24 21:52:53 -05:00
XtraCube 9ae9094a85 oops fix that 2025-02-24 21:52:06 -05:00
XtraCube 1c6fa9a84d major modifier overhaul 2025-02-24 21:51:02 -05:00
XtraCube 0ebec6d0f1 fix testing thing 2025-02-23 20:28:24 -05:00
XtraCube 0bed367eda Merge branch 'dev' into rpc-modifier-arguments
# Conflicts:
#	MiraAPI/Patches/PlayerControlPatches.cs
#	MiraAPI/Patches/VentPatches.cs
2025-02-23 20:27:20 -05:00
XtraCube 176a1d5e5c Merge pull request #27 from All-Of-Us-Mods/modifier-improvements
Modifier improvements
2025-02-23 20:15:53 -05:00
XtraCube fb19b4bc04 better naming for "stackable" modifier 2025-02-23 20:13:12 -05:00
XtraCube 8fb8d18be9 fix name 2025-02-23 19:10:57 -05:00
XtraCube b1846fae26 Merge branch 'dev' into modifier-improvements
# Conflicts:
#	MiraAPI/Modifiers/BaseModifier.cs
#	MiraAPI/Patches/Freeplay/TaskAdderPatches.cs
2025-02-23 19:08:57 -05:00
XtraCube 8b8f9ea5db utilize new modifier extension stuff 2025-02-23 19:06:59 -05:00
XtraCube bbec3c1958 fix something i almost broke 2025-02-23 19:06:12 -05:00
XtraCube 758b1d3183 organize task add patches 2025-02-23 19:06:12 -05:00
XtraCube d8131d1f5d fix pietros mistake and cleanup things 2025-02-23 19:06:12 -05:00
XtraCube 9ccf7104cb better summary comment 2025-02-23 19:06:12 -05:00
Pietrodjaowjao bc12c5a5f7 Change util to TMP_Text (all textmeshpro render components) 2025-02-23 19:06:12 -05:00
XtraCube 5dfbd5dc8f add masking to task adder roles 2025-02-23 19:06:12 -05:00
XtraCube 84c8f743f8 i dont know why this is even a bug 2025-02-23 19:06:12 -05:00
XtraCube 3905a3b394 . 2025-02-23 19:06:12 -05:00
XtraCube fb5ff4b53e freeplay modifiers 2025-02-23 19:06:09 -05:00
XtraCube 047312a197 Merge pull request #26 from All-Of-Us-Mods/freeplay-modifiers
freeplay modifiers
2025-02-23 19:05:01 -05:00
XtraCube 8e0a8f0585 fix something i almost broke 2025-02-23 19:02:22 -05:00
XtraCube 4849b52b47 organize task add patches 2025-02-23 18:59:14 -05:00
XtraCube 9cc9a137cc fix pietros mistake and cleanup things 2025-02-23 18:54:51 -05:00
XtraCube 055b097c21 better summary comment 2025-02-23 18:32:23 -05:00
XtraCube 87187fe205 improve modifier extensions and add more method for dealing with modifiers 2025-02-23 18:25:25 -05:00
XtraCube 975e8cb9b7 allow stackable modifiers 2025-02-23 18:24:56 -05:00
Pietrodjaowjao 6775294a19 Change util to TMP_Text (all textmeshpro render components) 2025-02-23 20:22:11 -03:00
XtraCube 2af89a678f add masking to task adder roles 2025-02-23 16:34:59 -05:00
XtraCube dda46e5903 i dont know why this is even a bug 2025-02-23 15:45:31 -05:00
ang-xd ba92d9608c Updated role settings appearance + role options 2025-02-22 21:12:54 -05:00
XtraCube 52ff4bfbfc . 2025-02-22 18:59:19 -05:00
XtraCube b6dda5f970 freeplay modifiers 2025-02-22 18:54:20 -05:00
XtraCube 9504862bea add format string option to number options 2025-02-21 12:01:28 -05:00
XtraCube 4b6ffc65df fix after murder event 2025-02-21 09:26:53 -05:00
XtraCube ccde63068b fix lobby view pane issues 2025-02-18 21:49:54 -05:00
XtraCube 5e16429acf fix more scrolling issues 2025-02-18 11:15:13 -05:00
XtraCube 1e47500686 fix scrolling issues 2025-02-18 11:03:50 -05:00
XtraCube 0b1cf998f8 fix coloring issues and hidden roles in rolesettingsmenu 2025-02-17 21:59:58 -05:00
XtraCube 14a3669031 fix rolebehaviour stubs cuz im an idiot 2025-02-17 11:52:57 -05:00
XtraCube ae79cd87d9 :shush: 2025-02-17 11:37:02 -05:00
XtraCube fb99f02549 i forgor 2025-02-17 11:10:26 -05:00
XtraCube 8382b9adf1 clearer naming 2025-02-17 11:08:12 -05:00
XtraCube cb1a818377 role configuration improvements 2025-02-17 11:03:39 -05:00
XtraCube e950278bf9 seperate some role configs 2025-02-17 10:58:25 -05:00
XtraCube 3de9482233 add missing minigame stubs 2025-02-17 10:32:28 -05:00
XtraCube 4508aaeb55 add role stubs 2025-02-17 10:32:18 -05:00
XtraCube ee15a1acbe fix neutral default role group title 2025-02-17 09:46:09 -05:00
XtraCube 113c716fd3 hide role groups in settings menu 2025-02-17 00:00:37 -05:00
ang-xd f7c34fb5cd Add ShowInFreeplay configuration 2025-02-16 23:13:04 -05:00
XtraCube 37446964c5 change neutral team to Custom and add more customization 2025-02-16 22:33:16 -05:00
XtraCube 8e2535ada2 yes it works 2025-02-02 20:42:23 -05:00
XtraCube ce81d8c1ff it works? 2025-02-02 20:36:14 -05:00
XtraCube 9485099ab9 RPC add modifier with arguments 2025-02-02 16:09:06 -05:00
61 changed files with 2424 additions and 686 deletions

No files matched your search

@@ -3,6 +3,7 @@ using MiraAPI.Example.Options.Roles;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.Hud;
using MiraAPI.Modifiers;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
+1 -1
View File
@@ -1,6 +1,6 @@
using MiraAPI.Example.Modifiers;
using MiraAPI.Hud;
using MiraAPI.Utilities;
using MiraAPI.Modifiers;
using MiraAPI.Utilities.Assets;
using UnityEngine;
@@ -0,0 +1,24 @@
using MiraAPI.Example.GameOver;
using MiraAPI.Example.Roles;
using MiraAPI.GameEnd;
using MiraAPI.Hud;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Example.Buttons;
public class NeutralKillerButton : CustomActionButton
{
public override string Name => "Win Game";
public override float Cooldown => 0f;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
protected override void OnClick()
{
CustomGameOver.Trigger<NeutralKillerGameOver>([PlayerControl.LocalPlayer.Data]);
}
public override bool Enabled(RoleBehaviour? role)
{
return role is NeutralKillerRole;
}
}
@@ -0,0 +1,15 @@
using MiraAPI.GameEnd;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Example.GameOver;
public class NeutralKillerGameOver : CustomGameOver
{
public override void AfterEndGameSetup(EndGameManager endGameManager)
{
endGameManager.WinText.text = "Outcast Killer Wins!";
endGameManager.WinText.color = Color.magenta;
endGameManager.BackgroundBar.material.SetColor(ShaderID.Color, Color.magenta);
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using MiraAPI.Modifiers.Types;
namespace MiraAPI.Example.Modifiers;
@@ -1,6 +1,5 @@
using Il2CppSystem;
using MiraAPI.Example.Roles;
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using UnityEngine;
@@ -1,5 +1,4 @@
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using MiraAPI.Modifiers.Types;
namespace MiraAPI.Example.Modifiers;
+1 -1
View File
@@ -16,7 +16,7 @@ public class ExampleOptions : AbstractOptionGroup
[ModdedToggleOption("Toggle Opt 2")]
public bool ToggleOpt2 { get; set; } = true;
[ModdedNumberOption("Number Opt", min: 0, max: 10, suffixType: MiraNumberSuffixes.Percent)]
[ModdedNumberOption("Number Opt", min: 0, max: 10, increment: .25f, formatString: "0.00", suffixType: MiraNumberSuffixes.Percent)]
public float NumberOpt { get; set; } = 4f;
[ModdedEnumOption("Best API", typeof(BestApi), ["Mira API", "Mitochondria", "Reactor"])]
+15 -6
View File
@@ -1,23 +1,32 @@
using MiraAPI.Roles;
using MiraAPI.Example.GameOver;
using MiraAPI.GameEnd;
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
public class NeutralKillerRole : ImpostorRole, ICustomRole
{
public string RoleName => "Neutral Killer";
public string RoleDescription => "Neutral who can kill.";
public string RoleName => "Outcast Killer";
public string RoleDescription => "Outcast who can kill.";
public string RoleLongDescription => RoleDescription;
public Color RoleColor => Color.magenta;
public ModdedRoleTeams Team => ModdedRoleTeams.Neutral;
public ModdedRoleTeams Team => ModdedRoleTeams.Custom;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
public CustomRoleConfiguration Configuration => new(this)
{
UseVanillaKillButton = true,
CanGetKilled = true,
CanUseVent = true,
};
public RoleOptionsGroup RoleOptionsGroup { get; } = new("Outcast", Color.gray);
public TeamIntroConfiguration? IntroConfiguration { get; } = new(
Color.gray,
"OUTCAST",
"You are an Outcast. You do not have a team.");
public override void SpawnTaskHeader(PlayerControl playerControl)
{
// remove existing task header.
@@ -25,6 +34,6 @@ public class NeutralKillerRole : ImpostorRole, ICustomRole
public override bool DidWin(GameOverReason gameOverReason)
{
return GameManager.Instance.DidHumansWin(gameOverReason);
return gameOverReason == CustomGameOver.GameOverReason<NeutralKillerGameOver>();
}
}
@@ -1,4 +1,4 @@
namespace MiraAPI.Events.Vanilla;
namespace MiraAPI.Events.Vanilla.Usables;
/// <summary>
/// Event for <see cref="PlayerControl"/> using a <see cref="IUsable"/> from Vanilla Among Us. Will always be ran locally.
+74
View File
@@ -0,0 +1,74 @@
using System.Collections.Generic;
using MiraAPI.Networking;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
namespace MiraAPI.GameEnd;
/// <summary>
/// Custom Game Over.
/// </summary>
public abstract class CustomGameOver
{
/// <summary>
/// Gets the current CustomGameOver.
/// </summary>
public static CustomGameOver? Instance { get; internal set; }
/// <summary>
/// Runs before the base game calls EndGameManager.SetEverythingUp.
/// </summary>
/// <param name="endGameManager">The EndGameManager instance.</param>
/// <returns>Return True to use the run the original method, return False to skip it.</returns>
public virtual bool BeforeEndGameSetup(EndGameManager endGameManager)
{
return true;
}
/// <summary>
/// Runs after the base game calls EndGameManager.SetEverythingUp.
/// </summary>
/// <param name="endGameManager">The EndGameManager instance.</param>
public virtual void AfterEndGameSetup(EndGameManager endGameManager)
{
}
/// <summary>
/// Get the GameOverReason associated with this CustomGameOver.
/// </summary>
/// <typeparam name="T">Type of the custom game over.</typeparam>
/// <returns>The GameOverReason associated with the custom game over.</returns>
public static GameOverReason GameOverReason<T>() where T : CustomGameOver
{
return (GameOverReason)GameOverManager.GetGameOverId<T>();
}
/// <summary>
/// Send a custom game over.
/// </summary>
/// <param name="winners">A collection of winners.</param>
/// <typeparam name="T">Type of the custom game over.</typeparam>
public static void Trigger<T>(IEnumerable<NetworkedPlayerInfo> winners) where T : CustomGameOver
{
if (!AmongUsClient.Instance.AmHost)
{
Logger<MiraApiPlugin>.Error("Only the host can send a custom game over.");
return;
}
var reason = GameOverManager.GetGameOverId<T>();
var data = new GameOverData(reason, [.. winners]);
Rpc<CustomGameOverRpc>.Instance.Send(PlayerControl.LocalPlayer, data, true);
}
/// <summary>
/// Implicitly convert a CustomGameOver to a GameOverReason.
/// </summary>
/// <param name="gameOver">The CustomGameOver instance.</param>
/// <returns>The GameOverReason associated with the CustomGameOver.</returns>
public static implicit operator GameOverReason(CustomGameOver gameOver)
{
return (GameOverReason)GameOverManager.GetGameOverId(gameOver.GetType());
}
}
+10
View File
@@ -0,0 +1,10 @@
using System.Collections.Generic;
namespace MiraAPI.GameEnd;
/// <summary>
/// Data for a game over.
/// </summary>
/// <param name="Reason">Reason for the game over.</param>
/// <param name="Winners">A collection of winners.</param>
public record struct GameOverData(int Reason, List<NetworkedPlayerInfo> Winners);
+89
View File
@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using Reactor.Utilities;
namespace MiraAPI.GameEnd;
/// <summary>
/// Manage custom game overs.
/// </summary>
public static class GameOverManager
{
private static readonly Dictionary<Type, int> GameOverIds = [];
private static readonly Dictionary<int, Type> GameOverTypes = [];
private static int _nextId = Enum.GetNames<GameOverReason>().Length;
/// <summary>
/// Register a custom game over.
/// </summary>
/// <param name="gameOverType">Type of the custom game over.</param>
/// <exception cref="ArgumentException">Thrown when the type is not a subclass of CustomGameOver, is abstract, or does not have a parameterless constructor.</exception>
/// <returns>>True if the game over was registered successfully, false otherwise.</returns>
public static bool RegisterGameOver(Type gameOverType)
{
if (!typeof(CustomGameOver).IsAssignableFrom(gameOverType))
{
return false;
}
if (gameOverType.IsAbstract)
{
Logger<MiraApiPlugin>.Error("The type must not be abstract.");
return false;
}
if (gameOverType.GetConstructor(Type.EmptyTypes) == null)
{
Logger<MiraApiPlugin>.Error("The type must have a parameterless constructor.");
return false;
}
GameOverIds.Add(gameOverType, _nextId);
GameOverTypes.Add(_nextId, gameOverType);
_nextId++;
return true;
}
/// <summary>
/// Create an instance of a custom game over.
/// </summary>
/// <param name="id">ID of the custom game over.</param>
/// <param name="customGameOver">The created instance of the custom game over.</param>
/// <returns>An instance of the custom game over.</returns>
public static bool TryGetGameOver(int id, out CustomGameOver? customGameOver)
{
if (GameOverTypes.TryGetValue(id, out var gameOverType))
{
customGameOver = Activator.CreateInstance(gameOverType) as CustomGameOver;
return customGameOver != null;
}
customGameOver = null;
return false;
}
/// <summary>
/// Get the ID of a custom game over.
/// </summary>
/// <typeparam name="T">Type of the custom game over.</typeparam>
/// <returns>The ID of the custom game over.</returns>
public static int GetGameOverId<T>() where T : CustomGameOver
{
return GetGameOverId(typeof(T));
}
/// <summary>
/// Get the ID of a custom game over.
/// </summary>
/// <param name="gameOverType">Type of the custom game over.</param>
/// <returns>The ID of the custom game over.</returns>
/// <exception cref="ArgumentException">Thrown when the type is not registered.</exception>
public static int GetGameOverId(Type gameOverType)
{
if (GameOverIds.TryGetValue(gameOverType, out var id))
return id;
throw new ArgumentException($"{gameOverType.FullName} is not a registered custom game over!");
}
}
@@ -15,13 +15,14 @@ public class ModdedNumberOptionAttribute(
float max,
float increment = 1,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false,
Type? roleType = null)
: ModdedOptionAttribute(title, roleType)
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
return new ModdedNumberOption(Title, (float)(value ?? min+increment), min, max, increment, suffixType, zeroInfinity, RoleType);
return new ModdedNumberOption(Title, (float)(value ?? min+increment), min, max, increment, suffixType, formatString, zeroInfinity, RoleType);
}
/// <inheritdoc />
@@ -147,7 +147,7 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
// SetUpFromData method doesnt work correctly so we must set the values manually
stringOption.Title = StringName;
stringOption.Values = (Data as StringGameSetting)?.Values ?? new Il2CppStructArray<StringNames>(0);
stringOption.Value = Convert.ToInt32(Value);
stringOption.Value = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo);
OptionBehaviour = stringOption;
@@ -157,13 +157,13 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
/// <inheritdoc />
public override float GetFloatData()
{
return Convert.ToSingle(Value);
return Convert.ToSingle(Value, NumberFormatInfo.InvariantInfo);
}
/// <inheritdoc />
public override NetData GetNetData()
{
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value)));
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value, NumberFormatInfo.InvariantInfo)!));
}
/// <inheritdoc />
@@ -175,13 +175,13 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
/// <inheritdoc />
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
{
return (T)Enum.Parse(typeof(T), optionBehaviour.GetInt().ToString());
return (T)Enum.Parse(typeof(T), optionBehaviour.GetInt().ToString(NumberFormatInfo.InvariantInfo));
}
/// <inheritdoc />
protected override void OnValueChanged(T newValue)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(Convert.ToInt32(newValue)), false);
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo)), false);
if (!OptionBehaviour)
{
return;
@@ -189,7 +189,7 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
if (OptionBehaviour is StringOption opt)
{
opt.Value = Convert.ToInt32(newValue);
opt.Value = Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo);
}
}
}
@@ -46,6 +46,7 @@ public class ModdedNumberOption : ModdedOption<float>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="roleType">An optional role type.</param>
public ModdedNumberOption(
@@ -55,6 +56,7 @@ public class ModdedNumberOption : ModdedOption<float>
float max,
float increment,
MiraNumberSuffixes suffixType,
string? formatString = null,
bool zeroInfinity = false,
Type? roleType = null) : base(title, defaultValue, roleType)
{
@@ -74,7 +76,13 @@ public class ModdedNumberOption : ModdedOption<float>
data.Value = Value;
data.Increment = Increment;
data.ValidRange = new FloatRange(Min, Max);
data.FormatString = Increment % 1 == 0 && Value % 1 == 0 && Min % 1 == 0 && Max % 1 == 0 ? "0" : "0.0"; // not sure if the == checks will work since this is floats but we'll find out
data.FormatString = formatString ??
(!Mathf.Approximately(defaultValue, 0) ||
!Mathf.Approximately(Increment % 1, 0) ||
!Mathf.Approximately(Value % 1, 0) ||
!Mathf.Approximately(Min % 1, 0) ||
!Mathf.Approximately(Max % 1, 0) ? "0.0" : "0");
data.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = (NumberSuffixes)SuffixType;
data.OptionName = FloatOptionNames.Invalid;
+2 -1
View File
@@ -3,6 +3,7 @@ using MiraAPI.Events.Mira;
using MiraAPI.Patches;
using MiraAPI.Utilities.Assets;
using System;
using System.Globalization;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
@@ -421,7 +422,7 @@ public abstract class CustomActionButton
{
Button?.SetFillUp(Timer, EffectDuration);
Button!.cooldownTimerText.text = Mathf.CeilToInt(Timer).ToString();
Button!.cooldownTimerText.text = Mathf.CeilToInt(Timer).ToString(NumberFormatInfo.InvariantInfo);
Button!.cooldownTimerText.gameObject.SetActive(true);
}
else
+6 -3
View File
@@ -10,17 +10,20 @@ using UnityEngine;
namespace MiraAPI;
/// <summary>
/// The main plugin class for Mira API.
/// </summary>
[BepInAutoPlugin("mira.api", "MiraAPI")]
[BepInProcess("Among Us.exe")]
[BepInDependency(ReactorPlugin.Id)]
[ReactorModFlags(ModFlags.RequireOnAllClients)]
public partial class MiraApiPlugin : BasePlugin
{
private static MiraPluginManager? PluginManager { get; set; }
public Harmony Harmony { get; } = new(Id);
public static Color MiraColor { get; } = new Color32(238, 154, 112, 255);
private static MiraPluginManager? PluginManager { get; set; }
internal Harmony Harmony { get; } = new(Id);
/// <inheritdoc />
public override void Load()
{
Harmony.PatchAll();
+25 -3
View File
@@ -1,4 +1,6 @@
namespace MiraAPI.Modifiers;
using System;
namespace MiraAPI.Modifiers;
/// <summary>
/// Base class for all modifiers.
@@ -16,9 +18,19 @@ public abstract class BaseModifier
public ModifierComponent? ModifierComponent { get; internal set; }
/// <summary>
/// Gets the modifier id.
/// Gets a value indicating whether the modifier has been initialized.
/// </summary>
public uint ModifierId { get; internal set; }
public bool Initialized { get; internal set; }
/// <summary>
/// Gets the unique ID of the modifier.
/// </summary>
public Guid UniqueId { get; internal set; } = Guid.Empty;
/// <summary>
/// Gets the type ID of the modifier.
/// </summary>
public uint TypeId => ModifierManager.GetModifierTypeId(GetType()) ?? throw new InvalidOperationException("Modifier is not registered.");
/// <summary>
/// Gets the modifier name.
@@ -30,6 +42,16 @@ public abstract class BaseModifier
/// </summary>
public virtual bool HideOnUi => false;
/// <summary>
/// Gets a value indicating whether the modifier is shown in the freeplay menu.
/// </summary>
public virtual bool ShowInFreeplay => false;
/// <summary>
/// Gets a value indicating whether the modifier is unique. If true, the player can only have one instance of this modifier.
/// </summary>
public virtual bool Unique => true;
/// <summary>
/// Gets the HUD information for this modifier. Defaults to the modifier name. Does nothing if <see cref="HideOnUi"/> is true.
/// </summary>
+274 -64
View File
@@ -67,6 +67,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
foreach (var modifier in _toAdd)
{
Modifiers.Add(modifier);
modifier.Initialized = true;
modifier.OnActivate();
if (modifier is TimedModifier { AutoStart: true } timer)
@@ -103,14 +104,12 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
return;
}
var filteredModifiers = Modifiers.Where(mod => !mod.HideOnUi);
var filteredModifiers = Modifiers.Where(mod => !mod.HideOnUi).ToArray();
var baseModifiers = filteredModifiers as BaseModifier[] ?? filteredModifiers.ToArray();
if (baseModifiers.Length != 0 && !MeetingHud.Instance)
if (filteredModifiers.Length != 0 && !MeetingHud.Instance)
{
var stringBuild = new StringBuilder();
foreach (var mod in baseModifiers)
foreach (var mod in filteredModifiers)
{
stringBuild.Append(CultureInfo.InvariantCulture, $"\n{mod.GetHudString()}");
}
@@ -123,45 +122,178 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
}
/// <summary>
/// Removes a modifier from the player.
/// Gets a collection of modifiers by type.
/// </summary>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>A collection of modifiers.</returns>
[HideFromIl2Cpp]
public IEnumerable<T> GetModifiers<T>(Func<T, bool>? predicate=null) where T : BaseModifier
{
return Modifiers.OfType<T>().Where(x => predicate == null || predicate(x));
}
/// <summary>
/// Gets a collection of modifiers by type.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>A collection of modifiers.</returns>
[HideFromIl2Cpp]
public void RemoveModifier(Type type)
public IEnumerable<BaseModifier> GetModifiers(Type type, Func<BaseModifier, bool>? predicate=null)
{
var modifier = Modifiers.Find(x => x.GetType() == type);
return Modifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x)));
}
if (modifier is null)
{
Logger<MiraApiPlugin>.Error($"Cannot remove modifier {type.Name} because it is not active.");
return;
}
/// <summary>
/// Gets a collection of modifiers by type ID.
/// </summary>
/// <param name="id">The modifier's type ID.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>A collection of modifiers.</returns>
[HideFromIl2Cpp]
public IEnumerable<BaseModifier> GetModifiers(uint id, Func<BaseModifier, bool>? predicate=null)
{
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
$"Cannot get modifier with id {id} because it is not registered.");
RemoveModifier(modifier);
return GetModifiers(type, predicate);
}
/// <summary>
/// Tries to get a modifier by its type.
/// </summary>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier<T>(out T? modifier, Func<T, bool>? predicate = null) where T : BaseModifier
{
modifier = GetModifier(predicate);
return modifier != null;
}
/// <summary>
/// Tries to get a modifier by its type.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier(Type type, out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
{
modifier = GetModifier(type, predicate);
return modifier != null;
}
/// <summary>
/// Tries to get a modifier by its type ID.
/// </summary>
/// <param name="id">The modifier type ID.</param>
/// <param name="modifier">The modifier or null.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier(uint id, out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
{
modifier = GetModifier(id, predicate);
return modifier != null;
}
/// <summary>
/// Tries to get a modifier by its unique ID.
/// </summary>
/// <param name="modifierGuid">The modifier unique ID.</param>
/// <param name="modifier">The modifier or null.</param>
/// <returns>True if the modifier was found, false otherwise.</returns>
[HideFromIl2Cpp]
public bool TryGetModifier(Guid modifierGuid, out BaseModifier? modifier)
{
modifier = GetModifier(modifierGuid);
return modifier != null;
}
/// <summary>
/// Gets a modifier by its type.
/// </summary>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>The Modifier if it is found, null otherwise.</returns>
[HideFromIl2Cpp]
public T? GetModifier<T>(Func<T, bool>? predicate = null) where T : BaseModifier
{
return GetModifiers(predicate).FirstOrDefault();
}
/// <summary>
/// Gets a modifier by its type.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>The Modifier if it is found, null otherwise.</returns>
[HideFromIl2Cpp]
public BaseModifier? GetModifier(Type type, Func<BaseModifier, bool>? predicate = null)
{
return GetModifiers(type).FirstOrDefault(predicate ?? (_ => true));
}
/// <summary>
/// Gets a modifier by its type ID.
/// </summary>
/// <param name="id">The modifier ID.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
/// <returns>The Modifier if it is found, null otherwise.</returns>
[HideFromIl2Cpp]
public BaseModifier? GetModifier(uint id, Func<BaseModifier, bool>? predicate = null)
{
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
$"Cannot get modifier with id {id} because it is not registered.");
return GetModifier(type, predicate);
}
/// <summary>
/// Gets a modifier by unique ID.
/// </summary>
/// <param name="modifierGuid">The modifier's unique ID.</param>
/// <returns>The modifier if it is found, or null.</returns>
[HideFromIl2Cpp]
public BaseModifier? GetModifier(Guid modifierGuid)
{
return Modifiers.Find(x => x.UniqueId == modifierGuid);
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <typeparam name="T">The modifier type.</typeparam>
/// <param name="predicate">The predicate to check the modifier by.</param>
[HideFromIl2Cpp]
public void RemoveModifier<T>() where T : BaseModifier
public void RemoveModifier<T>(Func<T, bool>? predicate = null) where T : BaseModifier
{
RemoveModifier(typeof(T));
RemoveModifier(typeof(T), x => predicate == null || predicate((T)x));
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <param name="modifierId">The modifier ID.</param>
/// <param name="type">The modifier type.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
[HideFromIl2Cpp]
public void RemoveModifier(uint modifierId)
public void RemoveModifier(Type type, Func<BaseModifier, bool>? predicate = null)
{
var modifier = Modifiers.Find(x => x.ModifierId == modifierId);
var modifiers = Modifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x))).ToList();
if (modifiers.Count > 1)
{
throw new InvalidOperationException($"Cannot remove modifier {type.Name} because there are multiple instances of that modifier.");
}
var modifier = modifiers.FirstOrDefault();
if (modifier is null)
{
Logger<MiraApiPlugin>.Error($"Cannot remove modifier with id {modifierId} because it is not active.");
Logger<MiraApiPlugin>.Error($"Cannot remove modifier {type.Name} because it is not active.");
return;
}
@@ -184,6 +316,48 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
_toRemove.Add(modifier);
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <param name="typeId">The modifier's type ID.</param>
/// <param name="predicate">The predicate to check the modifier by.</param>
[HideFromIl2Cpp]
public void RemoveModifier(uint typeId, Func<BaseModifier, bool>? predicate = null)
{
var type = ModifierManager.GetModifierType(typeId) ?? throw new InvalidOperationException(
$"Cannot remove modifier with id {typeId} because it is not registered.");
RemoveModifier(type, predicate);
}
/// <summary>
/// Removes a modifier from the player.
/// </summary>
/// <param name="uniqueId">The modifier's unique ID.</param>
[HideFromIl2Cpp]
public void RemoveModifier(Guid uniqueId)
{
var modifier = GetModifier(uniqueId);
if (modifier == null)
{
Logger<MiraApiPlugin>.Error($"Cannot remove modifier with unique id {uniqueId} because it is not active.");
return;
}
RemoveModifier(modifier);
}
/// <summary>
/// Adds a modifier to the player.
/// </summary>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <typeparam name="T">The Type of the modifier.</typeparam>
/// <returns>The new modifier.</returns>
[HideFromIl2Cpp]
public T? AddModifier<T>(params object[] args) where T : BaseModifier
{
return AddModifier(typeof(T), args) as T;
}
/// <summary>
/// Adds a modifier to the player.
/// </summary>
@@ -192,24 +366,32 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public BaseModifier? AddModifier(BaseModifier modifier)
{
if (Modifiers.Contains(modifier))
// TODO: Make a proper synchronization system.
if (LobbyBehaviour.Instance)
{
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {modifier.ModifierId}!");
Logger<MiraApiPlugin>.Warning($"Modifiers added in the lobby won't sync to new players!");
}
var id = modifier.TypeId;
if (modifier.Unique && Modifiers.Find(x => x.TypeId == id) != null)
{
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {id}!");
return null;
}
var modifierId = ModifierManager.GetModifierId(modifier.GetType());
if (modifierId == null)
if (Modifiers.Contains(modifier))
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier {modifier.GetType().Name} because it has no ID!");
Logger<MiraApiPlugin>.Error($"Player already has this modifier!");
return null;
}
_toAdd.Add(modifier);
modifier.Player = _player;
modifier.ModifierComponent = this;
modifier.ModifierId = modifierId.Value;
if (modifier.UniqueId == Guid.Empty)
{
modifier.UniqueId = Guid.NewGuid();
}
return modifier;
}
@@ -217,62 +399,90 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
/// Adds a modifier to the player.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The modifier that was added.</returns>
[HideFromIl2Cpp]
public BaseModifier? AddModifier(Type type)
public BaseModifier? AddModifier(Type type, params object[] args)
{
var modifierId = ModifierManager.GetModifierId(type);
if (modifierId == null)
BaseModifier? modifier;
if (args.Length > 0)
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier {type.Name} because it is not registered.");
return null;
modifier = ModifierFactory.CreateInstance(type, args);
}
else
{
modifier = Activator.CreateInstance(type) as BaseModifier;
if (modifier == null)
{
throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier.");
}
}
if (Modifiers.Find(x => x.ModifierId == modifierId) != null)
{
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {modifierId}!");
return null;
}
if (Activator.CreateInstance(type) is not BaseModifier modifier)
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier {type.Name} because it is null.");
return null;
}
AddModifier(modifier);
return modifier;
return AddModifier(modifier);
}
/// <summary>
/// Adds a modifier to the player.
/// </summary>
/// <typeparam name="T">The Type of the modifier.</typeparam>
/// <returns>The new modifier.</returns>
/// <param name="id">The ID of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The modifier if it was created, or null if it failed.</returns>
[HideFromIl2Cpp]
public T? AddModifier<T>() where T : BaseModifier
public BaseModifier? AddModifier(uint id, params object[] args)
{
return AddModifier(typeof(T)) as T;
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
$"Cannot add modifier with id {id} because it is not registered.");
return AddModifier(type, args);
}
/// <summary>
/// Checks if a player has an active or queued modifier by its ID.
/// </summary>
/// <param name="id">The Modifier ID.</param>
/// <returns>True if the Modifier is present, false otherwise.</returns>
public bool HasModifier(uint id)
{
return ActiveModifiers.Exists(x => x.ModifierId == id) || _toAdd.Exists(x => x.ModifierId == id);
}
/// <summary>
/// Checks if a player has an active or queued modifier by its type.
/// Checks if a player has an active modifier by its type.
/// </summary>
/// <param name="predicate">The predicate to check the modifier.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>True if the Modifier is present, false otherwise.</returns>
public bool HasModifier<T>()
[HideFromIl2Cpp]
public bool HasModifier<T>(Func<T, bool>? predicate=null) where T : BaseModifier
{
return ActiveModifiers.Exists(x => x is T) || _toAdd.Exists(x => x is T);
return Modifiers.Exists(x => x is T modifier && (predicate == null || predicate(modifier)));
}
/// <summary>
/// Checks if a player has an active modifier by its type.
/// </summary>
/// <param name="type">The modifier type.</param>
/// <param name="predicate">The predicate to check the modifier.</param>
/// <returns>True if the Modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(Type type, Func<BaseModifier, bool>? predicate=null)
{
return Modifiers.Exists(x => x.GetType() == type && (predicate == null || predicate(x)));
}
/// <summary>
/// Checks if a player has an active modifier by its type ID.
/// </summary>
/// <param name="id">The modifier's type ID.</param>
/// <param name="predicate">The predicate to check the modifier.</param>
/// <returns>True if the modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(uint id, Func<BaseModifier, bool>? predicate=null)
{
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
$"Cannot get modifier with id {id} because it is not registered.");
return HasModifier(type, predicate);
}
/// <summary>
/// Checks if a player has an active modifier by its unique ID.
/// </summary>
/// <param name="id">The modifier's guid.</param>
/// <returns>True if the modifier is present, false otherwise.</returns>
[HideFromIl2Cpp]
public bool HasModifier(Guid id)
{
return Modifiers.Exists(x => x.UniqueId == id);
}
}
+396
View File
@@ -0,0 +1,396 @@
using System;
using System.Collections.Generic;
using MiraAPI.Networking;
using MiraAPI.Networking.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
namespace MiraAPI.Modifiers;
/// <summary>
/// Extensions for modifiers.
/// </summary>
public static class ModifierExtensions
{
/// <summary>
/// Gets the dictionary to cache ModifierComponents.
/// </summary>
public static Dictionary<PlayerControl, ModifierComponent> ModifierComponents { get; } = [];
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="target">The player to add the modifier to.</param>
/// <param name="typeId">The modifier type ID.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
public static void RpcAddModifier(this PlayerControl target, uint typeId, params object[] args)
{
_ = ModifierManager.GetModifierType(typeId) ?? throw new InvalidOperationException(
$"Modifier with ID {typeId} is not registered.");
Rpc<AddModifierRpc>.Instance.Send(target, new ModifierData(typeId, Guid.NewGuid(), args));
}
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="player">The player to add the modifier to.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
public static void RpcAddModifier(this PlayerControl player, Type type, params object[] args)
{
var id = ModifierManager.GetModifierTypeId(type) ?? throw new InvalidOperationException(
$"Modifier {type.Name} is not registered.");
player.RpcAddModifier(id, args);
}
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="player">The player to add the modifier to.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <typeparam name="T">The modifier Type.</typeparam>
public static void RpcAddModifier<T>(this PlayerControl player, params object[] args) where T : BaseModifier
{
player.RpcAddModifier(typeof(T), args);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="target">The player to remove the modifier from.</param>
/// <param name="uniqueId">The unique ID of the modifier.</param>
[MethodRpc((uint)MiraRpc.RemoveModifier)]
public static void RpcRemoveModifier(this PlayerControl target, Guid uniqueId)
{
target.RemoveModifier(uniqueId);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player by type ID.
/// </summary>
/// <param name="target">The player to remove the modifier from.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RpcRemoveModifier(
this PlayerControl target,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
var modifier = target.GetModifier(typeId, predicate);
if (modifier is null)
{
Logger<MiraApiPlugin>.Error($"Player {target.PlayerId} does not have modifier with type ID {typeId}.");
return;
}
target.RpcRemoveModifier(modifier.UniqueId);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="player">The player to remove the modifier from.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RpcRemoveModifier(
this PlayerControl player,
Type type,
Func<BaseModifier, bool>? predicate = null)
{
var id = ModifierManager.GetModifierTypeId(type) ?? throw new InvalidOperationException(
$"Modifier {type.Name} is not registered.");
player.RpcRemoveModifier(id, predicate);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="player">The player to remove the modifier from.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
public static void RpcRemoveModifier<T>(this PlayerControl player, Func<BaseModifier, bool>? predicate = null)
where T : BaseModifier
{
player.RpcRemoveModifier(typeof(T), predicate);
}
/// <summary>
/// Gets the ModifierComponent for a player.
/// </summary>
/// <param name="player">The PlayerControl object.</param>
/// <returns>A ModifierComponent if there is one, null otherwise.</returns>
public static ModifierComponent GetModifierComponent(this PlayerControl player)
{
if (ModifierComponents.TryGetValue(player, out var component))
{
return component;
}
component = player.GetComponent<ModifierComponent>();
if (!component)
{
throw new InvalidOperationException("ModifierComponent is not attached to the player.");
}
ModifierComponents[player] = component;
return component;
}
/// <summary>
/// Checks if the player has a specific modifier.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null) where T : BaseModifier
{
return player.GetModifierComponent().HasModifier(predicate);
}
/// <summary>
/// Checks if the player has a specific modifier by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier(this PlayerControl player, Type type, Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().HasModifier(type, predicate);
}
/// <summary>
/// Checks if the player has a specific modifier by type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().HasModifier(typeId, predicate);
}
/// <summary>
/// Checks if the player has a specific modifier by its GUID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="uniqueId">The unique ID of the modifier.</param>
/// <returns>True if the player has the modifier, false otherwise.</returns>
public static bool HasModifier(this PlayerControl player, Guid uniqueId)
{
return player.GetModifierComponent().HasModifier(uniqueId);
}
/// <summary>
/// Gets a specific modifier from the player.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static T? GetModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null) where T : BaseModifier
{
return player.GetModifierComponent().GetModifier(predicate);
}
/// <summary>
/// Gets a specific modifier from the player by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static BaseModifier? GetModifier(
this PlayerControl player,
Type type,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifier(type, predicate);
}
/// <summary>
/// Gets a specific modifier from the player by its type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static BaseModifier? GetModifier(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifier(typeId, predicate);
}
/// <summary>
/// Gets a specific modifier from the player by its GUID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="uniqueId">The GUID of the modifier.</param>
/// <returns>The modifier if found, null otherwise.</returns>
public static BaseModifier? GetModifier(
this PlayerControl player,
Guid uniqueId)
{
return player.GetModifierComponent().GetModifier(uniqueId);
}
/// <summary>
/// Gets all modifiers of a specific type from the player.
/// </summary>
/// <typeparam name="T">The type of the modifiers.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>A collection of modifiers.</returns>
public static IEnumerable<T> GetModifiers<T>(this PlayerControl player, Func<T, bool>? predicate = null)
where T : BaseModifier
{
return player.GetModifierComponent().GetModifiers(predicate);
}
/// <summary>
/// Gets all modifiers of a specific type from the player.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifiers.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>A collection of modifiers.</returns>
public static IEnumerable<BaseModifier> GetModifiers(
this PlayerControl player,
Type type,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifiers(type, predicate);
}
/// <summary>
/// Gets all modifiers of a specific type from the player by type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifiers.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
/// <returns>A collection of modifiers.</returns>
public static IEnumerable<BaseModifier> GetModifiers(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
return player.GetModifierComponent().GetModifiers(typeId, predicate);
}
/// <summary>
/// Removes a specific modifier from the player.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="modifier">The modifier to remove.</param>
public static void RemoveModifier(this PlayerControl player, BaseModifier modifier)
{
player.GetModifierComponent().RemoveModifier(modifier);
}
/// <summary>
/// Removes a specific modifier from the player.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RemoveModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null)
where T : BaseModifier
{
player.GetModifierComponent().RemoveModifier(predicate);
}
/// <summary>
/// Removes a specific modifier from the player by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RemoveModifier(this PlayerControl player, Type type, Func<BaseModifier, bool>? predicate = null)
{
player.GetModifierComponent().RemoveModifier(type, predicate);
}
/// <summary>
/// Removes a specific modifier from the player by its type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
public static void RemoveModifier(
this PlayerControl player,
uint typeId,
Func<BaseModifier, bool>? predicate = null)
{
player.GetModifierComponent().RemoveModifier(typeId, predicate);
}
/// <summary>
/// Removes a specific modifier from the player by its GUID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="uniqueId">The GUID of the modifier.</param>
public static void RemoveModifier(
this PlayerControl player,
Guid uniqueId)
{
player.GetModifierComponent().RemoveModifier(uniqueId);
}
/// <summary>
/// Adds a specific modifier to the player.
/// </summary>
/// <typeparam name="T">The type of the modifier.</typeparam>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The added modifier.</returns>
public static T? AddModifier<T>(this PlayerControl player, params object[] args) where T : BaseModifier
{
return player.GetModifierComponent().AddModifier<T>(args);
}
/// <summary>
/// Adds a specific modifier to the player.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="modifier">The modifier to add.</param>
/// <returns>The added modifier.</returns>
public static BaseModifier? AddModifier(this PlayerControl player, BaseModifier modifier)
{
return player.GetModifierComponent().AddModifier(modifier);
}
/// <summary>
/// Adds a specific modifier to the player by type.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="type">The type of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The added modifier.</returns>
public static BaseModifier? AddModifier(this PlayerControl player, Type type, params object[] args)
{
return player.GetModifierComponent().AddModifier(type, args);
}
/// <summary>
/// Adds a specific modifier to the player by type ID.
/// </summary>
/// <param name="player">The PlayerControl instance.</param>
/// <param name="typeId">The type ID of the modifier.</param>
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
/// <returns>The added modifier.</returns>
public static BaseModifier? AddModifier(this PlayerControl player, uint typeId, params object[] args)
{
return player.GetModifierComponent().AddModifier(typeId, args);
}
}
+102
View File
@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MiraAPI.Utilities;
namespace MiraAPI.Modifiers;
/// <summary>
/// Factory for creating instances of a modifier. More efficient than using reflection.
/// </summary>
public static class ModifierFactory
{
private static readonly Dictionary<(Type, Type[]), Func<object[], BaseModifier>> _constructorCache = [];
private static Func<object[], BaseModifier> CreateConstructor(Type type, params object[] args)
{
var constructorInfo = type.GetBestConstructor(args) ?? throw new InvalidOperationException(
$"Could not find a constructor for type {type} with the specified arguments.");
var parameters = constructorInfo.GetParameters();
var argsParam = Expression.Parameter(typeof(object[]), "args");
var constructorParams = new Expression[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var paramType = parameters[i].ParameterType;
var paramAccess = Expression.ArrayIndex(argsParam, Expression.Constant(i));
var convertedParam = Expression.Convert(paramAccess, paramType);
constructorParams[i] = convertedParam;
}
var newExpr = Expression.New(constructorInfo, constructorParams);
var lambda = Expression.Lambda<Func<object[], BaseModifier>>(newExpr, argsParam);
return lambda.Compile();
}
/// <summary>
/// Creates a modifier with the specified type and arguments.
/// </summary>
/// <param name="type">Modifier type.</param>
/// <param name="args">Arguments.</param>
/// <returns>An instance of the modifier.</returns>
public static BaseModifier CreateInstance(Type type, params object[] args)
{
var argTypes = args.Select(arg => arg?.GetType() ?? typeof(object)).ToArray();
var key = (type, argTypes);
if (!_constructorCache.TryGetValue(key, out var constructor))
{
constructor = CreateConstructor(type, args);
_constructorCache[key] = constructor;
}
return constructor(args);
}
}
/// <summary>
/// Factory for creating instances of a modifier. More efficient than using reflection.
/// </summary>
/// <typeparam name="T">The modifier type.</typeparam>
public static class ModifierFactory<T> where T : BaseModifier
{
private static readonly Func<object[], T> Constructor = CreateConstructor();
private static Func<object[], T> CreateConstructor(params object[] args)
{
var constructorInfo = typeof(T).GetBestConstructor(args) ?? throw new InvalidOperationException(
$"Could not find a constructor for type {typeof(T)} with the specified arguments.");
var parameters = constructorInfo.GetParameters();
var argsParam = Expression.Parameter(typeof(object[]), "args");
var constructorParams = new Expression[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var paramType = parameters[i].ParameterType;
var paramAccess = Expression.ArrayIndex(argsParam, Expression.Constant(i));
var convertedParam = Expression.Convert(paramAccess, paramType);
constructorParams[i] = convertedParam;
}
var newExpr = Expression.New(constructorInfo, constructorParams);
var lambda = Expression.Lambda<Func<object[], T>>(newExpr, argsParam);
return lambda.Compile();
}
/// <summary>
/// Creates an instance of the modifier.
/// </summary>
/// <param name="args">Parameters for the constructor.</param>
/// <returns>An instance of the modifier.</returns>
public static T CreateInstance(params object[] args)
{
return Constructor(args);
}
}
+22 -80
View File
@@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using MiraAPI.Modifiers.Types;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using Random = System.Random;
@@ -21,16 +21,16 @@ public static class ModifierManager
private static readonly Dictionary<Type, uint> TypeToIdModifierMap = [];
private static readonly Dictionary<int, List<uint>> PrioritiesToIdsMap = [];
private static uint _nextId;
private static uint _nextTypeId;
private static uint GetNextId()
private static uint GetNextTypeId()
{
_nextId++;
return _nextId;
_nextTypeId++;
return _nextTypeId;
}
/// <summary>
/// Gets the modifier type from the id.
/// Gets the modifier type from the type id.
/// </summary>
/// <param name="id">The ID.</param>
/// <returns>The Type of the modifier.</returns>
@@ -44,20 +44,27 @@ public static class ModifierManager
/// </summary>
/// <param name="type">The Type.</param>
/// <returns>The ID of the modifier.</returns>
public static uint? GetModifierId(Type type)
public static uint? GetModifierTypeId(Type type)
{
return TypeToIdModifierMap.GetValueOrDefault(type);
if (!TypeToIdModifierMap.TryGetValue(type, out var id))
{
return null;
}
return id;
}
internal static bool RegisterModifier(Type modifierType)
internal static bool RegisterModifier(Type modifierType, MiraPluginInfo info)
{
if (!typeof(BaseModifier).IsAssignableFrom(modifierType))
{
return false;
}
IdToTypeModifierMap.Add(GetNextId(), modifierType);
TypeToIdModifierMap.Add(modifierType, _nextId);
IdToTypeModifierMap.Add(GetNextTypeId(), modifierType);
TypeToIdModifierMap.Add(modifierType, _nextTypeId);
var bm = (BaseModifier)FormatterServices.GetUninitializedObject(modifierType); // this probably isn't a great idea
info.Modifiers.Add(bm);
if (!typeof(GameModifier).IsAssignableFrom(modifierType))
{
@@ -72,7 +79,7 @@ public static class ModifierManager
PrioritiesToIdsMap[priority] = list = [];
}
list.Add(_nextId);
list.Add(_nextTypeId);
return true;
}
@@ -134,7 +141,7 @@ public static class ModifierManager
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
var plr = plrs.Where(x => IsGameModifierValid(x, mod!, id)).Random();
if (plr == null)
if (!plr || plr == null)
{
Logger<MiraApiPlugin>.Warning($"Somehow valid players for modifier {mod!.ModifierName} disappeared");
}
@@ -149,71 +156,6 @@ public static class ModifierManager
private static bool IsGameModifierValid(PlayerControl player, GameModifier modifier, uint modifierId)
{
return (player.Data.Role is not ICustomRole role || role.IsModifierApplicable(modifier)) &&
modifier.IsModifierValidOn(player.Data.Role) &&
!player.HasModifier(modifierId);
}
internal static void SyncAllModifiers(int targetId = -1)
{
var data = new List<NetData>();
foreach (var player in PlayerControl.AllPlayerControls)
{
data.Add(GetPlayerModifiers(player));
}
Rpc<SyncModifiersRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, [.. data]);
}
internal static void HandleSyncModifiers(NetData[] data)
{
foreach (var netData in data)
{
var ids = new uint[netData.Data.Length / 4];
Buffer.BlockCopy(netData.Data, 0, ids, 0, netData.Data.Length);
var plr = GameData.Instance.GetPlayerById((byte)netData.Id).Object;
var modifierComponent = plr.GetComponent<ModifierComponent>();
if (!modifierComponent)
{
continue;
}
modifierComponent.ClearModifiers();
foreach (var id in ids)
{
if (!IdToTypeModifierMap.TryGetValue(id, out var type))
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier with id {id} because it is not registered.");
continue;
}
modifierComponent.AddModifier(type);
}
}
}
private static NetData GetPlayerModifiers(PlayerControl? player)
{
if (player == null || !player)
{
return new NetData(0, []);
}
List<byte> bytes = [];
var modifierComponent = player.GetComponent<ModifierComponent>();
if (modifierComponent == null || !modifierComponent)
{
return new NetData(player.PlayerId, []);
}
foreach (var modifier in modifierComponent.ActiveModifiers)
{
bytes.AddRange(BitConverter.GetBytes(TypeToIdModifierMap[modifier.GetType()]));
}
return new NetData(player.PlayerId, [.. bytes]);
modifier.IsModifierValidOn(player.Data.Role) && !player.HasModifier(modifierId);
}
}
+3
View File
@@ -5,6 +5,9 @@
/// </summary>
public abstract class GameModifier : BaseModifier
{
/// <inheritdoc />
public override bool ShowInFreeplay => true;
/// <summary>
/// Gets the chance of the modifier being assigned to a player.
/// </summary>
+5 -3
View File
@@ -17,7 +17,7 @@ public abstract class TimedModifier : BaseModifier
/// <summary>
/// Gets a value indicating whether the timer should start automatically when added.
/// </summary>
public virtual bool AutoStart => false;
public virtual bool AutoStart => true;
/// <summary>
/// Gets a value indicating whether the modifier should be removed when the timer completes.
@@ -27,7 +27,9 @@ public abstract class TimedModifier : BaseModifier
/// <summary>
/// Called when the timer completes.
/// </summary>
public abstract void OnTimerComplete();
public virtual void OnTimerComplete()
{
}
/// <summary>
/// Gets or sets a value indicating whether the timer is active.
@@ -102,7 +104,7 @@ public abstract class TimedModifier : BaseModifier
if (RemoveOnComplete)
{
ModifierComponent?.RemoveModifier(ModifierId);
ModifierComponent?.RemoveModifier(this);
}
}
+64
View File
@@ -0,0 +1,64 @@
using System.Collections.Generic;
using Hazel;
using InnerNet;
using MiraAPI.GameEnd;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
namespace MiraAPI.Networking;
/// <summary>
/// Custom Game Over RPC.
/// </summary>
/// <inheritdoc />
[RegisterCustomRpc((uint)MiraRpc.CustomGameOver)]
public class CustomGameOverRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, GameOverData>(plugin, id)
{
/// <inheritdoc />
public override RpcLocalHandling LocalHandling => RpcLocalHandling.After;
/// <inheritdoc />
public override void Write(MessageWriter writer, GameOverData data)
{
writer.WritePacked(data.Reason);
writer.WritePacked(data.Winners.Count);
foreach (var player in data.Winners)
{
writer.WriteNetObject(player);
}
}
/// <inheritdoc />
public override GameOverData Read(MessageReader reader)
{
var reason = reader.ReadPackedInt32();
var count = reader.ReadPackedInt32();
var data = new List<NetworkedPlayerInfo>(count);
for (var i = 0; i < count; i++)
{
data.Add(reader.ReadNetObject<NetworkedPlayerInfo>());
}
return new GameOverData(reason, data);
}
/// <inheritdoc />
public override void Handle(PlayerControl innerNetObject, GameOverData data)
{
if (GameOverManager.TryGetGameOver(data.Reason, out var gameOver))
{
CustomGameOver.Instance = gameOver;
if (AmongUsClient.Instance.AmHost)
{
GameManager.Instance.RpcEndGame(gameOver!, false);
}
}
else
{
CustomGameOver.Instance = null;
Logger<MiraApiPlugin>.Error($"Unknown game over reason: {data.Reason}");
}
}
}
+3 -3
View File
@@ -263,6 +263,9 @@ public static class CustomMurderRpc
deadBody.enabled = true;
}
var afterMurderEvent = new AfterMurderEvent(source, target);
MiraEventManager.InvokeEvent(afterMurderEvent);
if (!isParticipant)
{
yield break;
@@ -275,8 +278,5 @@ public static class CustomMurderRpc
PlayerControl.LocalPlayer.isKilling = false;
source.isKilling = false;
var afterMurderEvent = new AfterMurderEvent(source, target);
MiraEventManager.InvokeEvent(afterMurderEvent);
}
}
+32
View File
@@ -0,0 +1,32 @@
using System;
using Hazel;
using Reactor.Networking.Attributes;
using Reactor.Networking.Serialization;
namespace MiraAPI.Networking;
/// <summary>
/// Converter for <see cref="Guid"/>.
/// </summary>
[MessageConverter]
public class GuidConverter : MessageConverter<Guid>
{
/// <summary>
/// Writes a <see cref="Guid"/> to the writer.
/// </summary>
/// <inheritdoc />
public override void Write(MessageWriter writer, Guid value)
{
writer.WriteBytesAndSize(value.ToByteArray());
}
/// <summary>
/// Reads a <see cref="Guid"/> from the reader.
/// </summary>
/// <inheritdoc />
/// <returns>A GUID object.</returns>
public override Guid Read(MessageReader reader, Type objectType)
{
return new Guid(reader.ReadBytesAndSize());
}
}
+5
View File
@@ -34,4 +34,9 @@ public enum MiraRpc : uint
/// Custom Murder RPC.
/// </summary>
CustomMurder,
/// <summary>
/// Custom Game Over RPC.
/// </summary>
CustomGameOver,
}
@@ -0,0 +1,76 @@
using System;
using Hazel;
using MiraAPI.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Networking.Serialization;
namespace MiraAPI.Networking.Modifiers;
/// <summary>
/// Remote procedure call for adding a modifier.
/// </summary>
/// <param name="plugin">Mira plugin.</param>
/// <param name="id">RPC ID.</param>
[RegisterCustomRpc((uint)MiraRpc.AddModifier)]
public class AddModifierRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, ModifierData>(plugin, id)
{
/// <inheritdoc />
public override RpcLocalHandling LocalHandling => RpcLocalHandling.Before;
/// <inheritdoc />
public override void Write(MessageWriter writer, ModifierData data)
{
writer.WritePacked(data.TypeId);
writer.WriteBytesAndSize(data.UniqueId.ToByteArray());
writer.WritePacked(data.Args.Length);
foreach (var arg in data.Args)
{
writer.Write(arg.GetType().AssemblyQualifiedName);
writer.Serialize(arg);
}
}
/// <inheritdoc />
public override ModifierData Read(MessageReader reader)
{
var modId = reader.ReadPackedUInt32();
var guid = new Guid(reader.ReadBytesAndSize());
var argCount = reader.ReadPackedUInt32();
var objects = new object[argCount];
if (argCount > 0)
{
var types = new Type[argCount];
for (var i = 0; i < argCount; i++)
{
var name = reader.ReadString();
types[i] = Type.GetType(name) ?? throw new InvalidOperationException($"Type not found: {name}");
objects[i] = reader.Deserialize(types[i]);
}
}
return new ModifierData(modId, guid, objects);
}
/// <inheritdoc />
public override void Handle(PlayerControl player, ModifierData data)
{
var type = ModifierManager.GetModifierType(data.TypeId) ?? throw new InvalidOperationException($"Modifier type not found for ID {data.TypeId}.");
BaseModifier? modifier;
if (data.Args.Length > 0)
{
modifier = ModifierFactory.CreateInstance(type, data.Args);
}
else
{
modifier = Activator.CreateInstance(type) as BaseModifier;
if (modifier == null)
{
throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier.");
}
}
modifier.UniqueId = data.UniqueId;
player.AddModifier(modifier);
}
}
@@ -0,0 +1,40 @@
using System;
using Hazel;
using InnerNet;
using MiraAPI.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Serialization;
namespace MiraAPI.Networking.Modifiers;
/// <summary>
/// Converter for serializing and deserializing <see cref="BaseModifier"/> objects.
/// </summary>
[MessageConverter]
public class ModifierConverter : MessageConverter<BaseModifier>
{
/// <summary>
/// Writes a <see cref="BaseModifier"/> to the writer.
/// </summary>
/// <param name="writer">The writer to write to.</param>
/// <param name="value">The <see cref="BaseModifier"/> to write.</param>
public override void Write(MessageWriter writer, BaseModifier value)
{
writer.WriteNetObject(value.Player);
writer.WriteBytesAndSize(value.UniqueId.ToByteArray());
}
/// <summary>
/// Reads a <see cref="BaseModifier"/> from the reader.
/// </summary>
/// <param name="reader">The reader to read from.</param>
/// <param name="objectType">The type of the object to read.</param>
/// <returns>The <see cref="BaseModifier"/> that was read.</returns>
/// <exception cref="InvalidOperationException">Thrown if the modifier is not found.</exception>
public override BaseModifier Read(MessageReader reader, Type objectType)
{
var player = reader.ReadNetObject<PlayerControl>();
var guid = new Guid(reader.ReadBytesAndSize());
return player.GetModifier(guid) ?? throw new InvalidOperationException($"Modifier with GUID {guid} not found for player {player.NetId}.");
}
}
@@ -0,0 +1,11 @@
using System;
namespace MiraAPI.Networking.Modifiers;
/// <summary>
/// Modifier data for networking.
/// </summary>
/// <param name="TypeId">The ID of the modifier.</param>
/// <param name="UniqueId">The unique ID of the modifier.</param>
/// <param name="Args">Parameters for constructor.</param>
public record struct ModifierData(uint TypeId, Guid UniqueId, object[] Args);
-52
View File
@@ -1,52 +0,0 @@
using Hazel;
using MiraAPI.Modifiers;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
namespace MiraAPI.Networking;
[RegisterCustomRpc((uint)MiraRpc.SyncModifiers)]
internal sealed class SyncModifiersRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
{
public override RpcLocalHandling LocalHandling => RpcLocalHandling.None;
public override void Write(MessageWriter writer, NetData[]? data)
{
if (data == null)
{
writer.WritePacked(0U);
return;
}
writer.WritePacked((uint)data.Length);
foreach (var netData in data)
{
writer.WritePacked(netData.Id);
writer.WriteBytesAndSize(netData.Data);
}
}
public override NetData[] Read(MessageReader reader)
{
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 data;
}
public override void Handle(PlayerControl playerControl, NetData[]? data)
{
if (AmongUsClient.Instance.HostId != playerControl.OwnerId)
{
return;
}
ModifierManager.HandleSyncModifiers(data ?? []);
}
}
+2 -4
View File
@@ -3,16 +3,15 @@ using InnerNet;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Player;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
namespace MiraAPI.Patches;
/// <summary>
/// Sync all options, role settings, and modifiers to the player when they join the game.
/// Sync all settings to the player when they join the game.
/// </summary>
[HarmonyPatch(typeof(AmongUsClient))]
public static class AmongUsClientSyncPatch
internal static class AmongUsClientSyncPatch
{
[HarmonyPostfix]
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CreatePlayer))]
@@ -33,7 +32,6 @@ public static class AmongUsClientSyncPatch
ModdedOptionsManager.SyncAllOptions(clientData.Id);
CustomRoleManager.SyncAllRoleSettings(clientData.Id);
ModifierManager.SyncAllModifiers(clientData.Id);
}
[HarmonyPostfix]
@@ -4,17 +4,19 @@ using UnityEngine;
namespace MiraAPI.Patches.Colors;
[HarmonyPatch(typeof(PlayerTab))]
/// <summary>
/// This patch adds scrolling to the colors tab in the player customization menu.
/// </summary>
[HarmonyPatch(typeof(PlayerTab), nameof(PlayerTab.OnEnable))]
public static class ScrollingColorsPatch
{
// Collider
private static BoxCollider2D? _collider;
/// <summary>
/// Add scrolling to the colors tab
/// Add scrolling to the colors tab.
/// </summary>
[HarmonyPostfix, HarmonyPatch("OnEnable")]
public static void AddScrollingToColorsTabPatch(PlayerTab __instance)
public static void Postfix(PlayerTab __instance)
{
if (!PlayerCustomizationMenu.Instance)
{
+21 -8
View File
@@ -1,19 +1,32 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.GameEnd;
namespace MiraAPI.Patches.Events;
/// <summary>
/// Patch for trigging the GameEndEvent.
/// </summary>
[HarmonyPatch]
public static class EndGamePatches
[HarmonyPatch(typeof(EndGameManager), nameof(EndGameManager.SetEverythingUp))]
internal static class EndGamePatches
{
[HarmonyPostfix]
[HarmonyPatch(typeof(EndGameManager), nameof(EndGameManager.SetEverythingUp))]
public static void SetEverythingUpPatch(EndGameManager __instance)
public static bool Prefix(EndGameManager __instance)
{
if (CustomGameOver.Instance is not { } gameOver)
{
return true;
}
var result = gameOver.BeforeEndGameSetup(__instance);
return result;
}
public static void Postfix(EndGameManager __instance)
{
if (CustomGameOver.Instance is { } gameOver)
{
gameOver.AfterEndGameSetup(__instance);
CustomGameOver.Instance = null;
}
var @event = new GameEndEvent(__instance);
MiraEventManager.InvokeEvent(@event);
}
@@ -2,7 +2,7 @@
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
namespace MiraAPI.Patches;
namespace MiraAPI.Patches.Events;
/// <summary>
/// General patches for the KillAnimation class.
+1 -1
View File
@@ -1,8 +1,8 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla;
using System.Collections.Generic;
using System.Reflection;
using MiraAPI.Events.Vanilla.Usables;
namespace MiraAPI.Patches.Events;
@@ -0,0 +1,36 @@
using HarmonyLib;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Patches.Freeplay;
[HarmonyPatch(typeof(TaskAddButton))]
internal static class TaskAddButtonPatches
{
[HarmonyPrefix]
[HarmonyPatch(nameof(TaskAddButton.Start))]
public static bool StartPrefix(TaskAddButton __instance)
{
// if this becomes problematic in the future, find a new method.
if (uint.TryParse(__instance.name, out var result))
{
__instance.Overlay.sprite = __instance.CheckImage;
__instance.Overlay.enabled = PlayerControl.LocalPlayer.HasModifier(result);
return false;
}
return true;
}
[HarmonyPostfix]
[HarmonyPatch(nameof(TaskAddButton.Role), MethodType.Setter)]
public static void RoleGetterPatch(TaskAddButton __instance)
{
if (__instance.role is ICustomRole { Team: ModdedRoleTeams.Custom } customRole)
{
__instance.FileImage.color = customRole.IntroConfiguration?.IntroTeamColor ?? Color.gray;
}
__instance.RolloverHandler.OutColor = __instance.FileImage.color;
}
}
@@ -1,28 +1,27 @@
using AmongUs.GameOptions;
using System;
using System.Globalization;
using System.Linq;
using AmongUs.GameOptions;
using HarmonyLib;
using System;
using System.Collections.Generic;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Roles;
namespace MiraAPI.Patches.Freeplay;
/// <summary>
/// Patch TaskAdder for organizing Roles and adding scroller.
/// </summary>
[HarmonyPatch]
public static class TaskAdderPatch
[HarmonyPatch(typeof(TaskAdderGame))]
internal static class TaskAdderPatches
{
private static readonly Dictionary<string, string> ModsFolders = [];
private static Scroller? _scroller;
[HarmonyPostfix]
[HarmonyPatch(typeof(TaskAdderGame), nameof(TaskAdderGame.Begin))]
[HarmonyPatch(nameof(TaskAdderGame.Begin))]
public static void AddRolesFolder(TaskAdderGame __instance)
{
GameObject inner = new("Inner");
@@ -63,41 +62,38 @@ public static class TaskAdderPatch
rolesFolder.FolderName = "Roles";
rolesFolder.name = "RolesFolder";
var modifiersFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
modifiersFolder.gameObject.SetActive(false);
modifiersFolder.FolderName = "Modifiers";
modifiersFolder.name = "ModifiersFolder";
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
{
if (plugin.CustomRoles.Count == 0)
if (plugin.CustomRoles.Any(x => x.Value is ICustomRole { Configuration.ShowInFreeplay: true }))
{
continue;
var newFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
newFolder.name = plugin.PluginId+":Roles";
newFolder.FolderName = plugin.PluginInfo.Metadata.Name;
newFolder.gameObject.SetActive(false);
rolesFolder.SubFolders.Add(newFolder);
}
var newFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
newFolder.FolderName = newFolder.name = plugin.PluginInfo.Metadata.Name;
newFolder.gameObject.SetActive(false);
rolesFolder.SubFolders.Add(newFolder);
if (!ModsFolders.ContainsKey(plugin.PluginInfo.Metadata.Name))
if (plugin.Modifiers.Exists(x => x.ShowInFreeplay))
{
ModsFolders.Add(plugin.PluginInfo.Metadata.Name, plugin.PluginId);
var newFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
newFolder.name = plugin.PluginId+":Modifiers";
newFolder.FolderName = plugin.PluginInfo.Metadata.Name;
newFolder.gameObject.SetActive(false);
modifiersFolder.SubFolders.Add(newFolder);
}
}
__instance.Root.SubFolders.Add(rolesFolder);
__instance.Root.SubFolders.Add(modifiersFolder);
__instance.GoToRoot();
}
[HarmonyPostfix]
[HarmonyPatch(typeof(TaskAddButton), "Role", MethodType.Setter)]
public static void RoleGetterPatch(TaskAddButton __instance)
{
if (__instance.role is ICustomRole { Team: ModdedRoleTeams.Neutral })
{
__instance.FileImage.color = Color.gray;
}
__instance.RolloverHandler.OutColor = __instance.FileImage.color;
}
private static void AddFileAsChildCustom(
this TaskAdderGame instance,
TaskAddButton item,
@@ -122,8 +118,8 @@ public static class TaskAdderPatch
// yes it might be crazy patching the entire method, but i tried so many other methods and only this works :cry:
[HarmonyPrefix]
[HarmonyPatch(typeof(TaskAdderGame), nameof(TaskAdderGame.ShowFolder))]
public static bool ShowPatch(TaskAdderGame __instance, [HarmonyArgument(0)] TaskFolder taskFolder)
[HarmonyPatch(nameof(TaskAdderGame.ShowFolder))]
public static bool ShowPatch(TaskAdderGame __instance, TaskFolder taskFolder)
{
var stringBuilder = new Il2CppSystem.Text.StringBuilder(64);
__instance.Hierarchy.Add(taskFolder);
@@ -186,23 +182,23 @@ public static class TaskAdderPatch
switch (taskAddButton.MyTask.TaskType)
{
case TaskTypes.DivertPower:
{
var targetSystem = taskAddButton.MyTask.Cast<DivertPowerTask>().TargetSystem;
taskAddButton.Text.text = TranslationController.Instance.GetString(
StringNames.DivertPowerTo,
TranslationController.Instance.GetString(targetSystem));
break;
}
{
var targetSystem = taskAddButton.MyTask.Cast<DivertPowerTask>().TargetSystem;
taskAddButton.Text.text = TranslationController.Instance.GetString(
StringNames.DivertPowerTo,
TranslationController.Instance.GetString(targetSystem));
break;
}
case TaskTypes.FixWeatherNode:
{
var nodeId = taskAddButton.MyTask.Cast<WeatherNodeTask>().NodeId;
taskAddButton.Text.text =
TranslationController.Instance.GetString(
StringNames.FixWeatherNode) + " " +
TranslationController.Instance.GetString(
WeatherSwitchGame.ControlNames[nodeId]);
break;
}
{
var nodeId = taskAddButton.MyTask.Cast<WeatherNodeTask>().NodeId;
taskAddButton.Text.text =
TranslationController.Instance.GetString(
StringNames.FixWeatherNode) + " " +
TranslationController.Instance.GetString(
WeatherSwitchGame.ControlNames[nodeId]);
break;
}
default:
taskAddButton.Text.text =
TranslationController.Instance.GetString(taskAddButton.MyTask.TaskType);
@@ -269,46 +265,31 @@ public static class TaskAdderPatch
}
}
if (ModsFolders.TryGetValue(taskFolder.FolderName, out var guid))
if (taskFolder)
{
var plugin = MiraPluginManager.GetPluginByGuid(guid);
for (var m = 0; m < plugin.CustomRoles.Count; m++)
var split = taskFolder.name.Split(':');
if (split.Length == 2)
{
var roleBehaviour = plugin.CustomRoles.ElementAt(m).Value;
if (roleBehaviour.Role == RoleTypes.ImpostorGhost || roleBehaviour.Role == RoleTypes.CrewmateGhost ||
roleBehaviour.IsDead)
{
continue;
}
var pluginId = split[0];
var folderName = split[1];
var taskAddButton2 = Object.Instantiate(__instance.RoleButton);
taskAddButton2.SafePositionWorld = __instance.SafePositionWorld;
taskAddButton2.Text.text = "Be_" + roleBehaviour.NiceName + ".exe";
__instance.AddFileAsChildCustom(taskAddButton2, ref num, ref num2, ref num3);
taskAddButton2.Role = roleBehaviour;
if (taskAddButton2.Button == null)
if (MiraPluginManager.GetPluginByGuid(pluginId) is { } plugin)
{
continue;
}
ControllerManager.Instance.AddSelectableUiElement(taskAddButton2.Button);
switch (m)
{
case 0 when __instance.restorePreviousSelectionFound != null:
ControllerManager.Instance.SetDefaultSelection(__instance.restorePreviousSelectionFound);
__instance.restorePreviousSelectionByFolderName = string.Empty;
__instance.restorePreviousSelectionFound = null;
break;
case 0:
ControllerManager.Instance.SetDefaultSelection(taskAddButton2.Button);
break;
if (folderName == "Roles(Clone)")
{
PluginRoles(__instance, plugin, ref num, ref num2, ref num3);
}
else if (folderName == "Modifiers(Clone)")
{
PluginModifiers(__instance, plugin, ref num, ref num2, ref num3);
}
}
}
}
foreach (var chip in __instance.ActiveItems)
{
chip.GetComponentInChildren<TextMeshPro>().EnableMasking();
chip.GetComponentInChildren<TextMeshPro>().EnableStencilMasking();
chip.GetComponent<SpriteRenderer>().maskInteraction = SpriteMaskInteraction.VisibleInsideMask;
}
@@ -328,4 +309,98 @@ public static class TaskAdderPatch
ControllerManager.Instance.SetBackButton(__instance.FolderBackButton);
return false;
}
private static void PluginModifiers(
TaskAdderGame instance,
MiraPluginInfo plugin,
ref float num,
ref float num2,
ref float num3)
{
for (var m = 0; m < plugin.Modifiers.Count; m++)
{
var modifier = plugin.Modifiers[m];
if (!modifier.ShowInFreeplay)
{
continue;
}
var taskAddButton = Object.Instantiate(instance.RoleButton);
taskAddButton.name = modifier.TypeId.ToString(NumberFormatInfo.InvariantInfo);
taskAddButton.role = null;
taskAddButton.MyTask = null;
taskAddButton.SafePositionWorld = instance.SafePositionWorld;
taskAddButton.Text.text = modifier.ModifierName;
taskAddButton.Text.EnableMasking();
taskAddButton.Button.OnClick = new Button.ButtonClickedEvent();
taskAddButton.Button.OnClick.AddListener((UnityEngine.Events.UnityAction)(() =>
{
var id = modifier.TypeId;
if (PlayerControl.LocalPlayer.HasModifier(id))
{
PlayerControl.LocalPlayer.RemoveModifier(id);
taskAddButton.Overlay.enabled = false;
}
else
{
PlayerControl.LocalPlayer.AddModifier(id);
taskAddButton.Overlay.enabled = true;
}
}));
instance.AddFileAsChildCustom(taskAddButton, ref num, ref num2, ref num3);
ControllerManager.Instance.AddSelectableUiElement(taskAddButton.Button);
switch (m)
{
case 0 when instance.restorePreviousSelectionFound != null:
ControllerManager.Instance.SetDefaultSelection(instance.restorePreviousSelectionFound);
instance.restorePreviousSelectionByFolderName = string.Empty;
instance.restorePreviousSelectionFound = null;
break;
case 0:
ControllerManager.Instance.SetDefaultSelection(taskAddButton.Button);
break;
}
}
}
private static void PluginRoles(TaskAdderGame instance, MiraPluginInfo plugin, ref float num, ref float num2, ref float num3)
{
for (var m = 0; m < plugin.CustomRoles.Count; m++)
{
var roleBehaviour = plugin.CustomRoles.ElementAt(m).Value;
if (roleBehaviour.Role == RoleTypes.ImpostorGhost || roleBehaviour.Role == RoleTypes.CrewmateGhost ||
roleBehaviour is ICustomRole { Configuration.ShowInFreeplay: false })
{
continue;
}
var taskAddButton2 = Object.Instantiate(instance.RoleButton);
taskAddButton2.SafePositionWorld = instance.SafePositionWorld;
taskAddButton2.Text.text = "Be_" + roleBehaviour.NiceName + ".exe";
taskAddButton2.Text.EnableMasking();
instance.AddFileAsChildCustom(taskAddButton2, ref num, ref num2, ref num3);
taskAddButton2.Role = roleBehaviour;
if (taskAddButton2.Button == null)
{
continue;
}
ControllerManager.Instance.AddSelectableUiElement(taskAddButton2.Button);
switch (m)
{
case 0 when instance.restorePreviousSelectionFound != null:
ControllerManager.Instance.SetDefaultSelection(instance.restorePreviousSelectionFound);
instance.restorePreviousSelectionByFolderName = string.Empty;
instance.restorePreviousSelectionFound = null;
break;
case 0:
ControllerManager.Instance.SetDefaultSelection(taskAddButton2.Button);
break;
}
}
}
}
+16 -22
View File
@@ -31,36 +31,30 @@ public static class IntroCutscenePatches
}
[HarmonyPrefix]
[HarmonyPatch(nameof(IntroCutscene.BeginImpostor))]
[HarmonyPatch(nameof(IntroCutscene.BeginCrewmate))]
public static bool BeginCrewmatePatch(IntroCutscene __instance)
public static bool BeginPrefix(IntroCutscene __instance, [HarmonyArgument(0)] ref Il2CppSystem.Collections.Generic.List<PlayerControl> yourTeam)
{
return PlayerControl.LocalPlayer.Data.Role is not ICustomRole customRole || customRole.SetupIntroTeam(__instance, ref yourTeam);
}
[HarmonyPostfix]
[HarmonyPatch(nameof(IntroCutscene.BeginImpostor))]
[HarmonyPatch(nameof(IntroCutscene.BeginCrewmate))]
public static void BeginPostfix(IntroCutscene __instance)
{
if (PlayerControl.LocalPlayer.Data.Role is not ICustomRole customRole)
{
return true;
return;
}
if (customRole.Team is not ModdedRoleTeams.Neutral)
if (customRole.IntroConfiguration is { } introConfig)
{
return true;
__instance.BackgroundBar.material.SetColor(ShaderID.Color, introConfig.IntroTeamColor);
__instance.TeamTitle.color = introConfig.IntroTeamColor;
__instance.TeamTitle.text = introConfig.IntroTeamTitle;
__instance.ImpostorText.text = introConfig.IntroTeamDescription;
}
var barTransform = __instance.BackgroundBar.transform;
var position = barTransform.position;
position.y -= 0.25f;
barTransform.position = position;
__instance.BackgroundBar.material.SetColor(ShaderID.Color, Color.gray);
__instance.TeamTitle.text = "NEUTRAL";
__instance.impostorScale = 1f;
__instance.ImpostorText.text = "You are Neutral. You do not have a team.";
__instance.TeamTitle.color = Color.gray;
__instance.ourCrewmate = __instance.CreatePlayer(
0,
Mathf.CeilToInt(7.5f),
PlayerControl.LocalPlayer.Data,
false);
return false;
}
/*
@@ -1,7 +1,7 @@
using System.Linq;
using HarmonyLib;
using MiraAPI.Modifiers;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
namespace MiraAPI.Patches.Modifiers;
@@ -24,7 +24,7 @@ public static class EndGameDidWinPatch
var didWin = networkedPlayerInfo.Role.DidWin(gameOverReason);
var modifierWin = networkedPlayerInfo.Object?.GetModifierComponent()?.ActiveModifiers.OfType<GameModifier>()
var modifierWin = networkedPlayerInfo.Object?.GetModifierComponent().GetModifiers<GameModifier>()
.FirstOrDefault(x => x.DidWin(gameOverReason) != null)?.DidWin(gameOverReason);
if (modifierWin != null)
{
@@ -157,8 +157,6 @@ public static class GameSettingMenuPatches
roles.AdvancedRolesSettings.gameObject.SetActive(false);
roles.RoleChancesSettings.gameObject.SetActive(true);
roles.SetQuotaTab();
roles.scrollBar.CalculateAndSetYBounds(roles.roleChances.Count + 5, 1f, 6f, 0.43f);
roles.scrollBar.ScrollToTop();
}
+36 -25
View File
@@ -6,6 +6,7 @@ using MiraAPI.Utilities.Assets;
using System;
using System.Collections.Generic;
using System.Linq;
using Reactor.Localization.Utilities;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
@@ -211,34 +212,43 @@ public static class LobbyViewPanePatches
var list = new List<Type>();
foreach (var team in Enum.GetValues<ModdedRoleTeams>())
{
var filteredRoles = SelectedMod.CustomRoles.Values
.OfType<ICustomRole>()
.Where(x => !x.Configuration.HideSettings && x.Team == team).ToList();
var roleGroups = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values.OfType<ICustomRole>()
.ToLookup(x => x.RoleOptionsGroup);
if (filteredRoles.Count == 0)
if (roleGroups is null)
{
return;
}
// sort the groups by priority
var sortedRoleGroups = roleGroups
.OrderBy(x => x.Key.Priority)
.ThenBy(x => x.Key.Name);
foreach (var grouping in sortedRoleGroups)
{
if (!grouping.Any())
{
continue;
}
var categoryHeaderRoleVariant =
Object.Instantiate(instance.categoryHeaderRoleOrigin, instance.settingsContainer, true);
var group = grouping.Key;
switch (team)
var name = group.Name switch
{
case ModdedRoleTeams.Crewmate:
categoryHeaderRoleVariant.SetHeader(StringNames.CrewmateRolesHeader, 61);
break;
case ModdedRoleTeams.Impostor:
categoryHeaderRoleVariant.SetHeader(StringNames.ImpostorRolesHeader, 61);
break;
default:
categoryHeaderRoleVariant.SetHeader(StringNames.CrewmateRolesHeader, 61);
categoryHeaderRoleVariant.Title.text = team + " Roles";
categoryHeaderRoleVariant.Background.color = Color.gray;
categoryHeaderRoleVariant.Title.color = Color.white;
break;
"Crewmate" => StringNames.CrewmateRolesHeader,
"Impostor" => StringNames.ImpostorRolesHeader,
_ => CustomStringName.CreateAndRegister(group.Name),
};
var categoryHeaderRoleVariant = Object.Instantiate(instance.categoryHeaderRoleOrigin, instance.settingsContainer, true);
categoryHeaderRoleVariant.SetHeader(name, 61);
if (name is not (StringNames.CrewmateRolesHeader or StringNames.ImpostorRolesHeader))
{
var veryDarkColor = group.Color.DarkenColor(.35f);
categoryHeaderRoleVariant.Title.color = veryDarkColor;
categoryHeaderRoleVariant.Background.color = group.Color;
}
categoryHeaderRoleVariant.transform.localScale = Vector3.one;
@@ -246,7 +256,7 @@ public static class LobbyViewPanePatches
instance.settingsInfo.Add(categoryHeaderRoleVariant.gameObject);
num -= 0.696f;
foreach (var customRole in filteredRoles)
foreach (var customRole in grouping)
{
var roleBehaviour = customRole as RoleBehaviour;
if (roleBehaviour == null)
@@ -259,8 +269,6 @@ public static class LobbyViewPanePatches
var numPerGame =
GameOptionsManager.Instance.CurrentGameOptions.RoleOptions.GetNumPerGame(roleBehaviour.Role);
var flag = numPerGame == 0;
var viewSettingsInfoPanelRoleVariant =
Object.Instantiate(
instance.infoPanelRoleOrigin,
@@ -273,7 +281,7 @@ public static class LobbyViewPanePatches
.Where(x => x.AdvancedRole == customRole.GetType())
.ToList();
if (!flag && advancedRoleOptions.Count > 0)
if (numPerGame > 0 && advancedRoleOptions.Count > 0)
{
list.Add(customRole.GetType());
}
@@ -286,6 +294,8 @@ public static class LobbyViewPanePatches
customRole.RoleColor,
customRole.Configuration.Icon.LoadAsset(),
true);
viewSettingsInfoPanelRoleVariant.iconSprite.transform.localScale = new Vector3(0.365f, 0.365f, 1f);
viewSettingsInfoPanelRoleVariant.iconSprite.transform.localPosition = new Vector3(0.7144f, -0.028f, -2);
viewSettingsInfoPanelRoleVariant.titleText.color =
viewSettingsInfoPanelRoleVariant.chanceTitle.color =
@@ -370,6 +380,7 @@ public static class LobbyViewPanePatches
maskLayer,
role.TeamType == RoleTeamTypes.Crewmate,
customRole.Configuration.Icon.LoadAsset());
viewPanel.header.icon.transform.localScale = new Vector3(0.465f, 0.465f, 1f);
viewPanel.divider.material.SetInt(PlayerMaterial.MaskLayer, maskLayer);
var num = viewPanel.yPosStart;
+239 -88
View File
@@ -4,10 +4,12 @@ using MiraAPI.Networking;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
@@ -20,10 +22,21 @@ namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(RolesSettingsMenu))]
public static class RoleSettingMenuPatches
{
private static Dictionary<RoleOptionsGroup, bool> RoleGroupHidden { get; set; } = new();
private static List<GameObject> Headers { get; set; } = new();
private static List<RoleOptionSetting> RoleOptionSettings { get; set; } = new();
private static float ScrollerNum { get; set; } = 0.522f;
[HarmonyPrefix]
[HarmonyPatch(nameof(RolesSettingsMenu.SetQuotaTab))]
public static bool PatchStart(RolesSettingsMenu __instance)
{
Headers.ForEach(Object.Destroy);
RoleOptionSettings.ForEach(Object.Destroy);
Headers.Clear();
RoleOptionSettings.Clear();
__instance.roleChances = new Il2CppSystem.Collections.Generic.List<RoleOptionSetting>();
__instance.advancedSettingChildren = new Il2CppSystem.Collections.Generic.List<OptionBehaviour>();
@@ -42,7 +55,7 @@ public static class RoleSettingMenuPatches
return true;
}
var num = 0.522f;
ScrollerNum = 0.522f;
__instance.AllButton.transform.parent.gameObject.SetActive(false);
__instance.AllButton.gameObject.SetActive(false);
@@ -54,92 +67,169 @@ public static class RoleSettingMenuPatches
var num3 = 0;
var crewRoles = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role is { Team: ModdedRoleTeams.Crewmate, Configuration.HideSettings: false })
.ToList() ?? [];
var roleGroups = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values.OfType<ICustomRole>()
.ToLookup(x => x.RoleOptionsGroup);
if (crewRoles is { Count: > 0 })
if (roleGroups is null)
{
var categoryHeaderEditRole = Object.Instantiate(
__instance.categoryHeaderEditRoleOrigin,
return true;
}
// sort the groups by priority
var sortedRoleGroups = roleGroups
.OrderBy(x => x.Key.Priority)
.ThenBy(x => x.Key.Name);
var quotaThing = __instance.categoryHeaderEditRoleOrigin.transform.FindChild("QuotaHeader");
var template = __instance.transform.parent.parent.GetComponent<GameSettingMenu>().GameSettingsTab.categoryHeaderOrigin;
foreach (var grouping in sortedRoleGroups)
{
if (!grouping.Any())
{
continue;
}
var group = grouping.Key;
RoleGroupHidden.TryAdd(group, false);
var name = group.Name switch
{
"Crewmate" => StringNames.CrewmateRolesHeader,
"Impostor" => StringNames.ImpostorRolesHeader,
_ => CustomStringName.CreateAndRegister(group.Name),
};
var categoryHeaderMasked = Object.Instantiate(
template,
Vector3.zero,
Quaternion.identity,
__instance.RoleChancesSettings.transform);
categoryHeaderEditRole.SetHeader(StringNames.CrewmateRolesHeader, 20);
categoryHeaderEditRole.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
foreach (var role in crewRoles)
categoryHeaderMasked.SetHeader(name, 20);
var quotaInst = Object.Instantiate(quotaThing, categoryHeaderMasked.transform);
quotaInst.transform.localScale = new Vector3(1.3f, 1.3f, 1.3f);
quotaInst.transform.localPosition = new Vector3(0.7f, -0.82f, 0);
var chanceText = quotaInst.transform.FindChild("Chance Text");
chanceText.transform.localPosition = new Vector3(4.3f, 0.0993f, 0);
var countText = quotaInst.transform.FindChild("# Text");
countText.transform.localPosition = new Vector3(1.9f, 0.0993f, 0f);
var blankLabel = quotaInst.transform.FindChild("BlankLabel").gameObject;
var chanceLabel = quotaInst.transform.FindChild("Chance Label").gameObject;
var countLabel = quotaInst.transform.FindChild("# Label").gameObject;
blankLabel.Destroy();
chanceLabel.Destroy();
countLabel.Destroy();
if (name is StringNames.CrewmateRolesHeader)
{
if (role is RoleBehaviour roleBehaviour)
categoryHeaderMasked.Title.color = Palette.CrewmateRoleHeaderTextBlue;
categoryHeaderMasked.Background.color = Palette.CrewmateRoleHeaderBlue;
}
else if (name is StringNames.ImpostorRolesHeader)
{
categoryHeaderMasked.Title.color = Palette.ImpostorRoleHeaderTextRed;
categoryHeaderMasked.Background.color = Palette.ImpostorRoleHeaderRed;
}
else
{
categoryHeaderMasked.Title.color = group.Color;
categoryHeaderMasked.Divider.color = group.Color;
categoryHeaderMasked.Background.color = group.Color;
}
categoryHeaderMasked.Title.color = categoryHeaderMasked.Title.color.IsColorDark() ?
categoryHeaderMasked.Title.color.LightenColor(0.3f) : categoryHeaderMasked.Title.color.LightenColor(0.1f);
categoryHeaderMasked.Title.fontStyle = __instance.categoryHeaderEditRoleOrigin.Title.fontStyle;
categoryHeaderMasked.Title.font = __instance.categoryHeaderEditRoleOrigin.Title.font;
categoryHeaderMasked.Title.fontMaterial = __instance.categoryHeaderEditRoleOrigin.Title.fontMaterial;
categoryHeaderMasked.Divider.color = categoryHeaderMasked.Background.color;
categoryHeaderMasked.Background.size = new Vector2(categoryHeaderMasked.Background.size.x + 1.5f, categoryHeaderMasked.Background.size.y);
categoryHeaderMasked.transform.localScale = Vector3.one * 0.63f;
categoryHeaderMasked.transform.localPosition = new Vector3(-0.44f, ScrollerNum, -2f);
categoryHeaderMasked.gameObject.SetActive(true);
quotaInst.gameObject.SetActive(!RoleGroupHidden[group]);
var label = RoleGroupHidden[group]
? "(Click to open)"
: "(Click to close)";
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();
Headers.Add(categoryHeaderMasked.gameObject);
ScrollerNum -= 0.422f;
if (!RoleGroupHidden[group])
{
foreach (var role in grouping)
{
CreateQuotaOption(__instance, roleBehaviour, ref num, num3);
if (role is not RoleBehaviour roleBehaviour)
{
continue;
}
var option = CreateQuotaOption(__instance, roleBehaviour, num3);
if (option is not null)
{
RoleOptionSettings.Add(option);
num3++;
}
}
num3++;
}
var boxCol = categoryHeaderMasked.gameObject.AddComponent<BoxCollider2D>();
boxCol.size = new Vector2(7, 0.7f);
boxCol.offset = new Vector2(1.5f, -0.3f);
var headerBtn = categoryHeaderMasked.gameObject.AddComponent<PassiveButton>();
headerBtn.ClickSound = __instance.BackButton.GetComponent<PassiveButton>().ClickSound;
headerBtn.OnMouseOver = new UnityEvent();
headerBtn.OnMouseOut = new UnityEvent();
headerBtn.OnClick.AddListener(
(UnityAction)(() =>
{
if (RoleGroupHidden.TryGetValue(group, out var value))
{
RoleGroupHidden[group] = !value;
}
foreach (var header in Headers)
{
header.Destroy();
}
Headers.Clear();
foreach (var option in RoleOptionSettings)
{
option.gameObject.Destroy();
}
RoleOptionSettings.Clear();
__instance.SetQuotaTab();
}));
headerBtn.SetButtonEnableState(true);
if (RoleGroupHidden.TryGetValue(group, out var value) && !value)
{
ScrollerNum -= 0.4f;
}
}
var impRoles = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role is { Team: ModdedRoleTeams.Impostor, Configuration.HideSettings: false })
.ToList() ?? [];
if (impRoles is { Count: > 0 })
{
num -= 0.4f;
var categoryHeaderEditRole2 = Object.Instantiate(
__instance.categoryHeaderEditRoleOrigin,
Vector3.zero,
Quaternion.identity,
__instance.RoleChancesSettings.transform);
categoryHeaderEditRole2.SetHeader(StringNames.ImpostorRolesHeader, 20);
categoryHeaderEditRole2.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
foreach (var role in impRoles)
{
if (role is RoleBehaviour roleBehaviour)
{
CreateQuotaOption(__instance, roleBehaviour, ref num, num3);
}
num3++;
}
}
var neutRoles = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role is { Team: ModdedRoleTeams.Neutral, Configuration.HideSettings: false })
.ToList() ?? [];
if (neutRoles is { Count: > 0 })
{
num -= 0.4f;
var categoryHeaderEditRole3 = Object.Instantiate(
__instance.categoryHeaderEditRoleOrigin,
Vector3.zero,
Quaternion.identity,
__instance.RoleChancesSettings.transform);
categoryHeaderEditRole3.SetHeader(StringNames.None, 20);
categoryHeaderEditRole3.Title.text = "Neutral Roles";
categoryHeaderEditRole3.Background.color = Color.gray;
categoryHeaderEditRole3.Title.color = Color.white;
categoryHeaderEditRole3.transform.localPosition = new Vector3(4.986f, num, -2f);
num -= 0.522f;
foreach (var role in neutRoles)
{
if (role is RoleBehaviour roleBehaviour)
{
CreateQuotaOption(__instance, roleBehaviour, ref num, num3);
}
num3++;
}
}
__instance.scrollBar.SetScrollBounds();
return false;
}
private static void SetScrollBounds(this Scroller scroller)
{
scroller.CalculateAndSetYBounds(1 + 1.5f * Headers.Count + RoleOptionSettings.Count, 1f, 6f, 0.43f);
}
[HarmonyPrefix]
[HarmonyPatch(nameof(RolesSettingsMenu.Update))]
public static bool UpdatePatch()
@@ -151,7 +241,12 @@ public static class RoleSettingMenuPatches
[HarmonyPatch(nameof(RolesSettingsMenu.OpenChancesTab))]
public static void OpenChancesTabPostfix(RolesSettingsMenu __instance)
{
__instance.scrollBar.CalculateAndSetYBounds(__instance.roleChances.Count + 5, 1f, 6f, 0.43f);
if (GameSettingMenuPatches.SelectedModIdx == 0)
{
return;
}
__instance.scrollBar.SetScrollBounds();
__instance.scrollBar.ScrollToTop();
}
@@ -199,14 +294,15 @@ public static class RoleSettingMenuPatches
private static void CreateAdvancedSettings(RolesSettingsMenu __instance, RoleBehaviour role)
{
foreach (var option in __instance.advancedSettingChildren)
foreach (var optBehaviour in __instance.AdvancedRolesSettings.GetComponentsInChildren<OptionBehaviour>())
{
Object.Destroy(option.gameObject);
optBehaviour.gameObject.DestroyImmediate();
}
__instance.advancedSettingChildren.Clear();
var num = -0.872f;
var hasImage = role.RoleScreenshot != null;
var num = hasImage ? -0.872f : -1;
var filteredOptions = GameSettingMenuPatches.SelectedMod?.Options.Where(x => x.AdvancedRole == role.GetType()) ?? [];
@@ -223,7 +319,7 @@ public static class RoleSettingMenuPatches
__instance.stringOptionOrigin,
__instance.AdvancedRolesSettings.transform);
newOpt.transform.localPosition = new Vector3(2.17f, num, -2f);
newOpt.transform.localPosition = new Vector3(hasImage ? 2.17f : 1.1f, num, -2f);
newOpt.SetClickMask(__instance.ButtonClickMask);
SpriteRenderer[] componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
@@ -261,15 +357,63 @@ public static class RoleSettingMenuPatches
__instance.roleTitleText.text = TranslationController.Instance.GetString(
role.StringName,
new Il2CppReferenceArray<Il2CppSystem.Object>(0));
__instance.roleScreenshot.sprite = Sprite.Create(
customRole.Configuration.OptionsScreenshot.LoadAsset().texture,
new Rect(0, 0, 370, 230),
Vector2.one / 2,
100);
__instance.roleScreenshot.drawMode = SpriteDrawMode.Sliced;
var imgBg = __instance.AdvancedRolesSettings.transform.FindChild("Imagebackground");
var labelBg = __instance.AdvancedRolesSettings.transform.FindChild("InfoLabelBackground");
if (role.RoleScreenshot == null)
{
imgBg.gameObject.SetActive(false);
__instance.roleScreenshot.gameObject.SetActive(false);
__instance.roleDescriptionText.transform.parent.localPosition = new Vector3(1.5f, -0.2731f, -1);
__instance.roleDescriptionText.transform.parent.localScale = new Vector3(0.09f, 0.2f, 0.5687f);
labelBg.localPosition = new Vector3(-0.7f, 0.1054f, -2.5f);
}
else
{
imgBg.gameObject.SetActive(true);
__instance.roleScreenshot.gameObject.SetActive(true);
__instance.roleDescriptionText.transform.parent.localPosition = new Vector3(2.5176f, -0.2731f, -1f);
__instance.roleDescriptionText.transform.parent.localScale = new Vector3(0.0675f, 0.1494f, 0.5687f);
labelBg.transform.localPosition = new Vector3(1.082f, 0.1054f, -2.5f);
__instance.roleScreenshot.sprite = Sprite.Create(
role.RoleScreenshot.texture,
new Rect(0, 0, 370, 230),
Vector2.one / 2,
100);
__instance.roleScreenshot.drawMode = SpriteDrawMode.Sliced;
}
__instance.roleHeaderSprite.color = customRole.RoleColor;
__instance.roleHeaderText.color = customRole.RoleColor.GetAlternateColor();
var categoryHeaderMasked = __instance.AdvancedRolesSettings.transform.Find("CategoryHeaderMasked").GetComponent<CategoryHeaderMasked>();
if (categoryHeaderMasked.Title.gameObject.TryGetComponent<TextTranslatorTMP>(out var comp))
{
comp.Destroy();
}
categoryHeaderMasked.Title.text = "RETURN TO ROLE SETTINGS";
if (!categoryHeaderMasked.gameObject.TryGetComponent<PassiveButton>(out _))
{
var boxCol = categoryHeaderMasked.gameObject.AddComponent<BoxCollider2D>();
boxCol.size = new Vector2(7, 0.7f);
boxCol.offset = new Vector2(1.5f, -0.3f);
var headerBtn = categoryHeaderMasked.gameObject.AddComponent<PassiveButton>();
headerBtn.ClickSound = __instance.BackButton.GetComponent<PassiveButton>().ClickSound;
headerBtn.OnMouseOver = new UnityEvent();
headerBtn.OnMouseOut = new UnityEvent();
headerBtn.OnClick.AddListener(
(UnityAction)(() =>
{
__instance.OpenChancesTab();
}));
headerBtn.SetButtonEnableState(true);
}
var bg = __instance.AdvancedRolesSettings.transform.Find("Background");
bg.localPosition = new Vector3(1.4041f, -7.08f, 0);
bg.GetComponent<SpriteRenderer>().size = new Vector2(89.4628f, 100);
@@ -295,12 +439,17 @@ public static class RoleSettingMenuPatches
__instance.RefreshChildren();
}
private static void CreateQuotaOption(RolesSettingsMenu __instance, RoleBehaviour role, ref float yPos, int index)
private static RoleOptionSetting? CreateQuotaOption(RolesSettingsMenu __instance, RoleBehaviour role, int index)
{
if (role is not ICustomRole customRole)
{
Logger<MiraApiPlugin>.Error($"Role {role.NiceName} is not a custom role.");
return;
return null;
}
if (customRole.Configuration.HideSettings)
{
return null;
}
var roleOptionSetting = Object.Instantiate(
@@ -308,7 +457,7 @@ public static class RoleSettingMenuPatches
Vector3.zero,
Quaternion.identity,
__instance.RoleChancesSettings.transform);
roleOptionSetting.transform.localPosition = new Vector3(-0.15f, yPos, -2f);
roleOptionSetting.transform.localPosition = new Vector3(-0.1f, ScrollerNum, -2f);
roleOptionSetting.SetRole(GameOptionsManager.Instance.CurrentGameOptions.RoleOptions, role, 20);
roleOptionSetting.labelSprite.color = customRole.RoleColor;
@@ -355,7 +504,9 @@ public static class RoleSettingMenuPatches
if (index < GameSettingMenuPatches.SelectedMod?.CustomRoles.Count - 1)
{
yPos += -0.43f;
ScrollerNum += -0.43f;
}
return roleOptionSetting;
}
}
+1 -1
View File
@@ -126,6 +126,6 @@ public static class PlayerControlPatches
[HarmonyPatch(nameof(PlayerControl.OnDestroy))]
public static void PlayerControlOnDestroyPrefix(PlayerControl __instance)
{
Utilities.Extensions.ModifierComponents.Remove(__instance);
ModifierExtensions.ModifierComponents.Remove(__instance);
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ using UnityEngine;
namespace MiraAPI.Patches.Roles;
[HarmonyPatch(typeof(TaskPanelBehaviour))]
public static class TaskPanelPatch
internal static class TaskPanelPatch
{
/// <summary>
/// This patch is to override the automatic updating of the y position on the tab (which is in base game)
+12
View File
@@ -21,4 +21,16 @@ public static class MinigameStubs
{
// nothing needed
}
/// <summary>
/// Reverse patch for Minigame.Close.
/// </summary>
/// <param name="instance">The Minigame instance.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(Minigame), nameof(Minigame.Close), [])]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Close(Minigame instance)
{
// nothing needed
}
}
+229
View File
@@ -0,0 +1,229 @@
using System.Runtime.CompilerServices;
using HarmonyLib;
using Il2CppSystem.Text;
namespace MiraAPI.Patches.Stubs;
[HarmonyPatch]
public static class RoleBehaviourStubs
{
/// <summary>
/// Stub method for RoleBehaviour.Initialize.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="player">The PlayerControl to initialize.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.Initialize))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Initialize(RoleBehaviour instance, PlayerControl player)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.AdjustTasks.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="player">The PlayerControl to adjust tasks for.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.AdjustTasks))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AdjustTasks(RoleBehaviour instance, PlayerControl player)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.AppendTaskHint.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="taskStringBuilder">The StringBuilder to append the task hint to.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.AppendTaskHint), typeof(StringBuilder))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AppendTaskHint(RoleBehaviour instance, StringBuilder taskStringBuilder)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.CanUse.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="console">The IUsable console to check.</param>
/// <returns>Whether the console can be used.</returns>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.CanUse))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool CanUse(RoleBehaviour instance, IUsable console)
{
return default;
}
/// <summary>
/// Stub method for RoleBehaviour.Deinitialize.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="targetPlayer">The PlayerControl to deinitialize for.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.Deinitialize))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Deinitialize(RoleBehaviour instance, PlayerControl targetPlayer)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.DidWin.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="gameOverReason">The reason for game over.</param>
/// <returns>Whether the role won.</returns>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.DidWin))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool DidWin(RoleBehaviour instance, GameOverReason gameOverReason)
{
return default;
}
/// <summary>
/// Stub method for RoleBehaviour.FindClosestTarget.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <returns>The closest target PlayerControl.</returns>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.FindClosestTarget))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static PlayerControl FindClosestTarget(RoleBehaviour instance)
{
return null;
}
/// <summary>
/// Stub method for RoleBehaviour.GetAbilityDistance.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <returns>The ability distance.</returns>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.GetAbilityDistance))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static float GetAbilityDistance(RoleBehaviour instance)
{
return default;
}
/// <summary>
/// Stub method for RoleBehaviour.IsValidTarget.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="target">The NetworkedPlayerInfo to validate.</param>
/// <returns>Whether the target is valid.</returns>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.IsValidTarget))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool IsValidTarget(RoleBehaviour instance, NetworkedPlayerInfo target)
{
return default;
}
/// <summary>
/// Stub method for RoleBehaviour.OnDeath.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="reason">The reason for death.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.OnDeath))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void OnDeath(RoleBehaviour instance, DeathReason reason)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.OnMeetingStart.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.OnMeetingStart))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void OnMeetingStart(RoleBehaviour instance)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.OnVotingComplete.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.OnVotingComplete))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void OnVotingComplete(RoleBehaviour instance)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.SetCooldown.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.SetCooldown))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetCooldown(RoleBehaviour instance)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.SetPlayerTarget.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="target">The PlayerControl target to set.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.SetPlayerTarget))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetPlayerTarget(RoleBehaviour instance, PlayerControl target)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.SetUsableTarget.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="target">The IUsable target to set.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.SetUsableTarget))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetUsableTarget(RoleBehaviour instance, IUsable target)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.SpawnTaskHeader.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
/// <param name="playerControl">The PlayerControl to spawn the task header for.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.SpawnTaskHeader))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SpawnTaskHeader(RoleBehaviour instance, PlayerControl playerControl)
{
// nothing needed
}
/// <summary>
/// Stub method for RoleBehaviour.UseAbility.
/// </summary>
/// <param name="instance">The RoleBehaviour object.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(RoleBehaviour), nameof(RoleBehaviour.UseAbility))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void UseAbility(RoleBehaviour instance)
{
// nothing needed
}
}
+3 -3
View File
@@ -1,8 +1,8 @@
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Usables;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Patches;
@@ -35,8 +35,8 @@ public static class VentPatches
var canVent = role is ICustomRole customRole ? customRole.Configuration.CanUseVent : role.CanVent;
couldUse = canVent;
var modifiers = @object.GetModifierComponent()?.ActiveModifiers;
if (modifiers is { Count: > 0 })
var modifiers = @object.GetModifierComponent().ActiveModifiers;
if (modifiers.Count > 0)
{
switch (canVent)
{
+12
View File
@@ -5,6 +5,7 @@ using MiraAPI.GameOptions;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MiraAPI.Hud;
using MiraAPI.Modifiers;
namespace MiraAPI.PluginLoading;
@@ -21,6 +22,15 @@ public class MiraPluginInfo
PluginId = info.Metadata.GUID;
}
/// <summary>
/// Get a read only collection of this plugin's modifiers. This is probably not safe because they are uninitialized.
/// </summary>
/// <returns>Readonly collection of modifiers.</returns>
public IReadOnlyCollection<BaseModifier> GetModifiers()
{
return Modifiers.AsReadOnly();
}
/// <summary>
/// Get a read only collection of this plugin's Option Groups.
/// </summary>
@@ -61,6 +71,8 @@ public class MiraPluginInfo
internal List<IModdedOption> Options { get; } = [];
internal List<BaseModifier> Modifiers { get; } = [];
internal Dictionary<ushort, RoleBehaviour> CustomRoles { get; } = [];
internal Dictionary<int, CustomGameMode> GameModes { get; } = [];
+30 -11
View File
@@ -1,6 +1,12 @@
using BepInEx.Unity.IL2CPP;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using BepInEx.Unity.IL2CPP;
using MiraAPI.Colors;
using MiraAPI.Events;
using MiraAPI.GameEnd;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.Hud;
@@ -9,11 +15,6 @@ using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Networking;
using Reactor.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
namespace MiraAPI.PluginLoading;
@@ -48,7 +49,7 @@ public sealed class MiraPluginManager
continue;
}
if (RegisterModifier(type))
if (RegisterModifier(type, info))
{
continue;
}
@@ -69,6 +70,11 @@ public sealed class MiraPluginManager
continue;
}
if (RegisterGameOver(type))
{
continue;
}
RegisterColorClasses(type);
}
@@ -91,9 +97,22 @@ public sealed class MiraPluginManager
/// </summary>
/// <param name="pluginId">The plugin GUID.</param>
/// <returns>A MiraPluginInfo.</returns>
public static MiraPluginInfo GetPluginByGuid(string pluginId)
public static MiraPluginInfo? GetPluginByGuid(string pluginId)
{
return Instance._registeredPlugins.Values.First(plugin => plugin.PluginId == pluginId);
return Instance._registeredPlugins.Values.FirstOrDefault(plugin => plugin.PluginId == pluginId);
}
private static bool RegisterGameOver(Type type)
{
try
{
return GameOverManager.RegisterGameOver(type);
}
catch (Exception e)
{
Logger<MiraApiPlugin>.Error($"Failed to register game over {type.Name}: {e}");
return false;
}
}
private static bool RegisterOptions(Type type, MiraPluginInfo pluginInfo)
@@ -199,11 +218,11 @@ public sealed class MiraPluginManager
}
}
private static bool RegisterModifier(Type type)
private static bool RegisterModifier(Type type, MiraPluginInfo info)
{
try
{
return ModifierManager.RegisterModifier(type);
return ModifierManager.RegisterModifier(type, info);
}
catch (Exception e)
{
+41 -41
View File
@@ -7,7 +7,7 @@ namespace MiraAPI.Roles;
/// <summary>
/// Used to configure the specific settings of a role.
/// </summary>
public struct CustomRoleConfiguration
public record struct CustomRoleConfiguration
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomRoleConfiguration"/> struct.
@@ -17,11 +17,6 @@ public struct CustomRoleConfiguration
{
var roleBehaviour = role as RoleBehaviour;
MaxRoleCount = 15;
DefaultRoleCount = 0;
DefaultChance = 0;
OptionsScreenshot = Icon = MiraAssets.Empty;
AffectedByLightOnAirship = role.Team == ModdedRoleTeams.Crewmate;
KillButtonOutlineColor = role.Team switch
{
@@ -29,7 +24,6 @@ public struct CustomRoleConfiguration
ModdedRoleTeams.Crewmate => Palette.CrewmateBlue,
_ => role.RoleColor,
};
RoleHintType = RoleHintType.RoleTab;
GhostRole = role.Team is ModdedRoleTeams.Impostor ? RoleTypes.ImpostorGhost : RoleTypes.CrewmateGhost;
CanGetKilled = roleBehaviour?.IsDead == false && role.Team is not ModdedRoleTeams.Impostor;
UseVanillaKillButton = role.Team is ModdedRoleTeams.Impostor;
@@ -37,86 +31,92 @@ public struct CustomRoleConfiguration
CanUseSabotage = role.Team is ModdedRoleTeams.Impostor;
TasksCountForProgress = role.Team is ModdedRoleTeams.Crewmate;
HideSettings = roleBehaviour?.IsDead == true;
CanModifyChance = true;
ShowInFreeplay = roleBehaviour?.IsDead == false;
OptionsScreenshot = null;
}
/// <summary>
/// Gets the hard limit of players that can have this role. This property is used to set a limit in the Role Options menu. If set to 0, the role will not be assigned at start.
/// Gets or sets the hard limit of players that can have this role. This property is used to set a limit in the Role Options menu. If set to 0, the role will not be assigned at start.
/// </summary>
public int MaxRoleCount;
public int MaxRoleCount { get; set; } = 15;
/// <summary>
/// Gets the default role count.
/// Gets or sets the default role count.
/// </summary>
public int DefaultRoleCount;
public int DefaultRoleCount { get; set; } = 0;
/// <summary>
/// Gets the default role chance.
/// Gets or sets the default role chance.
/// </summary>
public int DefaultChance;
public int DefaultChance { get; set; } = 0;
/// <summary>
/// Whether the chance option can be changed or not.
/// Gets or sets a value indicating whether the chance option can be changed or not.
/// </summary>
public bool CanModifyChance;
public bool CanModifyChance { get; set; } = true;
/// <summary>
/// Gets the Sprite used for the Role Options menu screenshot.
/// Gets or sets the Sprite used for the Role Options menu screenshot.
/// </summary>
public LoadableAsset<Sprite> OptionsScreenshot;
public LoadableAsset<Sprite>? OptionsScreenshot { get; set; }
/// <summary>
/// Gets the Sprite used for the Role Icon.
/// Gets or sets the Sprite used for the Role Icon.
/// </summary>
public LoadableAsset<Sprite> Icon;
public LoadableAsset<Sprite> Icon { get; set; } = MiraAssets.Empty;
/// <summary>
/// Gets a value indicating whether the role is affected by light affectors on Airship.
/// Gets or sets a value indicating whether the role is affected by light affectors on Airship.
/// </summary>
public bool AffectedByLightOnAirship;
public bool AffectedByLightOnAirship { get; set; }
/// <summary>
/// Gets a value indicating whether the role can be killed by vanilla murder system.
/// Gets or sets a value indicating whether the role can be killed by vanilla murder system.
/// </summary>
public bool CanGetKilled;
public bool CanGetKilled { get; set; }
/// <summary>
/// Gets a value indicating whether the role should use the vanilla kill button.
/// Gets or sets a value indicating whether the role should use the vanilla kill button.
/// </summary>
public bool UseVanillaKillButton;
public bool UseVanillaKillButton { get; set; }
/// <summary>
/// Gets a value indicating whether the role can use vents.
/// Gets or sets a value indicating whether the role can use vents.
/// </summary>
public bool CanUseVent;
public bool CanUseVent { get; set; }
/// <summary>
/// Gets a value indicating whether the role can use the sabotage button.
/// Gets or sets a value indicating whether the role can use the sabotage button.
/// </summary>
public bool CanUseSabotage;
public bool CanUseSabotage { get; set; }
/// <summary>
/// Gets a value indicating whether the role's tasks count towards task progress.
/// Gets or sets a value indicating whether the role's tasks count towards task progress.
/// </summary>
public bool TasksCountForProgress;
public bool TasksCountForProgress { get; set; }
/// <summary>
/// Gets a value indicating whether the role should show up in the Role Options menu.
/// Gets or sets a value indicating whether the role should show up in the Role Options menu.
/// </summary>
public bool HideSettings;
public bool HideSettings { get; set; }
/// <summary>
/// Gets the outline color for the KillButton if <see cref="UseVanillaKillButton"/> is true.
/// Gets or sets a value indicating whether the role should show up in the Freeplay Role Selection menu.
/// </summary>
public Color KillButtonOutlineColor;
public bool ShowInFreeplay { get; set; }
/// <summary>
/// Gets the role hint style. See <see cref="RoleHintType"/> enum for all options.
/// Gets or sets the outline color for the KillButton if <see cref="UseVanillaKillButton"/> is true.
/// </summary>
public RoleHintType RoleHintType;
public Color KillButtonOutlineColor { get; set; }
/// <summary>
/// Gets the Ghost role that is applied when the player is killed.
/// Gets or sets the role hint style. See <see cref="RoleHintType"/> enum for all options.
/// </summary>
public RoleTypes GhostRole;
}
public RoleHintType RoleHintType { get; set; } = RoleHintType.RoleTab;
/// <summary>
/// Gets or sets the Ghost role that is applied when the player is killed.
/// </summary>
public RoleTypes GhostRole { get; set; }
}
+2 -2
View File
@@ -79,7 +79,7 @@ public static class CustomRoleManager
var roleId = RoleIds[roleType];
roleBehaviour.Role = (RoleTypes)roleId;
roleBehaviour.TeamType = customRole.Team == ModdedRoleTeams.Neutral ? RoleTeamTypes.Crewmate : (RoleTeamTypes)customRole.Team;
roleBehaviour.TeamType = customRole.Team == ModdedRoleTeams.Custom ? RoleTeamTypes.Crewmate : (RoleTeamTypes)customRole.Team;
roleBehaviour.NameColor = customRole.RoleColor;
roleBehaviour.StringName = CustomStringName.CreateAndRegister(customRole.RoleName);
roleBehaviour.BlurbName = CustomStringName.CreateAndRegister(customRole.RoleDescription);
@@ -91,7 +91,7 @@ public static class CustomRoleManager
roleBehaviour.CanVent = customRole.Configuration.CanUseVent;
roleBehaviour.DefaultGhostRole = customRole.Configuration.GhostRole;
roleBehaviour.MaxCount = customRole.Configuration.MaxRoleCount;
roleBehaviour.RoleScreenshot = customRole.Configuration.OptionsScreenshot.LoadAsset();
roleBehaviour.RoleScreenshot = customRole.Configuration.OptionsScreenshot?.LoadAsset();
if (roleBehaviour.IsDead)
{
+40
View File
@@ -43,6 +43,26 @@ public interface ICustomRole
/// </summary>
CustomRoleConfiguration Configuration { get; }
/// <summary>
/// Gets the role options group.
/// </summary>
public RoleOptionsGroup RoleOptionsGroup => Team switch
{
ModdedRoleTeams.Crewmate => RoleOptionsGroup.Crewmate,
ModdedRoleTeams.Impostor => RoleOptionsGroup.Impostor,
ModdedRoleTeams.Custom => RoleOptionsGroup.Neutral,
_ => new RoleOptionsGroup(RoleName, RoleColor),
};
/// <summary>
/// Gets the role's TeamIntroCutscene configuration.
/// </summary>
public TeamIntroConfiguration? IntroConfiguration => Team switch
{
ModdedRoleTeams.Custom => TeamIntroConfiguration.Neutral,
_ => null,
};
/// <summary>
/// Gets the parent mod of this role.
/// </summary>
@@ -138,6 +158,26 @@ public interface ICustomRole
return (PlayerControl.LocalPlayer.Data.Role.IsImpostor && player.Data.Role.IsImpostor) || PlayerControl.LocalPlayer.Data.IsDead;
}
/// <summary>
/// Allows the role to specify who is shown on the intro team screen.
/// </summary>
/// <param name="instance">The intro cutscene instance.</param>
/// <param name="yourTeam">The reference to the list of player in the team.</param>
/// <returns>True to use the original team intro code, false to skip.</returns>
public virtual bool SetupIntroTeam(IntroCutscene instance, ref Il2CppSystem.Collections.Generic.List<PlayerControl> yourTeam)
{
if (Team == ModdedRoleTeams.Custom)
{
var team = new Il2CppSystem.Collections.Generic.List<PlayerControl>();
team.Add(PlayerControl.LocalPlayer);
yourTeam = team;
}
return true;
}
/// <summary>
/// This method runs on the HudManager.Update method ONLY when the LOCAL player has this role.
/// </summary>
+1 -1
View File
@@ -4,5 +4,5 @@ public enum ModdedRoleTeams
{
Crewmate,
Impostor,
Neutral,
Custom,
}
+27
View File
@@ -0,0 +1,27 @@
using UnityEngine;
namespace MiraAPI.Roles;
/// <summary>
/// Represents a group of roles.
/// </summary>
/// <param name="Name">The group's name.</param>
/// <param name="Color">The group's color.</param>
/// <param name="Priority">The priority to sort by on role setting screen. Negative means first.</param>
public record struct RoleOptionsGroup(string Name, Color Color, int Priority = 0)
{
/// <summary>
/// Gets the default group for crewmates.
/// </summary>
public static RoleOptionsGroup Crewmate { get; } = new("Crewmate", Palette.CrewmateBlue, -2);
/// <summary>
/// Gets the default group for impostors.
/// </summary>
public static RoleOptionsGroup Impostor { get; } = new("Impostor", Palette.ImpostorRed, -1);
/// <summary>
/// Gets the default group for neutral roles.
/// </summary>
public static RoleOptionsGroup Neutral { get; } = new("Neutral Roles", Color.gray);
}
+20
View File
@@ -0,0 +1,20 @@
using UnityEngine;
namespace MiraAPI.Roles;
/// <summary>
/// Used to configure the TEAM part of the intro cutscene.
/// </summary>
/// <param name="IntroTeamColor">The color to show during the "Team" part of the intro cutscene.</param>
/// <param name="IntroTeamTitle">The title text to show during the "Team" part of the intro cutscene.</param>
/// <param name="IntroTeamDescription">The description text to show during the "Team" part of the intro cutscene.</param>
public record struct TeamIntroConfiguration(Color IntroTeamColor, string IntroTeamTitle, string IntroTeamDescription)
{
/// <summary>
/// Gets the default configuration for the "Neutral" team.
/// </summary>
public static TeamIntroConfiguration Neutral { get; } = new(
Color.gray,
"NEUTRAL",
"You are Neutral. You do not have a team.");
}
@@ -1,9 +1,8 @@
using System;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using Cpp2IL.Core.Extensions;
using Reactor.Utilities.Extensions;
using UnityEngine;
namespace MiraAPI.Utilities.Assets;
@@ -21,41 +20,112 @@ public class LoadableAudioResourceAsset(string path) : LoadableAsset<AudioClip>
/// </summary>
/// <returns>The asset to load.</returns>
/// <exception cref="NotSupportedException">Attempted to load an Audio file in non WAV format.</exception>
/// <exception cref="FileNotFoundException">Stream failed to load. Check if the name of your asset was correct.</exception>
/// <exception cref="MissingManifestResourceException">Stream failed to load. Check if the name of your asset was correct.</exception>
public override AudioClip LoadAsset()
{
var assetStream = _assembly.GetManifestResourceStream(path) ??
throw new FileNotFoundException(
"Stream failed to load. Check if the name of your asset was correct.");
var audioBytes = assetStream.ReadFully();
using var assetStream = _assembly.GetManifestResourceStream(path)
?? throw new MissingManifestResourceException($"Stream failed to load. Check if the asset name is correct: {path}");
var riffHeader = Encoding.ASCII.GetString(audioBytes.SubArray(0, 4));
var waveHeader = Encoding.ASCII.GetString(audioBytes.SubArray(8, 4));
using var reader = new BinaryReader(assetStream);
if (riffHeader != "RIFF" || waveHeader != "WAVE")
// Read RIFF header
if (Encoding.ASCII.GetString(reader.ReadBytes(4)) != "RIFF")
{
throw new NotSupportedException($"Attempted to load an Audio file in non WAV format '{path}'.");
throw new NotSupportedException("Invalid WAV file (missing RIFF header).");
}
int channels = BitConverter.ToInt16(audioBytes, 22);
var sampleRate = BitConverter.ToInt32(audioBytes, 24);
var dataSize = BitConverter.ToInt32(audioBytes, 40);
reader.ReadInt32(); // File size (ignore)
var audioData = new float[dataSize / 2];
for (var i = 0; i < audioData.Length; i++)
if (Encoding.ASCII.GetString(reader.ReadBytes(4)) != "WAVE")
{
audioData[i] = BitConverter.ToInt16(audioBytes, 44 + i * 2) / 32768.0f;
throw new NotSupportedException("Invalid WAV file (missing WAVE header).");
}
var audioClip = AudioClip.Create(
path,
audioData.Length,
channels,
sampleRate,
false
);
audioClip.SetData(audioData, 0);
// Read chunks
int channels = 0, sampleRate = 0, bitsPerSample = 0;
byte[]? audioData = null;
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
var chunkId = Encoding.ASCII.GetString(reader.ReadBytes(4));
var chunkSize = reader.ReadInt32();
// Format chunk
if (chunkId == "fmt ")
{
int audioFormat = reader.ReadInt16();
channels = reader.ReadInt16();
sampleRate = reader.ReadInt32();
reader.ReadInt32(); // Byte rate (ignore)
reader.ReadInt16(); // Block align (ignore)
bitsPerSample = reader.ReadInt16();
if (audioFormat != 1) // Only PCM supported
throw new NotSupportedException("Only PCM WAV files are supported.");
}
// Data chunk
else if (chunkId == "data")
{
audioData = reader.ReadBytes(chunkSize);
break; // No need to read further
}
else
{
reader.BaseStream.Seek(chunkSize, SeekOrigin.Current); // Skip unknown chunks
}
}
if (audioData == null)
{
throw new InvalidOperationException("WAV file does not contain audio data.");
}
if (channels == 0 || sampleRate == 0 || bitsPerSample == 0)
{
throw new InvalidOperationException("WAV file does not contain valid format information.");
}
// Convert PCM data to float array
var samples = ConvertPcmToFloat(audioData, bitsPerSample);
// Create the AudioClip
var audioClip = AudioClip.Create(path, samples.Length / channels, channels, sampleRate, false);
audioClip.SetData(samples, 0);
return audioClip;
}
// This is somewhat magic to me, I just copied it from elsewhere.
private static float[] ConvertPcmToFloat(byte[] pcmData, int bitsPerSample)
{
var sampleCount = pcmData.Length / (bitsPerSample / 8);
var floatData = new float[sampleCount];
for (var i = 0; i < sampleCount; i++)
{
var byteIndex = i * (bitsPerSample / 8);
switch (bitsPerSample)
{
case 8:
floatData[i] = (pcmData[byteIndex] - 128) / 128f; // 8-bit PCM is unsigned
break;
case 16:
floatData[i] = BitConverter.ToInt16(pcmData, byteIndex) / 32768f;
break;
case 24:
var sample24 = pcmData[byteIndex] | (pcmData[byteIndex + 1] << 8) | (pcmData[byteIndex + 2] << 16);
if (sample24 > 0x7FFFFF) sample24 -= 0x1000000; // Convert from unsigned to signed
floatData[i] = sample24 / 8388608f;
break;
case 32:
floatData[i] = BitConverter.ToInt32(pcmData, byteIndex) / 2147483648f;
break;
default:
throw new NotSupportedException($"Unsupported bit depth: {bitsPerSample}");
}
}
return floatData;
}
}
+74 -132
View File
@@ -1,13 +1,13 @@
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Networking;
using MiraAPI.Roles;
using Reactor.Networking.Attributes;
using Reactor.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TMPro;
using UnityEngine;
namespace MiraAPI.Utilities;
@@ -39,6 +39,74 @@ public static class Extensions
BitConverter.GetBytes(count.Value).AddRangeToArray(BitConverter.GetBytes(chance.Value)));
}
/// <summary>
/// Gets the best constructor for a type based on the specified arguments.
/// </summary>
/// <param name="type">The type to get the constructor from.</param>
/// <param name="args">The arguments to pass into the constructor.</param>
/// <returns>The best constructor.</returns>
public static ConstructorInfo? GetBestConstructor(this Type type, params object[] args)
{
return type.GetValidConstructors(args)
.OrderBy(
ctor => ctor.GetParameters()
.Select((p, i) => GetInheritanceDistance(args[i].GetType(), p.ParameterType))
.Sum())
.FirstOrDefault();
}
/// <summary>
/// Gets the constructors of a type that match the specified arguments.
/// </summary>
/// <param name="type">The type to get constructors from.</param>
/// <param name="args">The arguments to pass into the constructor.</param>
/// <returns>A collection of valid constructors.</returns>
public static IEnumerable<ConstructorInfo> GetValidConstructors(this Type type, params object[] args)
{
return type.GetConstructors().Where(
x =>
{
var parameters = x.GetParameters();
return parameters.Length == args.Length && Array.TrueForAll(
parameters,
t => t.ParameterType.IsInstanceOfType(args[t.Position]));
});
}
/// <summary>
/// Calculates the inheritance distance from the given type to its target base type.
/// Lower values mean the type is a closer match.
/// </summary>
/// <param name="from">The derived type.</param>
/// <param name="to">The base type.</param>
/// <returns>The distance between the types.</returns>
public static int GetInheritanceDistance(Type from, Type to)
{
if (!from.IsAssignableFrom(to))
{
return int.MaxValue;
}
var type = from;
var distance = 0;
while (type != null && type != to)
{
type = type.BaseType;
distance++;
}
return type == to ? distance : int.MaxValue;
}
/// <summary>
/// Enables stencil masking on a TMP text object.
/// </summary>
/// <param name="text">The TMP text.</param>
public static void EnableStencilMasking(this TMP_Text text)
{
text.fontMaterial.SetFloat(ShaderID.Stencil, 1);
text.fontMaterial.SetFloat(ShaderID.StencilComp, 4);
}
/// <summary>
/// Checks if a type is static.
/// </summary>
@@ -130,30 +198,6 @@ public static class Extensions
opt => opt.OptionBehaviour && opt.OptionBehaviour == optionBehaviour);
}
internal static Dictionary<PlayerControl, ModifierComponent> ModifierComponents { get; } = [];
/// <summary>
/// Gets the ModifierComponent for a player.
/// </summary>
/// <param name="player">The PlayerControl object.</param>
/// <returns>A ModifierComponent if there is one, null otherwise.</returns>
public static ModifierComponent? GetModifierComponent(this PlayerControl player)
{
if (ModifierComponents.TryGetValue(player, out var component))
{
return component;
}
component = player.GetComponent<ModifierComponent>();
if (component == null)
{
return null;
}
ModifierComponents[player] = component;
return component;
}
/// <summary>
/// Randomizes a list.
/// </summary>
@@ -174,105 +218,6 @@ public static class Extensions
return randomizedList;
}
/// <summary>
/// Gets a modifier by its type, or null if the player doesn't have it.
/// </summary>
/// <param name="player">The PlayerControl object.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>The Modifier if it is found, null otherwise.</returns>
public static T? GetModifier<T>(this PlayerControl? player) where T : BaseModifier
{
return player?.GetModifierComponent()?.ActiveModifiers.Find(x => x is T) as T;
}
/// <summary>
/// Checks if a player has a modifier.
/// </summary>
/// <param name="player">The PlayerControl object.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
/// <returns>True if the Modifier is present, false otherwise.</returns>
public static bool HasModifier<T>(this PlayerControl? player) where T : BaseModifier
{
return player?.GetModifierComponent() != null &&
player.GetModifierComponent()!.HasModifier<T>();
}
/// <summary>
/// Checks if a player has a modifier by its ID.
/// </summary>
/// <param name="player">The PlayerControl object.</param>
/// <param name="id">The Modifier ID.</param>
/// <returns>True if the Modifier is present, false otherwise.</returns>
public static bool HasModifier(this PlayerControl? player, uint id)
{
return player?.GetModifierComponent() != null &&
player.GetModifierComponent()!.HasModifier(id);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="target">The player to remove the modifier from.</param>
/// <param name="modifierId">The ID of the modifier.</param>
[MethodRpc((uint)MiraRpc.RemoveModifier)]
public static void RpcRemoveModifier(this PlayerControl target, uint modifierId)
{
target.GetModifierComponent()?.RemoveModifier(modifierId);
}
/// <summary>
/// Remote Procedure Call to remove a modifier from a player.
/// </summary>
/// <param name="player">The player to remove the modifier from.</param>
/// <typeparam name="T">The Type of the Modifier.</typeparam>
public static void RpcRemoveModifier<T>(this PlayerControl player) where T : BaseModifier
{
var id = ModifierManager.GetModifierId(typeof(T));
if (id == null)
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier {typeof(T).Name} because it is not registered.");
return;
}
player.RpcRemoveModifier(id.Value);
}
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="target">The player to add the modifier to.</param>
/// <param name="modifierId">The modifier ID.</param>
[MethodRpc((uint)MiraRpc.AddModifier)]
public static void RpcAddModifier(this PlayerControl target, uint modifierId)
{
var type = ModifierManager.GetModifierType(modifierId);
if (type == null)
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier with id {modifierId} because it is not registered.");
return;
}
target.GetModifierComponent()?.AddModifier(type);
}
/// <summary>
/// Remote Procedure Call to add a modifier to a player.
/// </summary>
/// <param name="player">The player to add the modifier to.</param>
/// <typeparam name="T">The modifier Type.</typeparam>
public static void RpcAddModifier<T>(this PlayerControl player) where T : BaseModifier
{
var id = ModifierManager.GetModifierId(typeof(T));
if (id == null)
{
Logger<MiraApiPlugin>.Error($"Cannot add modifier {typeof(T).Name} because it is not registered.");
return;
}
player.RpcAddModifier(id.Value);
}
/// <summary>
/// Darkens a color by a specified amount.
/// </summary>
@@ -328,6 +273,7 @@ public static class Extensions
.GetNearestDeadBodies(playerControl.GetTruePosition(), radius, Helpers.CreateFilter(Constants.NotShipMask))
.Find(component => component && !component.Reported);
}
/// <summary>
/// Finds the nearest object of a specified type to a player. It will only work if the object has a collider.
/// </summary>
@@ -376,10 +322,6 @@ public static class Extensions
return predicate != null ? filteredPlayers.Find(predicate) : filteredPlayers.FirstOrDefault();
}
private static readonly int _outline = Shader.PropertyToID("_Outline");
private static readonly int _outlineColor = Shader.PropertyToID("_OutlineColor");
private static readonly int _addColor = Shader.PropertyToID("_AddColor");
/// <summary>
/// Fixed version of Reactor's SetOutline.
/// </summary>
@@ -387,8 +329,8 @@ public static class Extensions
/// <param name="color">The outline color.</param>
public static void UpdateOutline(this Renderer renderer, Color? color)
{
renderer.material.SetFloat(_outline, color.HasValue ? 1 : 0);
renderer.material.SetColor(_outlineColor, color.HasValue ? color.Value : Color.clear);
renderer.material.SetColor(_addColor, color.HasValue ? color.Value : Color.clear);
renderer.material.SetFloat(ShaderID.Outline, color.HasValue ? 1 : 0);
renderer.material.SetColor(ShaderID.OutlineColor, color ?? Color.clear);
renderer.material.SetColor(ShaderID.AddColor, color ?? Color.clear);
}
}
+4
View File
@@ -1,8 +1,12 @@
using System.Collections.Generic;
using UnityEngine;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace MiraAPI.Utilities;
/// <summary>
/// Utility class for caching shader property IDs.
/// </summary>
public static class ShaderID
{
private static readonly Dictionary<string, int> Cache = [];