mirror of
https://github.com/All-Of-Us-Mods/MiraAPI.git
synced 2026-10-20 11:39:45 +00:00
Compare commits
301
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd818a18cf | ||
|
|
56d4e399d9 | ||
|
|
0d41ebbc13 | ||
|
|
9388ff487a | ||
|
|
720491e5cf | ||
|
|
9884df356e | ||
|
|
7ec4addacc | ||
|
|
bc9bc0ce24 | ||
|
|
aff1c311fa | ||
|
|
0d2a9d9700 | ||
|
|
669c541279 | ||
|
|
2e5f9639b3 | ||
|
|
e6d1f440c8 | ||
|
|
2ac8bdc240 | ||
|
|
d5d99001ea | ||
|
|
5628b79814 | ||
|
|
72a44f65f1 | ||
|
|
db6a336a63 | ||
|
|
90b23ec2ca | ||
|
|
20e927208c | ||
|
|
13ef3bdd49 | ||
|
|
b3ff6755bb | ||
|
|
67604600cd | ||
|
|
6e35de6185 | ||
|
|
a26ec51c7d | ||
|
|
3f6ae4cc41 | ||
|
|
15a2cdcd5b | ||
|
|
cf0bd6ec38 | ||
|
|
130236e899 | ||
|
|
3b7b247ac0 | ||
|
|
52de9a22de | ||
|
|
372a9e3aa9 | ||
|
|
10a9dcfa34 | ||
|
|
d46fdb0185 | ||
|
|
a361afbcbf | ||
|
|
24cdac0243 | ||
|
|
5fe75843ad | ||
|
|
a0436dcbba | ||
|
|
35be381a77 | ||
|
|
1298beb517 | ||
|
|
d41c19a176 | ||
|
|
476f4400ad | ||
|
|
2b46d90570 | ||
|
|
ae4aaf7af9 | ||
|
|
757b9436ca | ||
|
|
7ea10afffb | ||
|
|
0ab80c42f9 | ||
|
|
bc144568f4 | ||
|
|
07f402e659 | ||
|
|
1a6aed539a | ||
|
|
023cdaa470 | ||
|
|
98dd5ca056 | ||
|
|
1f3e21ce19 | ||
|
|
15e441dd71 | ||
|
|
8c67bbbd44 | ||
|
|
aa584a8f44 | ||
|
|
a8a584b61b | ||
|
|
acc4b1c8dd | ||
|
|
f9600bc906 | ||
|
|
f3da06870f | ||
|
|
9180dec9e1 | ||
|
|
ef6dedbd55 | ||
|
|
5d3c3ed319 | ||
|
|
5b22d667fd | ||
|
|
fb894c9f2c | ||
|
|
d0449f57b5 | ||
|
|
5ffd591258 | ||
|
|
cc0ac1b988 | ||
|
|
00b96f6e61 | ||
|
|
6cb7f9f145 | ||
|
|
b94472ee07 | ||
|
|
f8056c29da | ||
|
|
e7f9a3bb60 | ||
|
|
8d4f2baf1e | ||
|
|
11ba3dae64 | ||
|
|
86145f94f4 | ||
|
|
a9ded0b313 | ||
|
|
e0da386567 | ||
|
|
6f1da2de9f | ||
|
|
b85358e304 | ||
|
|
2c901bb9b9 | ||
|
|
68f40a96b7 | ||
|
|
a96ffc42f2 | ||
|
|
0907b14893 | ||
|
|
7a7204b0e0 | ||
|
|
e57e88c179 | ||
|
|
878eab25b8 | ||
|
|
e4f15f2ed9 | ||
|
|
bdc9fa28ac | ||
|
|
64604aff98 | ||
|
|
32a44d646d | ||
|
|
8f590b94a8 | ||
|
|
3ba71d8f19 | ||
|
|
96a47d480a | ||
|
|
bb72d885cf | ||
|
|
e242975d75 | ||
|
|
be6bc07a62 | ||
|
|
a6d55ec90f | ||
|
|
e5b6400eb8 | ||
|
|
0d1d1891a8 | ||
|
|
54d85a6996 | ||
|
|
531a799a24 | ||
|
|
3e6eb49d93 | ||
|
|
3fabe85a18 | ||
|
|
a3fc847d07 | ||
|
|
ddfad0752d | ||
|
|
f1846375ca | ||
|
|
fcb693e899 | ||
|
|
21bec074fa | ||
|
|
30516104aa | ||
|
|
e7508e299b | ||
|
|
b0cd1d30b3 | ||
|
|
9f3a40b48f | ||
|
|
31ffe6274c | ||
|
|
91c9a27df8 | ||
|
|
7484dd1a9f | ||
|
|
9c9964eecf | ||
|
|
78fad65b97 | ||
|
|
aef4d6daf1 | ||
|
|
87b94b1b6d | ||
|
|
cf92b97e8b | ||
|
|
bd0aa68cb8 | ||
|
|
f43a542134 | ||
|
|
efd176f7a4 | ||
|
|
b2fabdb139 | ||
|
|
a651099217 | ||
|
|
e2f39c29a8 | ||
|
|
140b697aaf | ||
|
|
a56b6d52ef | ||
|
|
3a36acd131 | ||
|
|
3adb7ef018 | ||
|
|
8c763e2a57 | ||
|
|
2df50112eb | ||
|
|
ce330325e4 | ||
|
|
516cc83170 | ||
|
|
89cd32d4a4 | ||
|
|
f0e37daf0e | ||
|
|
71e2f2e375 | ||
|
|
a5ddec48c8 | ||
|
|
9e6524817a | ||
|
|
5f4461f7e5 | ||
|
|
5e2ca191ba | ||
|
|
5af10b52a4 | ||
|
|
a0d3afc7c7 | ||
|
|
2e769d79f2 | ||
|
|
41305ad0e2 | ||
|
|
a8ac00d270 | ||
|
|
3cd7acbc70 | ||
|
|
ce583d11de | ||
|
|
31132e6e65 | ||
|
|
1a53e2b045 | ||
|
|
2418e17af6 | ||
|
|
6fb0afe14e | ||
|
|
32b368c1ef | ||
|
|
103c32f386 | ||
|
|
662b867dc5 | ||
|
|
adae0225e9 | ||
|
|
0d347b8b1b | ||
|
|
ab0063dd99 | ||
|
|
a35bf60870 | ||
|
|
692b9d7180 | ||
|
|
b99efaa420 | ||
|
|
2ecfa267d6 | ||
|
|
4fad586aa7 | ||
|
|
6d51e6806a | ||
|
|
b28a0a1253 | ||
|
|
51b54d4340 | ||
|
|
ea9bf162ea | ||
|
|
57105f487b | ||
|
|
c5e424e8ff | ||
|
|
d3b40aec5a | ||
|
|
521e5a12fd | ||
|
|
e6e4a86546 | ||
|
|
9afe821b0f | ||
|
|
a8d076656d | ||
|
|
be46ee7329 | ||
|
|
75a15dc090 | ||
|
|
cffb104392 | ||
|
|
bb0b678747 | ||
|
|
429b64fc03 | ||
|
|
bf5dadc6a0 | ||
|
|
b2137230da | ||
|
|
f48143610c | ||
|
|
9e8c05f21d | ||
|
|
2cfc5ac039 | ||
|
|
2f56c95b39 | ||
|
|
38f72c42a3 | ||
|
|
71b537dba9 | ||
|
|
e9beb3b423 | ||
|
|
5b608f5b3a | ||
|
|
23c0397afe | ||
|
|
2248726450 | ||
|
|
c60537cbd1 | ||
|
|
7917d4b5d9 | ||
|
|
bf795a2e36 | ||
|
|
144a95fa3b | ||
|
|
e25b78705b | ||
|
|
19ba9da2c3 | ||
|
|
ce9864ae8b | ||
|
|
8f76f21cb1 | ||
|
|
bc7b835dc8 | ||
|
|
f0b2f9ee2a | ||
|
|
25eafe664b | ||
|
|
db327604c5 | ||
|
|
1462061df9 | ||
|
|
fb40664bd0 | ||
|
|
3cba870980 | ||
|
|
ab2f03ee4d | ||
|
|
645d1dad1c | ||
|
|
a04e0d28db | ||
|
|
b04d9619b8 | ||
|
|
33fd657eb3 | ||
|
|
529fc89fc5 | ||
|
|
6ab283d39c | ||
|
|
08d8a48701 | ||
|
|
708534ed5c | ||
|
|
886ef0e31f | ||
|
|
0b9e54eb50 | ||
|
|
bad6648f44 | ||
|
|
86f970c989 | ||
|
|
7aafaf478c | ||
|
|
451a626370 | ||
|
|
e02c06ca07 | ||
|
|
e43cd0ceff | ||
|
|
e680b5c872 | ||
|
|
b6f304fe1d | ||
|
|
e52f48c20d | ||
|
|
d97588b356 | ||
|
|
68304a5eb8 | ||
|
|
f2add2a65b | ||
|
|
bbff2dd2d9 | ||
|
|
664f8cb2e8 | ||
|
|
d9081ed17b | ||
|
|
6f248221d6 | ||
|
|
989b511276 | ||
|
|
b67fdf5ab1 | ||
|
|
26afd47d2a | ||
|
|
2e0ecd95a6 | ||
|
|
669d5765e6 | ||
|
|
309094bdf8 | ||
|
|
49d09bb44f | ||
|
|
f77b694e78 | ||
|
|
e3cf884975 | ||
|
|
3d91c8de25 | ||
|
|
3387564f2d | ||
|
|
9e2787b781 | ||
|
|
90ed9b2a98 | ||
|
|
530cb79981 | ||
|
|
6f4eff7b38 | ||
|
|
2159b6aa89 | ||
|
|
9ec270bd68 | ||
|
|
c9ff839f12 | ||
|
|
d1116b3fce | ||
|
|
65a81d0fb4 | ||
|
|
26b94b0127 | ||
|
|
6443b5932b | ||
|
|
a619a975d7 | ||
|
|
81834a7f1a | ||
|
|
3015c6dd6a | ||
|
|
0e2eeea069 | ||
|
|
7e4a71739c | ||
|
|
caa27642db | ||
|
|
4a8fb38380 | ||
|
|
66375e884f | ||
|
|
9ae9094a85 | ||
|
|
1c6fa9a84d | ||
|
|
0ebec6d0f1 | ||
|
|
0bed367eda | ||
|
|
176a1d5e5c | ||
|
|
fb19b4bc04 | ||
|
|
8fb8d18be9 | ||
|
|
b1846fae26 | ||
|
|
8b8f9ea5db | ||
|
|
bbec3c1958 | ||
|
|
758b1d3183 | ||
|
|
d8131d1f5d | ||
|
|
9ccf7104cb | ||
|
|
bc12c5a5f7 | ||
|
|
5dfbd5dc8f | ||
|
|
84c8f743f8 | ||
|
|
3905a3b394 | ||
|
|
fb5ff4b53e | ||
|
|
047312a197 | ||
|
|
8e0a8f0585 | ||
|
|
4849b52b47 | ||
|
|
9cc9a137cc | ||
|
|
055b097c21 | ||
|
|
87187fe205 | ||
|
|
975e8cb9b7 | ||
|
|
6775294a19 | ||
|
|
2af89a678f | ||
|
|
dda46e5903 | ||
|
|
ba92d9608c | ||
|
|
52ff4bfbfc | ||
|
|
b6dda5f970 | ||
|
|
8e2535ada2 | ||
|
|
ce81d8c1ff | ||
|
|
9485099ab9 | ||
|
|
f5b4bdd1d4 | ||
|
|
cd6c4f5390 | ||
|
|
5cc29d903a |
No files matched your search
+1
-2
@@ -1,2 +1 @@
|
||||
[*.{cs,vb}]
|
||||
dotnet_diagnostic.CA1707.severity = none
|
||||
[*.{cs,vb}]
|
||||
@@ -3,6 +3,7 @@
|
||||
.vs/
|
||||
obj/
|
||||
bin/
|
||||
.qodo/
|
||||
|
||||
*.user
|
||||
*.lock.json
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
<Project>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Reactor" Version="2.3.1" />
|
||||
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.697" Private="false" ExcludeAssets="runtime;native" />
|
||||
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2024.10.29" PrivateAssets="all" />
|
||||
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.735" Private="false" ExcludeAssets="runtime;native" />
|
||||
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2025.4.15" PrivateAssets="all" />
|
||||
|
||||
<PackageReference Include="BepInEx.AutoPlugin" Version="1.1.0" PrivateAssets="all" />
|
||||
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.0.1" PrivateAssets="all" ExcludeAssets="runtime" />
|
||||
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.1.0-rc.1" PrivateAssets="all" ExcludeAssets="runtime" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="Copy" AfterTargets="Build" Condition="'$(AmongUs)' != ''">
|
||||
|
||||
@@ -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>
|
||||
@@ -34,7 +34,7 @@
|
||||
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556" PrivateAssets="all" />
|
||||
<AdditionalFiles Include="$(MSBuildThisFileDirectory)\stylecop.json" Link="stylecop.json" Visible="false" />
|
||||
|
||||
<PackageReference Include="SonarAnalyzer.CSharp" Version="9.32.0.97167">
|
||||
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.7.0.110445">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
|
||||
@@ -3,6 +3,7 @@ using MiraAPI.Example.Options.Roles;
|
||||
using MiraAPI.Example.Roles;
|
||||
using MiraAPI.GameOptions;
|
||||
using MiraAPI.Hud;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Utilities;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using UnityEngine;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
using MiraAPI.Example.Modifiers;
|
||||
using MiraAPI.Hud;
|
||||
using MiraAPI.Utilities;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using UnityEngine;
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using MiraAPI.Example.GameOver;
|
||||
using MiraAPI.Example.Roles;
|
||||
using MiraAPI.GameEnd;
|
||||
using MiraAPI.Hud;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Example.Buttons;
|
||||
|
||||
public class NeutralKillerButton : CustomActionButton
|
||||
{
|
||||
public override string Name => "Win Game";
|
||||
public override float Cooldown => 0f;
|
||||
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
|
||||
protected override void OnClick()
|
||||
{
|
||||
CustomGameOver.Trigger<NeutralKillerGameOver>([PlayerControl.LocalPlayer.Data]);
|
||||
}
|
||||
|
||||
public override bool Enabled(RoleBehaviour? role)
|
||||
{
|
||||
return role is NeutralKillerRole;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
using MiraAPI.Example.Options.Roles;
|
||||
using System.Collections;
|
||||
using MiraAPI.Example.Options.Roles;
|
||||
using MiraAPI.Example.Roles;
|
||||
using MiraAPI.GameOptions;
|
||||
using MiraAPI.Hud;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using Reactor.Utilities;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Example.Buttons.Teleporter;
|
||||
@@ -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)
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace MiraAPI.Example;
|
||||
public static class ExampleAssets
|
||||
{
|
||||
public static LoadableResourceAsset ExampleButton { get; } = new("MiraAPI.Example.Resources.ExampleButton.png");
|
||||
public static LoadableResourceAsset CallMeetingButton { get; } = new("MiraAPI.Example.Resources.CallMeeting.png");
|
||||
|
||||
// Credit to EpicHorrors for the teleport button asset.
|
||||
public static LoadableResourceAsset TeleportButton { get; } = new("MiraAPI.Example.Resources.TeleportButton.png");
|
||||
|
||||
@@ -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,12 +17,8 @@ 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);
|
||||
|
||||
MiraEventManager.RegisterEventHandler<BeforeMurderEvent>(@event =>
|
||||
// You can register event handlers with the MiraEventManager class.
|
||||
var handle = MiraEventManager.RegisterEventHandler<BeforeMurderEvent>(@event =>
|
||||
{
|
||||
Logger<ExamplePlugin>.Info($"{@event.Source.Data.PlayerName} is about to kill {@event.Target.Data.PlayerName}");
|
||||
});
|
||||
@@ -31,26 +32,64 @@ public static class ExampleEventHandlers
|
||||
{
|
||||
Logger<ExamplePlugin>.Info($"{@event.Player.Data.PlayerName} completed {@event.Task.TaskType.ToString()}");
|
||||
});
|
||||
|
||||
// You can also unregister event handlers using the handle returned from RegisterEventHandler.
|
||||
MiraEventManager.UnregisterEventHandler(handle);
|
||||
}
|
||||
|
||||
// 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!");
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using MiraAPI.Example.Roles;
|
||||
using MiraAPI.GameEnd;
|
||||
using MiraAPI.Utilities;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Example.GameOver;
|
||||
|
||||
public class NeutralKillerGameOver : CustomGameOver
|
||||
{
|
||||
public override bool VerifyCondition(PlayerControl playerControl, NetworkedPlayerInfo[] winners)
|
||||
{
|
||||
return winners is [{ Role: NeutralKillerRole }];
|
||||
}
|
||||
|
||||
public override void AfterEndGameSetup(EndGameManager endGameManager)
|
||||
{
|
||||
endGameManager.WinText.text = "Outcast Killer Wins!";
|
||||
endGameManager.WinText.color = Color.magenta;
|
||||
endGameManager.BackgroundBar.material.SetColor(ShaderID.Color, Color.magenta);
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,9 @@
|
||||
<ProjectReference Include="..\MiraAPI\MiraAPI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resources\ExampleButton.png" />
|
||||
<EmbeddedResource Include="Resources\FortniteBanner.jpeg" />
|
||||
<EmbeddedResource Include="Resources\TeleportButton.png" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resources\**\*.*" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\AmongUs.props" />
|
||||
</Project>
|
||||
@@ -1,19 +1,34 @@
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Example.Options.Modifiers;
|
||||
using MiraAPI.GameOptions;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Modifiers.Types;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Example.Modifiers;
|
||||
|
||||
public class CaptainModifier : GameModifier
|
||||
{
|
||||
public override string ModifierName => "Captain";
|
||||
public override LoadableAsset<Sprite>? ModifierIcon => ExampleAssets.CallMeetingButton;
|
||||
|
||||
public override int GetAmountPerGame()
|
||||
public override void OnDeath(DeathReason reason)
|
||||
{
|
||||
return 1;
|
||||
Player.RemoveModifier(this);
|
||||
}
|
||||
|
||||
public override string GetDescription()
|
||||
{
|
||||
return $"You can call a meeting from anywhere on the map.";
|
||||
}
|
||||
|
||||
public override int GetAssignmentChance()
|
||||
{
|
||||
return 100;
|
||||
return (int)OptionGroupSingleton<CaptainModifierSettings>.Instance.Chance;
|
||||
}
|
||||
|
||||
public override int GetAmountPerGame()
|
||||
{
|
||||
return (int)OptionGroupSingleton<CaptainModifierSettings>.Instance.Amount;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using Il2CppSystem;
|
||||
using MiraAPI.Example.Roles;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Modifiers.Types;
|
||||
using UnityEngine;
|
||||
|
||||
@@ -16,7 +15,7 @@ public class FreezeModifier : TimedModifier
|
||||
|
||||
public override void OnActivate()
|
||||
{
|
||||
if (Player?.AmOwner == true)
|
||||
if (Player.AmOwner)
|
||||
{
|
||||
Player.moveable = false;
|
||||
}
|
||||
@@ -26,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;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Modifiers.Types;
|
||||
using MiraAPI.Modifiers.Types;
|
||||
|
||||
namespace MiraAPI.Example.Modifiers;
|
||||
|
||||
public class HighPriorityModifier : GameModifier
|
||||
{
|
||||
public override string ModifierName => "High Priority";
|
||||
|
||||
public override string GetDescription()
|
||||
{
|
||||
return "You are high priority! Idrk what this means either tbh...";
|
||||
}
|
||||
|
||||
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 MiraAPI.Example.Roles;
|
||||
using MiraAPI.GameOptions;
|
||||
using MiraAPI.GameOptions.Attributes;
|
||||
using System;
|
||||
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)]
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -1,4 +1,7 @@
|
||||
using MiraAPI.Roles;
|
||||
using AmongUs.GameOptions;
|
||||
using MiraAPI.Patches.Stubs;
|
||||
using MiraAPI.Roles;
|
||||
using Reactor.Utilities;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
|
||||
@@ -12,36 +15,64 @@ public class ChameloenRole : CrewmateRole, ICustomRole
|
||||
public Color RoleColor => Palette.AcceptedGreen;
|
||||
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
|
||||
|
||||
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
|
||||
private bool _shouldHide;
|
||||
|
||||
public CustomRoleConfiguration Configuration => new(this)
|
||||
{
|
||||
OptionsScreenshot = ExampleAssets.Banner,
|
||||
IntroSound = CustomRoleUtils.GetIntroSound(RoleTypes.Shapeshifter),
|
||||
};
|
||||
|
||||
public void PlayerControlFixedUpdate(PlayerControl playerControl)
|
||||
public override void Initialize(PlayerControl player)
|
||||
{
|
||||
if (playerControl.MyPhysics.Velocity.magnitude > 0)
|
||||
Logger<ExamplePlugin>.Info("Initializing ChamelonRole for player: " + player.PlayerId);
|
||||
RoleBehaviourStubs.Initialize(this, player);
|
||||
_shouldHide = true;
|
||||
}
|
||||
|
||||
public void FixedUpdate()
|
||||
{
|
||||
if (!Player || !_shouldHide)
|
||||
{
|
||||
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
|
||||
TextMeshPro tmp = playerControl.cosmetics.nameText;
|
||||
return;
|
||||
}
|
||||
|
||||
if (Player.MyPhysics.Velocity.magnitude > 0)
|
||||
{
|
||||
var rend = Player.cosmetics.currentBodySprite.BodySprite;
|
||||
var tmp = Player.cosmetics.nameText;
|
||||
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, 1), Time.deltaTime * 4f);
|
||||
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, 1), Time.deltaTime * 4f);
|
||||
|
||||
foreach (var cosmetic in playerControl.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>())
|
||||
foreach (var cosmetic in Player.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>())
|
||||
{
|
||||
cosmetic.color = Color.Lerp(cosmetic.color, new Color(1, 1, 1, 1), Time.deltaTime * 4f);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
|
||||
TextMeshPro tmp = playerControl.cosmetics.nameText;
|
||||
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
|
||||
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
|
||||
SpriteRenderer rend = Player.cosmetics.currentBodySprite.BodySprite;
|
||||
TextMeshPro tmp = Player.cosmetics.nameText;
|
||||
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, Player.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
|
||||
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, Player.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
|
||||
|
||||
foreach (var cosmetic in playerControl.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>())
|
||||
foreach (var cosmetic in Player.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>())
|
||||
{
|
||||
cosmetic.color = Color.Lerp(cosmetic.color, new Color(1, 1, 1, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
|
||||
cosmetic.color = Color.Lerp(cosmetic.color, new Color(1, 1, 1, Player.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Deinitialize(PlayerControl targetPlayer)
|
||||
{
|
||||
Logger<ExamplePlugin>.Info("Deinitializing ChamelonRole for player: " + targetPlayer.PlayerId);
|
||||
RoleBehaviourStubs.Deinitialize(this, targetPlayer);
|
||||
_shouldHide = false;
|
||||
foreach (var cosmetic in Player.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>(true))
|
||||
{
|
||||
cosmetic.color = Color.white;
|
||||
}
|
||||
Player.cosmetics.currentBodySprite.BodySprite.color = Color.white;
|
||||
Player.cosmetics.nameText.color = Color.white;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using MiraAPI.Roles;
|
||||
using MiraAPI.Example.GameOver;
|
||||
using MiraAPI.GameEnd;
|
||||
using MiraAPI.Roles;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Example.Roles;
|
||||
@@ -22,7 +24,7 @@ public class NeutralKillerRole : ImpostorRole, ICustomRole
|
||||
|
||||
public TeamIntroConfiguration? IntroConfiguration { get; } = new(
|
||||
Color.gray,
|
||||
"NEUTRAL",
|
||||
"OUTCAST",
|
||||
"You are an Outcast. You do not have a team.");
|
||||
|
||||
public override void SpawnTaskHeader(PlayerControl playerControl)
|
||||
@@ -32,6 +34,6 @@ public class NeutralKillerRole : ImpostorRole, ICustomRole
|
||||
|
||||
public override bool DidWin(GameOverReason gameOverReason)
|
||||
{
|
||||
return GameManager.Instance.DidHumansWin(gameOverReason);
|
||||
return gameOverReason == CustomGameOver.GameOverReason<NeutralKillerGameOver>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
|
||||
namespace MiraAPI.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Event handle to use when unregistering an event.
|
||||
/// </summary>
|
||||
public class MiraEventHandle
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the type of event.
|
||||
/// </summary>
|
||||
public Type EventType { get; }
|
||||
|
||||
internal MiraEventWrapper EventWrapper { get; }
|
||||
|
||||
internal MiraEventHandle(Type type, MiraEventWrapper eventWrapper)
|
||||
{
|
||||
EventType = type;
|
||||
EventWrapper = eventWrapper;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using Reactor.Utilities;
|
||||
|
||||
namespace MiraAPI.Events;
|
||||
|
||||
@@ -19,14 +21,21 @@ public static class MiraEventManager
|
||||
public static bool InvokeEvent<T>(T eventInstance) where T : MiraEvent
|
||||
{
|
||||
EventWrappers.TryGetValue(typeof(T), out var handlers);
|
||||
if (handlers == null)
|
||||
if (handlers == null || handlers.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var handler in handlers)
|
||||
{
|
||||
((Action<T>)handler.EventHandler).Invoke(eventInstance);
|
||||
try
|
||||
{
|
||||
((Action<T>)handler.EventHandler).Invoke(eventInstance);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Error invoking event handler for {typeof(T).Name}: {ex.ToString()}");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -41,14 +50,21 @@ public static class MiraEventManager
|
||||
public static bool InvokeEvent(MiraEvent eventInstance, Type type)
|
||||
{
|
||||
EventWrappers.TryGetValue(type, out var handlers);
|
||||
if (handlers == null)
|
||||
if (handlers == null || handlers.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var handler in handlers)
|
||||
{
|
||||
handler.EventHandler.DynamicInvoke(eventInstance);
|
||||
try
|
||||
{
|
||||
handler.EventHandler.DynamicInvoke(eventInstance);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Error invoking event handler for {type.Name}: {ex.ToString()}");
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -57,25 +73,80 @@ public static class MiraEventManager
|
||||
/// <summary>
|
||||
/// Register an event.
|
||||
/// </summary>
|
||||
/// <param name="handler">The callback method/handler for the event.</param>
|
||||
/// <param name="priority">The priority of the event handler. Higher values are called first.</param>
|
||||
/// <typeparam name="T">Type of event.</typeparam>
|
||||
public static void RegisterEventHandler<T>(Action<T> handler, int priority = 0) where T : MiraEvent
|
||||
/// <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. Lower values are called first.</param>
|
||||
/// <returns>An event handle to use when unregistering the event.</returns>
|
||||
public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority = 0)
|
||||
{
|
||||
if (!EventWrappers.ContainsKey(typeof(T)))
|
||||
if (!type.IsSubclassOf(typeof(MiraEvent)))
|
||||
{
|
||||
EventWrappers.Add(typeof(T), []);
|
||||
throw new InvalidOperationException($"Type must be a subclass of MiraEvent: {type.FullName}");
|
||||
}
|
||||
|
||||
EventWrappers.TryAdd(type, []);
|
||||
var handlers = EventWrappers[type];
|
||||
|
||||
var @delegate = Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(type), methodInfo);
|
||||
var eventWrapper = new MiraEventWrapper(@delegate, priority);
|
||||
|
||||
var index = handlers.BinarySearch(eventWrapper, Comparer<MiraEventWrapper>.Create((a, b) => a.Priority.CompareTo(b.Priority)));
|
||||
|
||||
if (index < 0)
|
||||
{
|
||||
index = ~index;
|
||||
}
|
||||
|
||||
handlers.Insert(index, eventWrapper);
|
||||
return new MiraEventHandle(type, eventWrapper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register an event.
|
||||
/// </summary>
|
||||
/// <param name="handler">The callback method/handler for the event.</param>
|
||||
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
|
||||
/// <typeparam name="T">Type of event.</typeparam>
|
||||
/// <returns>An event handle to use when unregistering the event.</returns>
|
||||
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, int priority = 0) where T : MiraEvent
|
||||
{
|
||||
EventWrappers.TryAdd(typeof(T), []);
|
||||
|
||||
var handlers = EventWrappers[typeof(T)];
|
||||
handlers.Add(new MiraEventWrapper(handler, priority));
|
||||
var eventWrapper = new MiraEventWrapper(handler, priority);
|
||||
|
||||
var index = handlers.BinarySearch(eventWrapper, Comparer<MiraEventWrapper>.Create((a, b) => a.Priority.CompareTo(b.Priority)));
|
||||
|
||||
if (index < 0)
|
||||
{
|
||||
index = ~index;
|
||||
}
|
||||
|
||||
handlers.Insert(index, eventWrapper);
|
||||
return new MiraEventHandle(typeof(T), eventWrapper);
|
||||
}
|
||||
|
||||
internal static void SortAllHandlers()
|
||||
/// <summary>
|
||||
/// Unregister an event using the event handle.
|
||||
/// </summary>
|
||||
/// <param name="eventHandle">A handle to the event.</param>
|
||||
/// <returns>True if the event was unregistered successfully, false otherwise.</returns>
|
||||
public static bool UnregisterEventHandler(MiraEventHandle eventHandle)
|
||||
{
|
||||
foreach (var handlers in EventWrappers.Values)
|
||||
if (!EventWrappers.TryGetValue(eventHandle.EventType, out var handlers))
|
||||
{
|
||||
handlers.Sort((a, b) => a.Priority.CompareTo(b.Priority));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!handlers.Remove(eventHandle.EventWrapper))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (handlers.Count == 0)
|
||||
{
|
||||
EventWrappers.Remove(eventHandle.EventType);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ public class MiraEventWrapper
|
||||
public Delegate EventHandler { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the priority of the handler. Higher values are called first.
|
||||
/// Gets the priority of the handler. Lower values are called first.
|
||||
/// </summary>
|
||||
public int Priority { get; }
|
||||
|
||||
|
||||
@@ -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. Lower values are called first.
|
||||
/// </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. Lower values are called first.</param>
|
||||
public RegisterEventAttribute(int priority = 0)
|
||||
{
|
||||
Priority = priority;
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,21 @@ public class AfterMurderEvent : MiraEvent
|
||||
/// </summary>
|
||||
public PlayerControl Target { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the player's body, if it exists.
|
||||
/// </summary>
|
||||
public DeadBody? DeadBody { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="source">The killer.</param>
|
||||
/// <param name="target">The killed player.</param>
|
||||
public AfterMurderEvent(PlayerControl source, PlayerControl target)
|
||||
/// <param name="deadBody">The player's vody, if it exists.</param>
|
||||
public AfterMurderEvent(PlayerControl source, PlayerControl target, DeadBody? deadBody)
|
||||
{
|
||||
Source = source;
|
||||
Target = target;
|
||||
DeadBody = deadBody;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace MiraAPI.Events.Vanilla.Gameplay;
|
||||
|
||||
/// <summary>
|
||||
/// Invoked before RpcEndGame is called, allowing cancellation of the game end entirely.
|
||||
/// </summary>
|
||||
public class BeforeGameEndEvent : MiraCancelableEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reason for the game end.
|
||||
/// </summary>
|
||||
public GameOverReason Reason { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BeforeGameEndEvent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="reason">The reason for the game end.</param>
|
||||
public BeforeGameEndEvent(GameOverReason reason)
|
||||
{
|
||||
Reason = reason;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace MiraAPI.Events.Vanilla.Gameplay;
|
||||
|
||||
/// <summary>
|
||||
/// The event that is invoked when the intro cutscene has finished playing.
|
||||
/// </summary>
|
||||
public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the instance of the IntroCutscene.
|
||||
/// </summary>
|
||||
public IntroCutscene IntroCutscene { get; } = introCutscene;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace MiraAPI.Events.Vanilla.Gameplay;
|
||||
|
||||
/// <summary>
|
||||
/// Start Round event, invoked on IntroCutscene.OnDestroy and ExileController.WrapUp.
|
||||
/// </summary>
|
||||
public class RoundStartEvent : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the event was triggered by the IntroCutscene or ExileController.
|
||||
/// </summary>
|
||||
public bool TriggeredByIntro { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RoundStartEvent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="triggeredByIntro">Whether the event was triggered by the intro or not.</param>
|
||||
public RoundStartEvent(bool triggeredByIntro)
|
||||
{
|
||||
TriggeredByIntro = triggeredByIntro;
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ public class UpdateSystemEvent : MiraCancelableEvent
|
||||
/// Initializes a new instance of the <see cref="UpdateSystemEvent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="systemType">The SystemType being updated.</param>
|
||||
/// <param name="player">The player that is updating the system.</param>
|
||||
/// <param name="amount">Amount to update System to.</param>
|
||||
public UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byte amount)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace MiraAPI.Events.Vanilla.Meeting;
|
||||
|
||||
/// <summary>
|
||||
/// The event that is invoked when the meeting has ended.
|
||||
/// </summary>
|
||||
public class EndMeetingEvent(MeetingHud meetingHud) : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the MeetingHud instance.
|
||||
/// </summary>
|
||||
public MeetingHud MeetingHud { get; } = meetingHud;
|
||||
}
|
||||
@@ -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,50 @@
|
||||
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 a value indicating whether to prevent the vote from commencing.
|
||||
/// </summary>
|
||||
public bool PreventVote { 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;
|
||||
PreventVote = false;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace MiraAPI.Events.Vanilla.Meeting.Voting;
|
||||
|
||||
/// <summary>
|
||||
/// The event that is invoked when the voting phase of a meeting is complete.
|
||||
/// </summary>
|
||||
/// <param name="meetingHud">The MeetingHud instance.</param>
|
||||
public class VotingCompleteEvent(MeetingHud meetingHud) : MiraEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the MeetingHud instance.
|
||||
/// </summary>
|
||||
public MeetingHud MeetingHud { get; } = meetingHud;
|
||||
}
|
||||
@@ -15,14 +15,21 @@ public class PlayerDeathEvent : MiraEvent
|
||||
/// </summary>
|
||||
public DeathReason DeathReason { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the dead body associated with the player, if any.
|
||||
/// </summary>
|
||||
public DeadBody? DeadBody { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlayerDeathEvent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="player">The player who died.</param>
|
||||
/// <param name="reason">The reason the player died.</param>
|
||||
public PlayerDeathEvent(PlayerControl player, DeathReason reason)
|
||||
/// <param name="deadBody">The player's body, if it exists.</param>
|
||||
public PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody? deadBody)
|
||||
{
|
||||
Player = player;
|
||||
DeathReason = reason;
|
||||
DeadBody = deadBody;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace MiraAPI.Events.Vanilla;
|
||||
namespace MiraAPI.Events.Vanilla.Usables;
|
||||
|
||||
/// <summary>
|
||||
/// Event for <see cref="PlayerControl"/> using a <see cref="IUsable"/> from Vanilla Among Us. Will always be ran locally.
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.Collections.Generic;
|
||||
using MiraAPI.Networking;
|
||||
using Reactor.Networking.Rpc;
|
||||
|
||||
namespace MiraAPI.GameEnd;
|
||||
|
||||
/// <summary>
|
||||
/// Custom Game Over.
|
||||
/// </summary>
|
||||
public abstract class CustomGameOver
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the current CustomGameOver.
|
||||
/// </summary>
|
||||
public static CustomGameOver? Instance { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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, NetworkedPlayerInfo[] winners)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs before the base game calls EndGameManager.SetEverythingUp.
|
||||
/// </summary>
|
||||
/// <param name="endGameManager">The EndGameManager instance.</param>
|
||||
/// <returns>Return True to use the run the original method, return False to skip it.</returns>
|
||||
public virtual bool BeforeEndGameSetup(EndGameManager endGameManager)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs after the base game calls EndGameManager.SetEverythingUp.
|
||||
/// </summary>
|
||||
/// <param name="endGameManager">The EndGameManager instance.</param>
|
||||
public virtual void AfterEndGameSetup(EndGameManager endGameManager)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the GameOverReason associated with this CustomGameOver.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of the custom game over.</typeparam>
|
||||
/// <returns>The GameOverReason associated with the custom game over.</returns>
|
||||
public static GameOverReason GameOverReason<T>() where T : CustomGameOver
|
||||
{
|
||||
return (GameOverReason)GameOverManager.GetGameOverId<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send a custom game over.
|
||||
/// </summary>
|
||||
/// <param name="winners">A collection of winners.</param>
|
||||
/// <typeparam name="T">Type of the custom game over.</typeparam>
|
||||
public static void Trigger<T>(IEnumerable<NetworkedPlayerInfo> winners) where T : CustomGameOver
|
||||
{
|
||||
var reason = GameOverManager.GetGameOverId<T>();
|
||||
var data = new GameOverData(reason, [.. winners]);
|
||||
|
||||
Rpc<CustomGameOverRpc>.Instance.Send(PlayerControl.LocalPlayer, data, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Implicitly convert a CustomGameOver to a GameOverReason.
|
||||
/// </summary>
|
||||
/// <param name="gameOver">The CustomGameOver instance.</param>
|
||||
/// <returns>The GameOverReason associated with the CustomGameOver.</returns>
|
||||
public static implicit operator GameOverReason(CustomGameOver gameOver)
|
||||
{
|
||||
return (GameOverReason)GameOverManager.GetGameOverId(gameOver.GetType());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MiraAPI.GameEnd;
|
||||
|
||||
/// <summary>
|
||||
/// Data for a game over.
|
||||
/// </summary>
|
||||
/// <param name="Reason">Reason for the game over.</param>
|
||||
/// <param name="Winners">A collection of winners.</param>
|
||||
public record struct GameOverData(int Reason, List<NetworkedPlayerInfo> Winners);
|
||||
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Reactor.Utilities;
|
||||
|
||||
namespace MiraAPI.GameEnd;
|
||||
|
||||
/// <summary>
|
||||
/// Manage custom game overs.
|
||||
/// </summary>
|
||||
public static class GameOverManager
|
||||
{
|
||||
private static readonly Dictionary<Type, int> GameOverIds = [];
|
||||
private static readonly Dictionary<int, Type> GameOverTypes = [];
|
||||
|
||||
private static int _nextId = Enum.GetNames<GameOverReason>().Length;
|
||||
|
||||
/// <summary>
|
||||
/// Register a custom game over.
|
||||
/// </summary>
|
||||
/// <param name="gameOverType">Type of the custom game over.</param>
|
||||
/// <exception cref="ArgumentException">Thrown when the type is not a subclass of CustomGameOver, is abstract, or does not have a parameterless constructor.</exception>
|
||||
/// <returns>>True if the game over was registered successfully, false otherwise.</returns>
|
||||
public static bool RegisterGameOver(Type gameOverType)
|
||||
{
|
||||
if (!typeof(CustomGameOver).IsAssignableFrom(gameOverType))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (gameOverType.IsAbstract)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("The type must not be abstract.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (gameOverType.GetConstructor(Type.EmptyTypes) == null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("The type must have a parameterless constructor.");
|
||||
return false;
|
||||
}
|
||||
|
||||
GameOverIds.Add(gameOverType, _nextId);
|
||||
GameOverTypes.Add(_nextId, gameOverType);
|
||||
_nextId++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create an instance of a custom game over.
|
||||
/// </summary>
|
||||
/// <param name="id">ID of the custom game over.</param>
|
||||
/// <param name="customGameOver">The created instance of the custom game over.</param>
|
||||
/// <returns>An instance of the custom game over.</returns>
|
||||
public static bool TryGetGameOver(int id, [NotNullWhen(true)] out CustomGameOver? customGameOver)
|
||||
{
|
||||
if (GameOverTypes.TryGetValue(id, out var gameOverType))
|
||||
{
|
||||
customGameOver = Activator.CreateInstance(gameOverType) as CustomGameOver;
|
||||
return customGameOver != null;
|
||||
}
|
||||
|
||||
customGameOver = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the ID of a custom game over.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type of the custom game over.</typeparam>
|
||||
/// <returns>The ID of the custom game over.</returns>
|
||||
public static int GetGameOverId<T>() where T : CustomGameOver
|
||||
{
|
||||
return GetGameOverId(typeof(T));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the ID of a custom game over.
|
||||
/// </summary>
|
||||
/// <param name="gameOverType">Type of the custom game over.</param>
|
||||
/// <returns>The ID of the custom game over.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when the type is not registered.</exception>
|
||||
public static int GetGameOverId(Type gameOverType)
|
||||
{
|
||||
if (GameOverIds.TryGetValue(gameOverType, out var id))
|
||||
return id;
|
||||
|
||||
throw new ArgumentException($"{gameOverType.FullName} is not a registered custom game over!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
[*.cs]
|
||||
dotnet_diagnostic.CS1591.severity = none
|
||||
@@ -1,7 +1,7 @@
|
||||
using Reactor.Utilities;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Reactor.Utilities;
|
||||
|
||||
namespace MiraAPI.GameModes;
|
||||
|
||||
@@ -21,7 +21,7 @@ public static class CustomGameModeManager
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Current gamemode.
|
||||
/// Gets the current gamemode.
|
||||
/// </summary>
|
||||
public static CustomGameMode? ActiveMode { get; internal set; } = new DefaultMode();
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.GameOptions;
|
||||
@@ -11,11 +12,27 @@ public abstract class AbstractOptionGroup
|
||||
{
|
||||
internal List<IModdedOption> Options { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a list of the options which are a part of this group.
|
||||
/// </summary>
|
||||
public ReadOnlyCollection<IModdedOption> Children => new(Options);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the group. Visible in options menu.
|
||||
/// </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 +41,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 +49,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);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using MiraAPI.GameOptions.OptionTypes;
|
||||
using System;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using MiraAPI.GameOptions.OptionTypes;
|
||||
|
||||
namespace MiraAPI.GameOptions.Attributes;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using MiraAPI.GameOptions.OptionTypes;
|
||||
using MiraAPI.Utilities;
|
||||
using System;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using MiraAPI.GameOptions.OptionTypes;
|
||||
using MiraAPI.Utilities;
|
||||
|
||||
namespace MiraAPI.GameOptions.Attributes;
|
||||
|
||||
@@ -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 />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
using MiraAPI.GameOptions.OptionTypes;
|
||||
using System;
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using MiraAPI.GameOptions.OptionTypes;
|
||||
|
||||
namespace MiraAPI.GameOptions.Attributes;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,19 +6,100 @@ using UnityEngine;
|
||||
|
||||
namespace MiraAPI.GameOptions;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for modded options.
|
||||
/// </summary>
|
||||
public interface IModdedOption
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the unique identifier for the option.
|
||||
/// </summary>
|
||||
uint Id { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the option.
|
||||
/// </summary>
|
||||
string Title { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the StringName for the option, used for localization.
|
||||
/// </summary>
|
||||
StringNames StringName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the MiraPlugin that created this option.
|
||||
/// </summary>
|
||||
IMiraPlugin? ParentMod { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the game setting data for the option.
|
||||
/// </summary>
|
||||
BaseGameSetting Data { get; }
|
||||
Type? AdvancedRole { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the OptionBehaviour object of the option.
|
||||
/// </summary>
|
||||
OptionBehaviour? OptionBehaviour { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the visibility function for the option.
|
||||
/// </summary>
|
||||
Func<bool> Visible { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the option should be included with presets.
|
||||
/// </summary>
|
||||
bool IncludeInPreset { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ConfigDefinition for the option, used for BepInEx configuration.
|
||||
/// </summary>
|
||||
ConfigDefinition? ConfigDefinition { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates the option behaviour for the modded option.
|
||||
/// </summary>
|
||||
/// <param name="toggleOpt">The ToggleOption template.</param>
|
||||
/// <param name="numberOpt">The NumberOption template.</param>
|
||||
/// <param name="stringOpt">The StringOption template.</param>
|
||||
/// <param name="container">>The Transform container for the option.</param>
|
||||
/// <returns>>The created OptionBehaviour object.</returns>
|
||||
OptionBehaviour CreateOption(ToggleOption toggleOpt, NumberOption numberOpt, StringOption stringOpt, Transform container);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value as a float.
|
||||
/// </summary>
|
||||
/// <returns>>The value of the option as a float.</returns>
|
||||
float GetFloatData();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the NetData for the option, used for network synchronization.
|
||||
/// </summary>
|
||||
/// <returns>>Returns the NetData object for the option.</returns>
|
||||
NetData GetNetData();
|
||||
|
||||
/// <summary>
|
||||
/// Handles incoming network data for the option.
|
||||
/// </summary>
|
||||
/// <param name="data">>The byte array representing the network data.</param>
|
||||
void HandleNetData(byte[] data);
|
||||
|
||||
/// <summary>
|
||||
/// Saves the option to a preset configuration file.
|
||||
/// </summary>
|
||||
/// <param name="presetConfig">The ConfigFile representing the preset configuration.</param>
|
||||
/// <param name="saveDefault">Indicates whether to save the default value instead of the current value.</param>
|
||||
void SaveToPreset(ConfigFile presetConfig, bool saveDefault = false);
|
||||
|
||||
/// <summary>
|
||||
/// Binds the option to a configuration file.
|
||||
/// </summary>
|
||||
/// <param name="config">The ConfigFile to bind the option to.</param>
|
||||
void Bind(ConfigFile config);
|
||||
|
||||
/// <summary>
|
||||
/// Loads the option from a preset configuration file, applying the values to the option's configuration.
|
||||
/// </summary>
|
||||
/// <param name="presetConfig">The ConfigFile representing the preset configuration.</param>
|
||||
void LoadFromPreset(ConfigFile presetConfig);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace MiraAPI.GameOptions;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for classes that can be used for option groups.
|
||||
/// </summary>
|
||||
public interface IOptionable;
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using BepInEx.Configuration;
|
||||
@@ -42,10 +43,12 @@ public static class ModdedOptionsManager
|
||||
|
||||
Groups.Add(group);
|
||||
TypeToGroup.Add(type, group);
|
||||
pluginInfo.OptionGroups.Add(group);
|
||||
pluginInfo.InternalOptionGroups.Add(group);
|
||||
|
||||
typeof(OptionGroupSingleton<>).MakeGenericType(type)
|
||||
#pragma warning disable S3011
|
||||
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
|
||||
#pragma warning restore S3011
|
||||
.SetValue(null, group);
|
||||
|
||||
return true;
|
||||
@@ -108,7 +111,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 +122,7 @@ public static class ModdedOptionsManager
|
||||
option.ConfigDefinition = new ConfigDefinition(groupName, propertyName);
|
||||
|
||||
option.ParentMod = pluginInfo.MiraPlugin;
|
||||
option.AdvancedRole = group.AdvancedRole;
|
||||
|
||||
pluginInfo.Options.Add(option);
|
||||
|
||||
pluginInfo.InternalOptions.Add(option);
|
||||
ModdedOptions.Add(option.Id, option);
|
||||
group.Options.Add(option);
|
||||
}
|
||||
@@ -143,7 +143,7 @@ public static class ModdedOptionsManager
|
||||
// we dont know how other plugins handle their configs
|
||||
// this way, all the options are saved at once, instead of one by one
|
||||
var oldConfigSetting = new Dictionary<MiraPluginInfo, bool>();
|
||||
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
|
||||
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins)
|
||||
{
|
||||
oldConfigSetting.Add(plugin, plugin.PluginConfig.SaveOnConfigSet);
|
||||
plugin.PluginConfig.SaveOnConfigSet = false;
|
||||
@@ -159,7 +159,7 @@ public static class ModdedOptionsManager
|
||||
option.HandleNetData(netData.Data);
|
||||
}
|
||||
|
||||
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
|
||||
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins)
|
||||
{
|
||||
plugin.PluginConfig.Save();
|
||||
plugin.PluginConfig.SaveOnConfigSet = oldConfigSetting[plugin];
|
||||
@@ -176,7 +176,10 @@ public static class ModdedOptionsManager
|
||||
/// </summary>
|
||||
/// <param name="__originalMethod">The original setter method.</param>
|
||||
/// <param name="value">The new object value.</param>
|
||||
#pragma warning disable CA1707
|
||||
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")]
|
||||
public static void PropertySetterPatch(MethodBase __originalMethod, object value)
|
||||
#pragma warning restore CA1707
|
||||
{
|
||||
var attribute = OptionAttributes.First(pair => pair.Key.GetSetMethod() == __originalMethod).Value;
|
||||
attribute.SetValue(value);
|
||||
@@ -188,7 +191,10 @@ public static class ModdedOptionsManager
|
||||
/// <param name="__originalMethod">The original getter method.</param>
|
||||
/// <param name="__result">The result of the property getter.</param>
|
||||
/// <returns>False so the original getter gets skipped.</returns>
|
||||
#pragma warning disable CA1707
|
||||
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Harmony naming convention")]
|
||||
public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result)
|
||||
#pragma warning restore CA1707
|
||||
{
|
||||
var attribute = OptionAttributes.First(pair => pair.Key.GetGetMethod() == __originalMethod).Value;
|
||||
__result = attribute.GetValue();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Linq;
|
||||
|
||||
namespace MiraAPI.GameOptions;
|
||||
|
||||
#pragma warning disable CA1852
|
||||
internal class ModifierOptionGroup : AbstractOptionGroup
|
||||
#pragma warning restore CA1852
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ public class ModdedEnumOption : ModdedOption<int>
|
||||
/// <summary>
|
||||
/// Gets the string values of the enum.
|
||||
/// </summary>
|
||||
public string[]? Values { get; }
|
||||
public string[] Values { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ModdedEnumOption"/> class.
|
||||
@@ -27,8 +27,8 @@ 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)
|
||||
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
|
||||
public ModdedEnumOption(string title, int defaultValue, Type enumType, string[]? values = null, bool includeInPreset=true) : base(title, defaultValue, includeInPreset)
|
||||
{
|
||||
Values = values ?? Enum.GetNames(enumType);
|
||||
Data = ScriptableObject.CreateInstance<StringGameSetting>();
|
||||
@@ -38,7 +38,7 @@ public class ModdedEnumOption : ModdedOption<int>
|
||||
data.Type = global::OptionTypes.String;
|
||||
data.Values = values is null ?
|
||||
Enum.GetNames(enumType).Select(CustomStringName.CreateAndRegister).ToArray()
|
||||
: values.Select(CustomStringName.CreateAndRegister).ToArray();
|
||||
: [.. values.Select(CustomStringName.CreateAndRegister)];
|
||||
|
||||
data.Index = Value;
|
||||
}
|
||||
@@ -88,7 +88,7 @@ public class ModdedEnumOption : ModdedOption<int>
|
||||
/// <inheritdoc />
|
||||
protected override void OnValueChanged(int newValue)
|
||||
{
|
||||
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(newValue), false);
|
||||
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(newValue), false);
|
||||
if (!OptionBehaviour)
|
||||
{
|
||||
return;
|
||||
@@ -101,7 +101,6 @@ public class ModdedEnumOption : ModdedOption<int>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// An option for selecting an enum value.
|
||||
/// </summary>
|
||||
@@ -111,17 +110,16 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
|
||||
/// <summary>
|
||||
/// Gets the string values of the enum.
|
||||
/// </summary>
|
||||
public string[]? Values { get; }
|
||||
public string[] Values { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ModdedEnumOption{T}"/> class.
|
||||
/// </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)
|
||||
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
|
||||
public ModdedEnumOption(string title, T defaultValue, string[]? values = null, bool includeInPreset=true) : base(title, defaultValue, includeInPreset)
|
||||
{
|
||||
Values = values ?? Enum.GetNames(typeof(T));
|
||||
Data = ScriptableObject.CreateInstance<StringGameSetting>();
|
||||
@@ -131,9 +129,9 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
|
||||
data.Type = global::OptionTypes.String;
|
||||
data.Values = values is null ?
|
||||
Enum.GetNames(typeof(T)).Select(CustomStringName.CreateAndRegister).ToArray()
|
||||
: values.Select(CustomStringName.CreateAndRegister).ToArray();
|
||||
: [.. values.Select(CustomStringName.CreateAndRegister)];
|
||||
|
||||
data.Index = Convert.ToInt32(Value);
|
||||
data.Index = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -147,7 +145,7 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
|
||||
// SetUpFromData method doesnt work correctly so we must set the values manually
|
||||
stringOption.Title = StringName;
|
||||
stringOption.Values = (Data as StringGameSetting)?.Values ?? new Il2CppStructArray<StringNames>(0);
|
||||
stringOption.Value = Convert.ToInt32(Value);
|
||||
stringOption.Value = Convert.ToInt32(Value, NumberFormatInfo.InvariantInfo);
|
||||
|
||||
OptionBehaviour = stringOption;
|
||||
|
||||
@@ -157,13 +155,13 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
|
||||
/// <inheritdoc />
|
||||
public override float GetFloatData()
|
||||
{
|
||||
return Convert.ToSingle(Value);
|
||||
return Convert.ToSingle(Value, NumberFormatInfo.InvariantInfo);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override NetData GetNetData()
|
||||
{
|
||||
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value)));
|
||||
return new NetData(Id, Encoding.Unicode.GetBytes(Convert.ToString(Value, NumberFormatInfo.InvariantInfo)!));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -175,13 +173,13 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
|
||||
/// <inheritdoc />
|
||||
public override T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour)
|
||||
{
|
||||
return (T)Enum.Parse(typeof(T), optionBehaviour.GetInt().ToString());
|
||||
return (T)Enum.Parse(typeof(T), optionBehaviour.GetInt().ToString(NumberFormatInfo.InvariantInfo));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnValueChanged(T newValue)
|
||||
{
|
||||
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(Convert.ToInt32(newValue)), false);
|
||||
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo)), false);
|
||||
if (!OptionBehaviour)
|
||||
{
|
||||
return;
|
||||
@@ -189,7 +187,7 @@ public class ModdedEnumOption<T> : ModdedOption<T> where T : Enum
|
||||
|
||||
if (OptionBehaviour is StringOption opt)
|
||||
{
|
||||
opt.Value = Convert.ToInt32(newValue);
|
||||
opt.Value = Convert.ToInt32(newValue, NumberFormatInfo.InvariantInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
using AmongUs.GameOptions;
|
||||
using System;
|
||||
using AmongUs.GameOptions;
|
||||
using MiraAPI.Networking;
|
||||
using MiraAPI.Utilities;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
@@ -48,7 +48,7 @@ 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>
|
||||
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
|
||||
public ModdedNumberOption(
|
||||
string title,
|
||||
float defaultValue,
|
||||
@@ -58,7 +58,7 @@ public class ModdedNumberOption : ModdedOption<float>
|
||||
MiraNumberSuffixes suffixType,
|
||||
string? formatString = null,
|
||||
bool zeroInfinity = false,
|
||||
Type? roleType = null) : base(title, defaultValue, roleType)
|
||||
bool includeInPreset = true) : base(title, defaultValue, includeInPreset)
|
||||
{
|
||||
Min = min;
|
||||
Max = max;
|
||||
@@ -77,11 +77,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 +144,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)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
using BepInEx.Configuration;
|
||||
using System;
|
||||
using BepInEx.Configuration;
|
||||
using MiraAPI.Networking;
|
||||
using MiraAPI.PluginLoading;
|
||||
using MiraAPI.Roles;
|
||||
using Reactor.Localization.Utilities;
|
||||
using Reactor.Networking.Rpc;
|
||||
using System;
|
||||
using Reactor.Utilities;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.GameOptions.OptionTypes;
|
||||
@@ -17,29 +17,19 @@ public abstract class ModdedOption<T> : IModdedOption
|
||||
{
|
||||
private IMiraPlugin? _parentMod;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the unique identifier of the option.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public uint Id { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the option.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public string Title { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the StringName object of the option.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public StringNames StringName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the BaseGameSetting data of the option.
|
||||
/// </summary>
|
||||
public BaseGameSetting Data { get; protected init; }
|
||||
/// <inheritdoc />
|
||||
public BaseGameSetting Data { get; protected set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the parent mod of the option.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public IMiraPlugin? ParentMod
|
||||
{
|
||||
get => _parentMod;
|
||||
@@ -67,43 +57,25 @@ public abstract class ModdedOption<T> : IModdedOption
|
||||
/// </summary>
|
||||
public Action<T>? ChangedEvent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the visibility of the option.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public Func<bool> Visible { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the advanced role of the option.
|
||||
/// </summary>
|
||||
public Type? AdvancedRole { get; set; }
|
||||
/// <inheritdoc />
|
||||
public bool IncludeInPreset { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the option behaviour of the option.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public OptionBehaviour? OptionBehaviour { get; protected set; }
|
||||
|
||||
/// <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;
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
/// <param name="includeInPreset">Whether to include the option in the preset.</param>
|
||||
protected ModdedOption(string title, T defaultValue, bool includeInPreset = true)
|
||||
{
|
||||
Id = ModdedOptionsManager.NextId;
|
||||
Title = title;
|
||||
@@ -111,11 +83,7 @@ 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;
|
||||
}
|
||||
IncludeInPreset = includeInPreset;
|
||||
}
|
||||
|
||||
internal void ValueChanged(OptionBehaviour optionBehaviour)
|
||||
@@ -127,7 +95,8 @@ public abstract class ModdedOption<T> : IModdedOption
|
||||
/// Sets the value of the option.
|
||||
/// </summary>
|
||||
/// <param name="newValue">The new value.</param>
|
||||
public void SetValue(T newValue)
|
||||
/// <param name="sendRpc">Whether to send the value to other players.</param>
|
||||
public void SetValue(T newValue, bool sendRpc = true)
|
||||
{
|
||||
var oldVal = Value;
|
||||
Value = newValue;
|
||||
@@ -137,7 +106,7 @@ public abstract class ModdedOption<T> : IModdedOption
|
||||
ChangedEvent?.Invoke(Value);
|
||||
}
|
||||
|
||||
if (AmongUsClient.Instance.AmHost)
|
||||
if (sendRpc && AmongUsClient.Instance.AmHost)
|
||||
{
|
||||
if (ParentMod?.GetConfigFile().TryGetEntry<T>(ConfigDefinition, out var entry) == true)
|
||||
{
|
||||
@@ -150,22 +119,44 @@ public abstract class ModdedOption<T> : IModdedOption
|
||||
OnValueChanged(newValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the float data of the option.
|
||||
/// </summary>
|
||||
/// <returns>A float object representing the option's value.</returns>
|
||||
/// <inheritdoc />
|
||||
public void SaveToPreset(ConfigFile presetConfig, bool saveDefault=false)
|
||||
{
|
||||
if (ConfigDefinition is null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Attempted to save {Title} to preset, but ConfigDefinition is null.");
|
||||
return;
|
||||
}
|
||||
Bind(presetConfig);
|
||||
presetConfig[ConfigDefinition].BoxedValue = saveDefault ? DefaultValue : Value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Bind(ConfigFile config)
|
||||
{
|
||||
config.Bind(ConfigDefinition, DefaultValue);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void LoadFromPreset(ConfigFile presetConfig)
|
||||
{
|
||||
if (presetConfig.TryGetEntry(ConfigDefinition, out ConfigEntry<T> entry))
|
||||
{
|
||||
SetValue(entry.Value, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Attempted to load {Title} from preset, but ConfigDefinition is not found in preset.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public abstract float GetFloatData();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the net data of the option.
|
||||
/// </summary>
|
||||
/// <returns>A NetData object representing this option's data.</returns>
|
||||
/// <inheritdoc />
|
||||
public abstract NetData GetNetData();
|
||||
|
||||
/// <summary>
|
||||
/// Handles incoming net data.
|
||||
/// </summary>
|
||||
/// <param name="data">The NetData's byte array.</param>
|
||||
/// <inheritdoc />
|
||||
public abstract void HandleNetData(byte[] data);
|
||||
|
||||
/// <summary>
|
||||
@@ -181,14 +172,7 @@ public abstract class ModdedOption<T> : IModdedOption
|
||||
/// <returns>The value.</returns>
|
||||
public abstract T GetValueFromOptionBehaviour(OptionBehaviour optionBehaviour);
|
||||
|
||||
/// <summary>
|
||||
/// Creates the option behaviour.
|
||||
/// </summary>
|
||||
/// <param name="toggleOpt">The ToggleOption prefab.</param>
|
||||
/// <param name="numberOpt">The NumberOption prefab.</param>
|
||||
/// <param name="stringOpt">The StringOption prefab.</param>
|
||||
/// <param name="container">The options container.</param>
|
||||
/// <returns>A new OptionBehaviour for this modded option.</returns>
|
||||
/// <inheritdoc />
|
||||
public abstract OptionBehaviour CreateOption(
|
||||
ToggleOption toggleOpt,
|
||||
NumberOption numberOpt,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using MiraAPI.Networking;
|
||||
using System;
|
||||
using System;
|
||||
using MiraAPI.Networking;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
@@ -15,8 +15,8 @@ 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)
|
||||
/// <param name="includeInPreset">Whether to include this option in the preset or not.</param>
|
||||
public ModdedToggleOption(string title, bool defaultValue, bool includeInPreset=true) : base(title, defaultValue, includeInPreset)
|
||||
{
|
||||
Data = ScriptableObject.CreateInstance<CheckboxGameSetting>();
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using MiraAPI.Events;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Mira;
|
||||
using MiraAPI.Patches;
|
||||
using MiraAPI.Utilities;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
using UnityEngine.UI;
|
||||
@@ -35,6 +37,11 @@ public abstract class CustomActionButton
|
||||
/// </summary>
|
||||
public abstract LoadableAsset<Sprite> Sprite { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the format string for the cooldown timer.
|
||||
/// </summary>
|
||||
public virtual string CooldownTimerFormatString => "0";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the button's effect duration in seconds. If the button has no effect, set to 0.
|
||||
/// </summary>
|
||||
@@ -46,9 +53,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.
|
||||
@@ -63,27 +75,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.
|
||||
@@ -113,6 +125,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)(() =>
|
||||
@@ -157,7 +174,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)
|
||||
@@ -167,9 +184,12 @@ public abstract class CustomActionButton
|
||||
|
||||
this.Location = location;
|
||||
|
||||
if (!moveButton) return;
|
||||
if (!moveButton)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (HudManagerPatches._bottomLeft == null || HudManagerPatches._bottomRight == null)
|
||||
if (HudManagerPatches.BottomLeft == null || HudManagerPatches.BottomRight == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -177,17 +197,17 @@ public abstract class CustomActionButton
|
||||
switch (location)
|
||||
{
|
||||
case ButtonLocation.BottomLeft:
|
||||
var gridArrange = HudManagerPatches._bottomLeft.GetComponent<GridArrange>();
|
||||
var aspectPosition = HudManagerPatches._bottomLeft.GetComponent<AspectPosition>();
|
||||
var gridArrange = HudManagerPatches.BottomLeft.GetComponent<GridArrange>();
|
||||
var aspectPosition = HudManagerPatches.BottomLeft.GetComponent<AspectPosition>();
|
||||
|
||||
Button.transform.SetParent(HudManagerPatches._bottomLeft.transform);
|
||||
Button.transform.SetParent(HudManagerPatches.BottomLeft.transform);
|
||||
|
||||
gridArrange.Start();
|
||||
gridArrange.ArrangeChilds();
|
||||
aspectPosition.AdjustPosition();
|
||||
break;
|
||||
case ButtonLocation.BottomRight:
|
||||
Button.transform.SetParent(HudManagerPatches._bottomRight);
|
||||
Button.transform.SetParent(HudManagerPatches.BottomRight);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -206,6 +226,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>
|
||||
@@ -343,7 +372,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>
|
||||
@@ -397,9 +426,12 @@ public abstract class CustomActionButton
|
||||
/// <param name="playerControl">The local PlayerControl.</param>
|
||||
public virtual void FixedUpdateHandler(PlayerControl playerControl)
|
||||
{
|
||||
if (Timer >= 0 && !TimerPaused)
|
||||
if (Timer >= 0)
|
||||
{
|
||||
Timer -= Time.deltaTime;
|
||||
if (!TimerPaused)
|
||||
{
|
||||
Timer -= Time.deltaTime;
|
||||
}
|
||||
}
|
||||
else if (HasEffect && EffectActive)
|
||||
{
|
||||
@@ -408,25 +440,28 @@ public abstract class CustomActionButton
|
||||
OnEffectEnd();
|
||||
}
|
||||
|
||||
if (CanUse())
|
||||
if (Button)
|
||||
{
|
||||
Button?.SetEnabled();
|
||||
}
|
||||
else
|
||||
{
|
||||
Button?.SetDisabled();
|
||||
}
|
||||
if (CanUse())
|
||||
{
|
||||
Button!.SetEnabled();
|
||||
}
|
||||
else
|
||||
{
|
||||
Button!.SetDisabled();
|
||||
}
|
||||
|
||||
if (EffectActive)
|
||||
{
|
||||
Button?.SetFillUp(Timer, EffectDuration);
|
||||
if (EffectActive)
|
||||
{
|
||||
Button.SetFillUp(Timer, EffectDuration);
|
||||
|
||||
Button!.cooldownTimerText.text = Mathf.CeilToInt(Timer).ToString();
|
||||
Button!.cooldownTimerText.gameObject.SetActive(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Button?.SetCoolDown(Timer, Cooldown);
|
||||
Button.cooldownTimerText.text = Timer.ToString(CooldownTimerFormatString, NumberFormatInfo.InvariantInfo);
|
||||
Button.cooldownTimerText.gameObject.SetActive(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Button.SetCooldownFormat(Timer, Cooldown, CooldownTimerFormatString);
|
||||
}
|
||||
}
|
||||
|
||||
FixedUpdate(playerControl);
|
||||
@@ -442,7 +477,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.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using MiraAPI.Events.Mira;
|
||||
using MiraAPI.PluginLoading;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Reflection;
|
||||
using MiraAPI.Events.Mira;
|
||||
using MiraAPI.PluginLoading;
|
||||
|
||||
namespace MiraAPI.Hud;
|
||||
|
||||
@@ -29,9 +29,11 @@ public static class CustomButtonManager
|
||||
}
|
||||
|
||||
CustomButtons.Add(button);
|
||||
pluginInfo.Buttons.Add(button);
|
||||
pluginInfo.InternalButtons.Add(button);
|
||||
typeof(CustomButtonSingleton<>).MakeGenericType(buttonType)
|
||||
#pragma warning disable S3011
|
||||
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
|
||||
#pragma warning restore S3011
|
||||
.SetValue(null, button);
|
||||
|
||||
ButtonEventTypes.Add(buttonType, typeof(MiraButtonClickEvent<>).MakeGenericType(buttonType));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Linq;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
|
||||
namespace MiraAPI.Hud;
|
||||
|
||||
@@ -13,7 +14,6 @@ public static class CustomButtonSingleton<T> where T : CustomActionButton
|
||||
/// <summary>
|
||||
/// Gets the instance of the button.
|
||||
/// </summary>
|
||||
#pragma warning disable CA1000
|
||||
[SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "This is a utility class to get the instance of a custom action button.")]
|
||||
public static T Instance => _instance ??= CustomButtonManager.CustomButtons.OfType<T>().Single();
|
||||
#pragma warning restore CA1000
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
using AmongUs.GameOptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using AmongUs.GameOptions;
|
||||
using Il2CppInterop.Runtime.Attributes;
|
||||
using MiraAPI.Patches.Stubs;
|
||||
using Reactor.Utilities.Attributes;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
|
||||
|
||||
namespace MiraAPI.Hud;
|
||||
|
||||
@@ -16,22 +19,18 @@ namespace MiraAPI.Hud;
|
||||
/// </summary>
|
||||
/// <param name="il2CppPtr">Used by Il2Cpp. Do not use constructor, this is a MonoBehaviour.</param>
|
||||
[RegisterInIl2Cpp]
|
||||
[SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = "Unity Convention")]
|
||||
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Unity Convention")]
|
||||
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Unity Convention")]
|
||||
public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
|
||||
{
|
||||
public ShapeshifterPanel PanelPrefab;
|
||||
|
||||
public float XStart = -0.8f;
|
||||
|
||||
public float YStart = 2.15f;
|
||||
|
||||
public float XOffset = 1.95f;
|
||||
|
||||
public float YOffset = -0.65f;
|
||||
|
||||
public UiElement BackButton;
|
||||
|
||||
public UiElement DefaultButtonSelected;
|
||||
|
||||
public ShapeshifterPanel panelPrefab;
|
||||
public float xStart = -0.8f;
|
||||
public float yStart = 2.15f;
|
||||
public float xOffset = 1.95f;
|
||||
public float yOffset = -0.65f;
|
||||
public UiElement backButton;
|
||||
public UiElement defaultButtonSelected;
|
||||
public List<ShapeshifterPanel> potentialVictims;
|
||||
|
||||
/// <summary>
|
||||
@@ -42,17 +41,17 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
|
||||
{
|
||||
var shapeShifterRole = RoleManager.Instance.GetRole(RoleTypes.Shapeshifter);
|
||||
|
||||
var ogMenu = shapeShifterRole.TryCast<ShapeshifterRole>().ShapeshifterMenu;
|
||||
var ogMenu = shapeShifterRole.TryCast<ShapeshifterRole>()!.ShapeshifterMenu;
|
||||
var newMenu = Instantiate(ogMenu);
|
||||
var customMenu = newMenu.gameObject.AddComponent<CustomPlayerMenu>();
|
||||
|
||||
customMenu.PanelPrefab = newMenu.PanelPrefab;
|
||||
customMenu.XStart = newMenu.XStart;
|
||||
customMenu.YStart = newMenu.YStart;
|
||||
customMenu.XOffset = newMenu.XOffset;
|
||||
customMenu.YOffset = newMenu.YOffset;
|
||||
customMenu.BackButton = newMenu.BackButton;
|
||||
var back = customMenu.BackButton.GetComponent<PassiveButton>();
|
||||
customMenu.panelPrefab = newMenu.PanelPrefab;
|
||||
customMenu.xStart = newMenu.XStart;
|
||||
customMenu.yStart = newMenu.YStart;
|
||||
customMenu.xOffset = newMenu.XOffset;
|
||||
customMenu.yOffset = newMenu.YOffset;
|
||||
customMenu.backButton = newMenu.BackButton;
|
||||
var back = customMenu.backButton.GetComponent<PassiveButton>();
|
||||
back.OnClick.RemoveAllListeners();
|
||||
back.OnClick.AddListener((UnityAction)(() =>
|
||||
{
|
||||
@@ -65,7 +64,7 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
|
||||
|
||||
newMenu.DestroyImmediate();
|
||||
|
||||
customMenu.transform.SetParent(Camera.main.transform, false);
|
||||
customMenu.transform.SetParent(Camera.main!.transform, false);
|
||||
customMenu.transform.localPosition = new Vector3(0f, 0f, -50f);
|
||||
return customMenu;
|
||||
}
|
||||
@@ -75,6 +74,7 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
|
||||
ControllerManager.Instance.CloseOverlayMenu(name);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Begin(PlayerTask task)
|
||||
{
|
||||
throw new NotImplementedException("Use the other Begin method.");
|
||||
@@ -90,7 +90,7 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
|
||||
{
|
||||
MinigameStubs.Begin(this, null);
|
||||
|
||||
var back = BackButton.GetComponent<PassiveButton>();
|
||||
var back = backButton.GetComponent<PassiveButton>();
|
||||
back.OnClick.AddListener((UnityAction)(() =>
|
||||
{
|
||||
onClick(null);
|
||||
@@ -107,13 +107,13 @@ public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
|
||||
var num = i % 3;
|
||||
var num2 = i / 3;
|
||||
var flag = PlayerControl.LocalPlayer.Data.Role.NameColor == player.Data.Role.NameColor;
|
||||
var shapeshifterPanel = Instantiate(PanelPrefab, transform);
|
||||
shapeshifterPanel.transform.localPosition = new Vector3(XStart + num * XOffset, YStart + num2 * YOffset, -1f);
|
||||
var shapeshifterPanel = Instantiate(panelPrefab, transform);
|
||||
shapeshifterPanel.transform.localPosition = new Vector3(xStart + num * xOffset, yStart + num2 * yOffset, -1f);
|
||||
shapeshifterPanel.SetPlayer(i, player.Data, (Il2CppSystem.Action)(() => { onClick(player); }));
|
||||
shapeshifterPanel.NameText.color = flag ? player.Data.Role.NameColor : Color.white;
|
||||
potentialVictims.Add(shapeshifterPanel);
|
||||
list2.Add(shapeshifterPanel.Button);
|
||||
}
|
||||
ControllerManager.Instance.OpenOverlayMenu(name, BackButton, DefaultButtonSelected, list2);
|
||||
ControllerManager.Instance.OpenOverlayMenu(name, backButton, defaultButtonSelected, list2);
|
||||
}
|
||||
}
|
||||
@@ -10,17 +10,30 @@ using UnityEngine;
|
||||
|
||||
namespace MiraAPI;
|
||||
|
||||
/// <summary>
|
||||
/// The main plugin class for Mira API.
|
||||
/// </summary>
|
||||
[BepInAutoPlugin("mira.api", "MiraAPI")]
|
||||
[BepInProcess("Among Us.exe")]
|
||||
[BepInDependency(ReactorPlugin.Id)]
|
||||
[BepInDependency(ModCompatibility.SubmergedId, BepInDependency.DependencyFlags.SoftDependency)]
|
||||
[ReactorModFlags(ModFlags.RequireOnAllClients)]
|
||||
public partial class MiraApiPlugin : BasePlugin
|
||||
{
|
||||
private static MiraPluginManager? PluginManager { get; set; }
|
||||
|
||||
public Harmony Harmony { get; } = new(Id);
|
||||
/// <summary>
|
||||
/// Gets the branding Mira API color.
|
||||
/// </summary>
|
||||
public static Color MiraColor { get; } = new Color32(238, 154, 112, 255);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the default color for headers in the options menu.
|
||||
/// </summary>
|
||||
public static Color DefaultHeaderColor { get; } = new Color32(77, 77, 77, 255);
|
||||
|
||||
private static MiraPluginManager? PluginManager { get; set; }
|
||||
internal Harmony Harmony { get; } = new(Id);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Load()
|
||||
{
|
||||
Harmony.PatchAll();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using BepInEx.Unity.IL2CPP;
|
||||
|
||||
namespace MiraAPI;
|
||||
|
||||
/// <summary>
|
||||
/// Mod compatibility tools.
|
||||
/// </summary>
|
||||
public static class ModCompatibility
|
||||
{
|
||||
/// <summary>
|
||||
/// The ID for the Submerged mod.
|
||||
/// </summary>
|
||||
public const string SubmergedId = "Submerged";
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the Submerged mod is loaded.
|
||||
/// </summary>
|
||||
/// <param name="submergedAssembly">Submerged mod assembly if loaded, null otherwise.</param>
|
||||
/// <returns>True if the Submerged mod is loaded, false otherwise.</returns>
|
||||
public static bool SubmergedLoaded([NotNullWhen(true)] out Assembly? submergedAssembly)
|
||||
{
|
||||
var result = IL2CPPChainloader.Instance.Plugins.TryGetValue(SubmergedId, out var plugin);
|
||||
submergedAssembly = result ? plugin?.Instance.GetType().Assembly : null;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -1,14 +1,20 @@
|
||||
namespace MiraAPI.Modifiers;
|
||||
using System;
|
||||
using MiraAPI.GameOptions;
|
||||
using MiraAPI.PluginLoading;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using UnityEngine;
|
||||
|
||||
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.
|
||||
@@ -16,9 +22,27 @@ public abstract class BaseModifier
|
||||
public ModifierComponent? ModifierComponent { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the modifier id.
|
||||
/// Gets a value indicating whether the modifier has been initialized.
|
||||
/// </summary>
|
||||
public uint ModifierId { get; internal set; }
|
||||
public bool Initialized { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the unique ID of the modifier.
|
||||
/// </summary>
|
||||
public Guid UniqueId { get; internal set; } = Guid.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type ID of the modifier.
|
||||
/// </summary>
|
||||
public uint TypeId => ModifierManager.GetModifierTypeId(GetType()) ?? throw new InvalidOperationException("Modifier is not registered.");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the parent mod of the modifier.
|
||||
/// </summary>
|
||||
public MiraPluginInfo ParentMod => Array.Find(
|
||||
MiraPluginManager.Instance.RegisteredPlugins,
|
||||
x => x.InternalModifiers.Exists(y => y.TypeId == TypeId)
|
||||
) ?? throw new InvalidOperationException("Modifier is not registered.");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the modifier name.
|
||||
@@ -26,15 +50,30 @@ public abstract class BaseModifier
|
||||
public abstract string ModifierName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the modifier is hidden on the UI.
|
||||
/// Gets the modifier icon. Useless if HideOnUi is true.
|
||||
/// </summary>
|
||||
public virtual bool HideOnUi => false;
|
||||
public virtual LoadableAsset<Sprite>? ModifierIcon => null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HUD information for this modifier. Defaults to the modifier name. Does nothing if <see cref="HideOnUi"/> is true.
|
||||
/// Gets a value indicating whether the modifier is hidden on the UI. Will be hidden either way if no description is provided.
|
||||
/// </summary>
|
||||
/// <returns>The information string for the HUD.</returns>
|
||||
public virtual string GetHudString() => ModifierName;
|
||||
public virtual bool HideOnUi => GetDescription() == string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the modifier is shown in the freeplay menu.
|
||||
/// </summary>
|
||||
public virtual bool ShowInFreeplay => false;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the modifier is unique. If true, the player can only have one instance of this modifier.
|
||||
/// </summary>
|
||||
public virtual bool Unique => true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HUD description for this modifier. Does nothing if <see cref="HideOnUi"/> is true. Required to be visible on UI.
|
||||
/// </summary>
|
||||
/// <returns>The description string for the HUD.</returns>
|
||||
public virtual string GetDescription() => string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Called when the modifier is activated.
|
||||
@@ -72,6 +111,13 @@ public abstract class BaseModifier
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when a meeting starts.
|
||||
/// </summary>
|
||||
public virtual void OnMeetingStart()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the player can vent.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
using Il2CppInterop.Runtime.Attributes;
|
||||
using MiraAPI.Modifiers.Types;
|
||||
using MiraAPI.Utilities;
|
||||
using Reactor.Utilities;
|
||||
using Reactor.Utilities.Attributes;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using TMPro;
|
||||
using Il2CppInterop.Runtime.Attributes;
|
||||
using MiraAPI.Modifiers.ModifierDisplay;
|
||||
using MiraAPI.Modifiers.Types;
|
||||
using Reactor.Utilities;
|
||||
using Reactor.Utilities.Attributes;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Modifiers;
|
||||
@@ -24,14 +22,14 @@ 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;
|
||||
|
||||
private ModifierDisplayComponent? ModifierDisplay { get; set; }
|
||||
|
||||
[HideFromIl2Cpp]
|
||||
private List<BaseModifier> Modifiers { get; set; } = [];
|
||||
|
||||
private PlayerControl? _player;
|
||||
|
||||
private TextMeshPro? _modifierText;
|
||||
private PlayerControl _player = null!;
|
||||
|
||||
private readonly List<BaseModifier> _toRemove = [];
|
||||
|
||||
@@ -42,9 +40,18 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
|
||||
_toRemove.AddRange(Modifiers);
|
||||
}
|
||||
|
||||
private void Start()
|
||||
private void Awake()
|
||||
{
|
||||
_player = GetComponent<PlayerControl>();
|
||||
if (_player == null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("ModifierComponent could not find PlayerControl on the same GameObject.");
|
||||
Destroy(this);
|
||||
return;
|
||||
}
|
||||
|
||||
ModifierExtensions.ModifierComponents.Add(_player, this);
|
||||
|
||||
Modifiers = [];
|
||||
|
||||
if (!_player.AmOwner)
|
||||
@@ -52,22 +59,42 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
|
||||
return;
|
||||
}
|
||||
|
||||
_modifierText = Helpers.CreateTextLabel("ModifierText", HudManager.Instance.transform, AspectPosition.EdgeAlignments.RightTop, new Vector3(10.1f, 3.5f, 0), textAlignment: TextAlignmentOptions.Right);
|
||||
_modifierText.verticalAlignment = VerticalAlignmentOptions.Top;
|
||||
ModifierDisplay = ModifierDisplayComponent.CreateDisplay();
|
||||
ModifierDisplay?.UpdateModifiersList(Modifiers);
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
foreach (var modifier in _toRemove)
|
||||
var removed = _toRemove.Count > 0;
|
||||
foreach (var modifier in _toRemove.ToArray())
|
||||
{
|
||||
modifier.OnDeactivate();
|
||||
_toRemove.Remove(modifier);
|
||||
try
|
||||
{
|
||||
modifier.OnDeactivate();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Error while deactivating modifier {modifier.ModifierName}: {e.ToString()}");
|
||||
}
|
||||
|
||||
Modifiers.Remove(modifier);
|
||||
}
|
||||
|
||||
foreach (var modifier in _toAdd)
|
||||
var added = _toAdd.Count > 0;
|
||||
foreach (var modifier in _toAdd.ToArray())
|
||||
{
|
||||
_toAdd.Remove(modifier);
|
||||
Modifiers.Add(modifier);
|
||||
modifier.OnActivate();
|
||||
modifier.Initialized = true;
|
||||
try
|
||||
{
|
||||
modifier.OnActivate();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Error while activating modifier {modifier.ModifierName}: {e.ToString()}");
|
||||
}
|
||||
|
||||
if (modifier is TimedModifier { AutoStart: true } timer)
|
||||
{
|
||||
@@ -75,93 +102,228 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
|
||||
}
|
||||
}
|
||||
|
||||
if (_toAdd.Count > 0 || _toRemove.Count > 0)
|
||||
if (removed || added)
|
||||
{
|
||||
if (_player?.AmOwner == true)
|
||||
if (_player.AmOwner && HudManager.InstanceExists)
|
||||
{
|
||||
HudManager.Instance?.SetHudActive(_player, _player.Data.Role, HudManager.Instance.TaskPanel.isActiveAndEnabled);
|
||||
ModifierDisplay?.UpdateModifiersList(Modifiers);
|
||||
}
|
||||
_toAdd.Clear();
|
||||
_toRemove.Clear();
|
||||
|
||||
ActiveModifiers = Modifiers.ToImmutableList();
|
||||
}
|
||||
|
||||
foreach (var modifier in Modifiers)
|
||||
foreach (var modifier in ActiveModifiers)
|
||||
{
|
||||
modifier.FixedUpdate();
|
||||
try
|
||||
{
|
||||
modifier.FixedUpdate();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Error while (fixed) updating modifier {modifier.ModifierName}: {e.ToString()}");
|
||||
}
|
||||
}
|
||||
|
||||
if (_player.AmOwner && ModifierDisplay && HudManager.InstanceExists)
|
||||
{
|
||||
ModifierDisplay!.gameObject.SetActive(MeetingHud.Instance || HudManager.Instance.TaskPanel.isActiveAndEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
foreach (var modifier in Modifiers)
|
||||
foreach (var modifier in ActiveModifiers)
|
||||
{
|
||||
modifier.Update();
|
||||
}
|
||||
|
||||
if (!_modifierText || _player?.AmOwner == false)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var filteredModifiers = Modifiers.Where(mod => !mod.HideOnUi);
|
||||
|
||||
var baseModifiers = filteredModifiers as BaseModifier[] ?? filteredModifiers.ToArray();
|
||||
|
||||
if (baseModifiers.Length != 0 && !MeetingHud.Instance)
|
||||
{
|
||||
var stringBuild = new StringBuilder();
|
||||
foreach (var mod in baseModifiers)
|
||||
try
|
||||
{
|
||||
stringBuild.Append(CultureInfo.InvariantCulture, $"\n{mod.GetHudString()}");
|
||||
modifier.Update();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Error while updating modifier {modifier.ModifierName}: {e.ToString()}");
|
||||
}
|
||||
_modifierText!.text = $"<b><size=130%>Modifiers:</b></size>{stringBuild}";
|
||||
}
|
||||
else if (_modifierText!.text != string.Empty)
|
||||
{
|
||||
_modifierText.text = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
// Remove this component from the global list when destroyed
|
||||
ModifierExtensions.ModifierComponents.Remove(_player);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a modifier from the player.
|
||||
/// Gets a collection of modifiers by type.
|
||||
/// </summary>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <typeparam name="T">The Type of the Modifier.</typeparam>
|
||||
/// <returns>A collection of modifiers.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public IEnumerable<T> GetModifiers<T>(Func<T, bool>? predicate=null) where T : BaseModifier
|
||||
{
|
||||
return ActiveModifiers.OfType<T>().Where(x => predicate == null || predicate(x));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a collection of modifiers by type.
|
||||
/// </summary>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>A collection of modifiers.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public void RemoveModifier(Type type)
|
||||
public IEnumerable<BaseModifier> GetModifiers(Type type, Func<BaseModifier, bool>? predicate=null)
|
||||
{
|
||||
var modifier = Modifiers.Find(x => x.GetType() == type);
|
||||
return ActiveModifiers.Where(x => x.GetType() == type && (predicate == null || predicate(x)));
|
||||
}
|
||||
|
||||
if (modifier is null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Cannot remove modifier {type.Name} because it is not active.");
|
||||
return;
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets a collection of modifiers by type ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The modifier's type ID.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>A collection of modifiers.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public IEnumerable<BaseModifier> GetModifiers(uint id, Func<BaseModifier, bool>? predicate=null)
|
||||
{
|
||||
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
|
||||
$"Cannot get modifier with id {id} because it is not registered.");
|
||||
|
||||
RemoveModifier(modifier);
|
||||
return GetModifiers(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <typeparam name="T">The Type of the Modifier.</typeparam>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool TryGetModifier<T>([NotNullWhen(true)] out T? modifier, Func<T, bool>? predicate = null) where T : BaseModifier
|
||||
{
|
||||
modifier = GetModifier(predicate);
|
||||
return modifier != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool TryGetModifier(Type type, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
modifier = GetModifier(type, predicate);
|
||||
return modifier != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a modifier by its type ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The modifier type ID.</param>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool TryGetModifier(uint id, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
modifier = GetModifier(id, predicate);
|
||||
return modifier != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a modifier by its unique ID.
|
||||
/// </summary>
|
||||
/// <param name="modifierGuid">The modifier unique ID.</param>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool TryGetModifier(Guid modifierGuid, [NotNullWhen(true)] out BaseModifier? modifier)
|
||||
{
|
||||
modifier = GetModifier(modifierGuid);
|
||||
return modifier != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <typeparam name="T">The Type of the Modifier.</typeparam>
|
||||
/// <returns>The Modifier if it is found, null otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public T? GetModifier<T>(Func<T, bool>? predicate = null) where T : BaseModifier
|
||||
{
|
||||
return GetModifiers(predicate).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>The Modifier if it is found, null otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public BaseModifier? GetModifier(Type type, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return GetModifiers(type).FirstOrDefault(predicate ?? (_ => true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a modifier by its type ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The modifier ID.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>The Modifier if it is found, null otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public BaseModifier? GetModifier(uint id, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
|
||||
$"Cannot get modifier with id {id} because it is not registered.");
|
||||
|
||||
return GetModifier(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a modifier by unique ID.
|
||||
/// </summary>
|
||||
/// <param name="modifierGuid">The modifier's unique ID.</param>
|
||||
/// <returns>The modifier if it is found, or null.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public BaseModifier? GetModifier(Guid modifierGuid)
|
||||
{
|
||||
return ActiveModifiers.Find(x => x.UniqueId == modifierGuid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a modifier from the player.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The modifier type.</typeparam>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
[HideFromIl2Cpp]
|
||||
public void RemoveModifier<T>() where T : BaseModifier
|
||||
public void RemoveModifier<T>(Func<T, bool>? predicate = null) where T : BaseModifier
|
||||
{
|
||||
RemoveModifier(typeof(T));
|
||||
RemoveModifier(typeof(T), x => predicate == null || predicate((T)x));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a modifier from the player.
|
||||
/// </summary>
|
||||
/// <param name="modifierId">The modifier ID.</param>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
[HideFromIl2Cpp]
|
||||
public void RemoveModifier(uint modifierId)
|
||||
public void RemoveModifier(Type type, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
var modifier = Modifiers.Find(x => x.ModifierId == modifierId);
|
||||
var modifiers = 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.");
|
||||
}
|
||||
|
||||
var modifier = modifiers.FirstOrDefault();
|
||||
if (modifier is null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Cannot remove modifier with id {modifierId} because it is not active.");
|
||||
Logger<MiraApiPlugin>.Error($"Cannot remove modifier {type.Name} because it is not active.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -175,7 +337,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;
|
||||
@@ -184,6 +346,48 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
|
||||
_toRemove.Add(modifier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a modifier from the player.
|
||||
/// </summary>
|
||||
/// <param name="typeId">The modifier's type ID.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
[HideFromIl2Cpp]
|
||||
public void RemoveModifier(uint typeId, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
var type = ModifierManager.GetModifierType(typeId) ?? throw new InvalidOperationException(
|
||||
$"Cannot remove modifier with id {typeId} because it is not registered.");
|
||||
RemoveModifier(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a modifier from the player.
|
||||
/// </summary>
|
||||
/// <param name="uniqueId">The modifier's unique ID.</param>
|
||||
[HideFromIl2Cpp]
|
||||
public void RemoveModifier(Guid uniqueId)
|
||||
{
|
||||
var modifier = GetModifier(uniqueId);
|
||||
if (modifier == null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Cannot remove modifier with unique id {uniqueId} because it is not active.");
|
||||
return;
|
||||
}
|
||||
|
||||
RemoveModifier(modifier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a modifier to the player.
|
||||
/// </summary>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
/// <typeparam name="T">The Type of the modifier.</typeparam>
|
||||
/// <returns>The new modifier.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public T? AddModifier<T>(params object[] args) where T : BaseModifier
|
||||
{
|
||||
return AddModifier(typeof(T), args) as T;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a modifier to the player.
|
||||
/// </summary>
|
||||
@@ -192,24 +396,32 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
|
||||
[HideFromIl2Cpp]
|
||||
public BaseModifier? AddModifier(BaseModifier modifier)
|
||||
{
|
||||
if (Modifiers.Contains(modifier))
|
||||
// TODO: Make a proper synchronization system.
|
||||
if (LobbyBehaviour.Instance)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {modifier.ModifierId}!");
|
||||
Logger<MiraApiPlugin>.Warning($"Modifiers added in the lobby won't sync to new players!");
|
||||
}
|
||||
|
||||
var id = modifier.TypeId;
|
||||
if (modifier.Unique && ActiveModifiers.Find(x => x.TypeId == id) != null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {id}!");
|
||||
return null;
|
||||
}
|
||||
|
||||
var modifierId = ModifierManager.GetModifierId(modifier.GetType());
|
||||
|
||||
if (modifierId == null)
|
||||
if (ActiveModifiers.Contains(modifier))
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Cannot add modifier {modifier.GetType().Name} because it has no ID!");
|
||||
Logger<MiraApiPlugin>.Error($"Player already has this modifier!");
|
||||
return null;
|
||||
}
|
||||
|
||||
_toAdd.Add(modifier);
|
||||
modifier.Player = _player;
|
||||
modifier.ModifierComponent = this;
|
||||
modifier.ModifierId = modifierId.Value;
|
||||
if (modifier.UniqueId == Guid.Empty)
|
||||
{
|
||||
modifier.UniqueId = Guid.NewGuid();
|
||||
}
|
||||
return modifier;
|
||||
}
|
||||
|
||||
@@ -217,62 +429,147 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
|
||||
/// Adds a modifier to the player.
|
||||
/// </summary>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
/// <returns>The modifier that was added.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public BaseModifier? AddModifier(Type type)
|
||||
public BaseModifier? AddModifier(Type type, params object[] args)
|
||||
{
|
||||
var modifierId = ModifierManager.GetModifierId(type);
|
||||
if (modifierId == null)
|
||||
BaseModifier? modifier;
|
||||
if (args.Length > 0)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Cannot add modifier {type.Name} because it is not registered.");
|
||||
return null;
|
||||
modifier = ModifierFactory.CreateInstance(type, args);
|
||||
}
|
||||
else
|
||||
{
|
||||
modifier = Activator.CreateInstance(type) as BaseModifier;
|
||||
if (modifier == null)
|
||||
{
|
||||
throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier.");
|
||||
}
|
||||
}
|
||||
|
||||
if (Modifiers.Find(x => x.ModifierId == modifierId) != null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Player already has modifier with id {modifierId}!");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Activator.CreateInstance(type) is not BaseModifier modifier)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Cannot add modifier {type.Name} because it is null.");
|
||||
return null;
|
||||
}
|
||||
|
||||
AddModifier(modifier);
|
||||
|
||||
return modifier;
|
||||
return AddModifier(modifier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a modifier to the player.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The Type of the modifier.</typeparam>
|
||||
/// <returns>The new modifier.</returns>
|
||||
/// <param name="id">The ID of the modifier.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
/// <returns>The modifier if it was created, or null if it failed.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public T? AddModifier<T>() where T : BaseModifier
|
||||
public BaseModifier? AddModifier(uint id, params object[] args)
|
||||
{
|
||||
return AddModifier(typeof(T)) as T;
|
||||
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
|
||||
$"Cannot add modifier with id {id} because it is not registered.");
|
||||
|
||||
return AddModifier(type, args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active or queued modifier by its ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The Modifier ID.</param>
|
||||
/// <returns>True if the Modifier is present, false otherwise.</returns>
|
||||
public bool HasModifier(uint id)
|
||||
{
|
||||
return ActiveModifiers.Exists(x => x.ModifierId == id) || _toAdd.Exists(x => x.ModifierId == id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active or queued modifier by its type.
|
||||
/// Checks if a player has an active modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="predicate">The predicate to check the modifier.</param>
|
||||
/// <typeparam name="T">The Type of the Modifier.</typeparam>
|
||||
/// <returns>True if the Modifier is present, false otherwise.</returns>
|
||||
public bool HasModifier<T>()
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier<T>(Func<T, bool>? predicate=null) where T : BaseModifier
|
||||
{
|
||||
return ActiveModifiers.Exists(x => x is T) || _toAdd.Exists(x => x is T);
|
||||
return ActiveModifiers.Exists(x => x is T modifier && (predicate == null || predicate(modifier)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier.</param>
|
||||
/// <returns>True if the Modifier is present, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier(Type type, Func<BaseModifier, bool>? predicate=null)
|
||||
{
|
||||
return ActiveModifiers.Exists(x => x.GetType() == type && (predicate == null || predicate(x)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active modifier by its type ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The modifier's type ID.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier.</param>
|
||||
/// <returns>True if the modifier is present, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier(uint id, Func<BaseModifier, bool>? predicate=null)
|
||||
{
|
||||
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
|
||||
$"Cannot get modifier with id {id} because it is not registered.");
|
||||
|
||||
return HasModifier(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active modifier by its unique ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The modifier's guid.</param>
|
||||
/// <returns>True if the modifier is present, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier(Guid id)
|
||||
{
|
||||
return ActiveModifiers.Exists(x => x.UniqueId == id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
|
||||
/// <param name="predicate">The predicate to check the modifier.</param>
|
||||
/// <typeparam name="T">The Type of the Modifier.</typeparam>
|
||||
/// <returns>True if the Modifier is present, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier<T>(bool checkInactive, Func<T, bool>? predicate=null) where T : BaseModifier
|
||||
{
|
||||
return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr));
|
||||
bool MatchExpr(BaseModifier bm) => bm is T modifier && (predicate == null || predicate(modifier));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
|
||||
/// <param name="predicate">The predicate to check the modifier.</param>
|
||||
/// <returns>True if the Modifier is present, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier(Type type, bool checkInactive, Func<BaseModifier, bool>? predicate=null)
|
||||
{
|
||||
return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr));
|
||||
bool MatchExpr(BaseModifier bm) => bm.GetType() == type && (predicate == null || predicate(bm));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active modifier by its type ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The modifier's type ID.</param>
|
||||
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
|
||||
/// <param name="predicate">The predicate to check the modifier.</param>
|
||||
/// <returns>True if the modifier is present, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier(uint id, bool checkInactive, Func<BaseModifier, bool>? predicate=null)
|
||||
{
|
||||
var type = ModifierManager.GetModifierType(id) ?? throw new InvalidOperationException(
|
||||
$"Cannot get modifier with id {id} because it is not registered.");
|
||||
|
||||
return HasModifier(type, checkInactive, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a player has an active modifier by its unique ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The modifier's guid.</param>
|
||||
/// <param name="checkInactive">Whether to check inactive modifiers (those pending to be added).</param>
|
||||
/// <returns>True if the modifier is present, false otherwise.</returns>
|
||||
[HideFromIl2Cpp]
|
||||
public bool HasModifier(Guid id, bool checkInactive)
|
||||
{
|
||||
return ActiveModifiers.Exists(MatchExpr) || (checkInactive && _toAdd.Exists(MatchExpr));
|
||||
bool MatchExpr(BaseModifier bm) => bm.UniqueId == id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using HarmonyLib;
|
||||
using Il2CppInterop.Runtime.Attributes;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using Reactor.Utilities.Attributes;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace MiraAPI.Modifiers.ModifierDisplay;
|
||||
|
||||
/// <summary>
|
||||
/// The code used to display Mira modifiers.
|
||||
/// </summary>
|
||||
[RegisterInIl2Cpp]
|
||||
public class ModifierDisplayComponent(nint cppPtr) : MonoBehaviour(cppPtr)
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the instance of the Modifier Display.
|
||||
/// </summary>
|
||||
public static ModifierDisplayComponent? Instance { get; private set; }
|
||||
|
||||
private RectTransform _children = null!;
|
||||
private GameObject _modTemplate = null!;
|
||||
private PassiveButton _toggleButton = null!;
|
||||
private TextMeshPro _toggleBtnText = null!;
|
||||
|
||||
private RectTransform _pagination = null!;
|
||||
private TextMeshPro _pageText = null!;
|
||||
private PassiveButton _nextButton = null!;
|
||||
private PassiveButton _backButton = null!;
|
||||
|
||||
private int _currentPage;
|
||||
private const int ItemsPerPage = 3;
|
||||
|
||||
private readonly Dictionary<BaseModifier, ModifierUiComponent> _modifiers = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a read only dictionary of the created modifier UI components.
|
||||
/// </summary>
|
||||
[HideFromIl2Cpp]
|
||||
public ReadOnlyDictionary<BaseModifier, ModifierUiComponent> Modifiers => new(_modifiers);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the modifier display hud is currently open.
|
||||
/// </summary>
|
||||
public bool IsOpen { get; private set; }
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
|
||||
_children = transform.GetChild(0).GetComponent<RectTransform>();
|
||||
_modTemplate = transform.GetChild(2).gameObject;
|
||||
|
||||
_toggleButton = transform.GetChild(1).GetComponent<PassiveButton>();
|
||||
_toggleButton.OnClick = new Button.ButtonClickedEvent();
|
||||
_toggleButton.OnClick.AddListener((UnityAction)(() =>
|
||||
{
|
||||
IsOpen = !IsOpen;
|
||||
_children.gameObject.SetActive(!_children.gameObject.activeSelf);
|
||||
}));
|
||||
|
||||
_toggleButton.ClickSound = HudManager.Instance.GameMenu.StreamerModeButton.GetComponent<PassiveButton>().ClickSound;
|
||||
_toggleButton.HoverSound = HudManager.Instance.GameMenu.StreamerModeButton.GetComponent<PassiveButton>().HoverSound;
|
||||
_toggleButton.inactiveSprites = _toggleButton.transform.GetChild(1).gameObject;
|
||||
_toggleBtnText = _toggleButton.transform.GetChild(0).GetComponent<TextMeshPro>();
|
||||
|
||||
_pagination = _children.transform.GetChild(0).GetComponent<RectTransform>();
|
||||
_pageText = _pagination.transform.GetChild(0).GetComponent<TextMeshPro>();
|
||||
_nextButton = _pagination.transform.GetChild(1).GetComponent<PassiveButton>();
|
||||
_backButton = _pagination.transform.GetChild(2).GetComponent<PassiveButton>();
|
||||
|
||||
_toggleBtnText.font = _pageText.font = _nextButton.buttonText.font = _backButton.buttonText.font = HudManager.Instance.TaskPanel.taskText.font;
|
||||
_toggleBtnText.fontMaterial = _pageText.fontMaterial = _nextButton.buttonText.fontMaterial = _backButton.buttonText.fontMaterial = HudManager.Instance.TaskPanel.taskText.fontMaterial;
|
||||
|
||||
_nextButton.OnClick = new Button.ButtonClickedEvent();
|
||||
_nextButton.OnClick.AddListener((UnityAction)(() =>
|
||||
{
|
||||
_currentPage++;
|
||||
UpdatePage();
|
||||
}));
|
||||
|
||||
_backButton.OnClick = new Button.ButtonClickedEvent();
|
||||
_backButton.OnClick.AddListener((UnityAction)(() =>
|
||||
{
|
||||
_currentPage--;
|
||||
UpdatePage();
|
||||
}));
|
||||
|
||||
IsOpen = false;
|
||||
_children.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this to refresh the modifiers UI. Useful if you hide modifiers uis based on options.
|
||||
/// </summary>
|
||||
public void RefreshModifiers()
|
||||
{
|
||||
UpdateModifiersList([.. PlayerControl.LocalPlayer.GetModifierComponent().ActiveModifiers]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this to toggle the visibility of the modifiers tab.
|
||||
/// </summary>
|
||||
public void ToggleTab()
|
||||
{
|
||||
IsOpen = !IsOpen;
|
||||
_children.gameObject.SetActive(IsOpen);
|
||||
RefreshModifiers();
|
||||
}
|
||||
|
||||
internal void DestroyComponent(ModifierUiComponent component)
|
||||
{
|
||||
_modifiers.Remove(component.Modifier!);
|
||||
component.gameObject.DestroyImmediate();
|
||||
|
||||
RefreshModifiers();
|
||||
}
|
||||
|
||||
[HideFromIl2Cpp]
|
||||
internal static ModifierDisplayComponent CreateDisplay()
|
||||
{
|
||||
var gameObject = Instantiate(MiraAssets.ModifierDisplay.LoadAsset(), HudManager.Instance.transform);
|
||||
var minigame = gameObject.AddComponent<ModifierDisplayComponent>();
|
||||
return minigame;
|
||||
}
|
||||
|
||||
[HideFromIl2Cpp]
|
||||
private ModifierUiComponent CreateForModifier(BaseModifier modifier)
|
||||
{
|
||||
var newMod = Instantiate(_modTemplate, _children.transform);
|
||||
newMod.transform.name = modifier.ModifierName;
|
||||
var comp = newMod.AddComponent<ModifierUiComponent>();
|
||||
comp.Modifier = modifier;
|
||||
return comp;
|
||||
}
|
||||
|
||||
private void UpdatePage()
|
||||
{
|
||||
var totalPages = Mathf.CeilToInt((float)_modifiers.Count / ItemsPerPage);
|
||||
_currentPage = Mathf.Clamp(_currentPage, 0, Mathf.Max(0, totalPages - 1));
|
||||
|
||||
if (_modifiers.Count <= ItemsPerPage)
|
||||
{
|
||||
_modifiers.Do(x => x.Value.gameObject.SetActive(true));
|
||||
_pagination.gameObject.SetActive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
_pagination.gameObject.SetActive(true);
|
||||
if (_pageText != null)
|
||||
{
|
||||
_pageText.text = $"Page {_currentPage + 1}/{Mathf.Max(totalPages, 1)}";
|
||||
}
|
||||
|
||||
_nextButton.gameObject.SetActive(true);
|
||||
_backButton.gameObject.SetActive(true);
|
||||
|
||||
_modifiers.Do(x => x.Value.gameObject.SetActive(false));
|
||||
var start = _currentPage * ItemsPerPage;
|
||||
var end = Mathf.Min(start + ItemsPerPage, _modifiers.Count);
|
||||
var modifiers = _modifiers.ToArray();
|
||||
|
||||
for (var i = start; i < end; i++)
|
||||
{
|
||||
modifiers[i].Value.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
_pagination.SetAsLastSibling();
|
||||
}
|
||||
|
||||
[HideFromIl2Cpp]
|
||||
internal void UpdateModifiersList(List<BaseModifier> modifiers)
|
||||
{
|
||||
var filteredModifiers = modifiers.Where(x => !x.HideOnUi && x.GetDescription() != string.Empty).ToList();
|
||||
var modifiersToAdd = filteredModifiers.ToList();
|
||||
|
||||
foreach (var mod in _modifiers.ToArray())
|
||||
{
|
||||
if (modifiersToAdd.Contains(mod.Key))
|
||||
{
|
||||
modifiersToAdd.Remove(mod.Key);
|
||||
continue;
|
||||
}
|
||||
|
||||
mod.Value.gameObject.Destroy();
|
||||
_modifiers.Remove(mod.Key);
|
||||
}
|
||||
|
||||
_toggleBtnText.text = $"Modifiers ({filteredModifiers.Count})";
|
||||
|
||||
if (filteredModifiers.Count == 0)
|
||||
{
|
||||
_toggleButton.gameObject.SetActive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
_toggleButton.gameObject.SetActive(true);
|
||||
|
||||
foreach (var mod in modifiersToAdd)
|
||||
{
|
||||
_modifiers.Add(mod, CreateForModifier(mod));
|
||||
}
|
||||
|
||||
UpdatePage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Il2CppInterop.Runtime.Attributes;
|
||||
using Reactor.Utilities.Attributes;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Modifiers.ModifierDisplay;
|
||||
|
||||
/// <summary>
|
||||
/// The code placed on every Modifier HUD object. Used to handle updating.
|
||||
/// </summary>
|
||||
[RegisterInIl2Cpp]
|
||||
public class ModifierUiComponent(nint cppPtr) : MonoBehaviour(cppPtr)
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the modifier which this component is for.
|
||||
/// </summary>
|
||||
[HideFromIl2Cpp]
|
||||
public BaseModifier? Modifier { get; internal set; }
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
private SpriteRenderer modBg = null!;
|
||||
private TextMeshPro desc = null!;
|
||||
private SpriteRenderer icon = null!;
|
||||
private TextMeshPro nameText = null!;
|
||||
private RectTransform descRect = null!;
|
||||
// ReSharper restore InconsistentNaming
|
||||
private void Awake()
|
||||
{
|
||||
if (Modifier == null) return;
|
||||
|
||||
modBg = transform.GetChild(0).GetComponent<SpriteRenderer>();
|
||||
desc = modBg.transform.GetChild(0).GetComponent<TextMeshPro>();
|
||||
icon = modBg.transform.GetChild(1).GetComponent<SpriteRenderer>();
|
||||
var nameBg = transform.GetChild(1);
|
||||
nameText = nameBg.GetChild(0).GetComponent<TextMeshPro>();
|
||||
descRect = desc.gameObject.GetComponent<RectTransform>();
|
||||
|
||||
nameText.font = desc.font = HudManager.Instance.TaskPanel.taskText.font;
|
||||
nameText.fontMaterial = desc.fontMaterial = HudManager.Instance.TaskPanel.taskText.fontMaterial;
|
||||
}
|
||||
|
||||
// Might not be the best solution, but used to update name/description/icon if updated in the modifier.
|
||||
private void FixedUpdate()
|
||||
{
|
||||
if (Modifier == null || ModifierDisplayComponent.Instance == null || !ModifierDisplayComponent.Instance.IsOpen) return;
|
||||
|
||||
if (Modifier.HideOnUi || Modifier.GetDescription() == string.Empty)
|
||||
{
|
||||
ModifierDisplayComponent.Instance.DestroyComponent(this);
|
||||
return;
|
||||
}
|
||||
|
||||
nameText.text = Modifier.ModifierName;
|
||||
desc.text = Modifier.GetDescription();
|
||||
modBg.gameObject.SetActive(true);
|
||||
|
||||
icon.gameObject.SetActive(Modifier.ModifierIcon != null);
|
||||
if (icon.gameObject && icon.gameObject.activeSelf && Modifier.ModifierIcon != null)
|
||||
{
|
||||
icon.sprite = Modifier.ModifierIcon?.LoadAsset();
|
||||
icon.size = new Vector2(0.7f, 0.7f);
|
||||
icon.tileMode = SpriteTileMode.Continuous;
|
||||
descRect.localPosition = new Vector3(0.38f, -0.1f, -5);
|
||||
descRect.sizeDelta = new Vector2(2.38f, 0.65f);
|
||||
}
|
||||
else
|
||||
{
|
||||
descRect.localPosition = new Vector3(0, -0.1f, -5);
|
||||
descRect.sizeDelta = new Vector2(3.1f, 0.65f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using MiraAPI.Networking;
|
||||
using MiraAPI.Networking.Modifiers;
|
||||
using Reactor.Networking.Attributes;
|
||||
using Reactor.Networking.Rpc;
|
||||
using Reactor.Utilities;
|
||||
|
||||
namespace MiraAPI.Modifiers;
|
||||
|
||||
/// <summary>
|
||||
/// Extensions for modifiers.
|
||||
/// </summary>
|
||||
public static class ModifierExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the dictionary to cache ModifierComponents.
|
||||
/// </summary>
|
||||
public static Dictionary<PlayerControl, ModifierComponent> ModifierComponents { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Remote Procedure Call to add a modifier to a player.
|
||||
/// </summary>
|
||||
/// <param name="target">The player to add the modifier to.</param>
|
||||
/// <param name="typeId">The modifier type ID.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
public static void RpcAddModifier(this PlayerControl target, uint typeId, params object[] args)
|
||||
{
|
||||
_ = ModifierManager.GetModifierType(typeId) ?? throw new InvalidOperationException(
|
||||
$"Modifier with ID {typeId} is not registered.");
|
||||
|
||||
Rpc<AddModifierRpc>.Instance.Send(target, new ModifierData(typeId, Guid.NewGuid(), args), true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remote Procedure Call to add a modifier to a player.
|
||||
/// </summary>
|
||||
/// <param name="player">The player to add the modifier to.</param>
|
||||
/// <param name="type">The type of the modifier.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
public static void RpcAddModifier(this PlayerControl player, Type type, params object[] args)
|
||||
{
|
||||
var id = ModifierManager.GetModifierTypeId(type) ?? throw new InvalidOperationException(
|
||||
$"Modifier {type.Name} is not registered.");
|
||||
|
||||
player.RpcAddModifier(id, args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remote Procedure Call to add a modifier to a player.
|
||||
/// </summary>
|
||||
/// <param name="player">The player to add the modifier to.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
/// <typeparam name="T">The modifier Type.</typeparam>
|
||||
public static void RpcAddModifier<T>(this PlayerControl player, params object[] args) where T : BaseModifier
|
||||
{
|
||||
player.RpcAddModifier(typeof(T), args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remote Procedure Call to remove a modifier from a player.
|
||||
/// </summary>
|
||||
/// <param name="target">The player to remove the modifier from.</param>
|
||||
/// <param name="uniqueId">The unique ID of the modifier.</param>
|
||||
[MethodRpc((uint)MiraRpc.RemoveModifier, SendImmediately = true)]
|
||||
public static void RpcRemoveModifier(this PlayerControl target, Guid uniqueId)
|
||||
{
|
||||
target.RemoveModifier(uniqueId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remote Procedure Call to remove a modifier from a player by type ID.
|
||||
/// </summary>
|
||||
/// <param name="target">The player to remove the modifier from.</param>
|
||||
/// <param name="typeId">The type ID of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
public static void RpcRemoveModifier(
|
||||
this PlayerControl target,
|
||||
uint typeId,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
var modifier = target.GetModifier(typeId, predicate);
|
||||
if (modifier is null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Player {target.PlayerId} does not have modifier with type ID {typeId}.");
|
||||
return;
|
||||
}
|
||||
|
||||
target.RpcRemoveModifier(modifier.UniqueId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remote Procedure Call to remove a modifier from a player.
|
||||
/// </summary>
|
||||
/// <param name="player">The player to remove the modifier from.</param>
|
||||
/// <param name="type">The type of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
public static void RpcRemoveModifier(
|
||||
this PlayerControl player,
|
||||
Type type,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
var id = ModifierManager.GetModifierTypeId(type) ?? throw new InvalidOperationException(
|
||||
$"Modifier {type.Name} is not registered.");
|
||||
|
||||
player.RpcRemoveModifier(id, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remote Procedure Call to remove a modifier from a player.
|
||||
/// </summary>
|
||||
/// <param name="player">The player to remove the modifier from.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <typeparam name="T">The Type of the Modifier.</typeparam>
|
||||
public static void RpcRemoveModifier<T>(this PlayerControl player, Func<BaseModifier, bool>? predicate = null)
|
||||
where T : BaseModifier
|
||||
{
|
||||
player.RpcRemoveModifier(typeof(T), predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ModifierComponent for a player.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl object.</param>
|
||||
/// <returns>A ModifierComponent if there is one, null otherwise.</returns>
|
||||
public static ModifierComponent GetModifierComponent(this PlayerControl player)
|
||||
{
|
||||
if (ModifierComponents.TryGetValue(player, out var component))
|
||||
{
|
||||
return component;
|
||||
}
|
||||
|
||||
component = player.GetComponent<ModifierComponent>();
|
||||
if (!component)
|
||||
{
|
||||
throw new InvalidOperationException("ModifierComponent is not attached to the player.");
|
||||
}
|
||||
|
||||
ModifierComponents[player] = component;
|
||||
return component;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the player has a specific modifier.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the modifier.</typeparam>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>True if the player has the modifier, false otherwise.</returns>
|
||||
public static bool HasModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null) where T : BaseModifier
|
||||
{
|
||||
return player.GetModifierComponent().HasModifier(predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the player has a specific modifier by type.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="type">The type of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>True if the player has the modifier, false otherwise.</returns>
|
||||
public static bool HasModifier(this PlayerControl player, Type type, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().HasModifier(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the player has a specific modifier by type ID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="typeId">The type ID of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>True if the player has the modifier, false otherwise.</returns>
|
||||
public static bool HasModifier(
|
||||
this PlayerControl player,
|
||||
uint typeId,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().HasModifier(typeId, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the player has a specific modifier by its GUID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="uniqueId">The unique ID of the modifier.</param>
|
||||
/// <returns>True if the player has the modifier, false otherwise.</returns>
|
||||
public static bool HasModifier(this PlayerControl player, Guid uniqueId)
|
||||
{
|
||||
return player.GetModifierComponent().HasModifier(uniqueId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
/// Tries to get a modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <typeparam name="T">The Type of the Modifier.</typeparam>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
public static bool TryGetModifier<T>(this PlayerControl player, [NotNullWhen(true)] out T? modifier, Func<T, bool>? predicate = null) where T : BaseModifier
|
||||
{
|
||||
return player.GetModifierComponent().TryGetModifier(out modifier, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a modifier by its type.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="type">The modifier type.</param>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
public static bool TryGetModifier(this PlayerControl player, Type type, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().TryGetModifier(type, out modifier, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a modifier by its type ID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="id">The modifier type ID.</param>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <param name="predicate">The predicate to check the modifier by.</param>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
public static bool TryGetModifier(this PlayerControl player, uint id, [NotNullWhen(true)] out BaseModifier? modifier, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().TryGetModifier(id, out modifier, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get a modifier by its unique ID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="modifierGuid">The modifier unique ID.</param>
|
||||
/// <param name="modifier">The modifier or null.</param>
|
||||
/// <returns>True if the modifier was found, false otherwise.</returns>
|
||||
public static bool TryGetModifier(this PlayerControl player, Guid modifierGuid, [NotNullWhen(true)] out BaseModifier? modifier)
|
||||
{
|
||||
return player.GetModifierComponent().TryGetModifier(modifierGuid, out modifier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a specific modifier from the player.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the modifier.</typeparam>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>The modifier if found, null otherwise.</returns>
|
||||
public static T? GetModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null) where T : BaseModifier
|
||||
{
|
||||
return player.GetModifierComponent().GetModifier(predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a specific modifier from the player by type.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="type">The type of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>The modifier if found, null otherwise.</returns>
|
||||
public static BaseModifier? GetModifier(
|
||||
this PlayerControl player,
|
||||
Type type,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().GetModifier(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a specific modifier from the player by its type ID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="typeId">The type ID of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>The modifier if found, null otherwise.</returns>
|
||||
public static BaseModifier? GetModifier(
|
||||
this PlayerControl player,
|
||||
uint typeId,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().GetModifier(typeId, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a specific modifier from the player by its GUID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="uniqueId">The GUID of the modifier.</param>
|
||||
/// <returns>The modifier if found, null otherwise.</returns>
|
||||
public static BaseModifier? GetModifier(
|
||||
this PlayerControl player,
|
||||
Guid uniqueId)
|
||||
{
|
||||
return player.GetModifierComponent().GetModifier(uniqueId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all modifiers of a specific type from the player.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the modifiers.</typeparam>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>A collection of modifiers.</returns>
|
||||
public static IEnumerable<T> GetModifiers<T>(this PlayerControl player, Func<T, bool>? predicate = null)
|
||||
where T : BaseModifier
|
||||
{
|
||||
return player.GetModifierComponent().GetModifiers(predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all modifiers of a specific type from the player.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="type">The type of the modifiers.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>A collection of modifiers.</returns>
|
||||
public static IEnumerable<BaseModifier> GetModifiers(
|
||||
this PlayerControl player,
|
||||
Type type,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().GetModifiers(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all modifiers of a specific type from the player by type ID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="typeId">The type ID of the modifiers.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
/// <returns>A collection of modifiers.</returns>
|
||||
public static IEnumerable<BaseModifier> GetModifiers(
|
||||
this PlayerControl player,
|
||||
uint typeId,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
return player.GetModifierComponent().GetModifiers(typeId, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a specific modifier from the player.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="modifier">The modifier to remove.</param>
|
||||
public static void RemoveModifier(this PlayerControl player, BaseModifier modifier)
|
||||
{
|
||||
player.GetModifierComponent().RemoveModifier(modifier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a specific modifier from the player.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the modifier.</typeparam>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
public static void RemoveModifier<T>(this PlayerControl player, Func<T, bool>? predicate = null)
|
||||
where T : BaseModifier
|
||||
{
|
||||
player.GetModifierComponent().RemoveModifier(predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a specific modifier from the player by type.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="type">The type of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
public static void RemoveModifier(this PlayerControl player, Type type, Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
player.GetModifierComponent().RemoveModifier(type, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a specific modifier from the player by its type ID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="typeId">The type ID of the modifier.</param>
|
||||
/// <param name="predicate">Optional predicate to filter the modifiers.</param>
|
||||
public static void RemoveModifier(
|
||||
this PlayerControl player,
|
||||
uint typeId,
|
||||
Func<BaseModifier, bool>? predicate = null)
|
||||
{
|
||||
player.GetModifierComponent().RemoveModifier(typeId, predicate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a specific modifier from the player by its GUID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="uniqueId">The GUID of the modifier.</param>
|
||||
public static void RemoveModifier(
|
||||
this PlayerControl player,
|
||||
Guid uniqueId)
|
||||
{
|
||||
player.GetModifierComponent().RemoveModifier(uniqueId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a specific modifier to the player.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the modifier.</typeparam>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
/// <returns>The added modifier.</returns>
|
||||
public static T? AddModifier<T>(this PlayerControl player, params object[] args) where T : BaseModifier
|
||||
{
|
||||
return player.GetModifierComponent().AddModifier<T>(args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a specific modifier to the player.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="modifier">The modifier to add.</param>
|
||||
/// <returns>The added modifier.</returns>
|
||||
public static BaseModifier? AddModifier(this PlayerControl player, BaseModifier modifier)
|
||||
{
|
||||
return player.GetModifierComponent().AddModifier(modifier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a specific modifier to the player by type.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="type">The type of the modifier.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
/// <returns>The added modifier.</returns>
|
||||
public static BaseModifier? AddModifier(this PlayerControl player, Type type, params object[] args)
|
||||
{
|
||||
return player.GetModifierComponent().AddModifier(type, args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a specific modifier to the player by type ID.
|
||||
/// </summary>
|
||||
/// <param name="player">The PlayerControl instance.</param>
|
||||
/// <param name="typeId">The type ID of the modifier.</param>
|
||||
/// <param name="args">The arguments to initialize the modifier constructor with.</param>
|
||||
/// <returns>The added modifier.</returns>
|
||||
public static BaseModifier? AddModifier(this PlayerControl player, uint typeId, params object[] args)
|
||||
{
|
||||
return player.GetModifierComponent().AddModifier(typeId, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using MiraAPI.Utilities;
|
||||
|
||||
namespace MiraAPI.Modifiers;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating instances of a modifier. More efficient than using reflection.
|
||||
/// </summary>
|
||||
public static class ModifierFactory
|
||||
{
|
||||
private static readonly Dictionary<(Type, Type[]), Func<object[], BaseModifier>> ConstructorCache = [];
|
||||
|
||||
private static Func<object[], BaseModifier> CreateConstructor(Type type, params object[] args)
|
||||
{
|
||||
var constructorInfo = type.GetBestConstructor(args) ?? throw new InvalidOperationException(
|
||||
$"Could not find a constructor for type {type} with the specified arguments.");
|
||||
|
||||
var parameters = constructorInfo.GetParameters();
|
||||
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
var constructorParams = new Expression[parameters.Length];
|
||||
|
||||
for (var i = 0; i < parameters.Length; i++)
|
||||
{
|
||||
var paramType = parameters[i].ParameterType;
|
||||
var paramAccess = Expression.ArrayIndex(argsParam, Expression.Constant(i));
|
||||
var convertedParam = Expression.Convert(paramAccess, paramType);
|
||||
constructorParams[i] = convertedParam;
|
||||
}
|
||||
|
||||
var newExpr = Expression.New(constructorInfo, constructorParams);
|
||||
var lambda = Expression.Lambda<Func<object[], BaseModifier>>(newExpr, argsParam);
|
||||
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a modifier with the specified type and arguments.
|
||||
/// </summary>
|
||||
/// <param name="type">Modifier type.</param>
|
||||
/// <param name="args">Arguments.</param>
|
||||
/// <returns>An instance of the modifier.</returns>
|
||||
public static BaseModifier CreateInstance(Type type, params object[] args)
|
||||
{
|
||||
var argTypes = args.Select(arg => arg.GetType()).ToArray();
|
||||
var key = (type, argTypes);
|
||||
|
||||
if (!ConstructorCache.TryGetValue(key, out var constructor))
|
||||
{
|
||||
constructor = CreateConstructor(type, args);
|
||||
ConstructorCache[key] = constructor;
|
||||
}
|
||||
|
||||
return constructor(args);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating instances of a modifier. More efficient than using reflection.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The modifier type.</typeparam>
|
||||
public static class ModifierFactory<T> where T : BaseModifier
|
||||
{
|
||||
private static readonly Func<object[], T> Constructor = CreateConstructor();
|
||||
|
||||
private static Func<object[], T> CreateConstructor(params object[] args)
|
||||
{
|
||||
var constructorInfo = typeof(T).GetBestConstructor(args) ?? throw new InvalidOperationException(
|
||||
$"Could not find a constructor for type {typeof(T)} with the specified arguments.");
|
||||
|
||||
var parameters = constructorInfo.GetParameters();
|
||||
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
var constructorParams = new Expression[parameters.Length];
|
||||
|
||||
for (var i = 0; i < parameters.Length; i++)
|
||||
{
|
||||
var paramType = parameters[i].ParameterType;
|
||||
var paramAccess = Expression.ArrayIndex(argsParam, Expression.Constant(i));
|
||||
var convertedParam = Expression.Convert(paramAccess, paramType);
|
||||
constructorParams[i] = convertedParam;
|
||||
}
|
||||
|
||||
var newExpr = Expression.New(constructorInfo, constructorParams);
|
||||
var lambda = Expression.Lambda<Func<object[], T>>(newExpr, argsParam);
|
||||
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of the modifier.
|
||||
/// </summary>
|
||||
/// <param name="args">Parameters for the constructor.</param>
|
||||
/// <returns>An instance of the modifier.</returns>
|
||||
[SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "This is a factory class.")]
|
||||
public static T CreateInstance(params object[] args)
|
||||
{
|
||||
return Constructor(args);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using MiraAPI.Modifiers.Types;
|
||||
using MiraAPI.Networking;
|
||||
using MiraAPI.PluginLoading;
|
||||
using MiraAPI.Roles;
|
||||
using MiraAPI.Utilities;
|
||||
using Reactor.Networking.Rpc;
|
||||
using Reactor.Utilities;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using Random = System.Random;
|
||||
@@ -17,20 +16,25 @@ namespace MiraAPI.Modifiers;
|
||||
/// </summary>
|
||||
public static class ModifierManager
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether modifiers should be assigned to players.
|
||||
/// </summary>
|
||||
public static bool MiraAssignsModifiers { get; set; } = true;
|
||||
|
||||
private static readonly Dictionary<uint, Type> IdToTypeModifierMap = [];
|
||||
private static readonly Dictionary<Type, uint> TypeToIdModifierMap = [];
|
||||
private static readonly Dictionary<int, List<uint>> PrioritiesToIdsMap = [];
|
||||
|
||||
private static uint _nextId;
|
||||
private static uint _nextTypeId;
|
||||
|
||||
private static uint GetNextId()
|
||||
private static uint GetNextTypeId()
|
||||
{
|
||||
_nextId++;
|
||||
return _nextId;
|
||||
_nextTypeId++;
|
||||
return _nextTypeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the modifier type from the id.
|
||||
/// Gets the modifier type from the type id.
|
||||
/// </summary>
|
||||
/// <param name="id">The ID.</param>
|
||||
/// <returns>The Type of the modifier.</returns>
|
||||
@@ -44,104 +48,120 @@ public static class ModifierManager
|
||||
/// </summary>
|
||||
/// <param name="type">The Type.</param>
|
||||
/// <returns>The ID of the modifier.</returns>
|
||||
public static uint? GetModifierId(Type type)
|
||||
public static uint? GetModifierTypeId(Type type)
|
||||
{
|
||||
return TypeToIdModifierMap.GetValueOrDefault(type);
|
||||
if (!TypeToIdModifierMap.TryGetValue(type, out var id))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
internal static bool RegisterModifier(Type modifierType)
|
||||
internal static bool RegisterModifier(Type modifierType, MiraPluginInfo info)
|
||||
{
|
||||
if (!typeof(BaseModifier).IsAssignableFrom(modifierType))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
IdToTypeModifierMap.Add(GetNextId(), modifierType);
|
||||
TypeToIdModifierMap.Add(modifierType, _nextId);
|
||||
IdToTypeModifierMap.Add(GetNextTypeId(), modifierType);
|
||||
TypeToIdModifierMap.Add(modifierType, _nextTypeId);
|
||||
|
||||
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.InternalModifiers.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))
|
||||
{
|
||||
PrioritiesToIdsMap[priority] = list = [];
|
||||
}
|
||||
|
||||
list.Add(_nextId);
|
||||
list.Add(_nextTypeId);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static void AssignModifiers(List<PlayerControl> plrs)
|
||||
/// <summary>
|
||||
/// Assigns modifiers to players. ONLY CALL THIS METHOD IF YOU KNOW WHAT YOU ARE DOING.
|
||||
/// </summary>
|
||||
/// <param name="plrs">The players to assign modifiers to.</param>
|
||||
public static void AssignModifiers(List<PlayerControl> plrs)
|
||||
{
|
||||
var rand = new Random();
|
||||
|
||||
foreach (var priority in PrioritiesToIdsMap.Keys.OrderByDescending(x => x))
|
||||
// Filter and sort modifiers by descending priority.
|
||||
var modifiers = IdToTypeModifierMap
|
||||
.Where(x=>x.Value.IsAssignableTo(typeof(GameModifier)))
|
||||
.Select(x => Activator.CreateInstance(x.Value) as GameModifier)
|
||||
.OfType<GameModifier>()
|
||||
.Where(x => x.GetAmountPerGame() > 0 && x.GetAssignmentChance() > 0)
|
||||
.OrderByDescending(x => x.Priority())
|
||||
.ToArray();
|
||||
|
||||
foreach (var modifier in modifiers)
|
||||
{
|
||||
var filteredModifiers = new List<uint>();
|
||||
var assignments = modifier.GetAmountPerGame();
|
||||
|
||||
foreach (var id in PrioritiesToIdsMap[priority])
|
||||
var validPlayers = plrs.Where(x => IsGameModifierValid(x, modifier, modifier.TypeId)).ToList();
|
||||
if (validPlayers.Count == 0)
|
||||
{
|
||||
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
|
||||
var chance = Math.Clamp(mod!.GetAssignmentChance(), 0, 100);
|
||||
var count = mod.GetAmountPerGame();
|
||||
|
||||
if (chance == 0 || count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var maxCount = plrs.Count(x => IsGameModifierValid(x, mod, id));
|
||||
|
||||
if (maxCount == 0)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Warning($"No players are valid for {mod.ModifierName}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var num = Math.Clamp(count, 0, maxCount);
|
||||
|
||||
for (var i = 0; i < num; i++)
|
||||
{
|
||||
var randomNum = rand.Next(100);
|
||||
|
||||
if (randomNum < chance)
|
||||
{
|
||||
filteredModifiers.Add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filteredModifiers.Count == 0)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Warning($"No filtered modifiers for priority {priority}");
|
||||
Logger<MiraApiPlugin>.Warning($"No valid players for modifier {modifier.ModifierName}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var shuffledList = filteredModifiers.Randomize();
|
||||
assignments = Math.Min(assignments, validPlayers.Count);
|
||||
var availablePlayers = new List<PlayerControl>(validPlayers);
|
||||
|
||||
if (shuffledList.Count > plrs.Count)
|
||||
for (var i = 0; i < assignments; i++)
|
||||
{
|
||||
shuffledList = shuffledList.GetRange(0, plrs.Count);
|
||||
}
|
||||
var chance = Math.Clamp(modifier.GetAssignmentChance(), 0, 100);
|
||||
if (rand.Next(100) >= chance)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var id in shuffledList)
|
||||
{
|
||||
var mod = Activator.CreateInstance(IdToTypeModifierMap[id]) as GameModifier;
|
||||
var plr = plrs.Where(x => IsGameModifierValid(x, mod!, id)).Random();
|
||||
var candidates = availablePlayers
|
||||
.Where(x => IsGameModifierValid(x, modifier, modifier.TypeId))
|
||||
.ToList();
|
||||
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Warning(
|
||||
$"No available players for modifier {modifier.ModifierName} at assignment {i + 1}");
|
||||
break;
|
||||
}
|
||||
|
||||
var plr = candidates.Random();
|
||||
if (plr == null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Warning($"Somehow valid players for modifier {mod!.ModifierName} disappeared");
|
||||
}
|
||||
else
|
||||
{
|
||||
plr.RpcAddModifier(id);
|
||||
Logger<MiraApiPlugin>.Warning($"Valid player for modifier {modifier.ModifierName} disappeared");
|
||||
continue;
|
||||
}
|
||||
|
||||
plr.RpcAddModifier(modifier.TypeId);
|
||||
availablePlayers.Remove(plr);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,71 +169,6 @@ public static class ModifierManager
|
||||
private static bool IsGameModifierValid(PlayerControl player, GameModifier modifier, uint modifierId)
|
||||
{
|
||||
return (player.Data.Role is not ICustomRole role || role.IsModifierApplicable(modifier)) &&
|
||||
modifier.IsModifierValidOn(player.Data.Role) &&
|
||||
!player.HasModifier(modifierId);
|
||||
}
|
||||
|
||||
internal static void SyncAllModifiers(int targetId = -1)
|
||||
{
|
||||
var data = new List<NetData>();
|
||||
|
||||
foreach (var player in PlayerControl.AllPlayerControls)
|
||||
{
|
||||
data.Add(GetPlayerModifiers(player));
|
||||
}
|
||||
|
||||
Rpc<SyncModifiersRpc>.Instance.SendTo(PlayerControl.LocalPlayer, targetId, [.. data]);
|
||||
}
|
||||
|
||||
internal static void HandleSyncModifiers(NetData[] data)
|
||||
{
|
||||
foreach (var netData in data)
|
||||
{
|
||||
var ids = new uint[netData.Data.Length / 4];
|
||||
Buffer.BlockCopy(netData.Data, 0, ids, 0, netData.Data.Length);
|
||||
|
||||
var plr = GameData.Instance.GetPlayerById((byte)netData.Id).Object;
|
||||
var modifierComponent = plr.GetComponent<ModifierComponent>();
|
||||
|
||||
if (!modifierComponent)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
modifierComponent.ClearModifiers();
|
||||
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (!IdToTypeModifierMap.TryGetValue(id, out var type))
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error($"Cannot add modifier with id {id} because it is not registered.");
|
||||
continue;
|
||||
}
|
||||
|
||||
modifierComponent.AddModifier(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static NetData GetPlayerModifiers(PlayerControl? player)
|
||||
{
|
||||
if (player == null || !player)
|
||||
{
|
||||
return new NetData(0, []);
|
||||
}
|
||||
|
||||
List<byte> bytes = [];
|
||||
var modifierComponent = player.GetComponent<ModifierComponent>();
|
||||
if (modifierComponent == null || !modifierComponent)
|
||||
{
|
||||
return new NetData(player.PlayerId, []);
|
||||
}
|
||||
|
||||
foreach (var modifier in modifierComponent.ActiveModifiers)
|
||||
{
|
||||
bytes.AddRange(BitConverter.GetBytes(TypeToIdModifierMap[modifier.GetType()]));
|
||||
}
|
||||
|
||||
return new NetData(player.PlayerId, [.. bytes]);
|
||||
modifier.IsModifierValidOn(player.Data.Role) && !player.HasModifier(modifierId);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@
|
||||
/// </summary>
|
||||
public abstract class GameModifier : BaseModifier
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override bool ShowInFreeplay => true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the chance of the modifier being assigned to a player.
|
||||
/// </summary>
|
||||
@@ -31,7 +34,7 @@ public abstract class GameModifier : BaseModifier
|
||||
public virtual bool IsModifierValidOn(RoleBehaviour role) => true;
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the player won the game with this modifier.
|
||||
/// Determines whether the player won the game with this modifier. The modifier with the highest priority will override other modifiers.
|
||||
/// </summary>
|
||||
/// <param name="reason">The reason why the game ended.</param>
|
||||
/// <returns>True if the player won, false if they lost. Return null to use the player's default win condition.</returns>
|
||||
|
||||
@@ -17,7 +17,7 @@ public abstract class TimedModifier : BaseModifier
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the timer should start automatically when added.
|
||||
/// </summary>
|
||||
public virtual bool AutoStart => false;
|
||||
public virtual bool AutoStart => true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the modifier should be removed when the timer completes.
|
||||
@@ -27,7 +27,9 @@ public abstract class TimedModifier : BaseModifier
|
||||
/// <summary>
|
||||
/// Called when the timer completes.
|
||||
/// </summary>
|
||||
public abstract void OnTimerComplete();
|
||||
public virtual void OnTimerComplete()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the timer is active.
|
||||
@@ -43,12 +45,12 @@ public abstract class TimedModifier : BaseModifier
|
||||
public override bool HideOnUi => !TimerActive;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HUD information for Timed Modifier, including the time remaining.
|
||||
/// Gets the HUD description for Timed Modifier, including the time remaining.
|
||||
/// </summary>
|
||||
/// <returns>A string with the hud information + timer.</returns>
|
||||
public override string GetHudString()
|
||||
/// <returns>A string with the time remaining.</returns>
|
||||
public override string GetDescription()
|
||||
{
|
||||
return base.GetHudString() + $" <size=70%>({Math.Round(Duration - TimeRemaining, 0)}s/{Duration}s)</size>";
|
||||
return $"Remaining Time: {Math.Round(Duration - TimeRemaining, 0)}s/{Duration}s";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -102,7 +104,7 @@ public abstract class TimedModifier : BaseModifier
|
||||
|
||||
if (RemoveOnComplete)
|
||||
{
|
||||
ModifierComponent?.RemoveModifier(ModifierId);
|
||||
ModifierComponent?.RemoveModifier(this);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Collections.Generic;
|
||||
using Hazel;
|
||||
using InnerNet;
|
||||
using MiraAPI.GameEnd;
|
||||
using Reactor.Networking.Attributes;
|
||||
using Reactor.Networking.Rpc;
|
||||
using Reactor.Utilities;
|
||||
|
||||
namespace MiraAPI.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Custom Game Over RPC.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
[RegisterCustomRpc((uint)MiraRpc.CustomGameOver)]
|
||||
public class CustomGameOverRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, GameOverData>(plugin, id)
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override RpcLocalHandling LocalHandling => RpcLocalHandling.After;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Write(MessageWriter writer, GameOverData data)
|
||||
{
|
||||
writer.WritePacked(data.Reason);
|
||||
writer.WritePacked(data.Winners.Count);
|
||||
foreach (var player in data.Winners)
|
||||
{
|
||||
writer.WriteNetObject(player);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override GameOverData Read(MessageReader reader)
|
||||
{
|
||||
var reason = reader.ReadPackedInt32();
|
||||
var count = reader.ReadPackedInt32();
|
||||
var data = new List<NetworkedPlayerInfo>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
data.Add(reader.ReadNetObject<NetworkedPlayerInfo>());
|
||||
}
|
||||
|
||||
return new GameOverData(reason, data);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Handle(PlayerControl innerNetObject, GameOverData data)
|
||||
{
|
||||
if (GameOverManager.TryGetGameOver(data.Reason, out var gameOver))
|
||||
{
|
||||
if (!gameOver.VerifyCondition(innerNetObject, [.. data.Winners]))
|
||||
{
|
||||
Logger<MiraApiPlugin>.Info($"Game over condition not met for {gameOver.GetType().Name}");
|
||||
return;
|
||||
}
|
||||
|
||||
CustomGameOver.Instance = gameOver;
|
||||
|
||||
if (AmongUsClient.Instance.AmHost)
|
||||
{
|
||||
GameManager.Instance.RpcEndGame(gameOver, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CustomGameOver.Instance = null;
|
||||
Logger<MiraApiPlugin>.Error($"Unknown game over reason: {data.Reason}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
using AmongUs.GameOptions;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using AmongUs.Data;
|
||||
using AmongUs.GameOptions;
|
||||
using Assets.CoreScripts;
|
||||
using BepInEx.Unity.IL2CPP.Utils;
|
||||
using MiraAPI.Events;
|
||||
@@ -6,8 +9,6 @@ using MiraAPI.Events.Vanilla.Gameplay;
|
||||
using Reactor.Networking.Attributes;
|
||||
using Reactor.Networking.Rpc;
|
||||
using Reactor.Utilities.Extensions;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Networking;
|
||||
@@ -96,7 +97,7 @@ public static class CustomMurderRpc
|
||||
var flag = PlayerControl.LocalPlayer.Data.Role.Role == RoleTypes.GuardianAngel;
|
||||
if (flag && PlayerControl.LocalPlayer.Data.PlayerId == target.protectedByGuardianId)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(StringNames.StatsGuardianAngelCrewmatesProtected);
|
||||
DataManager.Player.Stats.IncrementStat(StatID.Role_GuardianAngel_CrewmatesProtected);
|
||||
AchievementManager.Instance.OnProtectACrewmate();
|
||||
}
|
||||
|
||||
@@ -127,14 +128,14 @@ public static class CustomMurderRpc
|
||||
DebugAnalytics.Instance.Analytics.Kill(target.Data, source.Data);
|
||||
if (source.AmOwner)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(
|
||||
DataManager.Player.Stats.IncrementStat(
|
||||
GameManager.Instance.IsHideAndSeek()
|
||||
? StringNames.StatsImpostorKills_HideAndSeek
|
||||
: StringNames.StatsImpostorKills);
|
||||
? StatID.HideAndSeek_ImpostorKills
|
||||
: StatID.ImpostorKills);
|
||||
|
||||
if (source.CurrentOutfitType == PlayerOutfitType.Shapeshifted)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(StringNames.StatsShapeshifterShiftedKills);
|
||||
DataManager.Player.Stats.IncrementStat(StatID.Role_Shapeshifter_ShiftedKills);
|
||||
}
|
||||
|
||||
if (Constants.ShouldPlaySfx() && playKillSound)
|
||||
@@ -152,7 +153,7 @@ public static class CustomMurderRpc
|
||||
target.gameObject.layer = LayerMask.NameToLayer("Ghost");
|
||||
if (target.AmOwner)
|
||||
{
|
||||
StatsManager.Instance.IncrementStat(StringNames.StatsTimesMurdered);
|
||||
DataManager.Player.Stats.IncrementStat(StatID.TimesMurdered);
|
||||
if (Minigame.Instance)
|
||||
{
|
||||
try
|
||||
@@ -263,7 +264,7 @@ public static class CustomMurderRpc
|
||||
deadBody.enabled = true;
|
||||
}
|
||||
|
||||
var afterMurderEvent = new AfterMurderEvent(source, target);
|
||||
var afterMurderEvent = new AfterMurderEvent(source, target, deadBody);
|
||||
MiraEventManager.InvokeEvent(afterMurderEvent);
|
||||
|
||||
if (!isParticipant)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using Hazel;
|
||||
using Reactor.Networking.Attributes;
|
||||
using Reactor.Networking.Serialization;
|
||||
|
||||
namespace MiraAPI.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Converter for <see cref="Guid"/>.
|
||||
/// </summary>
|
||||
[MessageConverter]
|
||||
public class GuidConverter : MessageConverter<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes a <see cref="Guid"/> to the writer.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
public override void Write(MessageWriter writer, Guid value)
|
||||
{
|
||||
writer.WriteBytesAndSize(value.ToByteArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a <see cref="Guid"/> from the reader.
|
||||
/// </summary>
|
||||
/// <inheritdoc />
|
||||
/// <returns>A GUID object.</returns>
|
||||
public override Guid Read(MessageReader reader, Type objectType)
|
||||
{
|
||||
return new Guid(reader.ReadBytesAndSize());
|
||||
}
|
||||
}
|
||||
@@ -34,4 +34,19 @@ public enum MiraRpc : uint
|
||||
/// Custom Murder RPC.
|
||||
/// </summary>
|
||||
CustomMurder,
|
||||
|
||||
/// <summary>
|
||||
/// Custom Game Over RPC.
|
||||
/// </summary>
|
||||
CustomGameOver,
|
||||
|
||||
/// <summary>
|
||||
/// Custom RPC to undo a player's vote.
|
||||
/// </summary>
|
||||
RemoveVote,
|
||||
|
||||
/// <summary>
|
||||
/// Custom RPC to replace Among Us CastVote.
|
||||
/// </summary>
|
||||
CastVote,
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using Hazel;
|
||||
using MiraAPI.Modifiers;
|
||||
using Reactor.Networking.Attributes;
|
||||
using Reactor.Networking.Rpc;
|
||||
using Reactor.Networking.Serialization;
|
||||
|
||||
namespace MiraAPI.Networking.Modifiers;
|
||||
|
||||
/// <summary>
|
||||
/// Remote procedure call for adding a modifier.
|
||||
/// </summary>
|
||||
/// <param name="plugin">Mira plugin.</param>
|
||||
/// <param name="id">RPC ID.</param>
|
||||
[RegisterCustomRpc((uint)MiraRpc.AddModifier)]
|
||||
public class AddModifierRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, ModifierData>(plugin, id)
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override RpcLocalHandling LocalHandling => RpcLocalHandling.Before;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Write(MessageWriter writer, ModifierData data)
|
||||
{
|
||||
writer.WritePacked(data.TypeId);
|
||||
writer.WriteBytesAndSize(data.UniqueId.ToByteArray());
|
||||
writer.WritePacked(data.Args.Length);
|
||||
foreach (var arg in data.Args)
|
||||
{
|
||||
writer.Write(arg.GetType().AssemblyQualifiedName);
|
||||
writer.Serialize(arg);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override ModifierData Read(MessageReader reader)
|
||||
{
|
||||
var modId = reader.ReadPackedUInt32();
|
||||
var guid = new Guid(reader.ReadBytesAndSize());
|
||||
var argCount = reader.ReadPackedUInt32();
|
||||
var objects = new object[argCount];
|
||||
|
||||
if (argCount > 0)
|
||||
{
|
||||
var types = new Type[argCount];
|
||||
for (var i = 0; i < argCount; i++)
|
||||
{
|
||||
var name = reader.ReadString();
|
||||
types[i] = Type.GetType(name) ?? throw new InvalidOperationException($"Type not found: {name}");
|
||||
objects[i] = reader.Deserialize(types[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return new ModifierData(modId, guid, objects);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Handle(PlayerControl player, ModifierData data)
|
||||
{
|
||||
var type = ModifierManager.GetModifierType(data.TypeId) ?? throw new InvalidOperationException($"Modifier type not found for ID {data.TypeId}.");
|
||||
BaseModifier? modifier;
|
||||
if (data.Args.Length > 0)
|
||||
{
|
||||
modifier = ModifierFactory.CreateInstance(type, data.Args);
|
||||
}
|
||||
else
|
||||
{
|
||||
modifier = Activator.CreateInstance(type) as BaseModifier;
|
||||
if (modifier == null)
|
||||
{
|
||||
throw new InvalidOperationException($"Cannot add modifier {type.Name} because it is not a valid modifier.");
|
||||
}
|
||||
}
|
||||
modifier.UniqueId = data.UniqueId;
|
||||
player.AddModifier(modifier);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using Hazel;
|
||||
using InnerNet;
|
||||
using MiraAPI.Modifiers;
|
||||
using Reactor.Networking.Attributes;
|
||||
using Reactor.Networking.Serialization;
|
||||
|
||||
namespace MiraAPI.Networking.Modifiers;
|
||||
|
||||
/// <summary>
|
||||
/// Converter for serializing and deserializing <see cref="BaseModifier"/> objects.
|
||||
/// </summary>
|
||||
[MessageConverter]
|
||||
public class ModifierConverter : MessageConverter<BaseModifier>
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes a <see cref="BaseModifier"/> to the writer.
|
||||
/// </summary>
|
||||
/// <param name="writer">The writer to write to.</param>
|
||||
/// <param name="value">The <see cref="BaseModifier"/> to write.</param>
|
||||
public override void Write(MessageWriter writer, BaseModifier value)
|
||||
{
|
||||
writer.WriteNetObject(value.Player);
|
||||
writer.WriteBytesAndSize(value.UniqueId.ToByteArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a <see cref="BaseModifier"/> from the reader.
|
||||
/// </summary>
|
||||
/// <param name="reader">The reader to read from.</param>
|
||||
/// <param name="objectType">The type of the object to read.</param>
|
||||
/// <returns>The <see cref="BaseModifier"/> that was read.</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the modifier is not found.</exception>
|
||||
public override BaseModifier Read(MessageReader reader, Type objectType)
|
||||
{
|
||||
var player = reader.ReadNetObject<PlayerControl>();
|
||||
var guid = new Guid(reader.ReadBytesAndSize());
|
||||
return player.GetModifier(guid) ?? throw new InvalidOperationException($"Modifier with GUID {guid} not found for player with ID: {player.PlayerId}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System;
|
||||
|
||||
namespace MiraAPI.Networking.Modifiers;
|
||||
|
||||
/// <summary>
|
||||
/// Modifier data for networking.
|
||||
/// </summary>
|
||||
/// <param name="TypeId">The ID of the modifier.</param>
|
||||
/// <param name="UniqueId">The unique ID of the modifier.</param>
|
||||
/// <param name="Args">Parameters for constructor.</param>
|
||||
public record struct ModifierData(uint TypeId, Guid UniqueId, object[] Args);
|
||||
@@ -1,52 +0,0 @@
|
||||
using Hazel;
|
||||
using MiraAPI.Modifiers;
|
||||
using Reactor.Networking.Attributes;
|
||||
using Reactor.Networking.Rpc;
|
||||
|
||||
namespace MiraAPI.Networking;
|
||||
|
||||
[RegisterCustomRpc((uint)MiraRpc.SyncModifiers)]
|
||||
internal sealed class SyncModifiersRpc(MiraApiPlugin plugin, uint id) : PlayerCustomRpc<MiraApiPlugin, NetData[]>(plugin, id)
|
||||
{
|
||||
public override RpcLocalHandling LocalHandling => RpcLocalHandling.None;
|
||||
|
||||
public override void Write(MessageWriter writer, NetData[]? data)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
writer.WritePacked(0U);
|
||||
return;
|
||||
}
|
||||
|
||||
writer.WritePacked((uint)data.Length);
|
||||
foreach (var netData in data)
|
||||
{
|
||||
writer.WritePacked(netData.Id);
|
||||
writer.WriteBytesAndSize(netData.Data);
|
||||
}
|
||||
}
|
||||
|
||||
public override NetData[] Read(MessageReader reader)
|
||||
{
|
||||
var length = reader.ReadPackedUInt32();
|
||||
var data = new NetData[length];
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var dataId = reader.ReadPackedUInt32();
|
||||
var bytes = reader.ReadBytesAndSize();
|
||||
data[i] = new NetData(dataId, bytes);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public override void Handle(PlayerControl playerControl, NetData[]? data)
|
||||
{
|
||||
if (AmongUsClient.Instance.HostId != playerControl.OwnerId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ModifierManager.HandleSyncModifiers(data ?? []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
[*.{cs,vb}]
|
||||
dotnet_diagnostic.CA1707.severity = none
|
||||
dotnet_diagnostic.CS1591.severity = none
|
||||
dotnet_diagnostic.SA1611.severity = none
|
||||
dotnet_diagnostic.SA1615.severity = none
|
||||
@@ -3,16 +3,15 @@ using InnerNet;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Player;
|
||||
using MiraAPI.GameOptions;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Roles;
|
||||
|
||||
namespace MiraAPI.Patches;
|
||||
|
||||
/// <summary>
|
||||
/// Sync all options, role settings, and modifiers to the player when they join the game.
|
||||
/// Sync all settings to the player when they join the game.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(AmongUsClient))]
|
||||
public static class AmongUsClientSyncPatch
|
||||
internal static class AmongUsClientSyncPatch
|
||||
{
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CreatePlayer))]
|
||||
@@ -33,7 +32,6 @@ public static class AmongUsClientSyncPatch
|
||||
|
||||
ModdedOptionsManager.SyncAllOptions(clientData.Id);
|
||||
CustomRoleManager.SyncAllRoleSettings(clientData.Id);
|
||||
ModifierManager.SyncAllModifiers(clientData.Id);
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using HarmonyLib;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Usables;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
|
||||
@@ -1,20 +1,48 @@
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Gameplay;
|
||||
using MiraAPI.GameEnd;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Patch for trigging the GameEndEvent.
|
||||
/// </summary>
|
||||
[HarmonyPatch]
|
||||
public static class EndGamePatches
|
||||
internal static class EndGamePatches
|
||||
{
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(EndGameManager), nameof(EndGameManager.SetEverythingUp))]
|
||||
public static void SetEverythingUpPatch(EndGameManager __instance)
|
||||
[HarmonyPatch(typeof(GameManager), nameof(GameManager.RpcEndGame))]
|
||||
public static class GameManagerPatches
|
||||
{
|
||||
var @event = new GameEndEvent(__instance);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
public static bool Prefix(GameOverReason endReason)
|
||||
{
|
||||
var @event = new BeforeGameEndEvent(endReason);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
|
||||
return !@event.IsCancelled;
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(EndGameManager), nameof(EndGameManager.SetEverythingUp))]
|
||||
public static class EndGameManagerPatches
|
||||
{
|
||||
public static bool Prefix(EndGameManager __instance)
|
||||
{
|
||||
if (CustomGameOver.Instance is not { } gameOver)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var result = gameOver.BeforeEndGameSetup(__instance);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void Postfix(EndGameManager __instance)
|
||||
{
|
||||
if (CustomGameOver.Instance is { } gameOver)
|
||||
{
|
||||
gameOver.AfterEndGameSetup(__instance);
|
||||
CustomGameOver.Instance = null;
|
||||
}
|
||||
|
||||
var @event = new GameEndEvent(__instance);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Gameplay;
|
||||
using MiraAPI.Utilities;
|
||||
|
||||
namespace MiraAPI.Patches;
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
/// <summary>
|
||||
/// General patches for the KillAnimation class.
|
||||
@@ -13,13 +14,17 @@ public static class KillAnimationPatches
|
||||
/// <summary>
|
||||
/// Used to trigger the <see cref="AfterMurderEvent"/>.
|
||||
/// </summary>
|
||||
/// <param name="source">The killer.</param>
|
||||
/// <param name="target">The target.</param>
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(KillAnimation), nameof(KillAnimation.CoPerformKill))]
|
||||
public static void KillAnimPostfix(PlayerControl source, PlayerControl target)
|
||||
[HarmonyPatch(typeof(KillAnimation._CoPerformKill_d__2), nameof(KillAnimation._CoPerformKill_d__2.MoveNext))]
|
||||
public static void KillAnimPostfix(KillAnimation._CoPerformKill_d__2 __instance)
|
||||
{
|
||||
var afterMurderEvent = new AfterMurderEvent(source, target);
|
||||
// Checking if state is -1 to wait for the end of coroutine.
|
||||
if (__instance.__1__state != -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var afterMurderEvent = new AfterMurderEvent(__instance.source, __instance.target, Helpers.GetBodyById(__instance.target.PlayerId));
|
||||
MiraEventManager.InvokeEvent(afterMurderEvent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using AmongUs.InnerNet.GameDataMessages;
|
||||
using HarmonyLib;
|
||||
using InnerNet;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Meeting;
|
||||
using MiraAPI.Utilities;
|
||||
using Reactor.Utilities;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
[HarmonyPatch]
|
||||
public static class ReportBodyEventPatch
|
||||
{
|
||||
private static bool ReportBodyEventHook(PlayerControl source, NetworkedPlayerInfo? target)
|
||||
{
|
||||
var body = target != null ? Helpers.GetBodyById(target.PlayerId) : null;
|
||||
|
||||
var @event = new ReportBodyEvent(source, target, body);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
return !@event.IsCancelled;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.ReportDeadBody))]
|
||||
public static bool PlayerControlCmdReportDeadBodyPrefix(PlayerControl __instance, NetworkedPlayerInfo? target)
|
||||
{
|
||||
return ReportBodyEventHook(__instance, target);
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(InnerNetClient), nameof(InnerNetClient.LateBroadcastReliableMessage))]
|
||||
public static bool LateBroadcastReliableMessagePrefix(IGameDataMessage rpcMessage)
|
||||
{
|
||||
var reportBodyMessage = rpcMessage.TryCast<RpcReportDeadBodyMessage>();
|
||||
|
||||
if (reportBodyMessage == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var source = AmongUsClient.Instance.FindObjectByNetId<PlayerControl>(reportBodyMessage.rpcObjectNetId);
|
||||
if (source == null)
|
||||
{
|
||||
Logger<MiraApiPlugin>.Error("Failed to find source player for RpcReportDeadBodyMessage with NetId: " + reportBodyMessage.rpcObjectNetId);
|
||||
return true;
|
||||
}
|
||||
|
||||
var target = GameData.Instance.GetPlayerById(reportBodyMessage.targetPlayerId);
|
||||
|
||||
return ReportBodyEventHook(source, target);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Gameplay;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
[HarmonyPatch(typeof(SpawnInMinigame), nameof(SpawnInMinigame.Close))]
|
||||
internal static class SpawnInMinigamePatch
|
||||
{
|
||||
public static void Postfix()
|
||||
{
|
||||
var @event = new RoundStartEvent(false);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Meeting;
|
||||
using MiraAPI.Utilities;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
[HarmonyPatch]
|
||||
public static class StartMeetingEventPatch
|
||||
{
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.CmdReportDeadBody))]
|
||||
public static bool PlayerControlCmdReportDeadBodyPrefix(PlayerControl __instance, NetworkedPlayerInfo? target)
|
||||
{
|
||||
var body = target != null ? Helpers.GetBodyById(target.PlayerId) : null;
|
||||
|
||||
var @event = new StartMeetingEvent(__instance, target, body);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
return !@event.IsCancelled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Gameplay;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
[HarmonyPatch]
|
||||
internal static class SubmergedSpawnGamePatch
|
||||
{
|
||||
public static bool Prepare()
|
||||
{
|
||||
return ModCompatibility.SubmergedLoaded(out _);
|
||||
}
|
||||
|
||||
public static IEnumerable<MethodBase> TargetMethods()
|
||||
{
|
||||
if (ModCompatibility.SubmergedLoaded(out var subAss) &&
|
||||
subAss.GetType("Submerged.SpawnIn.SubmarineSelectSpawn") is { } selectSpawn)
|
||||
{
|
||||
yield return AccessTools.Method(selectSpawn, "OnDestroy");
|
||||
}
|
||||
}
|
||||
|
||||
public static void Postfix()
|
||||
{
|
||||
var @event = new RoundStartEvent(false);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Usables;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using HarmonyLib;
|
||||
using System.Linq;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Events;
|
||||
using MiraAPI.Events.Vanilla.Usables;
|
||||
using System.Linq;
|
||||
|
||||
namespace MiraAPI.Patches.Events;
|
||||
|
||||
@@ -23,10 +23,10 @@ public static class VentEventPatches
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.RpcEnterVent))]
|
||||
public static bool PlayerPhysicsRpcEnterVentPrefix(PlayerPhysics __instance, int id)
|
||||
public static bool PlayerPhysicsRpcEnterVentPrefix(PlayerPhysics __instance, int ventId)
|
||||
{
|
||||
var pc = __instance.myPlayer;
|
||||
var vent = ShipStatus.Instance.AllVents.FirstOrDefault(v => v.Id == id);
|
||||
var vent = ShipStatus.Instance.AllVents.FirstOrDefault(v => v.Id == ventId);
|
||||
|
||||
var @event = new EnterVentEvent(pc, vent);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
@@ -40,10 +40,10 @@ public static class VentEventPatches
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.RpcExitVent))]
|
||||
public static bool PlayerPhysicsRpcExitVentPrefix(PlayerPhysics __instance, int id)
|
||||
public static bool PlayerPhysicsRpcExitVentPrefix(PlayerPhysics __instance, int ventId)
|
||||
{
|
||||
var pc = __instance.myPlayer;
|
||||
var vent = ShipStatus.Instance.AllVents.First(v => v.Id == id);
|
||||
var vent = ShipStatus.Instance.AllVents.First(v => v.Id == ventId);
|
||||
|
||||
var @event = new ExitVentEvent(pc, vent);
|
||||
MiraEventManager.InvokeEvent(@event);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.Roles;
|
||||
using UnityEngine;
|
||||
|
||||
namespace MiraAPI.Patches.Freeplay;
|
||||
|
||||
[HarmonyPatch(typeof(TaskAddButton))]
|
||||
internal static class TaskAddButtonPatches
|
||||
{
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(nameof(TaskAddButton.Start))]
|
||||
public static bool StartPrefix(TaskAddButton __instance)
|
||||
{
|
||||
// if this becomes problematic in the future, find a new method.
|
||||
if (uint.TryParse(__instance.name, out var result))
|
||||
{
|
||||
__instance.Overlay.sprite = __instance.CheckImage;
|
||||
__instance.Overlay.enabled = PlayerControl.LocalPlayer.HasModifier(result);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(nameof(TaskAddButton.Role), MethodType.Setter)]
|
||||
public static void RoleGetterPatch(TaskAddButton __instance)
|
||||
{
|
||||
if (__instance.role is ICustomRole { Team: ModdedRoleTeams.Custom } customRole)
|
||||
{
|
||||
__instance.FileImage.color = customRole.IntroConfiguration?.IntroTeamColor ?? Color.gray;
|
||||
}
|
||||
__instance.RolloverHandler.OutColor = __instance.FileImage.color;
|
||||
}
|
||||
}
|
||||
+144
-77
@@ -1,32 +1,27 @@
|
||||
using AmongUs.GameOptions;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using AmongUs.GameOptions;
|
||||
using HarmonyLib;
|
||||
using MiraAPI.Modifiers;
|
||||
using MiraAPI.PluginLoading;
|
||||
using MiraAPI.Roles;
|
||||
using MiraAPI.Utilities;
|
||||
using MiraAPI.Utilities.Assets;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace MiraAPI.Patches.Roles;
|
||||
namespace MiraAPI.Patches.Freeplay;
|
||||
|
||||
/// <summary>
|
||||
/// Patch TaskAdder for organizing Roles and adding scroller.
|
||||
/// </summary>
|
||||
[HarmonyPatch]
|
||||
public static class TaskAdderPatch
|
||||
[HarmonyPatch(typeof(TaskAdderGame))]
|
||||
internal static class TaskAdderPatches
|
||||
{
|
||||
private static readonly Dictionary<string, string> ModsFolders = [];
|
||||
private static Scroller? _scroller;
|
||||
private static Scroller _scroller = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Adds custom roles to the TaskAdder.
|
||||
/// </summary>
|
||||
/// <param name="__instance">TaskAdder instance.</param>
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(TaskAdderGame), nameof(TaskAdderGame.Begin))]
|
||||
[HarmonyPatch(nameof(TaskAdderGame.Begin))]
|
||||
public static void AddRolesFolder(TaskAdderGame __instance)
|
||||
{
|
||||
GameObject inner = new("Inner");
|
||||
@@ -67,45 +62,38 @@ public static class TaskAdderPatch
|
||||
rolesFolder.FolderName = "Roles";
|
||||
rolesFolder.name = "RolesFolder";
|
||||
|
||||
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
|
||||
var modifiersFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
|
||||
modifiersFolder.gameObject.SetActive(false);
|
||||
modifiersFolder.FolderName = "Modifiers";
|
||||
modifiersFolder.name = "ModifiersFolder";
|
||||
|
||||
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins)
|
||||
{
|
||||
if (plugin.CustomRoles.Count == 0)
|
||||
if (plugin.InternalRoles.Any(x => x.Value is ICustomRole { Configuration.ShowInFreeplay: true }))
|
||||
{
|
||||
continue;
|
||||
var newFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
|
||||
newFolder.name = plugin.PluginId+":Roles";
|
||||
newFolder.FolderName = plugin.PluginInfo.Metadata.Name;
|
||||
newFolder.gameObject.SetActive(false);
|
||||
rolesFolder.SubFolders.Add(newFolder);
|
||||
}
|
||||
|
||||
var newFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
|
||||
newFolder.FolderName = newFolder.name = plugin.PluginInfo.Metadata.Name;
|
||||
newFolder.gameObject.SetActive(false);
|
||||
rolesFolder.SubFolders.Add(newFolder);
|
||||
|
||||
if (!ModsFolders.ContainsKey(plugin.PluginInfo.Metadata.Name))
|
||||
if (plugin.InternalModifiers.Exists(x => x.ShowInFreeplay))
|
||||
{
|
||||
ModsFolders.Add(plugin.PluginInfo.Metadata.Name, plugin.PluginId);
|
||||
var newFolder = Object.Instantiate(__instance.RootFolderPrefab, _scroller.Inner);
|
||||
newFolder.name = plugin.PluginId+":Modifiers";
|
||||
newFolder.FolderName = plugin.PluginInfo.Metadata.Name;
|
||||
newFolder.gameObject.SetActive(false);
|
||||
modifiersFolder.SubFolders.Add(newFolder);
|
||||
}
|
||||
}
|
||||
|
||||
__instance.Root.SubFolders.Add(rolesFolder);
|
||||
__instance.Root.SubFolders.Add(modifiersFolder);
|
||||
|
||||
__instance.GoToRoot();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the color of the role button based on the role.
|
||||
/// </summary>
|
||||
/// <param name="__instance">TaskAddButton instance.</param>
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(TaskAddButton), nameof(TaskAddButton.Role), MethodType.Setter)]
|
||||
public static void RoleGetterPatch(TaskAddButton __instance)
|
||||
{
|
||||
if (__instance.role is ICustomRole { Team: ModdedRoleTeams.Custom } customRole)
|
||||
{
|
||||
__instance.FileImage.color = customRole.IntroConfiguration?.IntroTeamColor ?? Color.gray;
|
||||
}
|
||||
|
||||
__instance.RolloverHandler.OutColor = __instance.FileImage.color;
|
||||
}
|
||||
|
||||
private static void AddFileAsChildCustom(
|
||||
this TaskAdderGame instance,
|
||||
TaskAddButton item,
|
||||
@@ -130,8 +118,8 @@ public static class TaskAdderPatch
|
||||
|
||||
// yes it might be crazy patching the entire method, but i tried so many other methods and only this works :cry:
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(TaskAdderGame), nameof(TaskAdderGame.ShowFolder))]
|
||||
public static bool ShowPatch(TaskAdderGame __instance, [HarmonyArgument(0)] TaskFolder taskFolder)
|
||||
[HarmonyPatch(nameof(TaskAdderGame.ShowFolder))]
|
||||
public static bool ShowPatch(TaskAdderGame __instance, TaskFolder taskFolder)
|
||||
{
|
||||
var stringBuilder = new Il2CppSystem.Text.StringBuilder(64);
|
||||
__instance.Hierarchy.Add(taskFolder);
|
||||
@@ -277,52 +265,37 @@ public static class TaskAdderPatch
|
||||
}
|
||||
}
|
||||
|
||||
if (ModsFolders.TryGetValue(taskFolder.FolderName, out var guid))
|
||||
if (taskFolder)
|
||||
{
|
||||
var plugin = MiraPluginManager.GetPluginByGuid(guid);
|
||||
for (var m = 0; m < plugin.CustomRoles.Count; m++)
|
||||
var split = taskFolder.name.Split(':');
|
||||
if (split.Length == 2)
|
||||
{
|
||||
var roleBehaviour = plugin.CustomRoles.ElementAt(m).Value;
|
||||
if (roleBehaviour.Role == RoleTypes.ImpostorGhost || roleBehaviour.Role == RoleTypes.CrewmateGhost ||
|
||||
(roleBehaviour is ICustomRole customRole && !customRole.Configuration.ShowInFreeplay))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var pluginId = split[0];
|
||||
var folderName = split[1];
|
||||
|
||||
var taskAddButton2 = Object.Instantiate(__instance.RoleButton);
|
||||
taskAddButton2.SafePositionWorld = __instance.SafePositionWorld;
|
||||
taskAddButton2.Text.text = "Be_" + roleBehaviour.NiceName + ".exe";
|
||||
__instance.AddFileAsChildCustom(taskAddButton2, ref num, ref num2, ref num3);
|
||||
taskAddButton2.Role = roleBehaviour;
|
||||
if (taskAddButton2.Button == null)
|
||||
if (MiraPluginManager.GetPluginByGuid(pluginId) is { } plugin)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ControllerManager.Instance.AddSelectableUiElement(taskAddButton2.Button);
|
||||
switch (m)
|
||||
{
|
||||
case 0 when __instance.restorePreviousSelectionFound != null:
|
||||
ControllerManager.Instance.SetDefaultSelection(__instance.restorePreviousSelectionFound);
|
||||
__instance.restorePreviousSelectionByFolderName = string.Empty;
|
||||
__instance.restorePreviousSelectionFound = null;
|
||||
break;
|
||||
case 0:
|
||||
ControllerManager.Instance.SetDefaultSelection(taskAddButton2.Button);
|
||||
break;
|
||||
if (folderName == "Roles(Clone)")
|
||||
{
|
||||
PluginRoles(__instance, plugin, ref num, ref num2, ref num3);
|
||||
}
|
||||
else if (folderName == "Modifiers(Clone)")
|
||||
{
|
||||
PluginModifiers(__instance, plugin, ref num, ref num2, ref num3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var chip in __instance.ActiveItems)
|
||||
{
|
||||
chip.GetComponentInChildren<TextMeshPro>().EnableMasking();
|
||||
chip.GetComponentInChildren<TextMeshPro>().EnableStencilMasking();
|
||||
chip.GetComponent<SpriteRenderer>().maskInteraction = SpriteMaskInteraction.VisibleInsideMask;
|
||||
}
|
||||
|
||||
if (_scroller && _scroller != null)
|
||||
if (_scroller)
|
||||
{
|
||||
_scroller.CalculateAndSetYBounds(__instance.ActiveItems.Count, 6, 3, 1f);
|
||||
_scroller.CalculateAndSetYBounds(__instance.ActiveItems.Count, 6, 5, 1.4f);
|
||||
_scroller.SetYBoundsMin(0.0f);
|
||||
_scroller.ScrollToTop();
|
||||
}
|
||||
@@ -336,4 +309,98 @@ public static class TaskAdderPatch
|
||||
ControllerManager.Instance.SetBackButton(__instance.FolderBackButton);
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void PluginModifiers(
|
||||
TaskAdderGame instance,
|
||||
MiraPluginInfo plugin,
|
||||
ref float num,
|
||||
ref float num2,
|
||||
ref float num3)
|
||||
{
|
||||
for (var m = 0; m < plugin.InternalModifiers.Count; m++)
|
||||
{
|
||||
var modifier = plugin.InternalModifiers[m];
|
||||
if (!modifier.ShowInFreeplay)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var taskAddButton = Object.Instantiate(instance.RoleButton);
|
||||
taskAddButton.name = modifier.TypeId.ToString(NumberFormatInfo.InvariantInfo);
|
||||
taskAddButton.role = null;
|
||||
taskAddButton.MyTask = null;
|
||||
taskAddButton.SafePositionWorld = instance.SafePositionWorld;
|
||||
taskAddButton.Text.text = modifier.ModifierName;
|
||||
taskAddButton.Text.EnableMasking();
|
||||
|
||||
taskAddButton.Button.OnClick = new Button.ButtonClickedEvent();
|
||||
taskAddButton.Button.OnClick.AddListener((UnityEngine.Events.UnityAction)(() =>
|
||||
{
|
||||
var id = modifier.TypeId;
|
||||
if (PlayerControl.LocalPlayer.HasModifier(id))
|
||||
{
|
||||
PlayerControl.LocalPlayer.RemoveModifier(id);
|
||||
taskAddButton.Overlay.enabled = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
PlayerControl.LocalPlayer.AddModifier(id);
|
||||
taskAddButton.Overlay.enabled = true;
|
||||
}
|
||||
}));
|
||||
|
||||
instance.AddFileAsChildCustom(taskAddButton, ref num, ref num2, ref num3);
|
||||
|
||||
ControllerManager.Instance.AddSelectableUiElement(taskAddButton.Button);
|
||||
switch (m)
|
||||
{
|
||||
case 0 when instance.restorePreviousSelectionFound != null:
|
||||
ControllerManager.Instance.SetDefaultSelection(instance.restorePreviousSelectionFound);
|
||||
instance.restorePreviousSelectionByFolderName = string.Empty;
|
||||
instance.restorePreviousSelectionFound = null;
|
||||
break;
|
||||
case 0:
|
||||
ControllerManager.Instance.SetDefaultSelection(taskAddButton.Button);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void PluginRoles(TaskAdderGame instance, MiraPluginInfo plugin, ref float num, ref float num2, ref float num3)
|
||||
{
|
||||
for (var m = 0; m < plugin.InternalRoles.Count; m++)
|
||||
{
|
||||
var roleBehaviour = plugin.InternalRoles.ElementAt(m).Value;
|
||||
if (roleBehaviour.Role == RoleTypes.ImpostorGhost || roleBehaviour.Role == RoleTypes.CrewmateGhost ||
|
||||
roleBehaviour is ICustomRole { Configuration.ShowInFreeplay: false })
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var taskAddButton2 = Object.Instantiate(instance.RoleButton);
|
||||
taskAddButton2.SafePositionWorld = instance.SafePositionWorld;
|
||||
taskAddButton2.Text.text = "Be_" + roleBehaviour.NiceName + ".exe";
|
||||
taskAddButton2.Text.EnableMasking();
|
||||
|
||||
instance.AddFileAsChildCustom(taskAddButton2, ref num, ref num2, ref num3);
|
||||
taskAddButton2.Role = roleBehaviour;
|
||||
if (taskAddButton2.Button == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ControllerManager.Instance.AddSelectableUiElement(taskAddButton2.Button);
|
||||
switch (m)
|
||||
{
|
||||
case 0 when instance.restorePreviousSelectionFound != null:
|
||||
ControllerManager.Instance.SetDefaultSelection(instance.restorePreviousSelectionFound);
|
||||
instance.restorePreviousSelectionByFolderName = string.Empty;
|
||||
instance.restorePreviousSelectionFound = null;
|
||||
break;
|
||||
case 0:
|
||||
ControllerManager.Instance.SetDefaultSelection(taskAddButton2.Button);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
[*.cs]
|
||||
dotnet_diagnostic.S125.severity = none
|
||||
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user