Compare commits

...
50 Commits
Author SHA1 Message Date
XtraCube bb0b678747 fix VERY stupid issue with LobbyViewPanePatches.cs 2025-03-24 18:57:06 -04:00
XtraCube f48143610c fix incorrect chunking algorithm 2025-03-23 15:15:21 -04:00
XtraCube 2cfc5ac039 update example 2025-03-23 14:00:12 -04:00
XtraCube e9beb3b423 fix weird behaviour 2025-03-21 15:24:48 -04:00
ang-xd 7917d4b5d9 Make some changes to role registration for sounds 2025-03-16 19:05:12 -04:00
ang-xd bf795a2e36 Bug fixes with option screen & modifiers options 2025-03-15 23:47:05 -04:00
angxl wtf 144a95fa3b Merge pull request #31 from All-Of-Us-Mods/voting
Voting API
2025-03-15 21:10:19 -04:00
ang-xd e25b78705b Merge branch 'dev' into voting 2025-03-15 17:34:42 -04:00
ang-xd 19ba9da2c3 Remove debug method 2025-03-15 17:22:01 -04:00
ang-xd ce9864ae8b Lots of new Util methods, and fix opt header colors 2025-03-15 17:21:26 -04:00
XtraCube 8f76f21cb1 fix dummy voting in freeplay 2025-03-15 16:12:05 -04:00
ang-xd bc7b835dc8 Admit defeat to custom sprite assets 2025-03-15 15:04:57 -04:00
XtraCube f0b2f9ee2a fix bad naming 2025-03-14 17:39:27 -04:00
XtraCube 25eafe664b improve MeetingSelectEvent 2025-03-13 12:53:00 -04:00
XtraCube db327604c5 Remove PopulateResultsRpc and simplify. 2025-03-13 12:19:08 -04:00
XtraCube 1462061df9 fix REALLY stupid bug 2025-03-13 09:23:26 -04:00
XtraCube fb40664bd0 add CheckForEndVotingEvent.cs 2025-03-12 22:56:41 -04:00
XtraCube 3cba870980 add ProcessVotesEvent.cs and remove "weighting" 2025-03-12 22:30:54 -04:00
XtraCube ab2f03ee4d still broken 2025-03-12 20:13:20 -04:00
ang-xd 645d1dad1c Broken thing 2025-03-12 18:01:58 -04:00
XtraCube a04e0d28db WTF GIT FAIL! 2025-03-12 17:24:40 -04:00
XtraCube b04d9619b8 Merge branch 'dev' into voting
# Conflicts:
#	MiraAPI/Events/Vanilla/Meeting/ReportBodyEvent.cs
#	MiraAPI/Patches/Events/ReportBodyEventPatch.cs
#	MiraAPI/Utilities/Extensions.cs
2025-03-12 17:23:29 -04:00
XtraCube 33fd657eb3 add "OptionsMenuColor" to ICustomRole 2025-03-12 16:48:04 -04:00
XtraCube 529fc89fc5 add WCAG 2.1 compliant alternate color 2025-03-12 16:45:29 -04:00
XtraCube 6ab283d39c increase accessibility of properties in CustomActionButton.cs 2025-03-12 16:04:26 -04:00
XtraCube 08d8a48701 make Player not nullable in basemodifier (because it shouldnt ever be) 2025-03-12 16:02:15 -04:00
XtraCube 708534ed5c make Player not nullable in basemodifier (because it shouldnt ever be) 2025-03-12 16:01:34 -04:00
XtraCube 886ef0e31f fix ToAdd/ToRemove modifier bug 2025-03-12 15:26:24 -04:00
XtraCube 0b9e54eb50 voting API improvements 2025-03-10 22:29:33 -04:00
XtraCube bad6648f44 add weight to CustomVote 2025-03-10 21:52:16 -04:00
XtraCube 86f970c989 copy new meeting event from voting branch 2025-03-08 10:11:19 -05:00
XtraCube 7aafaf478c bump version 2025-03-08 10:10:55 -05:00
XtraCube 451a626370 Merge pull request #30 from All-Of-Us-Mods/optionable
Optionable Types
2025-03-04 18:50:20 -05:00
XtraCube e02c06ca07 final cleanup 2025-03-04 18:29:30 -05:00
XtraCube e43cd0ceff remove debug log 2025-03-04 17:00:16 -05:00
XtraCube e680b5c872 unity lifetime check 2025-03-04 17:00:05 -05:00
XtraCube b6f304fe1d organize example 2025-03-04 16:59:55 -05:00
XtraCube e52f48c20d allow any groups to be shown in modifiers menu 2025-03-03 19:28:20 -05:00
XtraCube d97588b356 add lobby view pane settings 2025-03-03 19:12:09 -05:00
XtraCube 68304a5eb8 simplify + partial unscuff 2025-03-03 17:10:14 -05:00
XtraCube f2add2a65b this is very broken idk why 2025-03-02 19:21:37 -05:00
XtraCube bbff2dd2d9 modifier options (WIP) 2025-03-01 18:34:18 -05:00
ang-xd 664f8cb2e8 Add PopulateResultsEvent.cs 2025-03-01 15:31:48 -05:00
ang-xd d9081ed17b Outline text method 2025-03-01 15:30:14 -05:00
XtraCube 6f248221d6 remove extra log 2025-03-01 12:38:04 -05:00
ang-xd 989b511276 Voting "API" 2025-02-28 23:19:34 -05:00
XtraCube b67fdf5ab1 optionable v1 2025-02-28 23:11:31 -05:00
XtraCube 26afd47d2a attribute event registration 2025-02-28 15:41:18 -05:00
XtraCube 2e0ecd95a6 fix things i forgot to commit 2025-02-28 10:17:39 -05:00
XtraCube 669d5765e6 add winner info to verify condition in gameover 2025-02-28 10:14:24 -05:00
72 changed files with 2401 additions and 514 deletions

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<VersionPrefix>0.1.9</VersionPrefix>
<VersionPrefix>0.2.0</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Authors>All Of Us, XtraCube, Angxl</Authors>
@@ -19,7 +19,7 @@ public class TeleportButton : CustomActionButton
public override int MaxUses => 2;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.TeleportButton;
public override Color TextOutlineColor => new Color32(221, 176, 152, 255);
public static bool IsZoom { get; private set; }
public override bool Enabled(RoleBehaviour? role)
+47 -11
View File
@@ -1,9 +1,14 @@
using MiraAPI.Events;
using System.Linq;
using MiraAPI.Events;
using MiraAPI.Events.Mira;
using MiraAPI.Events.Vanilla.Gameplay;
using MiraAPI.Events.Vanilla.Map;
using MiraAPI.Events.Vanilla.Meeting;
using MiraAPI.Events.Vanilla.Meeting.Voting;
using MiraAPI.Events.Vanilla.Player;
using MiraAPI.Example.Buttons.Freezer;
using MiraAPI.Example.Roles;
using MiraAPI.Utilities;
using Reactor.Utilities;
namespace MiraAPI.Example;
@@ -12,11 +17,7 @@ public static class ExampleEventHandlers
{
public static void Initialize()
{
// Register event handlers here
MiraEventManager.RegisterEventHandler<MiraButtonClickEvent<FreezeButton>>(FreezeButtonClickHandler, 1);
MiraEventManager.RegisterEventHandler<MiraButtonCancelledEvent<FreezeButton>>(FreezeButtonCancelledHandler);
MiraEventManager.RegisterEventHandler<UpdateSystemEvent>(UpdateSystemEventHandler);
// You can register event handlers with the MiraEventManager class.
MiraEventManager.RegisterEventHandler<BeforeMurderEvent>(@event =>
{
Logger<ExamplePlugin>.Info($"{@event.Source.Data.PlayerName} is about to kill {@event.Target.Data.PlayerName}");
@@ -33,24 +34,59 @@ public static class ExampleEventHandlers
});
}
// If you want to add extra votes to a player, do something like this.
[RegisterEvent]
public static void StartMeetingEvent(StartMeetingEvent _)
{
foreach (var plr in PlayerControl.AllPlayerControls.ToArray().Where(player => player.Data.Role is MayorRole))
{
plr.GetVoteData().IncreaseRemainingVotes(1);
}
}
// Example of using the Voting API to make a role similar to the Prosecutor from Town of Us.
[RegisterEvent(15)]
public static void HandleVoteEvent(HandleVoteEvent @event)
{
if (@event.VoteData.Owner.Data.Role is not NeutralKillerRole) return;
@event.VoteData.SetRemainingVotes(0);
for (var i = 0; i < 5; i++)
{
@event.VoteData.VoteForPlayer(@event.TargetId);
}
foreach (var plr in PlayerControl.AllPlayerControls.ToArray().Where(player => player != @event.VoteData.Owner))
{
plr.GetVoteData().Votes.Clear();
plr.GetVoteData().VotesRemaining = 0;
}
@event.Cancel();
}
// Events can be registered using an attribute as well.
[RegisterEvent]
public static void UpdateSystemEventHandler(UpdateSystemEvent @event)
{
Logger<ExamplePlugin>.Error(@event.SystemType.ToString());
}
// Example event handler
[RegisterEvent(1)]
public static void FreezeButtonClickHandler(MiraButtonClickEvent<FreezeButton> @event)
{
Logger<ExamplePlugin>.Warning("Freeze button clicked!");
if (PlayerControl.LocalPlayer.Data.PlayerName == "stupid")
{
@event.Cancel();
@event.Button.SetTimer(15f);
}
if (PlayerControl.LocalPlayer.Data.PlayerName != "stupid") return;
@event.Cancel();
@event.Button.SetTimer(15f);
}
// Example event handler
[RegisterEvent]
public static void FreezeButtonCancelledHandler(MiraButtonCancelledEvent<FreezeButton> @event)
{
Logger<ExamplePlugin>.Warning("Freeze button cancelled!");
@@ -7,9 +7,9 @@ namespace MiraAPI.Example.GameOver;
public class NeutralKillerGameOver : CustomGameOver
{
public override bool VerifyCondition(PlayerControl playerControl)
public override bool VerifyCondition(PlayerControl playerControl, NetworkedPlayerInfo[] winners)
{
return playerControl.Data.Role is NeutralKillerRole;
return winners is [{ Role: NeutralKillerRole }];
}
public override void AfterEndGameSetup(EndGameManager endGameManager)
+9 -7
View File
@@ -1,4 +1,6 @@
using MiraAPI.Modifiers.Types;
using MiraAPI.Example.Options.Modifiers;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers.Types;
namespace MiraAPI.Example.Modifiers;
@@ -6,13 +8,13 @@ public class CaptainModifier : GameModifier
{
public override string ModifierName => "Captain";
public override int GetAmountPerGame()
{
return 1;
}
public override int GetAssignmentChance()
{
return 100;
return (int)OptionGroupSingleton<CaptainModifierSettings>.Instance.Chance;
}
public override int GetAmountPerGame()
{
return (int)OptionGroupSingleton<CaptainModifierSettings>.Instance.Amount;
}
}
@@ -15,7 +15,7 @@ public class FreezeModifier : TimedModifier
public override void OnActivate()
{
if (Player?.AmOwner == true)
if (Player.AmOwner)
{
Player.moveable = false;
}
@@ -25,15 +25,15 @@ public class FreezeModifier : TimedModifier
{
base.FixedUpdate();
if (Player?.AmOwner == true || PlayerControl.LocalPlayer.Data.Role is FreezerRole)
if (Player.AmOwner || PlayerControl.LocalPlayer.Data.Role is FreezerRole)
{
Player?.cosmetics.SetOutline(true, new Nullable<Color>(Palette.LightBlue));
Player.cosmetics.SetOutline(true, new Nullable<Color>(Palette.LightBlue));
}
}
public override void OnTimerComplete()
{
if (Player?.AmOwner == true)
if (Player.AmOwner)
{
Player.moveable = true;
}
@@ -5,6 +5,7 @@ namespace MiraAPI.Example.Modifiers;
public class HighPriorityModifier : GameModifier
{
public override string ModifierName => "High Priority";
public override int GetAssignmentChance()
{
return 100;
@@ -0,0 +1,19 @@
using MiraAPI.Example.Modifiers;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
namespace MiraAPI.Example.Options.Modifiers;
public class CaptainModifierSettings : AbstractOptionGroup<CaptainModifier>
{
public override string GroupName => "Captain Settings";
[ModdedNumberOption("Amount", 0, 5)]
public float Amount { get; set; } = 1;
[ModdedNumberOption("Chance", 0, 100, 10)]
public float Chance { get; set; } = 50;
[ModdedNumberOption("Uses", 1, 5)]
public float NumUses { get; set; } = 3;
}
@@ -0,0 +1,13 @@
using MiraAPI.Example.Modifiers.Freezer;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
namespace MiraAPI.Example.Options.Modifiers;
public class FreezeModifierSettings : AbstractOptionGroup<FreezeModifier>
{
public override string GroupName => "Freeze";
[ModdedToggleOption("Use Color")]
public bool UseColor { get; set; } = true;
}
@@ -0,0 +1,19 @@
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
namespace MiraAPI.Example.Options.Modifiers;
public class GeneralModifierOptions : AbstractOptionGroup
{
public override string GroupName => "General";
public override uint GroupPriority => 0;
public override bool ShowInModifiersMenu => true;
[ModdedToggleOption("Some Boolean Option")]
public bool SomeBooleanOption { get; set; } = true;
[ModdedNumberOption("Number Option", 0, 10, 1)]
public float NumberOption { get; set; } = 5;
}
@@ -1,17 +1,14 @@
using System;
using MiraAPI.Example.Roles;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.Utilities;
namespace MiraAPI.Example.Options.Roles;
public class FreezerRoleSettings : AbstractOptionGroup
public class FreezerRoleSettings : AbstractOptionGroup<FreezerRole>
{
public override string GroupName => "Custom Role";
public override Type AdvancedRole => typeof(FreezerRole);
[ModdedNumberOption("Freeze Duration", 1, 15, 1, MiraNumberSuffixes.Seconds)]
public float FreezeDuration { get; set; } = 5;
@@ -1,5 +1,4 @@
using System;
using MiraAPI.Example.Roles;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
@@ -7,12 +6,10 @@ using MiraAPI.Utilities;
namespace MiraAPI.Example.Options.Roles;
public class TeleporterOptions : AbstractOptionGroup
public class TeleporterOptions : AbstractOptionGroup<TeleporterRole>
{
public override string GroupName => "Teleporter";
public override Type AdvancedRole => typeof(TeleporterRole);
public ModdedNumberOption TeleportCooldown { get; set; } = new("Teleport Cooldown", 10, 5, 60, 2.5f, MiraNumberSuffixes.Seconds);
[ModdedNumberOption("Teleport Duration", 5, 25, 1, MiraNumberSuffixes.Seconds)]
+5 -2
View File
@@ -1,4 +1,6 @@
using MiraAPI.Roles;
using AmongUs.GameOptions;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using TMPro;
using UnityEngine;
@@ -12,9 +14,10 @@ public class ChameloenRole : CrewmateRole, ICustomRole
public Color RoleColor => Palette.AcceptedGreen;
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
public CustomRoleConfiguration Configuration => new(this)
{
OptionsScreenshot = ExampleAssets.Banner,
IntroSound = CustomRoleUtils.GetIntroSound(RoleTypes.Shapeshifter),
};
public void PlayerControlFixedUpdate(PlayerControl playerControl)
+14
View File
@@ -0,0 +1,14 @@
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
public class MayorRole : CrewmateRole, ICustomRole
{
public string RoleName => "Mayor";
public string RoleLongDescription => "You get extra votes!";
public string RoleDescription => RoleLongDescription;
public Color RoleColor => new Color32(221, 176, 152, 255);
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
public CustomRoleConfiguration Configuration => new(this);
}
+26
View File
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Reactor.Utilities;
namespace MiraAPI.Events;
@@ -54,6 +56,30 @@ public static class MiraEventManager
return true;
}
/// <summary>
/// Register an event.
/// </summary>
/// <param name="type">The type of event.</param>
/// <param name="methodInfo">The MethodInfo of the event handler.</param>
/// <param name="priority">The priority of the event handler. Higher values are called first.</param>
public static void RegisterEventHandler(Type type, MethodInfo methodInfo, int priority = 0)
{
if (!type.IsSubclassOf(typeof(MiraEvent)))
{
Logger<MiraApiPlugin>.Error($"Type must be a subclass of MiraEvent: {nameof(type)}");
return;
}
if (!EventWrappers.TryGetValue(type, out var handlers))
{
handlers = [];
EventWrappers.Add(type, handlers);
}
var @delegate = Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(type), methodInfo);
handlers.Add(new MiraEventWrapper(@delegate, priority));
}
/// <summary>
/// Register an event.
/// </summary>
+24
View File
@@ -0,0 +1,24 @@
using System;
namespace MiraAPI.Events;
/// <summary>
/// Register an event.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class RegisterEventAttribute : Attribute
{
/// <summary>
/// Gets the priority of the event.
/// </summary>
public int Priority { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEventAttribute"/> class.
/// </summary>
/// <param name="priority">The priority of the event.</param>
public RegisterEventAttribute(int priority = 0)
{
Priority = priority;
}
}
@@ -0,0 +1,36 @@
namespace MiraAPI.Events.Vanilla.Meeting;
/// <summary>
/// The event that is invoked when a body is reported.
/// This is invoked in CmdReportBody.
/// </summary>
public class ReportBodyEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the player that is reporting the body.
/// </summary>
public PlayerControl Reporter { get; }
/// <summary>
/// Gets the player that is being reported. Will be null for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target { get; }
/// <summary>
/// Gets the body that is being reported. Will be null for emergency meeting.
/// </summary>
public DeadBody? Body { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ReportBodyEvent"/> class.
/// </summary>
/// <param name="reporter">The player who reported the body.</param>
/// <param name="target">The player being reported.</param>
/// <param name="body">The body being reported.</param>
public ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target, DeadBody? body)
{
Reporter = reporter;
Target = target;
Body = body;
}
}
@@ -1,35 +1,22 @@
namespace MiraAPI.Events.Vanilla.Meeting;
/// <summary>
/// The event that is invoked when a meeting is called.
/// The event that is invoked when a meeting is called. This event is not cancelable.
/// This event is called after Mira resets votes, so if you plan on adding votes to a specific player, do it with this event.
/// </summary>
public class StartMeetingEvent : MiraCancelableEvent
public class StartMeetingEvent : MiraEvent
{
/// <summary>
/// Gets the player that is calling the meeting.
/// Gets the MeetingHud instance.
/// </summary>
public PlayerControl Reporter { get; }
/// <summary>
/// Gets the player that is being reported. Will be null for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target { get; }
/// <summary>
/// Gets the body that is being reported. Will be null for emergency meeting.
/// </summary>
public DeadBody? Body { get; }
public MeetingHud MeetingHud { get; }
/// <summary>
/// Initializes a new instance of the <see cref="StartMeetingEvent"/> class.
/// </summary>
/// <param name="reporter">The player who reported the body.</param>
/// <param name="target">The player being reported.</param>
/// <param name="body">The body being reported.</param>
public StartMeetingEvent(PlayerControl reporter, NetworkedPlayerInfo? target, DeadBody? body)
/// <param name="meetingHud">The MeetingHud instance.</param>
public StartMeetingEvent(MeetingHud meetingHud)
{
Reporter = reporter;
Target = target;
Body = body;
MeetingHud = meetingHud;
}
}
@@ -0,0 +1,26 @@
namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <summary>
/// Checks if voting is complete. If canceled, the default end voting logic will be skipped.
/// </summary>
public class CheckForEndVotingEvent : MiraCancelableEvent
{
/// <summary>
/// Gets a value indicating whether default voting logic determines that voting is complete.
/// </summary>
public bool IsVotingComplete { get; }
/// <summary>
/// Gets or sets a value indicating whether the voting should be forced to end, regardless of the default logic.
/// </summary>
public bool ForceEndVoting { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CheckForEndVotingEvent"/> class.
/// </summary>
/// <param name="isVotingComplete">>True if voting is complete, false otherwise.</param>
public CheckForEndVotingEvent(bool isVotingComplete)
{
IsVotingComplete = isVotingComplete;
}
}
@@ -0,0 +1,44 @@
using MiraAPI.Voting;
namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <summary>
/// The event that is invoked when Mira handles a vote. This is invoked before Mira's behaviour, so be cautious.
/// If you intend on adding custom vote behaviour, cancel the event and do so.
/// If you are NOT canceling the event, keep in mind that Mira automatically removes a vote and adds the suspect to the VotedPlayers list after this event is invoked.
/// </summary>
public class HandleVoteEvent : MiraCancelableEvent
{
/// <summary>
/// Gets the instance of the voter's vote data.
/// </summary>
public PlayerVoteData VoteData { get; }
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId { get; }
/// <summary>
/// Gets the player info of the target.
/// </summary>
public NetworkedPlayerInfo TargetPlayerInfo { get; }
/// <summary>
/// Initializes a new instance of the <see cref="HandleVoteEvent"/> class.
/// </summary>
/// <param name="playerVoteData">The voter's data.</param>
/// <param name="targetId">The target's playerId.</param>
public HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId)
{
VoteData = playerVoteData;
Player = playerVoteData.Owner;
TargetId = targetId;
TargetPlayerInfo = GameData.Instance.GetPlayerById(targetId);
}
}
@@ -0,0 +1,43 @@
using MiraAPI.Voting;
namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <summary>
/// The event that is invoked when the player tries to select another player to vote.
/// </summary>
public class MeetingSelectEvent : MiraEvent
{
/// <summary>
/// Gets the instance of the voter's vote data.
/// </summary>
public PlayerVoteData VoteData { get; }
/// <summary>
/// Gets the player id of the target.
/// </summary>
public int TargetId { get; }
/// <summary>
/// Gets the player info of the target.
/// </summary>
public NetworkedPlayerInfo TargetPlayerInfo { get; }
/// <summary>
/// Gets or sets a value indicating whether the player is allowed to select the target.
/// </summary>
public bool AllowSelect { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MeetingSelectEvent"/> class.
/// </summary>
/// <param name="playerVoteData">The voter's data.</param>
/// <param name="targetId">The target's playerId.</param>
/// <param name="allowSelect">>Whether the player is allowed to select the target.</param>
public MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, bool allowSelect)
{
VoteData = playerVoteData;
TargetId = targetId;
TargetPlayerInfo = GameData.Instance.GetPlayerById((byte)targetId);
AllowSelect = allowSelect;
}
}
@@ -0,0 +1,25 @@
using System.Collections.Generic;
using MiraAPI.Voting;
namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <summary>
/// Called in VotingUtils.HandlePopulateResults.
/// Cancelling is NOT advised but if you do plan on cancelling, please ensure you account for displaying ALL player's votes.
/// </summary>
public class PopulateResultsEvent : MiraCancelableEvent
{
/// <summary>
/// Gets a list of networked votes.
/// </summary>
public List<CustomVote> Votes { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PopulateResultsEvent"/> class.
/// </summary>
/// <param name="votes">The list of votes.</param>
public PopulateResultsEvent(List<CustomVote> votes)
{
Votes = votes;
}
}
@@ -0,0 +1,48 @@
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Voting;
namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <summary>
/// Ran after calculating votes and before displaying the results. Only ran on the host.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="ProcessVotesEvent"/> class.
/// </remarks>
/// <param name="votes">>The list of votes that are being processed.</param>
/// <param name="exiledPlayer">The player to be exiled. Will be null if no player is to be exiled.</param>
public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exiledPlayer = null) : MiraEvent
{
private readonly List<CustomVote> _originalVotes = [.. votes];
private NetworkedPlayerInfo? _exiledPlayer = exiledPlayer;
/// <summary>
/// Gets a value indicating whether the exiled player has been modified by the event.
/// </summary>
public bool ExiledPlayerModified { get; private set; }
/// <summary>
/// Gets a value indicating whether the votes have been modified by the event.
/// </summary>
public bool VotesModified => !Votes.SequenceEqual(_originalVotes);
/// <summary>
/// Gets the list of votes that are being processed.
/// </summary>
public List<CustomVote> Votes { get; } = votes;
/// <summary>
/// Gets or sets the player to be exiled. Will be null if no player is to be exiled.
/// </summary>
public NetworkedPlayerInfo? ExiledPlayer
{
get => _exiledPlayer;
set
{
_exiledPlayer = value;
ExiledPlayerModified = true;
}
}
}
+2 -1
View File
@@ -18,8 +18,9 @@ public abstract class CustomGameOver
/// Verifies if the condition for this CustomGameOver is met.
/// </summary>
/// <param name="playerControl">The PlayerControl that requested the Game Over.</param>
/// <param name="winners">The collection of winners.</param>
/// <returns>True if the condition is met, otherwise false.</returns>
public virtual bool VerifyCondition(PlayerControl playerControl)
public virtual bool VerifyCondition(PlayerControl playerControl, NetworkedPlayerInfo[] winners)
{
return true;
}
+22 -6
View File
@@ -16,6 +16,17 @@ public abstract class AbstractOptionGroup
/// </summary>
public abstract string GroupName { get; }
/// <summary>
/// Gets the Optionable type of the group.
/// </summary>
public virtual Type? OptionableType => null;
/// <summary>
/// Gets a value indicating whether the group should be shown in the modifiers menu.
/// </summary>
// TODO: make this not a boolean
public virtual bool ShowInModifiersMenu => false;
/// <summary>
/// Gets the function that determines whether the group should be visible or not.
/// </summary>
@@ -24,7 +35,7 @@ public abstract class AbstractOptionGroup
/// <summary>
/// Gets the group color. This is used to color the group in the options menu.
/// </summary>
public virtual Color GroupColor => Color.clear;
public virtual Color GroupColor => MiraApiPlugin.DefaultHeaderColor;
/// <summary>
/// Gets the group priority. This is used to determine the order in which groups are displayed in the options menu.
@@ -32,12 +43,17 @@ public abstract class AbstractOptionGroup
/// </summary>
public virtual uint GroupPriority => uint.MaxValue;
/// <summary>
/// Gets the role the group is associated with. This is used for the advanced role options menu.
/// </summary>
public virtual Type? AdvancedRole => null;
internal bool AllOptionsHidden { get; set; }
internal CategoryHeaderMasked? Header { get; set; }
}
/// <summary>
/// Base class for option groups. An option group is a collection of options that are displayed together in the options menu.
/// </summary>
/// <typeparam name="T">The type of the optionable that this group contains.</typeparam>
public abstract class AbstractOptionGroup<T> : AbstractOptionGroup where T : IOptionable
{
/// <inheritdoc />
public override Type OptionableType => typeof(T);
}
@@ -8,12 +8,12 @@ namespace MiraAPI.GameOptions.Attributes;
/// Attribute for creating an enum option.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? values = null, Type? roleType = null)
: ModdedOptionAttribute(title, roleType)
public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? values = null)
: ModdedOptionAttribute(title)
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var opt = new ModdedEnumOption(Title, (int)(value ?? 0), enumType, values, RoleType);
var opt = new ModdedEnumOption(Title, (int)(value ?? 0), enumType, values);
return opt;
}
@@ -16,13 +16,12 @@ public class ModdedNumberOptionAttribute(
float increment = 1,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false,
Type? roleType = null)
: ModdedOptionAttribute(title, roleType)
bool zeroInfinity = false)
: ModdedOptionAttribute(title)
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
return new ModdedNumberOption(Title, (float)(value ?? min+increment), min, max, increment, suffixType, formatString, zeroInfinity, RoleType);
return new ModdedNumberOption(Title, (float)(value ?? min+increment), min, max, increment, suffixType, formatString, zeroInfinity);
}
/// <inheritdoc />
@@ -8,13 +8,12 @@ namespace MiraAPI.GameOptions.Attributes;
/// Attribute for a toggle option.
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="roleType">An optional role type.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedToggleOptionAttribute(string title, Type? roleType = null) : ModdedOptionAttribute(title, roleType)
public class ModdedToggleOptionAttribute(string title) : ModdedOptionAttribute(title)
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var toggleOpt = new ModdedToggleOption(Title, (bool)(value ?? false), RoleType);
var toggleOpt = new ModdedToggleOption(Title, (bool)(value ?? false));
return toggleOpt;
}
-1
View File
@@ -13,7 +13,6 @@ public interface IModdedOption
StringNames StringName { get; }
IMiraPlugin? ParentMod { get; set; }
BaseGameSetting Data { get; }
Type? AdvancedRole { get; set; }
OptionBehaviour? OptionBehaviour { get; }
Func<bool> Visible { get; set; }
ConfigDefinition? ConfigDefinition { get; set; }
+6
View File
@@ -0,0 +1,6 @@
namespace MiraAPI.GameOptions;
/// <summary>
/// Interface for classes that can be used for option groups.
/// </summary>
public interface IOptionable;
+1 -4
View File
@@ -108,7 +108,7 @@ public static class ModdedOptionsManager
RegisterOption(option, group, property.Name, pluginInfo);
}
private static void RegisterOption(
internal static void RegisterOption(
IModdedOption option,
AbstractOptionGroup group,
string propertyName,
@@ -119,10 +119,7 @@ public static class ModdedOptionsManager
option.ConfigDefinition = new ConfigDefinition(groupName, propertyName);
option.ParentMod = pluginInfo.MiraPlugin;
option.AdvancedRole = group.AdvancedRole;
pluginInfo.Options.Add(option);
ModdedOptions.Add(option.Id, option);
group.Options.Add(option);
}
@@ -0,0 +1,15 @@
using System.Linq;
namespace MiraAPI.GameOptions;
internal class ModifierOptionGroup : AbstractOptionGroup
{
public override string GroupName { get; }
public ModifierOptionGroup(string name, IModdedOption[] options, params AbstractOptionGroup[] groups)
{
GroupName = name;
Options.AddRange(options);
Options.AddRange(groups.SelectMany(x=>x.Options));
}
}
@@ -27,8 +27,7 @@ public class ModdedEnumOption : ModdedOption<int>
/// <param name="defaultValue">The default value as an int.</param>
/// <param name="enumType">The Enum type.</param>
/// <param name="values">An option list of string values to use in place of the enum name.</param>
/// <param name="roleType">An optional role type to specify for a specific role.</param>
public ModdedEnumOption(string title, int defaultValue, Type enumType, string[]? values = null, Type? roleType = null) : base(title, defaultValue, roleType)
public ModdedEnumOption(string title, int defaultValue, Type enumType, string[]? values = null) : base(title, defaultValue)
{
Values = values ?? Enum.GetNames(enumType);
Data = ScriptableObject.CreateInstance<StringGameSetting>();
@@ -101,7 +100,6 @@ public class ModdedEnumOption : ModdedOption<int>
}
}
/// <summary>
/// An option for selecting an enum value.
/// </summary>
@@ -118,10 +116,8 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="defaultValue">The default value as an int.</param>
/// <param name="enumType">The Enum type.</param>
/// <param name="values">An option list of string values to use in place of the enum name.</param>
/// <param name="roleType">An optional role type to specify for a specific role.</param>
public ModdedEnumOption(string title, T defaultValue, string[]? values = null, Type? roleType = null) : base(title, defaultValue, roleType)
public ModdedEnumOption(string title, T defaultValue, string[]? values = null) : base(title, defaultValue)
{
Values = values ?? Enum.GetNames(typeof(T));
Data = ScriptableObject.CreateInstance<StringGameSetting>();
@@ -48,7 +48,6 @@ public class ModdedNumberOption : ModdedOption<float>
/// <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(
string title,
float defaultValue,
@@ -57,8 +56,7 @@ public class ModdedNumberOption : ModdedOption<float>
float increment,
MiraNumberSuffixes suffixType,
string? formatString = null,
bool zeroInfinity = false,
Type? roleType = null) : base(title, defaultValue, roleType)
bool zeroInfinity = false) : base(title, defaultValue)
{
Min = min;
Max = max;
@@ -77,11 +75,11 @@ public class ModdedNumberOption : ModdedOption<float>
data.Increment = Increment;
data.ValidRange = new FloatRange(Min, Max);
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");
(defaultValue.IsInteger() &&
Increment.IsInteger() &&
Value.IsInteger() &&
Min.IsInteger() &&
Max.IsInteger() ? "0" : "0.0");
data.ZeroIsInfinity = ZeroInfinity;
data.SuffixType = (NumberSuffixes)SuffixType;
@@ -144,7 +142,7 @@ public class ModdedNumberOption : ModdedOption<float>
Value = Mathf.Clamp(newValue, Min, Max);
HudManager.Instance.Notifier.AddSettingsChangeMessage(
StringName,
Data?.GetValueString(Value),
Data.GetValueString(Value),
false);
if (OptionBehaviour is NumberOption opt)
@@ -2,7 +2,6 @@
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using Reactor.Localization.Utilities;
using Reactor.Networking.Rpc;
using UnityEngine;
@@ -72,11 +71,6 @@ public abstract class ModdedOption<T> : IModdedOption
/// </summary>
public Func<bool> Visible { get; set; }
/// <summary>
/// Gets or sets the advanced role of the option.
/// </summary>
public Type? AdvancedRole { get; set; }
/// <summary>
/// Gets or sets the option behaviour of the option.
/// </summary>
@@ -85,25 +79,14 @@ public abstract class ModdedOption<T> : IModdedOption
/// <summary>
/// Gets or sets the config definition of the option.
/// </summary>
public ConfigDefinition? ConfigDefinition
{
get => _configDefinition;
set
{
if (_configDefinition is not null) return;
_configDefinition = value;
}
}
private ConfigDefinition? _configDefinition;
public ConfigDefinition? ConfigDefinition { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedOption{T}"/> class.
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="roleType">The Role Type or null if it doesn't belong to a role.</param>
protected ModdedOption(string title, T defaultValue, Type? roleType)
protected ModdedOption(string title, T defaultValue)
{
Id = ModdedOptionsManager.NextId;
Title = title;
@@ -111,11 +94,6 @@ public abstract class ModdedOption<T> : IModdedOption
Value = defaultValue;
StringName = CustomStringName.CreateAndRegister(Title);
Visible = () => true;
if (roleType is not null && roleType.IsAssignableTo(typeof(ICustomRole)))
{
AdvancedRole = roleType;
}
}
internal void ValueChanged(OptionBehaviour optionBehaviour)
@@ -15,8 +15,7 @@ public class ModdedToggleOption : ModdedOption<bool>
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="roleType">An optional role type.</param>
public ModdedToggleOption(string title, bool defaultValue, Type? roleType = null) : base(title, defaultValue, roleType)
public ModdedToggleOption(string title, bool defaultValue) : base(title, defaultValue)
{
Data = ScriptableObject.CreateInstance<CheckboxGameSetting>();
+30 -11
View File
@@ -47,9 +47,14 @@ public abstract class CustomActionButton
public virtual int MaxUses => 0;
/// <summary>
/// Gets the location of the button on the screen.
/// Gets the button's text outline color.
/// </summary>
public virtual ButtonLocation Location { get; private set; } = ButtonLocation.BottomLeft;
public virtual Color TextOutlineColor => Color.clear;
/// <summary>
/// Gets or sets the location of the button on the screen.
/// </summary>
public virtual ButtonLocation Location { get; set; } = ButtonLocation.BottomLeft;
/// <summary>
/// Gets a value indicating whether the button has an effect ability.
@@ -64,27 +69,27 @@ public abstract class CustomActionButton
/// <summary>
/// Gets or sets a value indicating whether the effect is currently active, if there is one.
/// </summary>
public bool EffectActive { get; protected set; }
public bool EffectActive { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the timer is currently active.
/// </summary>
public bool TimerPaused { get; protected set; }
public bool TimerPaused { get; set; }
/// <summary>
/// Gets or sets the amount of uses left.
/// </summary>
public int UsesLeft { get; protected set; }
public int UsesLeft { get; set; }
/// <summary>
/// Gets or sets the timer variable to measure cooldowns and effects.
/// </summary>
public float Timer { get; protected set; }
public float Timer { get; set; }
/// <summary>
/// Gets the button object in game. This is created by Mira API automatically.
/// Gets or sets the button object in game. This is created by Mira API automatically.
/// </summary>
protected ActionButton? Button { get; private set; }
public ActionButton? Button { get; set; }
/// <summary>
/// The method used to create the button.
@@ -114,6 +119,11 @@ public abstract class CustomActionButton
Button.SetInfiniteUses();
}
if (TextOutlineColor != Color.clear)
{
SetTextOutline(TextOutlineColor);
}
var pb = Button.GetComponent<PassiveButton>();
pb.OnClick = new Button.ButtonClickedEvent();
pb.OnClick.AddListener((UnityAction)(() =>
@@ -158,7 +168,7 @@ public abstract class CustomActionButton
/// Allows you to change the button's location.
/// </summary>
/// <param name="location">The new location.</param>
/// <param name="moveButton">Whether the button's position should change ingame.</param>
/// <param name="moveButton">Whether the button's position should change in-game.</param>
public virtual void SetButtonLocation(ButtonLocation location, bool moveButton = true)
{
if (!HudManager.InstanceExists || Button == null)
@@ -207,6 +217,15 @@ public abstract class CustomActionButton
EffectActive = false;
}
/// <summary>
/// A utility function to change the outline color of the button's text.
/// </summary>
/// <param name="color">The new color.</param>
public virtual void SetTextOutline(Color color)
{
Button?.buttonLabelText.SetOutlineColor(color);
}
/// <summary>
/// A utility function to override the sprite of the button.
/// </summary>
@@ -344,7 +363,7 @@ public abstract class CustomActionButton
/// <returns>A value that represents whether the button should light up or not.</returns>
public virtual bool CanUse()
{
return !LimitedUses || UsesLeft > 0;
return PlayerControl.LocalPlayer.moveable && (!LimitedUses || UsesLeft > 0);
}
/// <summary>
@@ -443,7 +462,7 @@ public abstract class CustomActionButton<T> : CustomActionButton where T : MonoB
/// <summary>
/// Gets or sets the target object of the button.
/// </summary>
public T? Target { get; protected set; }
public T? Target { get; set; }
/// <summary>
/// Gets the distance the player must be from the target object to use the button.
+9 -1
View File
@@ -1,12 +1,19 @@
using BepInEx;
using System;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MonoMod.Utils;
using Reactor;
using Reactor.Networking;
using Reactor.Networking.Attributes;
using Reactor.Utilities;
using TMPro;
using UnityEngine;
using UnityEngine.ProBuilder;
using Delegate = Il2CppSystem.Delegate;
namespace MiraAPI;
@@ -20,6 +27,7 @@ namespace MiraAPI;
public partial class MiraApiPlugin : BasePlugin
{
public static Color MiraColor { get; } = new Color32(238, 154, 112, 255);
public static Color DefaultHeaderColor = new Color32(77, 77, 77, 255);
private static MiraPluginManager? PluginManager { get; set; }
internal Harmony Harmony { get; } = new(Id);
@@ -0,0 +1,10 @@
namespace MiraAPI.Modifiers;
/// <summary>
/// Represents the assignment configuration for a game modifier.
/// </summary>
/// <param name="DefaultAmount">The default amount of players that can have this modifier in a game.</param>
/// <param name="DefaultChance">The default chance of the modifier being assigned to a player.</param>
/// <param name="CreateAmountOption">Whether Mira should create an amount option for the modifier.</param>
/// <param name="CreateChanceOption">Whether Mira should create a chance option for the modifier.</param>
public record struct AssignmentConfiguration(int DefaultAmount, int DefaultChance, bool CreateAmountOption, bool CreateChanceOption);
+12 -2
View File
@@ -1,16 +1,18 @@
using System;
using MiraAPI.GameOptions;
using MiraAPI.PluginLoading;
namespace MiraAPI.Modifiers;
/// <summary>
/// Base class for all modifiers.
/// </summary>
public abstract class BaseModifier
public abstract class BaseModifier : IOptionable
{
/// <summary>
/// Gets the player that the modifier is attached to.
/// </summary>
public PlayerControl? Player { get; internal set; }
public PlayerControl Player { get; internal set; } = null!;
/// <summary>
/// Gets the modifier component that the modifier is attached to.
@@ -32,6 +34,14 @@ public abstract class BaseModifier
/// </summary>
public uint TypeId => ModifierManager.GetModifierTypeId(GetType()) ?? throw new InvalidOperationException("Modifier is not registered.");
/// <summary>
/// Gets the parent mod of the modifier.
/// </summary>
public MiraPluginInfo ParentMod => Array.Find(
MiraPluginManager.Instance.RegisteredPlugins(),
x => x.Modifiers.Exists(y => y.TypeId == TypeId)
) ?? throw new InvalidOperationException("Modifier is not registered.");
/// <summary>
/// Gets the modifier name.
/// </summary>
+32 -26
View File
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.Attributes;
@@ -25,7 +24,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
/// Gets the active modifiers on the player.
/// </summary>
[HideFromIl2Cpp]
public ImmutableList<BaseModifier> ActiveModifiers => Modifiers.ToImmutableList();
public ImmutableList<BaseModifier> ActiveModifiers { get; private set; } = ImmutableList<BaseModifier>.Empty;
[HideFromIl2Cpp]
private List<BaseModifier> Modifiers { get; set; } = [];
@@ -59,13 +58,13 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
private void FixedUpdate()
{
foreach (var modifier in _toRemove)
foreach (var modifier in _toRemove.ToArray())
{
modifier.OnDeactivate();
Modifiers.Remove(modifier);
}
foreach (var modifier in _toAdd)
foreach (var modifier in _toAdd.ToArray())
{
Modifiers.Add(modifier);
modifier.Initialized = true;
@@ -85,9 +84,11 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
}
_toAdd.Clear();
_toRemove.Clear();
ActiveModifiers = Modifiers.ToImmutableList();
}
foreach (var modifier in Modifiers)
foreach (var modifier in ActiveModifiers)
{
modifier.FixedUpdate();
}
@@ -95,7 +96,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
private void Update()
{
foreach (var modifier in Modifiers)
foreach (var modifier in ActiveModifiers)
{
modifier.Update();
}
@@ -105,21 +106,26 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
return;
}
var filteredModifiers = Modifiers.Where(mod => !mod.HideOnUi).ToArray();
if (MeetingHud.Instance)
{
return;
}
if (filteredModifiers.Length != 0 && !MeetingHud.Instance)
var showText = false;
var builder = new StringBuilder("<b><size=130%>Modifiers:</b></size>\n");
foreach (var modifier in ActiveModifiers)
{
var stringBuild = new StringBuilder();
foreach (var mod in filteredModifiers)
if (modifier.HideOnUi)
{
stringBuild.Append(CultureInfo.InvariantCulture, $"\n{mod.GetHudString()}");
continue;
}
_modifierText!.text = $"<b><size=130%>Modifiers:</b></size>{stringBuild}";
}
else if (_modifierText!.text != string.Empty)
{
_modifierText.text = string.Empty;
showText = true;
builder.AppendLine(modifier.GetHudString());
}
_modifierText!.text = showText ? builder.ToString() : string.Empty;
}
/// <summary>
@@ -131,7 +137,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public IEnumerable<T> GetModifiers<T>(Func<T, bool>? predicate=null) where T : BaseModifier
{
return Modifiers.OfType<T>().Where(x => predicate == null || predicate(x));
return ActiveModifiers.OfType<T>().Where(x => predicate == null || predicate(x));
}
/// <summary>
@@ -143,7 +149,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public IEnumerable<BaseModifier> GetModifiers(Type type, Func<BaseModifier, bool>? predicate=null)
{
return Modifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x)));
return ActiveModifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x)));
}
/// <summary>
@@ -263,7 +269,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public BaseModifier? GetModifier(Guid modifierGuid)
{
return Modifiers.Find(x => x.UniqueId == modifierGuid);
return ActiveModifiers.Find(x => x.UniqueId == modifierGuid);
}
/// <summary>
@@ -285,7 +291,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public void RemoveModifier(Type type, Func<BaseModifier, bool>? predicate = null)
{
var modifiers = Modifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x))).ToList();
var modifiers = ActiveModifiers.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.");
@@ -308,7 +314,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public void RemoveModifier(BaseModifier modifier)
{
if (!Modifiers.Contains(modifier))
if (!ActiveModifiers.Contains(modifier))
{
Logger<MiraApiPlugin>.Error($"Cannot remove modifier {modifier.ModifierName} because it is not active on this player.");
return;
@@ -374,13 +380,13 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
}
var id = modifier.TypeId;
if (modifier.Unique && Modifiers.Find(x => x.TypeId == id) != null)
if (modifier.Unique && ActiveModifiers.Find(x => x.TypeId == id) != null)
{
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {id}!");
return null;
}
if (Modifiers.Contains(modifier))
if (ActiveModifiers.Contains(modifier))
{
Logger<MiraApiPlugin>.Error($"Player already has this modifier!");
return null;
@@ -446,7 +452,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public bool HasModifier<T>(Func<T, bool>? predicate=null) where T : BaseModifier
{
return Modifiers.Exists(x => x is T modifier && (predicate == null || predicate(modifier)));
return ActiveModifiers.Exists(x => x is T modifier && (predicate == null || predicate(modifier)));
}
/// <summary>
@@ -458,7 +464,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public bool HasModifier(Type type, Func<BaseModifier, bool>? predicate=null)
{
return Modifiers.Exists(x => x.GetType() == type && (predicate == null || predicate(x)));
return ActiveModifiers.Exists(x => x.GetType() == type && (predicate == null || predicate(x)));
}
/// <summary>
@@ -484,6 +490,6 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
[HideFromIl2Cpp]
public bool HasModifier(Guid id)
{
return Modifiers.Exists(x => x.UniqueId == id);
return ActiveModifiers.Exists(x => x.UniqueId == id);
}
}
+24
View File
@@ -180,6 +180,30 @@ public static class ModifierExtensions
return player.GetModifierComponent().HasModifier(typeId, predicate);
}
/// <summary>
/// Clears all modifiers from a player.
/// </summary>
/// <param name="plr">The player you want to clear modifiers for.</param>
public static void ClearModifiers(this PlayerControl plr)
{
foreach (var mod in plr.GetModifierComponent().ActiveModifiers)
{
plr.RemoveModifier(mod);
}
}
/// <summary>
/// Clears all modifiers from a player.
/// </summary>
/// <param name="plr">The player you want to clear modifiers for.</param>
public static void RpcClearModifiers(this PlayerControl plr)
{
foreach (var mod in plr.GetModifierComponent().ActiveModifiers)
{
plr.RpcRemoveModifier(mod.UniqueId);
}
}
/// <summary>
/// Checks if the player has a specific modifier by its GUID.
/// </summary>
+21 -5
View File
@@ -63,16 +63,32 @@ public static class ModifierManager
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))
BaseModifier modifier;
if (modifierType.GetConstructor(Type.EmptyTypes) != null)
{
modifier = (BaseModifier)Activator.CreateInstance(modifierType)!;
}
else
{
// this is probably terrible but its good enough for now.
modifier = (BaseModifier)FormatterServices.GetUninitializedObject(modifierType);
}
info.Modifiers.Add(modifier);
if (modifier is not GameModifier gameModifier)
{
return true;
}
var mod = Activator.CreateInstance(modifierType) as GameModifier;
var priority = mod!.Priority();
if (modifierType.GetConstructor(Type.EmptyTypes) == null)
{
Logger<MiraApiPlugin>.Error($"Game Modifier {modifierType.FullName} does not have a parameterless constructor!");
return false;
}
var priority = gameModifier.Priority();
if (!PrioritiesToIdsMap.TryGetValue(priority, out var list))
{
+33
View File
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace MiraAPI.Modifiers;
/// <summary>
/// Utilities to make handling modifiers in-game easier.
/// </summary>
public static class ModifierUtils
{
/// <summary>
/// Gets a list of all active in-game modifiers.
/// </summary>
/// <param name="predicate">Select if modifier is valid to be added to list.</param>
/// <typeparam name="T">The modifier type.</typeparam>
/// <returns>A list of modifiers.</returns>
public static IEnumerable<T> GetActiveModifiers<T>(Func<T, bool>? predicate = null) where T : BaseModifier
{
return PlayerControl.AllPlayerControls.ToArray().SelectMany(x => x.GetModifiers<T>(predicate)).OfType<T>();
}
/// <summary>
/// Gets all players with a certain modifier.
/// </summary>
/// <param name="predicate">Select if modifier is valid.</param>
/// <typeparam name="T">The modifier type.</typeparam>
/// <returns>A list of players with that modifier.</returns>
public static IEnumerable<PlayerControl> GetPlayersWithModifier<T>(Func<T, bool>? predicate = null) where T : BaseModifier
{
return PlayerControl.AllPlayerControls.ToArray().Where(x => x.HasModifier<T>(predicate));
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ public class CustomGameOverRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<
{
if (GameOverManager.TryGetGameOver(data.Reason, out var gameOver))
{
if (!gameOver.VerifyCondition(innerNetObject))
if (!gameOver.VerifyCondition(innerNetObject, [.. data.Winners]))
{
Logger<MiraApiPlugin>.Info($"Game over condition not met for {gameOver.GetType().Name}");
return;
+5
View File
@@ -39,4 +39,9 @@ public enum MiraRpc : uint
/// Custom Game Over RPC.
/// </summary>
CustomGameOver,
/// <summary>
/// Custom RPC to undo a player's vote.
/// </summary>
RemoveVote,
}
@@ -6,7 +6,7 @@ using MiraAPI.Utilities;
namespace MiraAPI.Patches.Events;
[HarmonyPatch]
public static class StartMeetingEventPatch
public static class ReportBodyEventPatch
{
[HarmonyPrefix]
[HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.CmdReportDeadBody))]
@@ -14,7 +14,7 @@ public static class StartMeetingEventPatch
{
var body = target != null ? Helpers.GetBodyById(target.PlayerId) : null;
var @event = new StartMeetingEvent(__instance, target, body);
var @event = new ReportBodyEvent(__instance, target, body);
MiraEventManager.InvokeEvent(@event);
return !@event.IsCancelled;
}
+202 -149
View File
@@ -1,5 +1,8 @@
using System.Linq;
using System;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
@@ -7,6 +10,7 @@ using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Options;
@@ -30,64 +34,98 @@ public static class GameOptionsMenuPatch
}
var num = 2.1f;
var filteredGroups =
GameSettingMenuPatches.SelectedMod?.OptionGroups.Where(
x => x.AdvancedRole is null) ?? [];
foreach (var group in filteredGroups)
if (__instance.name == "MODIFIERS TAB")
{
if (group.Options.Count == 0 || group.Header is null)
ModifiersUpdate(ref num);
}
else
{
var filteredGroups =
GameSettingMenuPatches.SelectedMod?.OptionGroups
.Where(x => x.OptionableType == null && !x.ShowInModifiersMenu) ?? [];
foreach (var group in filteredGroups)
{
continue;
}
if (!group.GroupVisible.Invoke())
{
group.Header.gameObject.SetActive(false);
foreach (var option in group.Options)
{
option.OptionBehaviour?.gameObject.SetActive(false);
}
continue;
}
group.Header.gameObject.SetActive(true);
group.Header.transform.localScale = Vector3.one * 0.63f;
group.Header.transform.localPosition = new Vector3(-0.903f, num, -2f);
num -= 0.58f;
foreach (var opt in group.Options)
{
var newOpt = opt.OptionBehaviour;
if (newOpt is null)
{
continue;
}
if (!opt.Visible.Invoke())
{
newOpt.gameObject.SetActive(false);
continue;
}
if (!group.AllOptionsHidden)
{
newOpt.gameObject.SetActive(true);
newOpt.transform.localPosition = new Vector3(0.952f, num, -2f);
num -= 0.45f;
}
else
{
newOpt.gameObject.SetActive(false);
}
UpdateGroup(group, ref num);
}
}
__instance.scrollBar.SetYBoundsMax(-num - 1.65f);
}
private static void UpdateGroup(AbstractOptionGroup group, ref float num)
{
if (group.Options.Count == 0 || group.Header is null)
{
return;
}
if (!group.GroupVisible.Invoke())
{
group.Header.gameObject.SetActive(false);
foreach (var option in group.Options)
{
option.OptionBehaviour?.gameObject.SetActive(false);
}
return;
}
group.Header.gameObject.SetActive(true);
group.Header.transform.localScale = Vector3.one * 0.63f;
group.Header.transform.localPosition = new Vector3(-0.903f, num, -2f);
num -= 0.58f;
foreach (var opt in group.Options)
{
var newOpt = opt.OptionBehaviour;
if (newOpt is null)
{
continue;
}
if (!opt.Visible.Invoke())
{
newOpt.gameObject.SetActive(false);
continue;
}
if (!group.AllOptionsHidden)
{
newOpt.gameObject.SetActive(true);
newOpt.transform.localPosition = new Vector3(0.952f, num, -2f);
num -= 0.45f;
}
else
{
newOpt.gameObject.SetActive(false);
}
}
}
private static void ModifiersUpdate(ref float num)
{
var groups = GameSettingMenuPatches.SelectedMod?.OptionGroups
.Where(x => x.ShowInModifiersMenu || x.OptionableType?.IsAssignableTo(typeof(BaseModifier))==true) ?? [];
foreach (var modGroup in groups)
{
UpdateGroup(modGroup, ref num);
}
}
private static void ModifiersCreate(GameOptionsMenu menu)
{
var groups = GameSettingMenuPatches.SelectedMod?.OptionGroups
.Where(x => x.ShowInModifiersMenu || x.OptionableType?.IsAssignableTo(typeof(BaseModifier))==true) ?? [];
foreach (var group in groups)
{
CreateGroup(menu, group);
}
}
[HarmonyPrefix]
[HarmonyPatch(nameof(GameOptionsMenu.CreateSettings))]
public static bool SettingsPatch(GameOptionsMenu __instance)
@@ -99,106 +137,18 @@ public static class GameOptionsMenuPatch
__instance.MapPicker.gameObject.SetActive(false);
var filteredGroups = GameSettingMenuPatches.SelectedMod?.OptionGroups.Where(x => x.AdvancedRole is null) ?? [];
if (__instance.name == "MODIFIERS TAB")
{
ModifiersCreate(__instance);
return false;
}
var filteredGroups = GameSettingMenuPatches.SelectedMod?.OptionGroups
.Where(x => x.OptionableType == null && !x.ShowInModifiersMenu) ?? [];
foreach (var group in filteredGroups)
{
var categoryHeaderMasked = Object.Instantiate(
__instance.categoryHeaderOrigin,
Vector3.zero,
Quaternion.identity,
__instance.settingsContainer);
categoryHeaderMasked.SetHeader(CustomStringName.CreateAndRegister(group.GroupName), 20);
if (group.GroupColor != Color.clear)
{
categoryHeaderMasked.Background.color = group.GroupColor;
categoryHeaderMasked.Divider.color = group.GroupColor;
categoryHeaderMasked.Title.color = group.GroupColor.GetAlternateColor();
}
categoryHeaderMasked.Background.size = new Vector2(
categoryHeaderMasked.Background.size.x + 1.5f,
categoryHeaderMasked.Background.size.y);
categoryHeaderMasked.gameObject.SetActive(false);
group.Header = categoryHeaderMasked;
var newText = Object.Instantiate(categoryHeaderMasked.Title, categoryHeaderMasked.transform);
newText.text = "<size=70%>(Click to close)</size>";
newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f);
newText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
var options = group.Options.Select(
opt => opt.CreateOption(
__instance.checkboxOrigin,
__instance.numberOptionOrigin,
__instance.stringOptionOrigin,
__instance.settingsContainer));
foreach (var newOpt in options)
{
newOpt.SetClickMask(__instance.ButtonClickMask);
SpriteRenderer[] componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
foreach (var renderer in componentsInChildren)
{
if (group.GroupColor != Color.clear)
{
renderer.color = group.GroupColor.GetAlternateColor();
if (renderer.transform.parent.TryGetComponent<GameOptionButton>(out var btn))
{
btn.interactableColor = group.GroupColor.GetAlternateColor();
btn.interactableHoveredColor = Color.white;
}
}
renderer.material.SetInt(PlayerMaterial.MaskLayer, 20);
}
foreach (var textMeshPro in newOpt.GetComponentsInChildren<TextMeshPro>(true))
{
if (group.GroupColor != Color.clear)
{
textMeshPro.color = group.GroupColor;
}
textMeshPro.fontMaterial.SetFloat(ShaderID.StencilComp, 3f);
textMeshPro.fontMaterial.SetFloat(ShaderID.Stencil, 20);
}
if (newOpt is ToggleOption toggle)
{
toggle.CheckMark.sprite = MiraAssets.Checkmark.LoadAsset();
toggle.CheckMark.color =
group.GroupColor != Color.clear ? group.GroupColor : MiraAssets.AcceptedTeal;
var rend = toggle.CheckMark.transform.parent.FindChild("ActiveSprite")
.GetComponent<SpriteRenderer>();
rend.sprite = MiraAssets.CheckmarkBox.LoadAsset();
rend.color = group.GroupColor != Color.clear ? group.GroupColor : MiraAssets.AcceptedTeal;
}
__instance.Children.Add(newOpt);
newOpt.Initialize();
newOpt.gameObject.SetActive(false);
}
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)(() =>
{
group.AllOptionsHidden = !group.AllOptionsHidden;
newText.text = group.AllOptionsHidden
? "<size=70%>(Click to open)</size>"
: "<size=70%>(Click to close)</size>";
}));
headerBtn.SetButtonEnableState(true);
CreateGroup(__instance, group);
}
return false;
@@ -233,9 +183,112 @@ public static class GameOptionsMenuPatch
continue;
}
optionBehaviour.OnValueChanged = new System.Action<OptionBehaviour>(__instance.ValueChanged);
optionBehaviour.OnValueChanged = new Action<OptionBehaviour>(__instance.ValueChanged);
}
return false;
}
private static void CreateGroup(GameOptionsMenu menu, AbstractOptionGroup group)
{
var categoryHeaderMasked = Object.Instantiate(
menu.categoryHeaderOrigin,
Vector3.zero,
Quaternion.identity,
menu.settingsContainer);
categoryHeaderMasked.SetHeader(CustomStringName.CreateAndRegister(group.GroupName), 20);
categoryHeaderMasked.Background.color = group.GroupColor;
categoryHeaderMasked.Divider.color = group.GroupColor;
categoryHeaderMasked.Title.color = group.GroupColor.Equals(MiraApiPlugin.DefaultHeaderColor) ? Color.white : group.GroupColor.FindAlternateColor();
categoryHeaderMasked.Background.sprite = MiraAssets.CategoryHeader.LoadAsset();
categoryHeaderMasked.Background.sprite.texture.filterMode = FilterMode.Bilinear;
categoryHeaderMasked.Background.sprite.texture.wrapMode = TextureWrapMode.Clamp;
categoryHeaderMasked.Background.transform.localPosition = new Vector3(0.5f, -0.1833f, 0);
categoryHeaderMasked.Background.size = new Vector2(
categoryHeaderMasked.Background.size.x + 1.5f,
categoryHeaderMasked.Background.size.y);
categoryHeaderMasked.gameObject.SetActive(false);
group.Header = categoryHeaderMasked;
var newText = Object.Instantiate(categoryHeaderMasked.Title, categoryHeaderMasked.transform);
newText.text = "<size=70%>(Click to close)</size>";
newText.transform.localPosition = new Vector3(2.6249f, -0.165f, 0f);
newText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
var options = group.Options.Select(
opt => opt.CreateOption(
menu.checkboxOrigin,
menu.numberOptionOrigin,
menu.stringOptionOrigin,
menu.settingsContainer));
foreach (var newOpt in options)
{
newOpt.SetClickMask(menu.ButtonClickMask);
SpriteRenderer[] componentsInChildren = newOpt.GetComponentsInChildren<SpriteRenderer>(true);
foreach (var renderer in componentsInChildren)
{
if (group.GroupColor != MiraApiPlugin.DefaultHeaderColor)
{
renderer.color = group.GroupColor.FindAlternateColor();
if (renderer.transform.parent.TryGetComponent<GameOptionButton>(out var btn))
{
btn.interactableColor = group.GroupColor.FindAlternateColor();
btn.interactableHoveredColor = Color.white;
}
}
renderer.material.SetInt(PlayerMaterial.MaskLayer, 20);
}
foreach (var textMeshPro in newOpt.GetComponentsInChildren<TextMeshPro>(true))
{
if (group.GroupColor != MiraApiPlugin.DefaultHeaderColor)
{
textMeshPro.color = group.GroupColor;
}
textMeshPro.fontMaterial.SetFloat(ShaderID.StencilComp, 3f);
textMeshPro.fontMaterial.SetFloat(ShaderID.Stencil, 20);
}
if (newOpt is ToggleOption toggle)
{
toggle.CheckMark.sprite = MiraAssets.Checkmark.LoadAsset();
toggle.CheckMark.color = group.GroupColor != MiraApiPlugin.DefaultHeaderColor ? group.GroupColor : MiraAssets.AcceptedTeal;
var rend = toggle.CheckMark.transform.parent.FindChild("ActiveSprite")
.GetComponent<SpriteRenderer>();
rend.sprite = MiraAssets.CheckmarkBox.LoadAsset();
rend.color = group.GroupColor != MiraApiPlugin.DefaultHeaderColor ? group.GroupColor : MiraAssets.AcceptedTeal;
}
menu.Children.Add(newOpt);
newOpt.Initialize();
newOpt.gameObject.SetActive(false);
}
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 = menu.BackButton.GetComponent<PassiveButton>().ClickSound;
headerBtn.OnMouseOver = new UnityEvent();
headerBtn.OnMouseOut = new UnityEvent();
headerBtn.OnClick.AddListener(
(UnityAction)(() =>
{
group.AllOptionsHidden = !group.AllOptionsHidden;
newText.text = group.AllOptionsHidden
? "<size=70%>(Click to open)</size>"
: "<size=70%>(Click to close)</size>";
}));
headerBtn.SetButtonEnableState(true);
}
}
+335 -84
View File
@@ -1,8 +1,10 @@
using System;
using System.Linq;
using HarmonyLib;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
@@ -12,25 +14,64 @@ using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Options;
/// <summary>
/// Patches for the <see cref="GameSettingMenu"/> to add support for custom options.
/// </summary>
[HarmonyPatch(typeof(GameSettingMenu))]
public static class GameSettingMenuPatches
internal static class GameSettingMenuPatches
{
/// <summary>
/// Gets the currently selected mod index.
/// </summary>
public static int SelectedModIdx { get; private set; }
/// <summary>
/// Gets the currently selected mod.
/// </summary>
public static MiraPluginInfo? SelectedMod { get; private set; }
private static TextMeshPro? _text;
private static Vector3 _roleBtnOgPos;
private static Vector3 _smallRoleBtnOgPos;
private static Vector3 _modifierBtnOgPos;
private static GameOptionsMenu? _modifiersTab;
private static PassiveButton? _modifiersButton;
private static PassiveButton? _smallRolesButton;
[HarmonyPostfix]
[HarmonyPatch(nameof(GameSettingMenu.ChangeTab))]
public static void ChangeTabPostfix(GameSettingMenu __instance, int tabNum, bool previewOnly)
{
if ((previewOnly && Controller.currentTouchType == Controller.TouchType.Joystick) || !previewOnly)
{
if (_modifiersTab) _modifiersTab!.gameObject.SetActive(tabNum == 3);
_modifiersButton?.SelectButton(tabNum == 3);
_smallRolesButton?.SelectButton(tabNum == 2);
if (tabNum == 3)
{
if (__instance.RoleSettingsButton.gameObject.active)
{
__instance.RoleSettingsButton.SelectButton(true);
}
else
{
_modifiersButton?.SelectButton(true);
}
}
}
if (previewOnly)
{
return;
}
_modifiersButton?.SelectButton(tabNum == 3);
_smallRolesButton?.SelectButton(tabNum == 2);
if (tabNum != 3) return;
if (__instance.RoleSettingsButton.gameObject.active)
{
__instance.RoleSettingsButton.SelectButton(true);
}
else
{
_modifiersButton?.SelectButton(true);
}
}
/// <summary>
/// Prefix for the <see cref="GameSettingMenu.Start"/> method. Sets up the custom options.
@@ -54,45 +95,157 @@ public static class GameSettingMenuPatches
_text.fontSizeMax = 3.2f;
_text.overflowMode = TextOverflowModes.Overflow;
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
_text.alignment = TextAlignmentOptions.Center;
var nextButton = Object.Instantiate(__instance.BackButton, __instance.BackButton.transform.parent).gameObject;
nextButton.transform.localPosition = new Vector3(-2.2663f, 1.5272f, -25f);
nextButton.name = "RightArrowButton";
nextButton.transform.FindChild("Inactive").gameObject.GetComponent<SpriteRenderer>().sprite = MiraAssets.NextButton.LoadAsset();
nextButton.transform.FindChild("Active").gameObject.GetComponent<SpriteRenderer>().sprite = MiraAssets.NextButtonActive.LoadAsset();
nextButton.transform.FindChild("Inactive").gameObject.GetComponent<SpriteRenderer>().sprite =
MiraAssets.NextButton.LoadAsset();
nextButton.transform.FindChild("Active").gameObject.GetComponent<SpriteRenderer>().sprite =
MiraAssets.NextButtonActive.LoadAsset();
nextButton.gameObject.GetComponent<CloseButtonConsoleBehaviour>().DestroyImmediate();
var passiveButton = nextButton.gameObject.GetComponent<PassiveButton>();
passiveButton.OnClick = new ButtonClickedEvent();
passiveButton.OnClick.AddListener((UnityAction)(() =>
{
SelectedModIdx += 1;
if (SelectedModIdx > MiraPluginManager.Instance.RegisteredPlugins().Length)
passiveButton.OnClick.AddListener(
(UnityAction)(() =>
{
SelectedModIdx = 0;
}
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}));
SelectedModIdx += 1;
if (SelectedModIdx > MiraPluginManager.Instance.RegisteredPlugins().Length)
{
SelectedModIdx = 0;
}
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}));
var backButton = Object.Instantiate(nextButton, __instance.BackButton.transform.parent).gameObject;
backButton.transform.localPosition = new Vector3(-4.4209f, 1.5272f, -25f);
backButton.name = "LeftArrowButton";
backButton.gameObject.GetComponent<CloseButtonConsoleBehaviour>().Destroy();
backButton.transform.FindChild("Active").gameObject.GetComponent<SpriteRenderer>().flipX = backButton.transform.FindChild("Inactive").gameObject.GetComponent<SpriteRenderer>().flipX = true;
backButton.gameObject.GetComponent<PassiveButton>().OnClick.AddListener((UnityAction)(() =>
{
SelectedModIdx -= 1;
if (SelectedModIdx < 0)
backButton.transform.FindChild("Active").gameObject.GetComponent<SpriteRenderer>().flipX =
backButton.transform.FindChild("Inactive").gameObject.GetComponent<SpriteRenderer>().flipX = true;
backButton.gameObject.GetComponent<PassiveButton>().OnClick.AddListener(
(UnityAction)(() =>
{
SelectedModIdx = MiraPluginManager.Instance.RegisteredPlugins().Length;
SelectedModIdx -= 1;
if (SelectedModIdx < 0)
{
SelectedModIdx = MiraPluginManager.Instance.RegisteredPlugins().Length;
}
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}));
// clone game settings tab for modifiers
_modifiersTab = Object.Instantiate(__instance.GameSettingsTab, __instance.GameSettingsTab.transform.parent);
_modifiersTab.name = "MODIFIERS TAB";
// create button for modifiers
__instance.RoleSettingsButton.buttonText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
__instance.RoleSettingsButton.gameObject.SetActive(false);
_smallRolesButton = Object.Instantiate(
__instance.RoleSettingsButton,
__instance.RoleSettingsButton.transform.parent);
var pos = new Vector3(
-3.65f,
_smallRolesButton.transform.localPosition.y,
_smallRolesButton.transform.localPosition.z);
_smallRolesButton.transform.localPosition = pos;
_smallRolesButton.OnClick.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(2, false);
}));
_smallRolesButton.OnMouseOver.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(2, true);
}));
_smallRoleBtnOgPos = _smallRolesButton.transform.localPosition;
var roleText = _smallRolesButton.buttonText;
roleText.text = "Roles";
roleText.GetComponent<TextTranslatorTMP>().Destroy();
roleText.alignment = TextAlignmentOptions.Center;
roleText.transform.parent.localPosition = new Vector3(
-.525f,
roleText.transform.parent.localPosition.y,
roleText.transform.parent.localPosition.z);
foreach (var collider in _smallRolesButton.Colliders)
{
if (collider.TryCast<BoxCollider2D>() is { } col)
{
col.size = new Vector2(col.size.x / 2, col.size.y);
}
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}));
}
foreach (var rend in _smallRolesButton.GetComponentsInChildren<SpriteRenderer>(true))
{
rend.size = new Vector2(rend.size.x / 2, rend.size.y);
}
_modifiersButton = Object.Instantiate(_smallRolesButton, _smallRolesButton.transform.parent);
_modifiersButton.OnClick = new ButtonClickedEvent();
_modifiersButton.OnClick.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(3, false);
}));
_modifiersButton.OnMouseOver = new UnityEvent();
_modifiersButton.OnMouseOver.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(3, true);
}));
_modifiersButton.buttonText.text = "Modifiers";
pos.x = -2.27f;
_modifiersButton.transform.localPosition = pos;
_modifiersButton.name = "ModifiersButton";
_modifierBtnOgPos = _modifiersButton.transform.localPosition;
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}
private static void ChangeRoleSettingButton(bool replace, GameSettingMenu __instance)
{
__instance.RoleSettingsButton.OnClick = new ButtonClickedEvent();
__instance.RoleSettingsButton.OnMouseOver = new UnityEvent();
if (replace)
{
__instance.RoleSettingsButton.buttonText.text = "Modifiers Settings";
__instance.RoleSettingsButton.OnClick.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(3, false);
}));
__instance.RoleSettingsButton.OnMouseOver.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(3, true);
}));
}
else
{
__instance.RoleSettingsButton.buttonText.text = "Roles Settings";
__instance.RoleSettingsButton.OnClick.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(2, false);
}));
__instance.RoleSettingsButton.OnMouseOver.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(2, true);
}));
}
}
private static void UpdateText(GameSettingMenu menu, GameOptionsMenu settings, RolesSettingsMenu roles)
{
if (_text is not null && SelectedModIdx == 0)
@@ -109,84 +262,182 @@ public static class GameSettingMenuPatches
_text.text = name[..Math.Min(name.Length, 25)];
}
bool replaceWithModifiers = true;
_smallRolesButton!.transform.localPosition = _smallRoleBtnOgPos;
_modifiersButton!.transform.localPosition = _modifierBtnOgPos;
menu.RoleSettingsButton.transform.localPosition = _roleBtnOgPos;
menu.GameSettingsButton.gameObject.SetActive(true);
menu.RoleSettingsButton.gameObject.SetActive(true);
if (SelectedModIdx != 0)
{
if (SelectedMod?.Options.Where(x=>x.AdvancedRole==null).ToList().Count == 0)
var modHasRoles = SelectedMod!.CustomRoles.Count != 0;
var modHasModifiers = SelectedMod.OptionGroups.Exists(x => x.ShowInModifiersMenu || x.OptionableType?.IsAssignableTo(typeof(BaseModifier)) == true);
var modHasOptions = SelectedMod.OptionGroups.Exists(x => x.OptionableType == null && !x.ShowInModifiersMenu);
_modifiersButton.gameObject.SetActive(true);
_smallRolesButton.gameObject.SetActive(true);
menu.GameSettingsButton.gameObject.SetActive(true);
menu.RoleSettingsButton.gameObject.SetActive(false);
// If there are no registered custom roles in the selected mod, hide the button.
if (!modHasRoles)
{
_smallRolesButton.gameObject.SetActive(false);
if (roles.gameObject.active)
{
menu.ChangeTab(0, false);
}
// If the mod has modifiers, we can disable the smaller modifier button and enable the bigger one.
if (modHasModifiers)
{
_modifiersButton.gameObject.SetActive(false);
menu.RoleSettingsButton.gameObject.SetActive(true);
if (_modifiersTab!.gameObject.active)
{
menu.RoleSettingsButton.SelectButton(true);
}
}
}
// If there are no modifiers in the selected mod, hide the modifiers button.
if (!modHasModifiers)
{
replaceWithModifiers = false;
_modifiersButton.gameObject.SetActive(false);
if (_modifiersTab!.gameObject.active)
{
menu.ChangeTab(0, false);
}
// If the mod has roles, we can enable the bigger role button and disable the small one.
if (modHasRoles)
{
menu.RoleSettingsButton.gameObject.SetActive(true);
_smallRolesButton.gameObject.SetActive(false);
}
}
// If there are no custom game options registered (that aren't modifier options), hide game settings button.
if (!modHasOptions)
{
menu.GameSettingsButton.gameObject.SetActive(false);
}
if (SelectedMod?.CustomRoles.Count == 0)
{
menu.RoleSettingsButton.gameObject.SetActive(false);
}
if (settings.gameObject.active)
{
menu.ChangeTab(0, false);
}
if (!menu.GameSettingsButton.gameObject.active && menu.RoleSettingsButton.gameObject.active)
// If the mod has roles and modifiers, we can move their buttons to the game settings button position, since nothing is there.
if (menu.RoleSettingsButton.gameObject.active)
{
menu.RoleSettingsButton.transform.localPosition = menu.GameSettingsButton.transform.localPosition;
}
else if (_modifiersButton.gameObject.active && _smallRolesButton.gameObject.active)
{
_modifiersButton.transform.localPosition = new Vector3(
_modifiersButton.transform.localPosition.x,
menu.GameSettingsButton.transform.localPosition.y,
_modifiersButton.transform.localPosition.z);
_smallRolesButton.transform.localPosition = new Vector3(
_smallRolesButton.transform.localPosition.x,
menu.GameSettingsButton.transform.localPosition.y,
_smallRolesButton.transform.localPosition.z);
}
}
}
else
{
_modifiersButton.gameObject.SetActive(false);
_smallRolesButton.gameObject.SetActive(false);
menu.RoleSettingsButton.gameObject.SetActive(true);
menu.GameSettingsButton.gameObject.SetActive(true);
replaceWithModifiers = false;
if (_modifiersTab!.gameObject.active)
{
menu.RoleSettingsButton.transform.localPosition = menu.GameSettingsButton.transform.localPosition;
menu.ChangeTab(0, false);
}
}
if (roles.roleChances != null && SelectedMod != null && SelectedMod.CustomRoles.Count != 0)
if (menu.RoleSettingsButton.gameObject.active)
{
if (roles.advancedSettingChildren is not null)
{
foreach (var child in roles.advancedSettingChildren)
{
child.gameObject.DestroyImmediate();
}
roles.advancedSettingChildren.Clear();
roles.advancedSettingChildren = null;
}
foreach (var header in roles.RoleChancesSettings.transform.GetComponentsInChildren<CategoryHeaderEditRole>())
{
header.gameObject.DestroyImmediate();
}
foreach (var roleChance in roles.roleChances)
{
roleChance.gameObject.DestroyImmediate();
}
roles.roleChances.Clear();
roles.AdvancedRolesSettings.gameObject.SetActive(false);
roles.RoleChancesSettings.gameObject.SetActive(true);
roles.SetQuotaTab();
roles.scrollBar.ScrollToTop();
ChangeRoleSettingButton(replaceWithModifiers, menu);
}
if (settings.Children != null && SelectedMod?.OptionGroups.Count != 0)
CleanupTab(settings, roles);
}
private static void ClearOptions(Il2CppSystem.Collections.Generic.List<OptionBehaviour> options)
{
foreach (var child in options)
{
foreach (var child in settings.Children)
if (child.TryCast<GameOptionsMapPicker>() || !child.gameObject)
{
if (child.TryCast<GameOptionsMapPicker>())
{
continue;
}
continue;
}
child.gameObject.DestroyImmediate();
}
options.Clear();
}
if (!child.gameObject)
{
continue;
}
child.gameObject.DestroyImmediate();
private static void CleanupTab(GameOptionsMenu settings, RolesSettingsMenu roles)
{
void CleanupRoleSettings(RolesSettingsMenu rolesMenu)
{
if (rolesMenu.advancedSettingChildren != null)
{
ClearOptions(rolesMenu.advancedSettingChildren);
rolesMenu.advancedSettingChildren = null;
}
foreach (var header in settings.settingsContainer.GetComponentsInChildren<CategoryHeaderMasked>())
rolesMenu.RoleChancesSettings
.transform
.GetComponentsInChildren<CategoryHeaderEditRole>()
.ToList()
.ForEach(header => header.gameObject.DestroyImmediate());
foreach (var role in rolesMenu.roleChances)
{
header.gameObject.DestroyImmediate();
role.gameObject.DestroyImmediate();
}
rolesMenu.roleChances?.Clear();
settings.Children.Clear();
settings.Children = null;
rolesMenu.AdvancedRolesSettings.gameObject.SetActive(false);
rolesMenu.RoleChancesSettings.gameObject.SetActive(true);
rolesMenu.SetQuotaTab();
rolesMenu.scrollBar.ScrollToTop();
}
settings.Initialize();
settings.scrollBar.ScrollToTop();
void CleanupSettings(GameOptionsMenu gameOptMenu)
{
ClearOptions(gameOptMenu.Children);
gameOptMenu.Children = null;
gameOptMenu.settingsContainer
.GetComponentsInChildren<CategoryHeaderMasked>()
.ToList()
.ForEach(header => header.gameObject.DestroyImmediate());
gameOptMenu.Initialize();
gameOptMenu.scrollBar.ScrollToTop();
}
if (roles.roleChances != null && SelectedMod?.CustomRoles.Count > 0)
{
CleanupRoleSettings(roles);
}
if (settings.Children != null && SelectedMod?.OptionGroups.Count > 0)
{
CleanupSettings(settings);
}
if (_modifiersTab?.Children?.Count > 0)
{
CleanupSettings(_modifiersTab);
}
}
}
+86 -51
View File
@@ -2,11 +2,14 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
using Reactor.Utilities.Extensions;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
@@ -17,17 +20,38 @@ namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(LobbyViewSettingsPane))]
public static class LobbyViewPanePatches
{
private static int CurrentSelectedMod { get; set; }
private static int SelectedModIdx { get; set; }
private static MiraPluginInfo? SelectedMod => CurrentSelectedMod == 0
private static MiraPluginInfo? SelectedMod => SelectedModIdx == 0
? null
: MiraPluginManager.Instance.RegisteredPlugins()[CurrentSelectedMod - 1];
: MiraPluginManager.Instance.RegisteredPlugins()[SelectedModIdx - 1];
private static PassiveButton? ModifiersTabButton { get; set; }
private static StringNames ModifiersTabName { get; } = CustomStringName.CreateAndRegister("ModifiersTab");
[HarmonyPostfix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.Awake))]
public static void AwakePatch(LobbyViewSettingsPane __instance)
{
__instance.gameModeText.transform.localPosition = new Vector3(-2.3f, 2.4f, -2);
__instance.gameModeText.GetComponent<TextTranslatorTMP>().Destroy();
// create modifiers button
ModifiersTabButton = Object.Instantiate(__instance.rolesTabButton, __instance.rolesTabButton.transform.parent);
ModifiersTabButton.buttonText.gameObject.GetComponent<TextTranslatorTMP>().Destroy();
ModifiersTabButton.name = "ModifiersTabButton";
var pos = ModifiersTabButton.transform.localPosition;
pos.x = 2.1f;
ModifiersTabButton.transform.localPosition = pos;
ModifiersTabButton.buttonText.text = "Modifiers";
ModifiersTabButton.OnClick = new Button.ButtonClickedEvent();
ModifiersTabButton.OnClick.AddListener(
(UnityAction)(() =>
{
__instance.ChangeTab(ModifiersTabName);
}));
ModifiersTabButton.gameObject.SetActive(SelectedModIdx!=0);
// Create the next button
var nextButton = Object.Instantiate(__instance.BackButton, __instance.BackButton.transform.parent).gameObject;
@@ -49,14 +73,13 @@ public static class LobbyViewPanePatches
passiveButton.OnClick.AddListener(
(UnityAction)(() =>
{
CurrentSelectedMod += 1;
if (CurrentSelectedMod > MiraPluginManager.Instance.RegisteredPlugins().Length)
SelectedModIdx += 1;
if (SelectedModIdx > MiraPluginManager.Instance.RegisteredPlugins().Length)
{
CurrentSelectedMod = 0;
SelectedModIdx = 0;
}
__instance.RefreshTab();
__instance.scrollBar.ScrollToTop();
Refresh(__instance);
}));
// Create the back button
@@ -72,34 +95,56 @@ public static class LobbyViewPanePatches
passiveButton2.OnClick.AddListener(
(UnityAction)(() =>
{
CurrentSelectedMod -= 1;
if (CurrentSelectedMod < 0)
SelectedModIdx -= 1;
if (SelectedModIdx < 0)
{
CurrentSelectedMod = MiraPluginManager.Instance.RegisteredPlugins().Length;
SelectedModIdx = MiraPluginManager.Instance.RegisteredPlugins().Length;
}
__instance.RefreshTab();
__instance.scrollBar.ScrollToTop();
Refresh(__instance);
}));
}
[HarmonyPostfix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.Update))]
public static void UpdatePatch(LobbyViewSettingsPane __instance)
private static void Refresh(LobbyViewSettingsPane menu)
{
__instance.gameModeText.text = SelectedMod?.PluginInfo.Metadata.Name ?? "Default";
ModifiersTabButton?.gameObject.SetActive(SelectedModIdx != 0);
menu.gameModeText.text = SelectedMod?.PluginInfo.Metadata.Name ?? "Default";
menu.RefreshTab();
menu.scrollBar.ScrollToTop();
}
[HarmonyPrefix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.SetTab))]
public static bool SetTabPatch(LobbyViewSettingsPane __instance)
{
if (__instance.currentTab != ModifiersTabName || SelectedMod == null)
{
ModifiersTabButton?.SelectButton(false);
return true;
}
__instance.taskTabButton.SelectButton(false);
__instance.rolesTabButton.SelectButton(false);
ModifiersTabButton?.SelectButton(true);
var filteredGroups = SelectedMod.OptionGroups
.Where(x => x.GroupVisible() && (x.ShowInModifiersMenu || x.OptionableType?.IsAssignableTo(typeof(BaseModifier))==true));
DrawOptions(__instance, filteredGroups);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(LobbyViewSettingsPane.DrawNormalTab))]
public static bool DrawNormalTabPatch(LobbyViewSettingsPane __instance)
{
if (CurrentSelectedMod == 0)
if (SelectedModIdx == 0 || SelectedMod == null)
{
return true;
}
DrawOptionsTab(__instance);
var filteredGroups = SelectedMod.OptionGroups
.Where(x => x.OptionableType == null && x.GroupVisible.Invoke());
DrawOptions(__instance, filteredGroups);
return false;
}
@@ -107,7 +152,7 @@ public static class LobbyViewPanePatches
[HarmonyPatch(nameof(LobbyViewSettingsPane.DrawRolesTab))]
public static bool DrawRolesTabPatch(LobbyViewSettingsPane __instance)
{
if (CurrentSelectedMod == 0)
if (SelectedModIdx == 0)
{
return true;
}
@@ -116,29 +161,22 @@ public static class LobbyViewPanePatches
return false;
}
private static void DrawOptionsTab(LobbyViewSettingsPane instance)
private static void DrawOptions(LobbyViewSettingsPane menu, IEnumerable<AbstractOptionGroup> groups)
{
if (SelectedMod == null)
{
return;
}
var num = 1.44f;
var filteredGroups = SelectedMod.OptionGroups.Where(x => x.GroupVisible.Invoke() && x.AdvancedRole is null);
foreach (var group in filteredGroups)
foreach (var group in groups)
{
var categoryHeaderMasked = Object.Instantiate(
instance.categoryHeaderOrigin,
instance.settingsContainer,
menu.categoryHeaderOrigin,
menu.settingsContainer,
true);
categoryHeaderMasked.SetHeader(StringNames.Name, 61);
categoryHeaderMasked.Title.text = group.GroupName;
categoryHeaderMasked.transform.localScale = Vector3.one;
categoryHeaderMasked.transform.localPosition = new Vector3(-9.77f, num, -2f);
instance.settingsInfo.Add(categoryHeaderMasked.gameObject);
num -= 0.85f;
menu.settingsInfo.Add(categoryHeaderMasked.gameObject);
num -= 1.05f;
var i = 0;
@@ -150,8 +188,8 @@ public static class LobbyViewPanePatches
}
var viewSettingsInfoPanel = Object.Instantiate(
instance.infoPanelOrigin,
instance.settingsContainer,
menu.infoPanelOrigin,
menu.settingsContainer,
true);
viewSettingsInfoPanel.transform.localScale = Vector3.one;
float num2;
@@ -160,7 +198,7 @@ public static class LobbyViewPanePatches
num2 = -8.95f;
if (i > 0)
{
num -= 0.59f;
num -= 0.85f;
}
}
else
@@ -184,14 +222,14 @@ public static class LobbyViewPanePatches
viewSettingsInfoPanel.SetInfo(data.Title, data.GetValueString(option.GetFloatData()), 61);
}
instance.settingsInfo.Add(viewSettingsInfoPanel.gameObject);
menu.settingsInfo.Add(viewSettingsInfoPanel.gameObject);
i++;
}
num -= 0.59f;
num -= 0.85f;
}
instance.scrollBar.CalculateAndSetYBounds(instance.settingsInfo.Count + 10, 2f, 6f, 0.59f);
menu.scrollBar.CalculateAndSetYBounds(menu.settingsInfo.Count + 10, 2f, 6f, 0.85f);
}
private static void DrawRolesTab(LobbyViewSettingsPane instance)
@@ -212,14 +250,9 @@ public static class LobbyViewPanePatches
var list = new List<Type>();
var roleGroups = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values.OfType<ICustomRole>()
var roleGroups = SelectedMod.CustomRoles.Values.OfType<ICustomRole>()
.ToLookup(x => x.RoleOptionsGroup);
if (roleGroups is null)
{
return;
}
// sort the groups by priority
var sortedRoleGroups = roleGroups
.OrderBy(x => x.Key.Priority)
@@ -277,8 +310,9 @@ public static class LobbyViewPanePatches
viewSettingsInfoPanelRoleVariant.transform.localScale = Vector3.one;
viewSettingsInfoPanelRoleVariant.transform.localPosition = new Vector3(num2, num, -2f);
var advancedRoleOptions = SelectedMod.Options
.Where(x => x.AdvancedRole == customRole.GetType())
var advancedRoleOptions = SelectedMod.OptionGroups
.Where(x => x.OptionableType == customRole.GetType())
.SelectMany(x => x.Options)
.ToList();
if (numPerGame > 0 && advancedRoleOptions.Count > 0)
@@ -292,7 +326,7 @@ public static class LobbyViewPanePatches
chancePerGame,
61,
customRole.RoleColor,
customRole.Configuration.Icon.LoadAsset(),
customRole.Configuration.Icon?.LoadAsset() ?? MiraAssets.Empty.LoadAsset(),
true);
viewSettingsInfoPanelRoleVariant.iconSprite.transform.localScale = new Vector3(0.365f, 0.365f, 1f);
viewSettingsInfoPanelRoleVariant.iconSprite.transform.localPosition = new Vector3(0.7144f, -0.028f, -2);
@@ -379,15 +413,16 @@ public static class LobbyViewPanePatches
role.StringName,
maskLayer,
role.TeamType == RoleTeamTypes.Crewmate,
customRole.Configuration.Icon.LoadAsset());
customRole.Configuration.Icon != null ? customRole.Configuration.Icon.LoadAsset() : MiraAssets.Empty.LoadAsset());
viewPanel.header.icon.transform.localScale = new Vector3(0.465f, 0.465f, 1f);
viewPanel.divider.material.SetInt(PlayerMaterial.MaskLayer, maskLayer);
var num = viewPanel.yPosStart;
var num2 = 1.08f;
var filteredOptions = SelectedMod.Options
.Where(x => x.AdvancedRole == roleType)
var filteredOptions = SelectedMod.OptionGroups
.Where(x => x.OptionableType == roleType)
.SelectMany(x=>x.Options)
.ToList();
for (var i = 0; i < filteredOptions.Count; i++)
@@ -127,32 +127,37 @@ public static class RoleSettingMenuPatches
chanceLabel.Destroy();
countLabel.Destroy();
if (name is StringNames.CrewmateRolesHeader)
{
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.Background.sprite = MiraAssets.CategoryHeader.LoadAsset();
categoryHeaderMasked.Background.sprite.texture.filterMode = FilterMode.Bilinear;
categoryHeaderMasked.Background.sprite.texture.wrapMode = TextureWrapMode.Clamp;
categoryHeaderMasked.Title.color = categoryHeaderMasked.Title.color.IsColorDark() ?
categoryHeaderMasked.Title.color.LightenColor(0.3f) : categoryHeaderMasked.Title.color.LightenColor(0.1f);
categoryHeaderMasked.Background.transform.localPosition = new Vector3(0.5f, -0.1833f, 0);
switch (name)
{
case StringNames.CrewmateRolesHeader:
categoryHeaderMasked.Title.color = Palette.CrewmateRoleHeaderTextBlue;
categoryHeaderMasked.Background.color = Palette.CrewmateRoleHeaderBlue;
break;
case StringNames.ImpostorRolesHeader:
categoryHeaderMasked.Title.color = Palette.ImpostorRoleHeaderTextRed;
categoryHeaderMasked.Background.color = Palette.ImpostorRoleHeaderRed;
break;
default:
categoryHeaderMasked.Title.color = group.Color.Equals(MiraApiPlugin.DefaultHeaderColor) ? Color.white : group.Color.FindAlternateColor();
categoryHeaderMasked.Divider.color = group.Color;
categoryHeaderMasked.Background.color = group.Color;
break;
}
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.transform.localPosition = new Vector3(0.55f, -0.1833f, 0);
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);
@@ -241,7 +246,7 @@ public static class RoleSettingMenuPatches
[HarmonyPatch(nameof(RolesSettingsMenu.OpenChancesTab))]
public static void OpenChancesTabPostfix(RolesSettingsMenu __instance)
{
if (GameSettingMenuPatches.SelectedModIdx == 0)
if (GameSettingMenuPatches.SelectedModIdx == 0 || !__instance.scrollBar)
{
return;
}
@@ -304,15 +309,14 @@ public static class RoleSettingMenuPatches
var hasImage = role.RoleScreenshot != null;
var num = hasImage ? -0.872f : -1;
var filteredOptions = GameSettingMenuPatches.SelectedMod?.Options.Where(x => x.AdvancedRole == role.GetType()) ?? [];
// TODO: create sub groups under the role settings.
var filteredOptions = GameSettingMenuPatches.SelectedMod?.OptionGroups
.Where(x=> x.OptionableType == role.GetType())
.SelectMany(x=>x.Options)
.ToList() ?? [];
foreach (var option in filteredOptions)
{
if (option.AdvancedRole is not null && option.AdvancedRole != role.GetType())
{
continue;
}
var newOpt = option.CreateOption(
__instance.checkboxOrigin,
__instance.numberOptionOrigin,
@@ -384,8 +388,8 @@ public static class RoleSettingMenuPatches
__instance.roleScreenshot.drawMode = SpriteDrawMode.Sliced;
}
__instance.roleHeaderSprite.color = customRole.RoleColor;
__instance.roleHeaderText.color = customRole.RoleColor.GetAlternateColor();
__instance.roleHeaderSprite.color = customRole.OptionsMenuColor;
__instance.roleHeaderText.color = customRole.OptionsMenuColor.FindAlternateColor();
var categoryHeaderMasked = __instance.AdvancedRolesSettings.transform.Find("CategoryHeaderMasked").GetComponent<CategoryHeaderMasked>();
@@ -460,18 +464,18 @@ public static class RoleSettingMenuPatches
roleOptionSetting.transform.localPosition = new Vector3(-0.1f, ScrollerNum, -2f);
roleOptionSetting.SetRole(GameOptionsManager.Instance.CurrentGameOptions.RoleOptions, role, 20);
roleOptionSetting.labelSprite.color = customRole.RoleColor;
roleOptionSetting.labelSprite.color = customRole.OptionsMenuColor;
roleOptionSetting.OnValueChanged = new Action<OptionBehaviour>(ValueChanged);
roleOptionSetting.SetClickMask(__instance.ButtonClickMask);
__instance.roleChances.Add(roleOptionSetting);
roleOptionSetting.titleText.transform.localPosition = new Vector3(-0.5376f, -0.2923f, 0f);
roleOptionSetting.titleText.color = customRole.RoleColor.GetAlternateColor();
roleOptionSetting.titleText.color = customRole.OptionsMenuColor.FindAlternateColor();
roleOptionSetting.titleText.horizontalAlignment = HorizontalAlignmentOptions.Left;
if (GameSettingMenuPatches.SelectedMod is null ||
GameSettingMenuPatches.SelectedMod.Options.Exists(
x => x.AdvancedRole != null && x.AdvancedRole.IsInstanceOfType(role)))
GameSettingMenuPatches.SelectedMod.OptionGroups
.Exists(x => x.OptionableType == role.GetType()))
{
var newButton = Object.Instantiate(roleOptionSetting.buttons[0], roleOptionSetting.transform);
newButton.name = "ConfigButton";
@@ -484,7 +488,7 @@ public static class RoleSettingMenuPatches
var passiveButton = newButton.GetComponent<GameOptionButton>();
passiveButton.OnClick = new ButtonClickedEvent();
passiveButton.interactableColor = btnRend.color = customRole.RoleColor.GetAlternateColor();
passiveButton.interactableColor = btnRend.color = customRole.OptionsMenuColor.FindAlternateColor();
passiveButton.interactableHoveredColor = Color.white;
passiveButton.OnClick.AddListener((UnityAction)(() => { ChangeTab(role, __instance); }));
@@ -504,7 +508,7 @@ public static class RoleSettingMenuPatches
if (index < GameSettingMenuPatches.SelectedMod?.CustomRoles.Count - 1)
{
ScrollerNum += -0.43f;
ScrollerNum -= 0.43f;
}
return roleOptionSetting;
+9 -2
View File
@@ -6,6 +6,7 @@ using MiraAPI.Events.Vanilla.Player;
using MiraAPI.Hud;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using MiraAPI.Voting;
using Reactor.Utilities.Extensions;
namespace MiraAPI.Patches;
@@ -24,12 +25,18 @@ public static class PlayerControlPatches
[HarmonyPatch(nameof(PlayerControl.Start))]
public static void PlayerControlStartPostfix(PlayerControl __instance)
{
if (__instance.gameObject.TryGetComponent<ModifierComponent>(out var comp))
if (__instance.gameObject.TryGetComponent<ModifierComponent>(out var modifierComp))
{
comp.DestroyImmediate();
modifierComp.DestroyImmediate();
}
if (__instance.gameObject.TryGetComponent<PlayerVoteData>(out var voteComp))
{
voteComp.DestroyImmediate();
}
__instance.gameObject.AddComponent<ModifierComponent>();
__instance.gameObject.AddComponent<PlayerVoteData>();
}
/// <summary>
@@ -1,4 +1,5 @@
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
namespace MiraAPI.Patches.Roles;
@@ -21,6 +22,14 @@ public static class GameStartupPatch
}
_runOnce = true;
if (MiraPluginManager.Instance.QueuedRoleRegistrations.Count <= 0) return;
foreach (var queue in MiraPluginManager.Instance.QueuedRoleRegistrations)
{
CustomRoleManager.RegisterRoleTypes(queue.Value, queue.Key);
}
MiraPluginManager.Instance.QueuedRoleRegistrations.Clear();
CustomRoleManager.RegisterInRoleManager();
}
}
+1 -1
View File
@@ -22,4 +22,4 @@ public static class RoleBehaviourPatch
__result = behaviour.RoleColor;
return false;
}
}
}
+11
View File
@@ -33,4 +33,15 @@ public static class MinigameStubs
{
// nothing needed
}
/// <summary>
/// Fixes the error when creating custom minigames. Credit to Submerged for discovering this fix.
/// </summary>
/// <param name="__instance">The Minigame instance.</param>
[HarmonyPrefix]
[HarmonyPatch(typeof(Minigame), nameof(Minigame.Begin))]
public static void MinigameErrorFixPatch(Minigame __instance)
{
__instance.logger ??= new Logger("Minigame", Logger.Level.Info, Logger.Category.Gameplay);
}
}
@@ -0,0 +1,16 @@
using HarmonyLib;
using MiraAPI.Utilities;
namespace MiraAPI.Patches.Voting;
[HarmonyPatch(typeof(DummyBehaviour), nameof(DummyBehaviour.Update))]
internal static class DummyBehaviourPatch
{
public static void Postfix(DummyBehaviour __instance)
{
if (MeetingHud.Instance && __instance.myPlayer.GetVoteData())
{
__instance.voted = __instance.myPlayer.GetVoteData().VotesRemaining == 0;
}
}
}
+237
View File
@@ -0,0 +1,237 @@
using System.Linq;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Meeting;
using MiraAPI.Events.Vanilla.Meeting.Voting;
using MiraAPI.Utilities;
using MiraAPI.Voting;
namespace MiraAPI.Patches.Voting;
[HarmonyPatch(typeof(MeetingHud))]
internal static class MeetingHudPatches
{
[HarmonyPostfix]
[HarmonyPatch(nameof(MeetingHud.Start))]
public static void MeetingHudStartPatch(MeetingHud __instance)
{
foreach (var plr in PlayerControl.AllPlayerControls)
{
var voteData = plr.GetVoteData();
voteData.Votes.Clear();
voteData.SetRemainingVotes(1);
if (plr.Data.IsDead || plr.Data.Disconnected)
{
voteData.SetRemainingVotes(0);
}
}
var @event = new StartMeetingEvent(__instance);
MiraEventManager.InvokeEvent(@event);
}
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.Select))]
public static bool SelectPatch(MeetingHud __instance, int suspectStateIdx)
{
var voteData = PlayerControl.LocalPlayer.GetVoteData();
var hasVotes = voteData.VotesRemaining > 0;
var hasVotedFor = voteData.VotedFor((byte)suspectStateIdx);
var @event = new MeetingSelectEvent(voteData, suspectStateIdx, hasVotes && !hasVotedFor);
MiraEventManager.InvokeEvent(@event);
return @event.AllowSelect;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.HandleDisconnect), typeof(PlayerControl), typeof(DisconnectReasons))]
public static bool HandleDisconnect(MeetingHud __instance, PlayerControl pc)
{
if (!AmongUsClient.Instance.AmHost || __instance.playerStates is null || !pc || !GameData.Instance)
{
return false;
}
var playerVoteArea = __instance.playerStates.First(pv => pv.TargetPlayerId == pc.PlayerId);
playerVoteArea.AmDead = true;
playerVoteArea.Overlay.gameObject.SetActive(true);
foreach (var player in Helpers.GetAlivePlayers())
{
var pva = __instance.playerStates.First(pv => pv.TargetPlayerId == player.PlayerId);
var voteData = player.GetVoteData();
if (pva.AmDead || !voteData.VotedFor(pc.PlayerId))
{
continue;
}
voteData.Votes.RemoveAll(x=>x.Suspect==pc.PlayerId);
voteData.VotesRemaining += 1;
VotingUtils.RpcRemoveVote(PlayerControl.LocalPlayer, player.PlayerId, pc.PlayerId);
}
__instance.SetDirtyBit(1U);
__instance.CheckForEndVoting();
if (__instance.state == MeetingHud.VoteStates.Results)
{
__instance.SetupProceedButton();
}
return false;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.CastVote))]
public static bool CastVotePatch(MeetingHud __instance, byte srcPlayerId, byte suspectPlayerId)
{
var plr = GameData.Instance.GetPlayerById(srcPlayerId);
if (plr == null)
{
return false;
}
var voteData = plr.Object.GetVoteData();
if (voteData == null || voteData.VotesRemaining == 0 ||
voteData.VotedFor(suspectPlayerId))
{
return false;
}
VotingUtils.HandleVote(voteData, suspectPlayerId);
__instance.SetDirtyBit(1U);
__instance.CheckForEndVoting();
if (voteData.VotesRemaining != 0)
{
return false;
}
__instance.playerStates.First(x => x.TargetPlayerId == srcPlayerId).SetVote(suspectPlayerId);
PlayerControl.LocalPlayer.RpcSendChatNote(srcPlayerId, ChatNoteTypes.DidVote);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(nameof(MeetingHud.CmdCastVote))]
public static void CmdCastVotePatch(MeetingHud __instance, byte playerId, byte suspectIdx)
{
var plr = GameData.Instance.GetPlayerById(playerId);
var voteData = plr.Object.GetVoteData();
if (!AmongUsClient.Instance.AmHost)
{
if (voteData == null || voteData.VotesRemaining == 0 ||
voteData.VotedFor(suspectIdx))
{
return;
}
VotingUtils.HandleVote(voteData, suspectIdx);
if (voteData.VotesRemaining == 0)
{
__instance.playerStates.First(x => x.TargetPlayerId == playerId).SetVote(suspectIdx);
}
}
if (PlayerControl.LocalPlayer.PlayerId != playerId)
{
return;
}
SoundManager.Instance.PlaySound(__instance.VoteLockinSound, false);
foreach (var playerVoteArea in __instance.playerStates)
{
playerVoteArea.ClearButtons();
}
__instance.SkipVoteButton.ClearButtons();
var localVoteData = PlayerControl.LocalPlayer.GetVoteData();
if (localVoteData == null || localVoteData.VotesRemaining != 0) return;
__instance.SkipVoteButton.voteComplete = true;
__instance.SkipVoteButton.gameObject.SetActive(false);
}
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.CheckForEndVoting))]
public static bool EndCheck(MeetingHud __instance)
{
var shouldEnd = !Helpers.GetAlivePlayers().Exists(plr => plr.GetVoteData().VotesRemaining > 0);
var checkEndEvent = new CheckForEndVotingEvent(shouldEnd);
MiraEventManager.InvokeEvent(checkEndEvent);
shouldEnd = checkEndEvent.ForceEndVoting || checkEndEvent is { IsCancelled: false, IsVotingComplete: true };
if (!shouldEnd)
{
return false;
}
var votes = VotingUtils.CalculateVotes();
var exiled = VotingUtils.GetExiled(votes, out var isTie);
var @event = new ProcessVotesEvent(votes, exiled);
MiraEventManager.InvokeEvent(@event);
if (@event.VotesModified)
{
votes = @event.Votes;
exiled = VotingUtils.GetExiled(votes, out isTie);
}
if (@event.ExiledPlayerModified)
{
exiled = @event.ExiledPlayer;
}
var voterStates = new Il2CppStructArray<MeetingHud.VoterState>([
.. votes.Select(
v=> new MeetingHud.VoterState
{
VoterId = v.Voter,
VotedForId = v.Suspect,
})
]);
__instance.RpcVotingComplete(voterStates, exiled, isTie);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.PopulateResults))]
public static bool PopulateResultsPatch(MeetingHud __instance, ref Il2CppStructArray<MeetingHud.VoterState> states)
{
var votes = states.Select(x=> new CustomVote(x.VoterId, x.VotedForId)).ToList();
var @event = new PopulateResultsEvent(votes);
MiraEventManager.InvokeEvent(@event);
if (@event.IsCancelled)
{
return false;
}
VotingUtils.HandlePopulateResults(votes);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(nameof(MeetingHud.Confirm))]
public static bool ConfirmPatch(MeetingHud __instance, [HarmonyArgument(0)] byte suspect)
{
__instance.CmdCastVote(PlayerControl.LocalPlayer.PlayerId, suspect);
return false;
}
}
+22 -4
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using BepInEx.Unity.IL2CPP;
@@ -26,7 +27,7 @@ public sealed class MiraPluginManager
private readonly Dictionary<Assembly, MiraPluginInfo> _registeredPlugins = [];
internal MiraPluginInfo[] RegisteredPlugins() => [.. _registeredPlugins.Values];
internal Dictionary<MiraPluginInfo, List<Type>> QueuedRoleRegistrations { get; } = new();
internal static MiraPluginManager Instance { get; private set; } = new();
internal void Initialize()
@@ -49,6 +50,23 @@ public sealed class MiraPluginManager
continue;
}
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
{
var eventAttribute = method.GetCustomAttribute<RegisterEventAttribute>();
if (eventAttribute != null)
{
var parameters = method.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent)))
{
Logger<MiraApiPlugin>.Error($"Invalid event registration method {method.Name} in {type.Name}");
continue;
}
var paramType = parameters[0].ParameterType;
MiraEventManager.RegisterEventHandler(paramType, method, eventAttribute.Priority);
}
}
if (RegisterModifier(type, info))
{
continue;
@@ -61,7 +79,7 @@ public sealed class MiraPluginManager
if (RegisterRoleAttribute(type, info, out var role))
{
roles.Add(role!);
roles.Add(role);
continue;
}
@@ -79,7 +97,7 @@ public sealed class MiraPluginManager
}
info.OptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
CustomRoleManager.RegisterRoleTypes(roles, info);
QueuedRoleRegistrations.Add(info, roles);
_registeredPlugins.Add(assembly, info);
Logger<MiraApiPlugin>.Info($"Registering mod {pluginInfo.Metadata.GUID} with Mira API.");
@@ -155,7 +173,7 @@ public sealed class MiraPluginManager
return false;
}
private static bool RegisterRoleAttribute(Type type, MiraPluginInfo pluginInfo, out Type? role)
private static bool RegisterRoleAttribute(Type type, MiraPluginInfo pluginInfo, [NotNullWhen(true)] out Type? role)
{
role = null;
try
Binary file not shown.

After

Width:  |  Height:  |  Size: 872 B

+12 -3
View File
@@ -1,6 +1,8 @@
using AmongUs.GameOptions;
using Il2CppSystem.Web.Util;
using MiraAPI.Utilities.Assets;
using UnityEngine;
using Helpers = MiraAPI.Utilities.Helpers;
namespace MiraAPI.Roles;
@@ -32,7 +34,9 @@ public record struct CustomRoleConfiguration
TasksCountForProgress = role.Team is ModdedRoleTeams.Crewmate;
HideSettings = roleBehaviour?.IsDead == true;
ShowInFreeplay = roleBehaviour?.IsDead == false;
OptionsScreenshot = null;
IntroSound = role.Team is ModdedRoleTeams.Crewmate
? CustomRoleManager.CrewmateIntroSound
: CustomRoleManager.ImpostorIntroSound;
}
/// <summary>
@@ -58,12 +62,17 @@ public record struct CustomRoleConfiguration
/// <summary>
/// Gets or sets the Sprite used for the Role Options menu screenshot.
/// </summary>
public LoadableAsset<Sprite>? OptionsScreenshot { get; set; }
public LoadableAsset<Sprite>? OptionsScreenshot { get; set; } = null;
/// <summary>
/// Gets or sets the Sprite used for the Role Icon.
/// </summary>
public LoadableAsset<Sprite> Icon { get; set; } = MiraAssets.Empty;
public LoadableAsset<Sprite>? Icon { get; set; } = null;
/// <summary>
/// Gets or sets the Intro sound for the Role.
/// </summary>
public LoadableAsset<AudioClip>? IntroSound { get; set; } = null;
/// <summary>
/// Gets or sets a value indicating whether the role is affected by light affectors on Airship.
+29
View File
@@ -7,12 +7,14 @@ using Il2CppInterop.Runtime.Injection;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.TextCore;
using Object = UnityEngine.Object;
namespace MiraAPI.Roles;
@@ -22,6 +24,18 @@ namespace MiraAPI.Roles;
/// </summary>
public static class CustomRoleManager
{
/// <summary>
/// The default Among Us Crewmate Intro Sound.
/// </summary>
public static readonly LoadableAsset<AudioClip> CrewmateIntroSound =
CustomRoleUtils.GetIntroSound(RoleTypes.Crewmate)!;
/// <summary>
/// The default Among Us Impostor Intro Sound.
/// </summary>
public static readonly LoadableAsset<AudioClip> ImpostorIntroSound =
CustomRoleUtils.GetIntroSound(RoleTypes.Impostor)!;
internal static readonly Dictionary<ushort, RoleBehaviour> CustomRoles = [];
internal static readonly Dictionary<Type, ushort> RoleIds = [];
@@ -93,6 +107,21 @@ public static class CustomRoleManager
roleBehaviour.MaxCount = customRole.Configuration.MaxRoleCount;
roleBehaviour.RoleScreenshot = customRole.Configuration.OptionsScreenshot?.LoadAsset();
if (customRole.Configuration.Icon != null)
{
var asset = customRole.Configuration.Icon.LoadAsset();
if (asset != null)
{
roleBehaviour.RoleIconSolid = asset;
roleBehaviour.RoleIconWhite = asset;
}
}
if (customRole.Configuration.IntroSound != null)
{
roleBehaviour.IntroSound = customRole.Configuration.IntroSound.LoadAsset();
}
if (roleBehaviour.IsDead)
{
RoleManager.GhostRoles.Add(roleBehaviour.Role);
+62
View File
@@ -0,0 +1,62 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using AmongUs.GameOptions;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Roles;
/// <summary>
/// Utilities to make handling roles in-game easier.
/// </summary>
public static class CustomRoleUtils
{
/// <summary>
/// Gets all active in-game roles.
/// </summary>
/// <returns>A list of roles.</returns>
// ReSharper disable once MemberCanBePrivate.Global
public static IEnumerable<RoleBehaviour> GetActiveRoles() => PlayerControl.AllPlayerControls.ToArray().Select(x => x.Data.Role);
/// <summary>
/// Gets all active in-game roles in a certain team.
/// </summary>
/// <param name="team">The team you would like to check for.</param>
/// <returns>A list of roles with the team.</returns>
public static IEnumerable<RoleBehaviour> GetActiveRolesOfTeam(ModdedRoleTeams team) => GetActiveRoles().Where(x => x is ICustomRole customRole && customRole.Team == team);
/// <summary>
/// Gets all active in-game roles of a certain type.
/// </summary>
/// <typeparam name="T">The role Type you would like to check for. Must be a RoleBehaviour.</typeparam>
/// <returns>A list of roles with that specific type.</returns>
public static IEnumerable<T> GetActiveRolesOfType<T>() where T : RoleBehaviour => GetActiveRoles().OfType<T>();
/// <summary>
/// Creates a string builder for the Role Tab.
/// </summary>
/// <param name="role">The ICustomRole object.</param>
/// <returns>A StringBuilder.</returns>
public static StringBuilder CreateForRole(ICustomRole role)
{
var taskStringBuilder = new StringBuilder();
taskStringBuilder.AppendLine(CultureInfo.InvariantCulture, $"{role.RoleColor.ToTextColor()}You are a <b>{role.RoleName}.</b></color>");
taskStringBuilder.Append("<size=70%>");
taskStringBuilder.AppendLine(CultureInfo.InvariantCulture, $"{role.RoleLongDescription}");
return taskStringBuilder;
}
/// <summary>
/// Returns an intro sound from a role.
/// </summary>
/// <param name="roleType">The role type.</param>
/// <returns>The intro sound.</returns>
public static LoadableAsset<AudioClip>? GetIntroSound(RoleTypes roleType)
{
var role = RoleManager.Instance.AllRoles.FirstOrDefault(role => role.Role == roleType);
if (role is ICustomRole customRole) return customRole.Configuration.IntroSound;
return new PreloadedAsset<AudioClip>(role!.IntroSound);
}
}
+10 -4
View File
@@ -1,5 +1,6 @@
using System.Text;
using BepInEx.Configuration;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
@@ -11,7 +12,7 @@ namespace MiraAPI.Roles;
/// <summary>
/// Interface for custom roles.
/// </summary>
public interface ICustomRole
public interface ICustomRole : IOptionable
{
/// <summary>
/// Gets the name of the role.
@@ -33,6 +34,11 @@ public interface ICustomRole
/// </summary>
Color RoleColor { get; }
/// <summary>
/// Gets the color that should be used in the options menu.
/// </summary>
Color OptionsMenuColor => RoleColor;
/// <summary>
/// Gets the team of the role.
/// </summary>
@@ -46,7 +52,7 @@ public interface ICustomRole
/// <summary>
/// Gets the role options group.
/// </summary>
public RoleOptionsGroup RoleOptionsGroup => Team switch
RoleOptionsGroup RoleOptionsGroup => Team switch
{
ModdedRoleTeams.Crewmate => RoleOptionsGroup.Crewmate,
ModdedRoleTeams.Impostor => RoleOptionsGroup.Impostor,
@@ -57,7 +63,7 @@ public interface ICustomRole
/// <summary>
/// Gets the role's TeamIntroCutscene configuration.
/// </summary>
public TeamIntroConfiguration? IntroConfiguration => Team switch
TeamIntroConfiguration? IntroConfiguration => Team switch
{
ModdedRoleTeams.Custom => TeamIntroConfiguration.Neutral,
_ => null,
@@ -200,7 +206,7 @@ public interface ICustomRole
/// Get the custom Role Tab text for this role.
/// </summary>
/// <returns>A StringBuilder with the role tab text.</returns>
StringBuilder SetTabText() => Helpers.CreateForRole(this);
StringBuilder SetTabText() => CustomRoleUtils.CreateForRole(this);
/// <summary>
/// Determine whether a given modifier can be applied to this role.
+1
View File
@@ -10,6 +10,7 @@ public static class MiraAssets
public static readonly LoadableResourceAsset NextButtonActive = new("MiraAPI.Resources.NextButtonActive.png");
public static readonly LoadableResourceAsset Cog = new("MiraAPI.Resources.Cog.png");
public static readonly LoadableResourceAsset Checkmark = new("MiraAPI.Resources.Checkmark.png");
public static readonly LoadableResourceAsset CategoryHeader = new("MiraAPI.Resources.CategoryHeader.png");
public static readonly LoadableResourceAsset CheckmarkBox = new("MiraAPI.Resources.CheckMarkBox.png");
public static readonly Color32 AcceptedTeal = new(43, 233, 198, 255);
}
@@ -0,0 +1,19 @@
using System;
namespace MiraAPI.Utilities.Assets;
/// <summary>
/// An implementation for creating loadable assets from preloaded assets.
/// </summary>
/// <inheritdoc cref="LoadableAsset{T}"/>
/// <inheritdoc />
public class PreloadedAsset<T>(T asset) : LoadableAsset<T> where T : UnityEngine.Object
{
private readonly T loadedAsset = asset ?? throw new ArgumentNullException(nameof(asset));
/// <inheritdoc />
public override T LoadAsset()
{
return loadedAsset;
}
}
+5 -1
View File
@@ -1,4 +1,5 @@
using System;
using System.IO;
using System.Reflection;
using Reactor.Utilities.Extensions;
using UnityEngine;
@@ -30,6 +31,9 @@ public static class SpriteTools
throw new ArgumentException($"Resource not found: {resourcePath}");
}
return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), pixelsPerUnit);
tex.name = resourcePath;
var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), pixelsPerUnit);
sprite.name = resourcePath;
return sprite;
}
}
+89
View File
@@ -0,0 +1,89 @@
using UnityEngine;
namespace MiraAPI.Utilities;
/// <summary>
/// Extension methods for the Color struct.
/// </summary>
public static class ColorExtensions
{
/// <summary>
/// Gets the relative luminance of a color (WCAG 2.1 specification).
/// </summary>
/// <param name="color">Color to calculate luminance for.</param>
/// <returns>Relative luminance value.</returns>
public static float GetRelativeLuminance(this Color color)
{
var r = color.r <= 0.03928f ? color.r / 12.92f : Mathf.Pow((color.r + 0.055f) / 1.055f, 2.4f);
var g = color.g <= 0.03928f ? color.g / 12.92f : Mathf.Pow((color.g + 0.055f) / 1.055f, 2.4f);
var b = color.b <= 0.03928f ? color.b / 12.92f : Mathf.Pow((color.b + 0.055f) / 1.055f, 2.4f);
return 0.2126f * r + 0.7152f * g + 0.0722f * b;
}
/// <summary>
/// Calculates the contrast ratio between two colors (WCAG 2.1 specification).
/// </summary>
/// <param name="colorA">First color.</param>
/// <param name="colorB">Second color.</param>
/// <returns>Contrast ratio between the two colors.</returns>
public static float GetContrastRatio(this Color colorA, Color colorB)
{
var luminanceA = colorA.GetRelativeLuminance();
var luminanceB = colorB.GetRelativeLuminance();
return (Mathf.Max(luminanceA, luminanceB) + 0.05f) / (Mathf.Min(luminanceA, luminanceB) + 0.05f);
}
/// <summary>
/// Generates an accessible alternate color with sufficient contrast.
/// </summary>
/// <param name="color">Base color.</param>
/// <param name="desiredRatio">Target contrast ratio (default 4.5f for AA).</param>
/// <returns>Alternate color with sufficient contrast.</returns>
public static Color FindAlternateColor(this Color color, float desiredRatio = 4.5f)
{
var lightColor = FindMinimumContrastColor(color, Color.white, desiredRatio);
var darkColor = FindMinimumContrastColor(color, Color.black, desiredRatio);
return lightColor.GetContrastRatio(color) >= darkColor.GetContrastRatio(color) ? lightColor : darkColor;
}
/// <summary>
/// Finds the color with the minimum contrast ratio to the target color.
/// </summary>
/// <param name="baseColor">The base color to start from.</param>
/// <param name="targetColor">The target color to compare against.</param>
/// <param name="desiredRatio">The desired contrast ratio.</param>
/// <returns>The color with the minimum contrast ratio to the target color.</returns>
public static Color FindMinimumContrastColor(Color baseColor, Color targetColor, float desiredRatio)
{
var baseLuminance = baseColor.GetRelativeLuminance();
var isLightening = targetColor == Color.white;
var targetLuminance = isLightening
? desiredRatio * (baseLuminance + 0.05f) - 0.05f
: (baseLuminance + 0.05f) / desiredRatio - 0.05f;
if (isLightening && targetLuminance > 1f) return Color.white;
if (!isLightening && targetLuminance < 0f) return Color.black;
float low = 0f, high = 1f;
var bestColor = targetColor;
for (var i = 0; i < 10; i++)
{
var t = (low + high) / 2f;
var testColor = Color.Lerp(baseColor, targetColor, t);
var testLuminance = testColor.GetRelativeLuminance();
if ((isLightening && testLuminance >= targetLuminance) || (!isLightening && testLuminance <= targetLuminance))
{
high = t;
bestColor = testColor;
}
else
{
low = t;
}
}
return bestColor;
}
}
+115 -1
View File
@@ -2,10 +2,12 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
using MiraAPI.Roles;
using MiraAPI.Voting;
using Reactor.Utilities;
using TMPro;
using UnityEngine;
@@ -39,6 +41,105 @@ public static class Extensions
BitConverter.GetBytes(count.Value).AddRangeToArray(BitConverter.GetBytes(chance.Value)));
}
/// <summary>
/// Gets a PlayerControl from their PlayerVoteArea in a meeting.
/// </summary>
/// <param name="state">The vote area.</param>
/// <returns>The player's PlayerControl.</returns>
public static PlayerControl? GetPlayer(this PlayerVoteArea state) => GameData.Instance.GetPlayerById(state.TargetPlayerId)?.Object;
/// <summary>
/// Gets an int representing the amount of tasks a player has left.
/// </summary>
/// <param name="player">The player.</param>
/// <returns>A count of how many tasks the player has left.</returns>
public static int GetTasksLeft(this PlayerControl player) => player.Data.Tasks.ToArray().Count(x => !x.Complete);
/// <summary>
/// Checks if a PlayerControl is the game's host.
/// </summary>
/// <param name="playerControl">The player you're checking for.</param>
/// <returns>If the player is the host, true, else false.</returns>
public static bool IsHost(this PlayerControl playerControl)
{
return TutorialManager.InstanceExists || AmongUsClient.Instance.HostId == playerControl.OwnerId;
}
/// <summary>
/// Determines if a float is an integer.
/// </summary>
/// <param name="number">The float number.</param>
/// <returns>True if the float is an integer, false otherwise.</returns>
public static bool IsInteger(this float number)
{
return Mathf.Approximately(number, Mathf.Round(number));
}
/// <summary>
/// Gets a cache of player's vote data components to improve performance.
/// </summary>
public static Dictionary<PlayerControl, PlayerVoteData> VoteDataComponents { get; } = [];
/// <summary>
/// Gets the PlayerVoteData of a player.
/// </summary>
/// <param name="player">The PlayerControl object.</param>
/// <returns>A PlayerVoteData if there is one, null otherwise.</returns>
public static PlayerVoteData GetVoteData(this PlayerControl player)
{
if (VoteDataComponents.TryGetValue(player, out var component))
{
return component;
}
component = player.GetComponent<PlayerVoteData>();
if (!component)
{
throw new InvalidOperationException("PlayerVoteData is not attached to the player.");
}
VoteDataComponents[player] = component;
return component;
}
public static KeyValuePair<byte, int> MaxPair(this Dictionary<byte, int> self, out bool tie)
{
tie = true;
var result = new KeyValuePair<byte, int>(byte.MaxValue, int.MinValue);
foreach (var keyValuePair in self)
{
if (keyValuePair.Value > result.Value)
{
result = keyValuePair;
tie = false;
}
else if (keyValuePair.Value == result.Value)
{
tie = true;
}
}
return result;
}
public static KeyValuePair<byte, float> MaxPair(this Dictionary<byte, float> self, out bool tie)
{
tie = true;
var result = new KeyValuePair<byte, float>(byte.MaxValue, int.MinValue);
foreach (var keyValuePair in self)
{
if (keyValuePair.Value > result.Value)
{
result = keyValuePair;
tie = false;
}
else if (Math.Abs(keyValuePair.Value - result.Value) < .05)
{
tie = true;
}
}
return result;
}
/// <summary>
/// Gets the best constructor for a type based on the specified arguments.
/// </summary>
@@ -55,6 +156,17 @@ public static class Extensions
.FirstOrDefault();
}
/// <summary>
/// Gets a proper string for an enum. (with spaces).
/// </summary>
/// <param name="enum">The enum you would like to change.</param>
/// <returns>A proper string for the enum.</returns>
public static string ToDisplayString(this Enum @enum)
{
var regex = new Regex(@"([^\^])([A-Z][a-z$])");
return regex.Replace(@enum.ToString(), m => $"{m.Groups[1].Value} {m.Groups[2].Value}");
}
/// <summary>
/// Gets the constructors of a type that match the specified arguments.
/// </summary>
@@ -171,12 +283,13 @@ public static class Extensions
if (count + length > chunkSize)
{
chunks.Enqueue(current.ToArray());
chunks.Enqueue([.. current]);
current.Clear();
count = 0;
}
current.Add(netData);
count += length;
}
if (current.Count > 0)
@@ -235,6 +348,7 @@ public static class Extensions
/// <param name="color">The original color.</param>
/// <param name="amount">The amount to darken or lighten the original color by between 0.0 and 1.0.</param>
/// <returns>An alternate color that has been darkened or lightened.</returns>
[Obsolete("Use FindAlternateColor for WACG compliance.")]
public static Color GetAlternateColor(this Color color, float amount = 0.45f)
{
return color.IsColorDark() ? LightenColor(color, amount) : DarkenColor(color, amount);
+134 -11
View File
@@ -2,8 +2,6 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using MiraAPI.Roles;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -24,6 +22,123 @@ public static class Helpers
return PlayerControl.AllPlayerControls.ToArray().Where(x => !x.Data.IsDead).ToList();
}
/// <summary>
/// Determines whether a given probability check succeeds.
/// </summary>
/// <param name="probability">An integer value representing the success probability (0-100).</param>
/// <returns>True if the number falls in the range, false if not.</returns>
public static bool CheckChance(int probability)
{
switch (probability)
{
case 0:
return false;
case 100:
return true;
default:
{
var num = Random.RandomRangeInt(1, 101);
return num <= probability;
}
}
}
/// <summary>
/// Retrieves a vent from the ID.
/// </summary>
/// <param name="id">The vent ID.</param>
/// <returns>The vent.</returns>
public static Vent? GetVentById(int id)
{
return ShipStatus.Instance.AllVents.FirstOrDefault(vent => vent.Id == id);
}
/// <summary>
/// Creates an arrow.
/// </summary>
/// <param name="parent">The arrow gameObject's parent.</param>
/// <param name="color">The color of the arrow.</param>
/// <returns>The created ArrowBehaviour.</returns>
public static ArrowBehaviour CreateArrow(Transform parent, Color color)
{
var prefab = Object.FindObjectOfType<ArrowBehaviour>(true);
var arrow = Object.Instantiate(prefab, parent);
arrow.image = arrow.gameObject.GetComponent<SpriteRenderer>();
arrow.image.color = color;
arrow.gameObject.layer = 5;
arrow.gameObject.SetActive(true);
return arrow;
}
/// <summary>
/// Get the closest object of a specific type.
/// </summary>
/// <param name="objectList">A list of all the objects you'd like to check the distance for.</param>
/// <param name="position">The position of where you want to check from. For example: PlayerControl.LocalPlayer.transform.position.</param>
/// <typeparam name="T">The object type.</typeparam>
/// <returns>The closest object.</returns>
public static T? FindClosestObjectOfType<T>(List<T> objectList, Vector3 position) where T : MonoBehaviour
{
T? closest = null;
var closestDistanceSqr = Mathf.Infinity;
foreach (var obj in objectList)
{
if (obj == null)
{
continue;
}
var sqrDistance = (obj.transform.position - position).sqrMagnitude;
if (sqrDistance < closestDistanceSqr)
{
closestDistanceSqr = sqrDistance;
closest = obj;
}
}
return closest;
}
/// <summary>
/// Creates and shows a notification.
/// </summary>
/// <param name="text">The text you want to display.</param>
/// <param name="color">The color of the text and image.</param>
/// <param name="clip">The sound you want to play with the notification.</param>
/// <param name="spr">The sprite beside the notification.</param>
/// <returns>The created notification.</returns>
public static LobbyNotificationMessage CreateAndShowNotification(string text, Color color, AudioClip? clip = null, Sprite? spr = null)
{
return CreateAndShowNotification(text, color, new Vector3(0f, 0f, -2f), clip, spr);
}
/// <summary>
/// Creates and shows a notification.
/// </summary>
/// <param name="text">The text you want to display.</param>
/// <param name="color">The color of the text and image.</param>
/// <param name="localPos">The position of the notification.</param>
/// <param name="clip">The sound you want to play with the notification.</param>
/// <param name="spr">The sprite beside the notification.</param>
/// <returns>The created notification.</returns>
public static LobbyNotificationMessage CreateAndShowNotification(string text, Color color, Vector3 localPos, AudioClip? clip = null, Sprite? spr = null)
{
var popper = HudManager.Instance.Notifier;
var newMessage = Object.Instantiate(popper.notificationMessageOrigin, Vector3.zero, Quaternion.identity, popper.transform);
newMessage.transform.localPosition = localPos;
newMessage.SetUp(text, spr ?? null, color, new System.Action(() => popper.OnMessageDestroy(newMessage)));
popper.lastMessageKey = -1;
popper.ShiftMessages();
popper.AddMessageToQueue(newMessage);
if (clip == null) return newMessage;
SoundManager.Instance.StopSound(clip);
SoundManager.Instance.PlaySound(clip, false, 2f);
return newMessage;
}
/// <summary>
/// Returns an empty coroutine.
/// </summary>
@@ -265,16 +380,24 @@ public static class Helpers
}
/// <summary>
/// Creates a string builder for the Role Tab.
/// Converts the first letter of a string to uppercase.
/// </summary>
/// <param name="role">The ICustomRole object.</param>
/// <returns>A StringBuilder.</returns>
public static StringBuilder CreateForRole(ICustomRole role)
/// <param name="str">The string.</param>
/// <returns>The fixed string.</returns>
public static string FirstLetterToUpper(string str)
{
var taskStringBuilder = new StringBuilder();
taskStringBuilder.AppendLine(CultureInfo.InvariantCulture, $"{role.RoleColor.ToTextColor()}You are a <b>{role.RoleName}.</b></color>");
taskStringBuilder.Append("<size=70%>");
taskStringBuilder.AppendLine(CultureInfo.InvariantCulture, $"{role.RoleLongDescription}");
return taskStringBuilder;
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower(CultureInfo.InvariantCulture));
}
/// <summary>
/// Gets a random string based on characters.
/// </summary>
/// <param name="length">The length of the string.</param>
/// <param name="chars">The characters in the random string.</param>
/// <returns>The random string.</returns>
public static string RandomString(int length, string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[Random.RandomRangeInt(0, s.Length)]).ToArray());
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace MiraAPI.Voting;
/// <summary>
/// Represents a custom vote.
/// </summary>
/// <param name="Voter">The player that voted.</param>
/// <param name="Suspect">The suspect being voted for.</param>
public record struct CustomVote(byte Voter, byte Suspect);
+108
View File
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using Reactor.Utilities.Attributes;
using UnityEngine;
namespace MiraAPI.Voting;
/// <summary>
/// Handles player votes, and removing/adding additional votes.
/// </summary>
[RegisterInIl2Cpp]
public class PlayerVoteData(nint cppPtr) : MonoBehaviour(cppPtr)
{
/// <summary>
/// Gets the owner of this component.
/// </summary>
public PlayerControl Owner { get; private set; } = null!;
/// <summary>
/// Gets the list of votes the owner has.
/// </summary>
public List<CustomVote> Votes { get; private set; } = [];
/// <summary>
/// Gets or sets the amount of votes the owner has left.
/// </summary>
public int VotesRemaining
{
get => _votesRemaining;
set => _votesRemaining = Math.Max(0, value);
}
private int _votesRemaining = 1;
private void Awake()
{
Owner = GetComponent<PlayerControl>();
if (Owner == null)
{
Destroy(this);
}
}
/// <summary>
/// Returns whether the owner has voted for the specified player.
/// </summary>
/// <param name="playerId">The target's playerId.</param>
/// <returns>True if the owner voted for the specified player, false otherwise.</returns>
public bool VotedFor(byte playerId)
{
return Votes.Exists(x => x.Suspect == playerId);
}
/// <summary>
/// Adds the voted player to the list.
/// </summary>
/// <param name="playerId">The target's playerId.</param>
public void VoteForPlayer(byte playerId)
{
Votes.Add(new CustomVote(Owner.PlayerId, playerId));
}
/// <summary>
/// Removes the specified vote.
/// </summary>
/// <param name="vote">The vote you would like to remove.</param>
public void RemovePlayerVote(CustomVote vote)
{
Votes.Remove(vote);
}
/// <summary>
/// Removes a single vote from the owner.
/// </summary>
/// <param name="playerId">The target's playerId.</param>
public void RemovePlayerVote(byte playerId)
{
Votes.Remove(Votes.Find(x=>x.Suspect==playerId));
}
/// <summary>
/// Sets the player's votes remaining.
/// </summary>
/// <param name="votesRemaining">The amount of votes you would like to set it to.</param>
public void SetRemainingVotes(int votesRemaining)
{
VotesRemaining = votesRemaining;
}
/// <summary>
/// Adds votes to the owner.
/// </summary>
/// <param name="amount">The amount of votes you would like to add.</param>
public void IncreaseRemainingVotes(int amount)
{
SetRemainingVotes(VotesRemaining + amount);
}
/// <summary>
/// Removes votes from the owner.
/// </summary>
/// <param name="amount">The amount of votes you would like to remove.</param>
public void DecreaseRemainingVotes(int amount)
{
SetRemainingVotes(VotesRemaining - amount);
}
}
+180
View File
@@ -0,0 +1,180 @@
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Meeting.Voting;
using MiraAPI.Networking;
using MiraAPI.Utilities;
using Reactor.Networking.Attributes;
using Reactor.Utilities;
namespace MiraAPI.Voting;
/// <summary>
/// Utilities used for the Mira voting system.
/// </summary>
public static class VotingUtils
{
private const byte SkipVoteId = 253;
/// <summary>
/// Gets the exiled player from the list of votes. Returns null if no player is to be exiled.
/// </summary>
/// <param name="votes">>The list of votes to check.</param>
/// <param name="isTie">Whether the vote is a tie.</param>
/// <returns>The player to be exiled. Will be null if no player is to be exiled.</returns>
public static NetworkedPlayerInfo? GetExiled(List<CustomVote> votes, out bool isTie)
{
var max = CalculateNumVotes(votes).MaxPair(out var tie);
isTie = tie;
var exiled = GameData.Instance.AllPlayers.ToArray().FirstOrDefault(v => !tie && v.PlayerId == max.Key);
if (exiled is null || exiled.IsDead || exiled.Disconnected)
{
exiled = null;
}
return exiled;
}
/// <summary>
/// Handles when a vote is added and allows for other mods to override/modify.
/// </summary>
/// <param name="voteData">The player's vote data.</param>
/// <param name="suspectIdx">Who the player voted for.</param>
public static void HandleVote(PlayerVoteData voteData, byte suspectIdx)
{
var @event = new HandleVoteEvent(voteData, suspectIdx);
MiraEventManager.InvokeEvent(@event);
if (@event.IsCancelled)
{
return;
}
voteData.DecreaseRemainingVotes(1);
voteData.VoteForPlayer(suspectIdx);
}
/// <summary>
/// Networks the removal of votes. Used to remove votes when a player disconnects.
/// </summary>
/// <param name="source">The player who is sending the RPC. Should be the host.</param>
/// <param name="voterId">The player who voted.</param>
/// <param name="votedFor">The player who the voter voted for.</param>
[MethodRpc((uint)MiraRpc.RemoveVote)]
public static void RpcRemoveVote(PlayerControl source, byte voterId, byte votedFor)
{
if (source.OwnerId != AmongUsClient.Instance.HostId)
{
return;
}
MeetingHud.Instance.playerStates.First(state => state.TargetPlayerId == voterId).UnsetVote();
if (PlayerControl.LocalPlayer.PlayerId != voterId)
{
return;
}
MeetingHud.Instance.playerStates.First(state => state.TargetPlayerId == votedFor).ThumbsDown.enabled = false;
if (!AmongUsClient.Instance.AmHost)
{
var voteData = PlayerControl.LocalPlayer.GetVoteData();
voteData.DecreaseRemainingVotes(1);
voteData.RemovePlayerVote(votedFor);
}
foreach (var t in MeetingHud.Instance.playerStates)
{
t.voteComplete = false;
}
MeetingHud.Instance.SkipVoteButton.voteComplete = false;
MeetingHud.Instance.SkipVoteButton.gameObject.SetActive(true);
}
/// <summary>
/// Calculates the total number of votes.
/// </summary>
/// <param name="votes">A list of calculated votes.</param>
/// <returns>The total votes.</returns>
public static Dictionary<byte, float> CalculateNumVotes(IEnumerable<CustomVote> votes)
{
var dictionary = new Dictionary<byte, float>();
foreach (var vote in votes.Select(v=>v.Suspect))
{
if (!dictionary.TryAdd(vote, 1))
{
dictionary[vote] += 1;
}
}
return dictionary;
}
/// <summary>
/// Calculates votes to check if all players have voted.
/// </summary>
/// <returns>The list of votes.</returns>
public static List<CustomVote> CalculateVotes()
{
return
[
.. Helpers.GetAlivePlayers()
.SelectMany(player => player.GetVoteData().Votes)
];
}
/// <summary>
/// Handles the populating of results locally. Called by the PopulateResultsRpc.
/// </summary>
/// <param name="votes">The list of networked votes.</param>
public static void HandlePopulateResults(List<CustomVote> votes)
{
PopulateResultsEvent @event = new PopulateResultsEvent(votes);
MiraEventManager.InvokeEvent(@event);
if (@event.IsCancelled)
{
return;
}
MeetingHud.Instance.TitleText.text =
DestroyableSingleton<TranslationController>.Instance.GetString(
StringNames.MeetingVotingResults,
Il2CppSystem.Array.Empty<Il2CppSystem.Object>());
var delays = new Dictionary<byte, int>();
var num = 0;
for (var i = 0; i < MeetingHud.Instance.playerStates.Length; i++)
{
var playerVoteArea = MeetingHud.Instance.playerStates[i];
playerVoteArea.ClearForResults();
foreach (var vote in votes)
{
var playerById = GameData.Instance.GetPlayerById(vote.Voter);
if (playerById == null)
{
Logger<MiraApiPlugin>.Error($"Couldn't find player info for voter: {vote.Voter}");
}
else if (i == 0 && vote.Suspect == SkipVoteId)
{
MeetingHud.Instance.BloopAVoteIcon(playerById, num, MeetingHud.Instance.SkippedVoting.transform);
num++;
}
else if (vote.Suspect == playerVoteArea.TargetPlayerId)
{
if (!delays.TryAdd(vote.Suspect, 0))
{
delays[vote.Suspect]++;
}
MeetingHud.Instance.BloopAVoteIcon(playerById, delays[vote.Suspect], playerVoteArea.transform);
}
}
}
}
}