Merge pull request #113 from All-Of-Us-Mods/dev

Next MiraAPI release
This commit is contained in:
Atony authored and GitHub committed 2026-10-18 18:00:39 -05:00
commit 94affd8bf3
354 files changed
+13457 -5363

No files matched your search

+106 -1
View File
@@ -1 +1,106 @@
[*.{cs,vb}]
[*.{cs,vb}]
# IDE0008: Use explicit type
dotnet_diagnostic.IDE0008.severity = none
# IDE0160: Convert to block scoped namespace
dotnet_diagnostic.IDE0160.severity = none
# IDE0011: Add braces
dotnet_diagnostic.IDE0011.severity = none
# CS8618: Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable.
dotnet_diagnostic.CS8618.severity = none
# CA1805: Do not initialize unnecessarily
dotnet_diagnostic.CA1805.severity = none
# S3358: Ternary operators should not be nested
dotnet_diagnostic.S3358.severity = none
# IDE1006: Naming Styles
dotnet_diagnostic.IDE1006.severity = none
# S3267: Use LINQ methods to simply foreach loops
dotnet_diagnostic.S3267.severity = none
# S125: Sections of code should not be commented out
dotnet_diagnostic.S125.severity = none
# SA1512: Single-line comments should not be followed by blank line
dotnet_diagnostic.SA1512.severity = none
# S2696: Instance members should not write to "static" fields
dotnet_diagnostic.S2696.severity = none
# S2245: Pseudorandom number generators (PRNGs) should not be used in security contexts
dotnet_diagnostic.S2245.severity = none
# IDE0130: Namespace does not match folder structure
dotnet_diagnostic.IDE0130.severity = none
# SA1633: File should have header
dotnet_diagnostic.SA1633.severity = none
# SA1101: Prefix local calls with this
dotnet_diagnostic.SA1101.severity = none
# SA1600: Elements should be documented
dotnet_diagnostic.SA1600.severity = none
# SA1516: Elements should be separated by blank line
dotnet_diagnostic.SA1516.severity = none
# SA1503: Braces should not be omitted
dotnet_diagnostic.SA1503.severity = none
# SA1201: Elements should appear in the correct order
dotnet_diagnostic.SA1201.severity = none
# SA1402: File may only contain a single type
dotnet_diagnostic.SA1402.severity = none
# SA1204: Static elements should appear before instance elements
dotnet_diagnostic.SA1204.severity = none
# SA1202: Elements should be ordered by access
dotnet_diagnostic.SA1202.severity = none
# SA1649: File name should match first type name
dotnet_diagnostic.SA1649.severity = none
# SA1313: Parameter names should begin with lower-case letter
dotnet_diagnostic.SA1313.severity = none
# SA1636: The file header copyright text should match the copyright text from the settings
dotnet_diagnostic.SA1636.severity = none
# SA1309: Field names should not begin with underscore
dotnet_diagnostic.SA1309.severity = none
# SA1407: Arithmetic expressions should declare precedence
dotnet_diagnostic.SA1407.severity = none
# SA1133: Each attribute should be placed in its own set of square brackets
dotnet_diagnostic.SA1133.severity = none
# IDE0001: Simplify Names
dotnet_diagnostic.IDE0001.severity = warning
# IDE0079: Remove unnecessary suppression
dotnet_diagnostic.IDE0079.severity = none
# S3903: Types should be defined in named namespaces
dotnet_diagnostic.S3903.severity = none
# IDE0045: Convert to conditional expression
dotnet_diagnostic.IDE0045.severity = none
# IDE0046: Convert to conditional expression
dotnet_diagnostic.IDE0046.severity = none
# S1244: Floating point numbers should not be tested for equality
dotnet_diagnostic.S1244.severity = none
# S2325: Methods and properties that don't access instance data should be static
dotnet_diagnostic.S2325.severity = none
+2 -2
View File
@@ -1,9 +1,9 @@
.git/
.idea/
.vs/
.vs*/
obj/
bin/
.qodo/
*.user
*.lock.json
*.lock.json
+1 -1
View File
@@ -2,7 +2,7 @@
<ItemGroup>
<PackageReference Include="Reactor" Version="2.5.0-ci.371" />
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.735" Private="false" ExcludeAssets="runtime;native" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2026.8.18" PrivateAssets="all" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2026.9.29" PrivateAssets="all" />
<PackageReference Include="BepInEx.AutoPlugin" Version="1.1.0" PrivateAssets="all" />
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.1.0-rc.1" PrivateAssets="all" ExcludeAssets="runtime" />
+6 -9
View File
@@ -28,18 +28,15 @@
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisMode>recommended</AnalysisMode>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<NoWarn>$(NoWarn);SA0001</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Roslynator.Analyzers" Version="5.0.0" PrivateAssets="all" />
<PackageReference Include="Roslynator.Formatting.Analyzers" Version="5.0.0" PrivateAssets="all" />
<PackageReference Include="Roslynator.CodeAnalysis.Analyzers" Version="5.0.0" PrivateAssets="all" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.32.0.713" PrivateAssets="all" />
<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="10.7.0.110445">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<AdditionalFiles Include="$(MSBuildThisFileDirectory)/stylecop.json" Link="stylecop.json" Visible="false" />
</ItemGroup>
<PropertyGroup>
<CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)\stylecop.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
</Project>
+29
View File
@@ -0,0 +1,29 @@
<assembly name="0Harmony">
<member name="T:HarmonyLib.HarmonyPatch">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor(JetBrains.Annotations.ImplicitUseTargetFlags)">
<argument>3</argument>
</attribute>
</member>
<member name="T:HarmonyLib.HarmonyPrefix">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
</member>
<member name="T:HarmonyLib.HarmonyPostfix">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
</member>
<member name="T:HarmonyLib.HarmonyTranspiler">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
</member>
<member name="T:HarmonyLib.HarmonyFinalizer">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
</member>
<member name="T:HarmonyLib.HarmonyPrepare">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
</member>
<member name="T:HarmonyLib.HarmonyTargetMethod">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
</member>
<member name="T:HarmonyLib.HarmonyTargetMethods">
<attribute ctor="M:JetBrains.Annotations.MeansImplicitUseAttribute.#ctor" />
</member>
</assembly>
+7
View File
@@ -0,0 +1,7 @@
[*.{cs,vb}]
# SA1602: Enumeration items should be documented.
dotnet_diagnostic.SA1602.severity = none
# SA1601: Partial elements should be documented
dotnet_diagnostic.SA1601.severity = none
+3 -5
View File
@@ -10,9 +10,7 @@ namespace MiraAPI.Example.Buttons;
public class MeetingButton : CustomActionButton
{
public override string Name => "button.callMeeting";
public override float Cooldown => 15;
public override int MaxUses => 3;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
@@ -30,10 +28,10 @@ public class MeetingButton : CustomActionButton
PlayerControl.LocalPlayer.NetTransform.Halt();
var minigame = Object.Instantiate(bt.MinigamePrefab, Camera.main!.transform, false);
var taskAdderGame = minigame as TaskAdderGame;
if (taskAdderGame != null)
var taskAdderGame = minigame.TryCast<TaskAdderGame>();
if (taskAdderGame)
{
taskAdderGame.SafePositionWorld = bt.SafePositionLocal + (Vector2)bt.transform.position;
taskAdderGame!.SafePositionWorld = bt.SafePositionLocal + (Vector2)bt.transform.position;
}
minigame.transform.localPosition = new Vector3(0f, 0f, -50f);
@@ -61,11 +61,14 @@ public class TeleportButton : CustomActionButton
{
Camera.main.orthographicSize = MeetingHud.Instance ? 3f : ft;
ResolutionManager.ResolutionChanged.Invoke((float)Screen.width / Screen.height, Screen.width, Screen.height, Screen.fullScreen);
foreach (var cam in Camera.allCameras) cam.orthographicSize = Camera.main.orthographicSize;
foreach (var cam in Camera.allCameras)
cam.orthographicSize = Camera.main.orthographicSize;
yield return null;
}
foreach (var cam in Camera.allCameras) cam.orthographicSize = zoomDistance;
foreach (var cam in Camera.allCameras)
cam.orthographicSize = zoomDistance;
ResolutionManager.ResolutionChanged.Invoke((float)Screen.width / Screen.height, Screen.width, Screen.height, Screen.fullScreen);
}
@@ -75,12 +78,14 @@ public class TeleportButton : CustomActionButton
{
Camera.main.orthographicSize = MeetingHud.Instance ? 3f : ft;
ResolutionManager.ResolutionChanged.Invoke((float)Screen.width / Screen.height, Screen.width, Screen.height, Screen.fullScreen);
foreach (var cam in Camera.allCameras) cam.orthographicSize = Camera.main.orthographicSize;
foreach (var cam in Camera.allCameras)
cam.orthographicSize = Camera.main.orthographicSize;
yield return null;
}
foreach (var cam in Camera.allCameras) cam.orthographicSize = 3f;
foreach (var cam in Camera.allCameras)
cam.orthographicSize = 3f;
HudManager.Instance.ShadowQuad.gameObject.SetActive(true);
IsZoom = false;
+3
View File
@@ -1,4 +1,5 @@
using MiraAPI.Hud;
using MiraAPI.Keybinds;
using MiraAPI.Translation;
using MiraAPI.Utilities.Assets;
using UnityEngine;
@@ -13,6 +14,8 @@ public class ThinkButton : CustomActionButton
public override int MaxUses => 1;
public override ButtonUsesMode UsesMode => ButtonUsesMode.PerRound;
public override LoadableAsset<Sprite> Sprite => ExampleAssets.ExampleButton;
public override MiraKeybind Keybind => MiraGlobalKeybinds.SecondaryAbility;
protected override void OnClick()
{
Button!.OverrideText("button.think.thinking".Translate());
+7
View File
@@ -1,4 +1,6 @@
using MiraAPI.Colors;
using MiraAPI.Colors.ColorSpaces;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Example;
@@ -14,4 +16,9 @@ public static class ExampleColors
public static CustomColor Rose { get; } = new("color.rose", new Color(0.98f, 0.26f, 0.62f));
public static CustomColor Gold { get; } = new("color.gold", new Color(1.0f, 0.84f, 0.0f));
public static VariableColor Rainbow { get; } = new("color.rainbow", t => new HsbColor(MathUtilities.PingPong(t, 1f, 0.3f), 1f, 1f))
{
ColorBrightness = CustomColorBrightness.Lighter,
};
}
+2 -2
View File
@@ -1,4 +1,4 @@
using MiraAPI.Keybinds;
using MiraAPI.Keybinds;
using Rewired;
namespace MiraAPI.Example;
@@ -6,5 +6,5 @@ namespace MiraAPI.Example;
[RegisterCustomKeybinds]
public static class ExampleKeybinds
{
public static MiraKeybind NeutralWinKeybind { get; } = new("Neutral Win", KeyboardKeyCode.C, [ModifierKey.Shift]);
public static MiraKeybind NeutralWinKeybind { get; } = new("Neutral Win", KeyboardKeyCode.C, ControllerButton.RightStick, [ModifierKey.Shift]);
}
+1 -1
View File
@@ -33,7 +33,7 @@ public class ExampleLocalSettings(ConfigFile config) : LocalSettingsTab(config)
public ConfigEntry<float> ExampleNumber { get; private set; } = config.Bind("General", "Example Number", 4f);
[LocalNumberSetting(min: 0.1f, max: 2.5f, increment: 0.1f, formatString: "0.0", suffixType: MiraNumberSuffixes.Multiplier)]
public ConfigEntry<float> ExampleFloatNumber { get; private set; } = config.Bind("General", "Example Multplier", 1f);
public ConfigEntry<float> ExampleFloatNumber { get; private set; } = config.Bind("General", "Example Multiplier", 1f);
[LocalEnumSetting]
public ConfigEntry<ExampleEnumSetting> ExampleEnum { get; private set; } = config.Bind("General", "Example Enum", ExampleEnumSetting.Fries);
+9 -3
View File
@@ -21,10 +21,16 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
{
MiraLocaleManager.Register("mira.example");
}
public Harmony Harmony { get; } = new(Id);
public string OptionsTitleText => "Mira API\nExample Mod";
public string CustomOptionMenuNameTwo => "angxl's Options";
public ConfigFile GetConfigFile() => Config;
public string OptionsTitleText { get; } = "Mira API\nExample Mod";
public string CustomOptionMenuNameTwo { get; } = "Example Options";
public ConfigFile GetConfigFile()
{
return Config;
}
public override void Load()
{
ExampleEventHandlers.Initialize();
+7 -7
View File
@@ -1,18 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Version>1.0.0</Version>
<Description>Example mod for Mira API</Description>
<Authors>Angxl, XtraCube</Authors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Authors>Author Name</Authors>
<NoWarn>$(NoWarn);EnableGenerateDocumentationFile</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\MiraAPI\MiraAPI.csproj" />
<ProjectReference Include="..\MiraAPI\MiraAPI.csproj" /> <!-- You typically would use the nuget package here: AllOfUs.MiraAPI -->
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\**\*.*" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\**\*.*" />
</ItemGroup>
<Import Project="..\AmongUs.props" />
</Project>
@@ -1,5 +1,4 @@
using Il2CppSystem;
using MiraAPI.Example.Roles;
using MiraAPI.Example.Roles;
using MiraAPI.Modifiers.Types;
using MiraAPI.Translation;
using UnityEngine;
@@ -28,7 +27,7 @@ public class FreezeModifier : TimedModifier
if (Player.AmOwner || PlayerControl.LocalPlayer.Data.Role is FreezerRole)
{
Player.cosmetics.SetOutline(true, new Nullable<Color>(Palette.LightBlue));
Player.cosmetics.SetOutline(true, new Il2CppSystem.Nullable<Color>(Palette.LightBlue));
}
}
+63 -6
View File
@@ -1,31 +1,88 @@
using MiraAPI.GameOptions;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Example.Options;
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Demo.")]
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Read above.")]
[SuppressMessage("Minor Code Smell", "S3400:Methods should not return constants", Justification = "Read above.")]
public class ExampleOptions : AbstractOptionGroup
{
public override string GroupName => "options.exampleOptions1";
public override Color GroupColor => Color.green;
public override bool ShowInMatchInfoGuide => true;
[ModdedToggleOption("options.exampleOptions1.toggleOpt1")]
public bool ToggleOpt { get; set; } = false;
[ModdedOptionVisibility] // Automatically resolves to using ToggleOpt1Visibility, can also target toggle options
public bool ToggleOpt1 { get; set; } = false;
[ModdedToggleOption("options.exampleOptions1.toggleOpt1")]
[ModdedToggleOption("options.exampleOptions1.toggleOpt2")]
[ModdedOptionVisibility(nameof(ToggleOpt1))] // ToggleOpt2 will be visible only when ToggleOpt1 is true
public bool ToggleOpt2 { get; set; } = true;
[ModdedNumberOption("options.exampleOptions1.numberOpt", min: 0, max: 10, increment: .25f, formatString: "0.00", suffixType: MiraNumberSuffixes.Percent)]
[ModdedOptionVisibility(nameof(NumberOptVisibility))] // Can also target static methods
public float NumberOpt { get; set; } = 4f;
[ModdedEnumOption("options.exampleOptions1.bestApi", typeof(BestApi), ["Mira API", "Mitochondria", "Reactor"])]
public BestApi Opt { get; set; } = BestApi.MiraAPI;
[ModdedNumberOption("options.exampleOptions1.numberOpt", min: 0, max: 10, suffixType: MiraNumberSuffixes.Distance)]
public int NumberOpt2 { get; set; } = 4; // Can also be int!
[ModdedEnumOption("options.exampleOptions1.bestApi", typeof(Api), ["Mira API", "Mitochondria", "Reactor"])]
public Api BestApi { get; set; } = Api.MiraAPI;
[ModdedEnumOption<Api>("options.exampleOptions1.worstApi", ["Mira API", "Mitochondria", "Reactor"])]
// These three can target both instance and static methods
[ModdedOptionGetter(nameof(GetApi))] // Can also automatically resolve to {Option Name}Getter
[ModdedOptionSetter(nameof(SetApi))] // Can also automatically resolve to {Option Name}Setter
[ModdedOptionChanged(nameof(ApiChanged))] // Can also automatically resolve to {Option Name}Changed
public Api WorstApi { get; set; } = Api.MiraAPI;
[ModdedEnumOptionList<ValueState>("Value State {0}", ["None", "Primary", "Secondary"])]
public ModdedArray<ValueState> ValueStates { get; set; } = [ValueState.Primary, ValueState.Secondary, ValueState.None, ValueState.None, ValueState.None];
[ModdedPlayerOption("options.exampleOptions1.players")]
public NetworkedPlayerInfo PlayerSelected { get; set; }
public bool ToggleOpt1Visibility()
{
return true;
}
public static bool NumberOptVisibility()
{
return true;
}
public static Api GetApi(Api currentValue)
{
return currentValue;
}
public static Api SetApi(Api newValue, Api oldValue)
{
return default;
}
public static void ApiChanged(Api currentValue)
{
// Something
}
}
public enum BestApi
public enum Api
{
MiraAPI,
Mitochondria,
Reactor,
}
public enum ValueState
{
None,
Primary,
Secondary,
}
+6 -2
View File
@@ -7,15 +7,17 @@ namespace MiraAPI.Example.Options;
public class ExampleOptions2 : AbstractOptionGroup
{
public override string GroupName => "options.exampleOptions2";
public override uint GroupPriority => 0; // This group will be displayed first. The default value is uint.MaxValue.
public override MenuCategory ParentMenu => MenuCategory.CustomTwo;
public override bool ShowInMatchInfoGuide => true;
public ModdedPlayerOption PlayerOption2 { get; } = new("options.exampleOptions2.youMustChoseAPlayer", false);
public ModdedPlayerOption PlayerOption { get; } = new("options.exampleOptions2.ehWhatever");
public ModdedToggleOption ToggleOpt1 { get; } = new("options.exampleOptions2.toggleOption1", false);
public ModdedOptionList<ModdedNumberOption> PlayerNums { get; } = new(5, i =>
new($"PlayerNum{i}", 2, 0, 5, 1, Utilities.MiraNumberSuffixes.None));
public ModdedToggleOption ToggleOpt2 { get; } = new("options.exampleOptions2.toggleOption2", false)
{
Visible = () => OptionGroupSingleton<ExampleOptions2>.Instance.ToggleOpt1, // implicit cast from ModdedToggleOption to bool
@@ -24,6 +26,8 @@ public class ExampleOptions2 : AbstractOptionGroup
public ModdedEnumOption<TestingData> EnumOpt { get; } = new("options.exampleOptions2.enumOpt", 0)
{
ChangedEvent = x => Logger<ExamplePlugin>.Info($"changed Enum Opt to {x}"),
Getter = currentValue => currentValue,
Setter = (newValue, oldValue) => newValue,
};
}
@@ -6,14 +6,12 @@ namespace MiraAPI.Example.Options.Modifiers;
public class GeneralModifierOptions : AbstractOptionGroup
{
public override string GroupName => "options.generalModifier";
public override uint GroupPriority => 0;
public override MenuCategory ParentMenu => MenuCategory.Modifiers;
[ModdedToggleOption("options.generalModifier.someBooleanOption")]
public bool SomeBooleanOption { get; set; } = true;
[ModdedNumberOption("options.generalModifier.numberOption", 0, 10, 1)]
[ModdedNumberOption("options.generalModifier.numberOption", 0, 10)]
public float NumberOption { get; set; } = 5;
}
+9 -6
View File
@@ -16,11 +16,11 @@
Your votes have double the power.</string>
<string name="ApiExample.Role.Crewmate.Mayor.TabDescription">You get one extra vote in the meeting!</string>
<string name="ApiExample.Role.Crewmate.Mayor.WikiDescription">The Mayor is a Crewmate role that gets two votes in the meeting, instead of the singular vote other Crewmates get.</string>
<string name="ApiExample.Role.Crewmate.Chamelon">Chamelon</string>
<string name="ApiExample.Role.Crewmate.Chamelon.IntroBlurb">Become one with the environment.</string>
<string name="ApiExample.Role.Crewmate.Chamelon.MedDescription">Fade out of everyone's vision by not moving.</string>
<string name="ApiExample.Role.Crewmate.Chamelon.TabDescription">Stay invisible while not moving.</string>
<string name="ApiExample.Role.Crewmate.Chamelon.WikiDescription">The Chamelon is a Crewmate role that slowly becomes invisible while standing still.</string>
<string name="ApiExample.Role.Crewmate.Chameleon">Chameleon</string>
<string name="ApiExample.Role.Crewmate.Chameleon.IntroBlurb">Become one with the environment.</string>
<string name="ApiExample.Role.Crewmate.Chameleon.MedDescription">Fade out of everyone's vision by not moving.</string>
<string name="ApiExample.Role.Crewmate.Chameleon.TabDescription">Stay invisible while not moving.</string>
<string name="ApiExample.Role.Crewmate.Chameleon.WikiDescription">The Chameleon is a Crewmate role that slowly becomes invisible while standing still.</string>
<string name="ApiExample.Role.Outcast.OutcastKiller">Outcast Killer</string>
<string name="ApiExample.Role.Outcast.OutcastKiller.IntroBlurb">Kill everyone else.</string>
<string name="ApiExample.Role.Outcast.OutcastKiller.MedDescription">Be the last outcast standing.
@@ -47,6 +47,8 @@ Eliminate every other faction.</string>
<string name="options.exampleOptions1.toggleOpt2">Toggle Opt 2</string>
<string name="options.exampleOptions1.numberOpt">Number Opt</string>
<string name="options.exampleOptions1.bestApi">Best API</string>
<string name="options.exampleOptions1.worstApi">Worst API</string>
<string name="options.exampleOptions1.players">Choose A Player</string>
<string name="options.exampleOptions2">Example Options 2</string>
<string name="options.exampleOptions2.youMustChoseAPlayer">YOU MUST CHOSE A PLAYER</string>
<string name="options.exampleOptions2.ehWhatever">Eh whatever</string>
@@ -73,11 +75,12 @@ Eliminate every other faction.</string>
<string name="settings.miraExample.exampleBool2">Example Bool 2</string>
<string name="settings.miraExample.slider">Slider</string>
<string name="settings.miraExample.exampleNumber">Example Number</string>
<string name="settings.miraExample.exampleMultiplier">Example Multplier</string>
<string name="settings.miraExample.exampleMultiplier">Example Multiplier</string>
<string name="settings.miraExample.exampleEnum">Example Enum</string>
<string name="settings.miraExample.button.exampleButton">Example Button</string>
<string name="gameover.outcastKiller.win">Outcast Killer Wins!</string>
<string name="color.cerulean">Cerulean</string>
<string name="color.rose">Rose</string>
<string name="color.gold">Gold</string>
<string name="color.rainbow">Rainbow</string>
</resources>
+11 -12
View File
@@ -3,20 +3,19 @@ using MiraAPI.Patches.Stubs;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using TMPro;
using UnityEngine;
namespace MiraAPI.Example.Roles;
public class ChameloenRole : CrewmateRole, ICustomRole
public class ChameleonRole : CrewmateRole, ICustomRole
{
public string IdPart => "Chamelon";
private bool shouldHide;
public string IdPart => "Chameleon";
public string IdPrefix => "ApiExample.Role.Crewmate";
public Color RoleColor => Palette.AcceptedGreen;
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
private bool _shouldHide;
public CustomRoleConfiguration Configuration => new(this)
{
OptionsScreenshot = ExampleAssets.Banner,
@@ -29,14 +28,14 @@ public class ChameloenRole : CrewmateRole, ICustomRole
public override void Initialize(PlayerControl player)
{
Logger<ExamplePlugin>.Info("Initializing ChamelonRole for player: " + player.PlayerId);
Logger<ExamplePlugin>.Info("Initializing ChameleonRole for player: " + player.PlayerId);
RoleBehaviourStubs.Initialize(this, player);
_shouldHide = true;
shouldHide = true;
}
public void FixedUpdate()
{
if (!Player || !_shouldHide)
if (!Player || !shouldHide)
{
return;
}
@@ -55,8 +54,8 @@ public class ChameloenRole : CrewmateRole, ICustomRole
}
else
{
SpriteRenderer rend = Player.cosmetics.currentBodySprite.BodySprite;
TextMeshPro tmp = Player.cosmetics.nameText;
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, Player.AmOwner ? 0.3f : 0),
@@ -75,9 +74,9 @@ public class ChameloenRole : CrewmateRole, ICustomRole
public override void Deinitialize(PlayerControl targetPlayer)
{
Logger<ExamplePlugin>.Info("Deinitializing ChamelonRole for player: " + targetPlayer.PlayerId);
Logger<ExamplePlugin>.Info("Deinitializing ChameleonRole for player: " + targetPlayer.PlayerId);
RoleBehaviourStubs.Deinitialize(this, targetPlayer);
_shouldHide = false;
shouldHide = false;
foreach (var cosmetic in Player.cosmetics.transform.GetComponentsInChildren<SpriteRenderer>(true))
{
cosmetic.color = Color.white;
+1 -1
View File
@@ -11,7 +11,7 @@ public class FreezerRole : ImpostorRole, ICustomRole
public Color RoleColor => Palette.Blue;
public ModdedRoleTeams Team => ModdedRoleTeams.Impostor;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
public CustomRoleConfiguration Configuration => new(this)
{
Icon = MiraAssets.ImpostorFile,
IconTmp = TmpSpriteUtils.CreateSpriteAsset(MiraAssets.ImpostorFile.LoadAsset(), "ApiExample.Role.Impostor.Freezer"),
+1 -1
View File
@@ -10,7 +10,7 @@ public class TeleporterRole : CrewmateRole, ICustomRole
public Color RoleColor => new Color32(221, 176, 152, 255);
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
public CustomRoleConfiguration Configuration => new(this)
{
OptionsScreenshot = ExampleAssets.Banner,
CanModifyChance = false,
+107
View File
@@ -0,0 +1,107 @@
using System;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Colors.ColorSpaces;
/// <summary>
/// A struct that denotes the CMYK (Cyan, Magenta, Yellow, Key) color space.
/// </summary>
/// <param name="c">The cyan component.</param>
/// <param name="m">The magenta component.</param>
/// <param name="y">The yellow component.</param>
/// <param name="k">The key component.</param>
/// <param name="a">The alpha component.</param>
[Serializable]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "Unity parity.")]
public record struct CmykColor(float c, float m, float y, float k, float a = 1f)
{
/// <summary>
/// Implicitly converts a <see cref="CmykColor"/> to a Unity <see cref="Color"/>.
/// </summary>
/// <param name="c">The color being converted.</param>
public static implicit operator Color(CmykColor c)
{
return ToColor(c);
}
/// <summary>
/// Implicitly converts a Unity <see cref="Color"/> to a <see cref="CmykColor"/>.
/// </summary>
/// <param name="c">The color being converted.</param>
public static implicit operator CmykColor(Color c)
{
return FromColor(c);
}
/// <summary>
/// Converts a <see cref="CmykColor"/> to a standard Unity RGB <see cref="Color"/>.
/// </summary>
/// <param name="cmyk">The CMYK color to convert.</param>
/// <returns>A Unity <see cref="Color"/> representing the same visual color.</returns>
public static Color ToColor(CmykColor cmyk)
{
var key = 1f - cmyk.k;
var r = (1f - cmyk.c) * key;
var g = (1f - cmyk.m) * key;
var b = (1f - cmyk.y) * key;
return new Color(MathUtilities.Clamp01(r), MathUtilities.Clamp01(g), MathUtilities.Clamp01(b), cmyk.a);
}
/// <summary>
/// Converts a standard Unity RGB <see cref="Color"/> to a <see cref="CmykColor"/>.
/// </summary>
/// <param name="color">The Unity Color to convert.</param>
/// <returns>A <see cref="CmykColor"/> representing the same visual color.</returns>
public static CmykColor FromColor(Color color)
{
var r = color.r;
var g = color.g;
var b = color.b;
var k = 1f - MathF.Max(r, MathF.Max(g, b));
if (k >= 1f)
return new CmykColor(0f, 0f, 0f, 1f, color.a);
var invK = 1f / (1f - k);
var c = (1f - r - k) * invK;
var m = (1f - g - k) * invK;
var y = (1f - b - k) * invK;
return new CmykColor(MathUtilities.Clamp01(c), MathUtilities.Clamp01(m), MathUtilities.Clamp01(y), MathUtilities.Clamp01(k), color.a);
}
/// <summary>
/// Linearly interpolates between two <see cref="CmykColor"/> values.
/// </summary>
/// <param name="a">The starting color.</param>
/// <param name="b">The ending color.</param>
/// <param name="t">The interpolation value between the two colors, clamped to a 0 to 1 range.</param>
/// <returns>The interpolated <see cref="CmykColor"/>.</returns>
public static CmykColor Lerp(CmykColor a, CmykColor b, float t)
{
return LerpUnclamped(a, b, MathUtilities.Clamp01(t));
}
/// <summary>
/// Linearly interpolates between two <see cref="CmykColor"/> values without clamping the interpolant.
/// </summary>
/// <param name="a">The starting color.</param>
/// <param name="b">The ending color.</param>
/// <param name="t">The interpolation value between the two colors.</param>
/// <returns>The interpolated <see cref="CmykColor"/>.</returns>
public static CmykColor LerpUnclamped(CmykColor a, CmykColor b, float t)
{
return new CmykColor(
MathUtilities.LerpUnclamped(a.c, b.c, t),
MathUtilities.LerpUnclamped(a.m, b.m, t),
MathUtilities.LerpUnclamped(a.y, b.y, t),
MathUtilities.LerpUnclamped(a.k, b.k, t),
MathUtilities.LerpUnclamped(a.a, b.a, t));
}
}
+136
View File
@@ -0,0 +1,136 @@
using System;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Colors.ColorSpaces;
/// <summary>
/// A struct that denotes the HSB (Hue, Saturation, Brightness) color space.
/// </summary>
/// <param name="h">The hue component.</param>
/// <param name="s">The saturation component.</param>
/// <param name="b">The brightness component.</param>
/// <param name="a">The alpha component.</param>
[Serializable]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "Unity parity.")]
public record struct HsbColor(float h, float s, float b, float a = 1f)
{
/// <summary>
/// Implicitly converts an <see cref="HsbColor"/> to a Unity <see cref="Color"/>.
/// </summary>
/// <param name="c">The color being converted.</param>
public static implicit operator Color(HsbColor c)
{
return ToColor(c);
}
/// <summary>
/// Implicitly converts a Unity <see cref="Color"/> to an <see cref="HsbColor"/>.
/// </summary>
/// <param name="c">The color being converted.</param>
public static implicit operator HsbColor(Color c)
{
return FromColor(c);
}
/// <summary>
/// Converts an <see cref="HsbColor"/> to a standard Unity RGB <see cref="Color"/>.
/// </summary>
/// <param name="hsb">The HSB color to convert.</param>
/// <returns>A Unity <see cref="Color"/> representing the same visual color.</returns>
public static Color ToColor(HsbColor hsb)
{
if (hsb.s <= float.Epsilon)
return new Color(MathUtilities.Clamp01(hsb.b), MathUtilities.Clamp01(hsb.b), MathUtilities.Clamp01(hsb.b), hsb.a);
var c = hsb.b * hsb.s;
var hPrime = hsb.h * 6f;
var x = c * (1f - MathF.Abs((hPrime % 2f) - 1f));
var m = hsb.b - c;
var (r, g, b) = hPrime switch
{
< 1f => (c, x, 0f),
< 2f => (x, c, 0f),
< 3f => (0f, c, x),
< 4f => (0f, x, c),
< 5f => (x, 0f, c),
<= 6f => (c, 0f, x),
_ => (0f, 0f, 0f),
};
return new Color(
MathUtilities.Clamp01(r + m),
MathUtilities.Clamp01(g + m),
MathUtilities.Clamp01(b + m),
hsb.a);
}
/// <summary>
/// Converts a standard Unity RGB <see cref="Color"/> to an <see cref="HsbColor"/>.
/// </summary>
/// <param name="color">The Unity Color to convert.</param>
/// <returns>An <see cref="HsbColor"/> representing the same visual color.</returns>
public static HsbColor FromColor(Color color)
{
var max = MathF.Max(color.r, MathF.Max(color.g, color.b));
var min = MathF.Min(color.r, MathF.Min(color.g, color.b));
var delta = max - min;
var h = 0f;
if (delta > 0f)
{
if (max == color.r)
h = (color.g - color.b) / delta % 6f;
else if (max == color.g)
h = (color.b - color.r) / delta + 2f;
else
h = (color.r - color.g) / delta + 4f;
h /= 6f;
if (h < 0f)
h += 1f;
}
var s = max == 0f ? 0f : delta / max;
var b = max;
return new HsbColor(h, s, b, color.a);
}
/// <summary>
/// Linearly interpolates between two <see cref="HsbColor"/> values, using the shortest path for the hue.
/// </summary>
/// <param name="a">The starting color.</param>
/// <param name="b">The ending color.</param>
/// <param name="t">The interpolation value between the two colors, clamped to a 0 to 1 range.</param>
/// <returns>The interpolated <see cref="HsbColor"/>.</returns>
public static HsbColor Lerp(HsbColor a, HsbColor b, float t)
{
return LerpUnclamped(a, b, MathUtilities.Clamp01(t));
}
/// <summary>
/// Linearly interpolates between two <see cref="HsbColor"/> values without clamping the interpolant.
/// </summary>
/// <param name="a">The starting color.</param>
/// <param name="b">The ending color.</param>
/// <param name="t">The interpolation value between the two colors.</param>
/// <returns>The interpolated <see cref="HsbColor"/>.</returns>
public static HsbColor LerpUnclamped(HsbColor a, HsbColor b, float t)
{
var hueDifference = MathUtilities.Repeat(b.h - a.h, 1f);
if (hueDifference > 0.5f)
hueDifference -= 1f;
return new HsbColor(
MathUtilities.Repeat(a.h + (hueDifference * t), 1f),
MathUtilities.LerpUnclamped(a.s, b.s, t),
MathUtilities.LerpUnclamped(a.b, b.b, t),
MathUtilities.LerpUnclamped(a.a, b.a, t));
}
}
+132
View File
@@ -0,0 +1,132 @@
using System;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Colors.ColorSpaces;
/// <summary>
/// A struct that denotes the HSL (Hue, Saturation, Lightness) color space.
/// </summary>
/// <param name="h">The hue component.</param>
/// <param name="s">The saturation component.</param>
/// <param name="l">The lightness component.</param>
/// <param name="a">The alpha component.</param>
[Serializable]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", Justification = "Unity parity.")]
public record struct HslColor(float h, float s, float l, float a = 1f)
{
/// <summary>
/// Implicitly converts an <see cref="HslColor"/> to a Unity <see cref="Color"/>.
/// </summary>
/// <param name="c">The color being converted.</param>
public static implicit operator Color(HslColor c)
{
return ToColor(c);
}
/// <summary>
/// Implicitly converts a Unity <see cref="Color"/> to an <see cref="HslColor"/>.
/// </summary>
/// <param name="c">The color being converted.</param>
public static implicit operator HslColor(Color c)
{
return FromColor(c);
}
/// <summary>
/// Converts an <see cref="HslColor"/> to a standard Unity RGB <see cref="Color"/>.
/// </summary>
/// <param name="hsl">The HSL color to convert.</param>
/// <returns>A Unity <see cref="Color"/> representing the same visual color.</returns>
public static Color ToColor(HslColor hsl)
{
if (hsl.s <= float.Epsilon)
return new Color(MathUtilities.Clamp01(hsl.l), MathUtilities.Clamp01(hsl.l), MathUtilities.Clamp01(hsl.l), hsl.a);
var c = (1f - MathF.Abs(2f * hsl.l - 1f)) * hsl.s;
var hPrime = hsl.h * 6f;
var x = c * (1f - MathF.Abs((hPrime % 2f) - 1f));
var m = hsl.l - c / 2f;
var (r, g, b) = hPrime switch
{
< 1f => (c, x, 0f),
< 2f => (x, c, 0f),
< 3f => (0f, c, x),
< 4f => (0f, x, c),
< 5f => (x, 0f, c),
<= 6f => (c, 0f, x),
_ => (0f, 0f, 0f),
};
return new Color(MathUtilities.Clamp01(r + m), MathUtilities.Clamp01(g + m), MathUtilities.Clamp01(b + m), hsl.a);
}
/// <summary>
/// Converts a standard Unity RGB <see cref="Color"/> to an <see cref="HslColor"/>.
/// </summary>
/// <param name="color">The Unity Color to convert.</param>
/// <returns>An <see cref="HslColor"/> representing the same visual color.</returns>
public static HslColor FromColor(Color color)
{
var max = MathF.Max(color.r, MathF.Max(color.g, color.b));
var min = MathF.Min(color.r, MathF.Min(color.g, color.b));
var l = (max + min) / 2f;
var delta = max - min;
var s = delta == 0f ? 0f : delta / (1f - MathF.Abs((2f * l) - 1f));
var h = 0f;
if (delta > 0f)
{
if (max == color.r)
h = (color.g - color.b) / delta % 6f;
else if (max == color.g)
h = (color.b - color.r) / delta + 2f;
else
h = (color.r - color.g) / delta + 4f;
h /= 6f;
if (h < 0f)
h += 1f;
}
return new HslColor(h, s, l, color.a);
}
/// <summary>
/// Linearly interpolates between two <see cref="HslColor"/> values, using the shortest path for the hue.
/// </summary>
/// <param name="a">The starting color.</param>
/// <param name="b">The ending color.</param>
/// <param name="t">The interpolation value between the two colors, clamped to a 0 to 1 range.</param>
/// <returns>The interpolated <see cref="HslColor"/>.</returns>
public static HslColor Lerp(HslColor a, HslColor b, float t)
{
return LerpUnclamped(a, b, MathUtilities.Clamp01(t));
}
/// <summary>
/// Linearly interpolates between two <see cref="HslColor"/> values without clamping the interpolant.
/// </summary>
/// <param name="a">The starting color.</param>
/// <param name="b">The ending color.</param>
/// <param name="t">The interpolation value between the two colors.</param>
/// <returns>The interpolated <see cref="HslColor"/>.</returns>
public static HslColor LerpUnclamped(HslColor a, HslColor b, float t)
{
var hueDifference = MathUtilities.Repeat(b.h - a.h, 1f);
if (hueDifference > 0.5f)
hueDifference -= 1f;
return new HslColor(
MathUtilities.Repeat(a.h + (hueDifference * t), 1f),
MathUtilities.LerpUnclamped(a.s, b.s, t),
MathUtilities.LerpUnclamped(a.l, b.l, t),
MathUtilities.LerpUnclamped(a.a, b.a, t));
}
}
+42 -10
View File
@@ -1,4 +1,5 @@
using MiraAPI.Translation;
using System.Diagnostics.CodeAnalysis;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
@@ -10,17 +11,37 @@ namespace MiraAPI.Colors;
/// <param name="name">The name of the option.</param>
/// <param name="mainColor">The main color.</param>
/// <param name="shadowColor">The shadow color.</param>
public sealed class CustomColor(StringNames name, Color32 mainColor, Color32 shadowColor)
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Internal code.")]
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1513:Closing brace should be followed by blank line", Justification = "Looks weird.")]
public class CustomColor(StringNames name, Color32 mainColor, Color32 shadowColor)
{
/// <summary>
/// Gets or sets the main color.
/// </summary>
public Color32 MainColor { get; set; } = mainColor;
public Color32 MainColor
{
get;
set
{
field = value;
InternalMainColor = value;
}
}
= mainColor;
/// <summary>
/// Gets or sets the shadow color.
/// </summary>
public Color32 ShadowColor { get; set; } = shadowColor;
public Color32 ShadowColor
{
get;
set
{
field = value;
InternalShadowColor = value;
}
}
= shadowColor;
/// <summary>
/// Gets or sets the name of the color.
@@ -32,18 +53,24 @@ public sealed class CustomColor(StringNames name, Color32 mainColor, Color32 sha
/// </summary>
public CustomColorBrightness ColorBrightness { get; set; } = CustomColorBrightness.Darker;
/// <inheritdoc />
public CustomColor(StringNames name, Color32 mainColor) : this(name, mainColor, mainColor.GetShadowColor(60))
internal Color InternalMainColor = mainColor;
internal Color InternalShadowColor = shadowColor;
/// <inheritdoc cref="CustomColor"/>
public CustomColor(StringNames name, Color32 mainColor)
: this(name, mainColor, mainColor.GetShadowColor(60))
{
}
/// <inheritdoc />
public CustomColor(string name, Color32 mainColor) : this(name, mainColor, mainColor.GetShadowColor(60))
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor)
: this(name, mainColor, mainColor.GetShadowColor(60))
{
}
/// <inheritdoc />
public CustomColor(string name, Color32 mainColor, Color32 shadowColor) : this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor)
/// <inheritdoc cref="CustomColor"/>
public CustomColor(string name, Color32 mainColor, Color32 shadowColor)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainColor, shadowColor)
{
}
}
@@ -53,6 +80,11 @@ public sealed class CustomColor(StringNames name, Color32 mainColor, Color32 sha
/// </summary>
public enum CustomColorBrightness
{
/// <summary>
/// An invalid color.
/// </summary>
Invalid = -1,
/// <summary>
/// A lighter color.
/// </summary>
+116 -2
View File
@@ -1,6 +1,8 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
using UnityEngine;
namespace MiraAPI.Colors;
@@ -15,13 +17,39 @@ public static class PaletteManager
public static CustomColor[] RegisteredColors => [.. CustomColors];
internal static readonly List<CustomColor> CustomColors = [];
internal static readonly HashSet<StringNames> VariableColorNames = [];
private static readonly CustomColorBrightness[] ColorBrightnessMap =
[
CustomColorBrightness.Darker, // Red
CustomColorBrightness.Darker, // Blue
CustomColorBrightness.Darker, // Green
CustomColorBrightness.Lighter, // Pink
CustomColorBrightness.Lighter, // Orange
CustomColorBrightness.Lighter, // Yellow
CustomColorBrightness.Darker, // Black
CustomColorBrightness.Lighter, // White
CustomColorBrightness.Darker, // Purple
CustomColorBrightness.Darker, // Brown
CustomColorBrightness.Lighter, // Cyan
CustomColorBrightness.Lighter, // Lime
CustomColorBrightness.Darker, // Maroon
CustomColorBrightness.Lighter, // Rose
CustomColorBrightness.Lighter, // Banana
CustomColorBrightness.Darker, // Gray
CustomColorBrightness.Darker, // Tan
CustomColorBrightness.Lighter, // Coral
];
private static int originalLength;
internal static void RegisterAllColors()
{
originalLength = Palette.PlayerColors.Length;
var colors = CustomColors.Select(x => x.MainColor).ToArray();
var shadowColors = CustomColors.Select(x => x.ShadowColor).ToArray();
var stringNames = CustomColors.Select(x =>
x.Name).ToArray();
var stringNames = CustomColors.Select(x => x.Name).ToArray();
Palette.PlayerColors = Palette.PlayerColors.ToArray().AddRangeToArray(colors);
Palette.ShadowColors = Palette.ShadowColors.ToArray().AddRangeToArray(shadowColors);
@@ -30,4 +58,90 @@ public static class PaletteManager
Palette.TextColors = Palette.TextColors.ToArray().AddRangeToArray(colors);
Palette.TextOutlineColors = Palette.TextOutlineColors.ToArray().AddRangeToArray(shadowColors);
}
/// <summary>
/// Checks to see if the provided color ID belongs to a variable color.
/// </summary>
/// <param name="colorId">The id of the color.</param>
/// <returns><c>true</c> if the color is a variable color; <c>false</c> otherwise.</returns>
public static bool IsVariable(int colorId)
{
if ((uint)colorId >= (uint)Palette.ColorNames.Length)
return false;
return VariableColorNames.Contains(Palette.ColorNames[colorId]);
}
/// <summary>
/// Checks to see if the provided color ID belongs to a custom color.
/// </summary>
/// <param name="colorId">The ID of the color.</param>
/// <returns><c>true</c> if the color is a custom color; <c>false</c> otherwise.</returns>
public static bool IsCustomColor(int colorId)
{
return (uint)(colorId - originalLength) < (uint)CustomColors.Count;
}
/// <summary>
/// Gets the main color of the provided color ID.
/// </summary>
/// <param name="colorId">The id of the color.</param>
/// <returns>The main color associated with the provided ID.</returns>
public static Color GetMainColor(int colorId)
{
if ((uint)colorId >= (uint)Palette.ColorNames.Length)
return Color.white;
return !TryGetCustomColor(colorId, out var custom)
? Palette.PlayerColors[colorId]
: (custom is VariableColor variable
? variable.EvaluateMainColor(Time.time)
: custom.InternalMainColor);
}
/// <summary>
/// Gets the shadow color of the provided color ID.
/// </summary>
/// <param name="colorId">The ID of the color.</param>
/// <returns>The shadow color associated with the provided ID.</returns>
public static Color GetShadowColor(int colorId)
{
if ((uint)colorId >= (uint)Palette.ColorNames.Length)
return Color.white;
return !TryGetCustomColor(colorId, out var custom)
? Palette.ShadowColors[colorId]
: (custom is VariableColor variable
? variable.EvaluateShadowColor(Time.time)
: custom.InternalShadowColor);
}
/// <summary>
/// Gets the brightness type of the color associated with the provided ID.
/// </summary>
/// <param name="colorId">The ID of the color.</param>
/// <returns>The brightness type of the provided ID.</returns>
public static CustomColorBrightness GetBrightness(int colorId)
{
if ((uint)colorId >= (uint)Palette.ColorNames.Length)
return CustomColorBrightness.Invalid;
return TryGetCustomColor(colorId, out var custom)
? custom.ColorBrightness
: ColorBrightnessMap[colorId];
}
internal static bool TryGetCustomColor(int colorId, [NotNullWhen(true)] out CustomColor? custom)
{
var index = colorId - originalLength;
if ((uint)index >= (uint)CustomColors.Count)
{
custom = null;
return false;
}
custom = CustomColors[index];
return true;
}
}
+72
View File
@@ -0,0 +1,72 @@
using System;
using MiraAPI.LocalSettings;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Colors;
/// <summary>
/// Represents a dynamic custom color that changes over time.
/// </summary>
/// <param name="name">The name of the color.</param>
/// <param name="mainEvaluator">The function to evaluate the dynamic main color.</param>
/// <param name="shadowEvaluator">The function to evaluate the dynamic shadow color.</param>
/// <param name="mainColor">The static main color used when dynamic colors are disabled.</param>
/// <param name="shadowColor">The static shadow color used when dynamic colors are disabled.</param>
/// <param name="defaultTime">The default time that is used to automatically fill in the static colors when the latter is not provided.</param>
public sealed class VariableColor(StringNames name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: CustomColor(name, mainColor ?? mainEvaluator(defaultTime), shadowColor ?? shadowEvaluator?.Invoke(defaultTime) ?? (mainColor ?? mainEvaluator(defaultTime)).GetShadowColor(60))
{
/// <summary>
/// Gets or sets a delegate that takes in a time value and returns the dynamic main color.
/// </summary>
public Func<float, Color> MainEvaluator { get; set; } = mainEvaluator;
/// <summary>
/// Gets or sets a delegate that takes in a time value and returns the dynamic shadow color.
/// </summary>
public Func<float, Color> ShadowEvaluator { get; set; } = shadowEvaluator ?? (t => mainEvaluator(t).GetShadowColor(0.24f));
/// <inheritdoc cref="VariableColor"/>
public VariableColor(StringNames name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Color32? mainColor = null, float defaultTime = 0f)
: this(name, mainEvaluator, null, mainColor, null, defaultTime)
{
}
/// <inheritdoc cref="VariableColor"/>
public VariableColor(string name, Func<float, Color> mainEvaluator, Func<float, Color>? shadowEvaluator, Color32? mainColor = null, Color32? shadowColor = null, float defaultTime = 0f)
: this(MiraLocaleManager.GetOrCreateLocaleString(name), mainEvaluator, shadowEvaluator, mainColor, shadowColor, defaultTime)
{
}
/// <summary>
/// Evaluates the dynamic main color based on the provided time value.
/// </summary>
/// <param name="time">The time to evaluate the color against.</param>
/// <returns>The dynamically evaluated color, or the static <see cref="CustomColor.MainColor"/> if static variable colors are enabled in the user's settings.</returns>
public Color EvaluateMainColor(float time)
{
return LocalSettingsTabSingleton<MiraApiSettings>.Instance.EnableVariableColors.Value
? MainEvaluator(time)
: InternalMainColor;
}
/// <summary>
/// Evaluates the dynamic shadow color based on the provided time value.
/// </summary>
/// <param name="time">The time to evaluate the color against.</param>
/// <returns>The dynamically evaluated color, or the static <see cref="CustomColor.ShadowColor"/> if static variable colors are enabled in the user's settings.</returns>
public Color EvaluateShadowColor(float time)
{
return LocalSettingsTabSingleton<MiraApiSettings>.Instance.EnableVariableColors.Value
? ShadowEvaluator(time)
: InternalShadowColor;
}
}
+102
View File
@@ -0,0 +1,102 @@
using System.Diagnostics.CodeAnalysis;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Colors;
using MiraAPI.Utilities;
using Reactor.Utilities.Attributes;
using UnityEngine;
namespace MiraAPI;
/// <summary>
/// The base class for variable color behaviour on <see cref="SpriteRenderer"/>s.
/// </summary>
[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity methods.")]
[SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = "Unity fields.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public abstract class BaseVariableColorBehaviour : MonoBehaviour
{
/// <summary>
/// The <see cref="VariableColor"/> to apply.
/// </summary>
protected VariableColor? color;
/// <summary>
/// Sets the current variable color.
/// </summary>
/// <param name="newColor">The new <see cref="VariableColor"/>.</param>
[HideFromIl2Cpp]
public void SetColor(VariableColor? newColor)
{
color = newColor;
}
}
/// <summary>
/// A mono script that adjusts the material colors of a <see cref="Renderer"/> component that it's attached to based on the provided variable color.
/// </summary>
[RegisterInIl2Cpp]
[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity methods.")]
public sealed class VariableColorBehaviour : BaseVariableColorBehaviour
{
private Renderer? rend;
private static readonly Color VisorColor = Palette.VisorColor;
/// <summary>
/// Sets the new <see cref="Renderer"/> target.
/// </summary>
/// <param name="newRend">The new <see cref="Renderer"/> that the script must target.</param>
public void SetRend(Renderer? newRend)
{
rend = newRend;
}
private void Awake()
{
rend = GetComponent<Renderer>();
}
private void Update()
{
if (color == null || rend == null)
return;
var time = Time.time;
var material = rend.material;
material.SetColor(ShaderID.VisorColor, VisorColor);
material.SetColor(ShaderID.BodyColor, color.EvaluateMainColor(time));
material.SetColor(ShaderID.BackColor, color.EvaluateShadowColor(time));
}
}
/// <summary>
/// A mono script that adjusts the graphic colors of a <see cref="SpriteRenderer"/> component that it's attached to based on the provided variable color.
/// </summary>
[RegisterInIl2Cpp]
[SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Unity methods.")]
public sealed class BasicVariableColorBehaviour : BaseVariableColorBehaviour
{
private SpriteRenderer? rend;
/// <summary>
/// Sets the new <see cref="SpriteRenderer"/> target.
/// </summary>
/// <param name="newRend">The new <see cref="SpriteRenderer"/> that the script must target.</param>
public void SetRend(SpriteRenderer? newRend)
{
rend = newRend;
}
private void Awake()
{
rend = GetComponent<SpriteRenderer>();
}
private void Update()
{
if (color != null && rend != null)
rend.color = color.EvaluateMainColor(Time.time);
}
}
@@ -6,39 +6,24 @@ namespace MiraAPI.Events.Mira;
/// Invoked when a <see cref="CustomActionButton"/> click is cancelled. Do not use for vanilla <see cref="AbilityButton"/>s.
/// </summary>
/// <typeparam name="T">The <see cref="CustomActionButton"/> type.</typeparam>
public sealed class MiraButtonCancelledEvent<T> : MiraEvent where T : CustomActionButton
/// <param name="button">The <see cref="CustomActionButton"/> whose click was cancelled.</param>
public sealed class MiraButtonCancelledEvent<T>(T button) : MiraEvent
where T : CustomActionButton
{
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public T Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonCancelledEvent{T}"/> class.
/// </summary>
/// <param name="button">The <see cref="CustomActionButton"/> whose click was cancelled.</param>
public MiraButtonCancelledEvent(T button)
{
Button = button;
}
public T Button { get; } = button;
}
/// <summary>
/// Invoked when a <see cref="CustomActionButton"/> click is cancelled. Do not use for vanilla <see cref="AbilityButton"/>s.
/// </summary>
public sealed class MiraButtonCancelledEvent : MiraEvent
/// <param name="button">The <see cref="CustomActionButton"/> whose click was cancelled.</param>
public sealed class MiraButtonCancelledEvent(CustomActionButton button) : MiraEvent
{
/// <summary>
/// Gets the <see cref="CustomActionButton"/> whose click was cancelled.
/// </summary>
public CustomActionButton Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonCancelledEvent"/> class.
/// </summary>
/// <param name="button">The <see cref="CustomActionButton"/> whose click was cancelled.</param>
public MiraButtonCancelledEvent(CustomActionButton button)
{
Button = button;
}
public CustomActionButton Button { get; } = button;
}
+9 -25
View File
@@ -6,46 +6,30 @@ namespace MiraAPI.Events.Mira;
/// Button click event for <see cref="CustomActionButton"/>s only. Do not use for vanilla <see cref="AbilityButton"/>s.
/// </summary>
/// <typeparam name="T">The <see cref="CustomActionButton"/> type.</typeparam>
public class MiraButtonClickEvent<T> : MiraCancelableEvent where T : CustomActionButton
/// <param name="button">The <see cref="CustomActionButton"/> that was clicked.</param>
/// <param name="genericClickEvent">The generic <see cref="MiraButtonClickEvent"/> invoked before button-specific events.</param>
public class MiraButtonClickEvent<T>(T button, MiraButtonClickEvent genericClickEvent) : MiraCancelableEvent
where T : CustomActionButton
{
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public T Button { get; }
public T Button { get; } = button;
/// <summary>
/// Gets the generic <see cref="MiraButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public MiraButtonClickEvent GenericClickEvent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonClickEvent{T}"/> class.
/// </summary>
/// <param name="button">The <see cref="CustomActionButton"/> that was clicked.</param>
/// <param name="genericClickEvent">The generic <see cref="MiraButtonClickEvent"/> invoked before button-specific events.</param>
public MiraButtonClickEvent(T button, MiraButtonClickEvent genericClickEvent)
{
GenericClickEvent = genericClickEvent;
Button = button;
}
public MiraButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
}
/// <summary>
/// Button click event for <see cref="CustomActionButton"/>s only. Do not use for vanilla <see cref="AbilityButton"/>s.
/// </summary>
public class MiraButtonClickEvent : MiraCancelableEvent
/// <param name="button">The <see cref="CustomActionButton"/> that was clicked.</param>
public class MiraButtonClickEvent(CustomActionButton button) : MiraCancelableEvent
{
/// <summary>
/// Gets the <see cref="CustomActionButton"/> that was clicked.
/// </summary>
public CustomActionButton Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraButtonClickEvent"/> class.
/// </summary>
/// <param name="button">The <see cref="CustomActionButton"/> that was clicked.</param>
public MiraButtonClickEvent(CustomActionButton button)
{
Button = button;
}
public CustomActionButton Button { get; } = button;
}
+5 -14
View File
@@ -5,26 +5,17 @@ namespace MiraAPI.Events.Mira;
/// <summary>
/// Event fired by Mira API to adjust the UI buttons at the top right of the screen.
/// </summary>
public class UiButtonPostResetEvent : MiraEvent
/// <param name="topUiRow">The <see cref="GameObject"/> for the top UI row.</param>
/// <param name="secondUiRow">The <see cref="GameObject"/> for the second UI row.</param>
public class UiButtonPostResetEvent(GameObject topUiRow, GameObject secondUiRow) : MiraEvent
{
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the very top UI row.
/// </summary>
public GameObject MainTopUiRow { get; }
public GameObject MainTopUiRow { get; } = topUiRow;
/// <summary>
/// Gets the <see cref="GameObject"/> parent for the second top UI row.
/// </summary>
public GameObject SecondTopUiRow { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UiButtonPostResetEvent"/> class.
/// </summary>
/// <param name="topUiRow">The <see cref="GameObject"/> for the top UI row.</param>
/// <param name="secondUiRow">The <see cref="GameObject"/> for the second UI row.</param>
public UiButtonPostResetEvent(GameObject topUiRow, GameObject secondUiRow)
{
MainTopUiRow = topUiRow;
SecondTopUiRow = secondUiRow;
}
public GameObject SecondTopUiRow { get; } = secondUiRow;
}
+8 -3
View File
@@ -17,9 +17,11 @@ public static class MiraEventManager
/// <param name="eventInstance">The <typeparamref name="T"/> instance.</param>
/// <typeparam name="T">Type of Event.</typeparam>
/// <returns>If there was an event handler invoked for this event, return <see langword="true"/>. Otherwise, return <see langword="false"/>.</returns>
public static bool InvokeEvent<T>(T eventInstance) where T : MiraEvent
public static bool InvokeEvent<T>(this T eventInstance)
where T : MiraEvent
{
EventWrappers.TryGetValue(typeof(T), out var handlers);
if (handlers == null || handlers.Count == 0)
{
return false;
@@ -46,9 +48,10 @@ public static class MiraEventManager
/// <param name="eventInstance">The <see cref="MiraEvent"/> instance.</param>
/// <param name="type">The type to use for handler lookup.</param>
/// <returns>If there was an event handler invoked for this event, return <see langword="true"/>. Otherwise, return <see langword="false"/>.</returns>
public static bool InvokeEvent(MiraEvent eventInstance, Type type)
public static bool InvokeEvent(this MiraEvent eventInstance, Type type)
{
EventWrappers.TryGetValue(type, out var handlers);
if (handlers == null || handlers.Count == 0)
{
return false;
@@ -107,7 +110,8 @@ public static class MiraEventManager
/// <param name="priority">The priority of the event handler. Lower values are called first.</param>
/// <typeparam name="T">Type of <see cref="MiraEvent"/> event.</typeparam>
/// <returns>A <see cref="MiraEventHandle"/> to use when unregistering the event.</returns>
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, int priority = 0) where T : MiraEvent
public static MiraEventHandle RegisterEventHandler<T>(Action<T> handler, int priority = 0)
where T : MiraEvent
{
EventWrappers.TryAdd(typeof(T), []);
@@ -146,6 +150,7 @@ public static class MiraEventManager
{
EventWrappers.Remove(eventHandle.EventType);
}
return true;
}
}
+5 -14
View File
@@ -5,26 +5,17 @@ namespace MiraAPI.Events;
/// <summary>
/// Wrapper for <see cref="MiraEvent"/> handlers.
/// </summary>
public class MiraEventWrapper
/// <param name="eventHandler">The action for the event handler.</param>
/// <param name="priority">The priority of the handler.</param>
public class MiraEventWrapper(Delegate eventHandler, int priority)
{
/// <summary>
/// Gets the event handler delegate.
/// </summary>
public Delegate EventHandler { get; }
public Delegate EventHandler { get; } = eventHandler;
/// <summary>
/// Gets the priority of the handler. Lower values are called first.
/// </summary>
public int Priority { get; }
/// <summary>
/// Initializes a new instance of the <see cref="MiraEventWrapper"/> class.
/// </summary>
/// <param name="eventHandler">The action for the event handler.</param>
/// <param name="priority">The priority of the handler.</param>
public MiraEventWrapper(Delegate eventHandler, int priority)
{
EventHandler = eventHandler;
Priority = priority;
}
public int Priority { get; } = priority;
}
+3 -11
View File
@@ -5,20 +5,12 @@ namespace MiraAPI.Events;
/// <summary>
/// Register a <see cref="MiraEvent"/> handler.
/// </summary>
/// <param name="priority">The priority of the event. Lower values are called first.</param>
[AttributeUsage(AttributeTargets.Method)]
public class RegisterEventAttribute : Attribute
public class RegisterEventAttribute(int priority = 0) : 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;
}
public int Priority { get; } = priority;
}
@@ -3,38 +3,44 @@
/// <summary>
/// Event that is invoked after a player is murdered. Only called after a successful murder. This event is not cancelable.
/// </summary>
public class AfterMurderEvent : MiraEvent
/// <param name="source">The <see cref="PlayerControl"/> that killed the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that was killed.</param>
/// <param name="framed">The <see cref="PlayerControl"/> that was framed.</param>
/// <param name="deadBody">The <paramref name="target"/>'s <see cref="global::DeadBody"/>, if it exists.</param>
/// <param name="isIndirect">Whether the murder was caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder ignored protection.</param>
public class AfterMurderEvent(PlayerControl source, PlayerControl target, PlayerControl? framed, DeadBody? deadBody, bool isIndirect = true, bool ignoreDefense = false) : MiraEvent
{
/// <summary>
/// Gets the <see cref="PlayerControl"/> that killed the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; }
public PlayerControl Source { get; } = source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was killed.
/// </summary>
public PlayerControl Target { get; }
public PlayerControl Target { get; } = target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that was framed, if any.
/// </summary>
public PlayerControl? Framed { get; }
public PlayerControl? Framed { get; } = framed;
/// <summary>
/// Gets a value indicating whether the murder was done indirectly.
/// This is commonly used to prevent the <see cref="Source"/> <see cref="PlayerControl"/> from being killed.
/// </summary>
public bool IsIndirectAttack { get; }
public bool IsIndirectAttack { get; } = isIndirect;
/// <summary>
/// Gets a value indicating whether the murder was able to bypass protective roles or general defense, such as <see cref="GuardianAngelRole"/>.
/// </summary>
public bool IgnoreDefense { get; }
public bool IgnoreDefense { get; } = ignoreDefense;
/// <summary>
/// Gets the <see cref="Target"/>'s <see cref="DeadBody"/>, if it exists.
/// </summary>
public DeadBody? DeadBody { get; }
public DeadBody? DeadBody { get; } = deadBody;
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
@@ -45,32 +51,8 @@ public class AfterMurderEvent : MiraEvent
/// <param name="isIndirect">Whether the murder was caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder ignored protection.</param>
public AfterMurderEvent(PlayerControl source, PlayerControl target, DeadBody? deadBody, bool isIndirect, bool ignoreDefense = false)
: this(source, target, null, deadBody, isIndirect, ignoreDefense)
{
Source = source;
Target = target;
Framed = null;
DeadBody = deadBody;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
}
/// <summary>
/// Initializes a new instance of the <see cref="AfterMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that killed the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that was killed.</param>
/// <param name="framed">The <see cref="PlayerControl"/> that was framed.</param>
/// <param name="deadBody">The <paramref name="target"/>'s <see cref="DeadBody"/>, if it exists.</param>
/// <param name="isIndirect">Whether the murder was caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder ignored protection.</param>
public AfterMurderEvent(PlayerControl source, PlayerControl target, PlayerControl framed, DeadBody? deadBody, bool isIndirect = true, bool ignoreDefense = false)
{
Source = source;
Target = target;
Framed = framed;
DeadBody = deadBody;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
}
/// <summary>
@@ -80,12 +62,7 @@ public class AfterMurderEvent : MiraEvent
/// <param name="target">The <see cref="PlayerControl"/> that was killed.</param>
/// <param name="deadBody">The <paramref name="target"/>'s <see cref="DeadBody"/>, if it exists.</param>
public AfterMurderEvent(PlayerControl source, PlayerControl target, DeadBody? deadBody)
: this(source, target, null, deadBody)
{
Source = source;
Target = target;
Framed = null;
DeadBody = deadBody;
IsIndirectAttack = false;
IgnoreDefense = false;
}
}
@@ -3,19 +3,11 @@
/// <summary>
/// Invoked before <see cref="GameManager.RpcEndGame"/> is called, allowing cancellation of the game end entirely.
/// </summary>
public class BeforeGameEndEvent : MiraCancelableEvent
/// <param name="reason">The reason for the game end.</param>
public class BeforeGameEndEvent(GameOverReason reason) : 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;
}
public GameOverReason Reason { get; } = reason;
}
@@ -5,38 +5,56 @@ namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Event that is invoked before a player is murdered. This event is cancelable.
/// </summary>
public sealed class BeforeMurderEvent : MiraCancelableEvent
/// <param name="source">The <see cref="PlayerControl"/> that is killing the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that is being killed.</param>
/// <param name="framed">The <see cref="PlayerControl"/> that is being framed.</param>
/// <param name="isIndirect">Whether the murder is caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder should ignore protection.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
public sealed class BeforeMurderEvent(PlayerControl source, PlayerControl target, PlayerControl? framed, bool isIndirect = true, bool ignoreDefense = false, MeetingCheck inMeeting = MeetingCheck.Ignore)
: MiraCancelableEvent
{
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is killing the <see cref="Target"/>.
/// </summary>
public PlayerControl Source { get; }
public PlayerControl Source { get; } = source;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being killed.
/// </summary>
public PlayerControl Target { get; }
public PlayerControl Target { get; } = target;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is being framed, if any.
/// </summary>
public PlayerControl? Framed { get; }
public PlayerControl? Framed { get; } = framed;
/// <summary>
/// Gets or sets a value indicating whether the murder is done indirectly.
/// This is commonly used to prevent the <see cref="Source"/> <see cref="PlayerControl"/> from being killed.
/// </summary>
public bool IsIndirectAttack { get; set; }
public bool IsIndirectAttack { get; set; } = isIndirect;
/// <summary>
/// Gets or sets a value indicating whether the murder should bypass protective roles or general defense, such as <see cref="GuardianAngelRole"/>.
/// </summary>
public bool IgnoreDefense { get; set; }
public bool IgnoreDefense { get; set; } = ignoreDefense;
/// <summary>
/// Gets whether the murder was meant to be done in a meeting, via an enum.
/// </summary>
public MeetingCheck InMeeting { get; }
public MeetingCheck InMeeting { get; } = inMeeting;
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that is killing the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that is being killed.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target, MeetingCheck inMeeting = MeetingCheck.Ignore)
: this(source, target, false, false, inMeeting)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
@@ -47,62 +65,7 @@ public sealed class BeforeMurderEvent : MiraCancelableEvent
/// <param name="ignoreDefense">Whether the murder should ignore protection.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target, bool isIndirect, bool ignoreDefense = false, MeetingCheck inMeeting = MeetingCheck.Ignore)
: this(source, target, null, isIndirect, ignoreDefense, inMeeting)
{
Source = source;
Target = target;
Framed = null;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
InMeeting = inMeeting;
}
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that is killing the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that is being killed.</param>
/// <param name="framed">The <see cref="PlayerControl"/> that is being framed.</param>
/// <param name="isIndirect">Whether the murder is caused indirectly.</param>
/// <param name="ignoreDefense">Whether the murder should ignore protection.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target, PlayerControl framed, bool isIndirect = true, bool ignoreDefense = false, MeetingCheck inMeeting = MeetingCheck.Ignore)
{
Source = source;
Target = target;
Framed = framed;
IsIndirectAttack = isIndirect;
IgnoreDefense = ignoreDefense;
InMeeting = inMeeting;
}
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that is killing the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that is being killed.</param>
/// <param name="inMeeting">Whether the murder is intended to be triggered in a meeting.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target, MeetingCheck inMeeting)
{
Source = source;
Target = target;
Framed = null;
IsIndirectAttack = false;
IgnoreDefense = false;
InMeeting = inMeeting;
}
/// <summary>
/// Initializes a new instance of the <see cref="BeforeMurderEvent"/> class.
/// </summary>
/// <param name="source">The <see cref="PlayerControl"/> that is killing the <paramref name="target"/>.</param>
/// <param name="target">The <see cref="PlayerControl"/> that is being killed.</param>
public BeforeMurderEvent(PlayerControl source, PlayerControl target)
{
Source = source;
Target = target;
Framed = null;
IsIndirectAttack = false;
IgnoreDefense = false;
InMeeting = MeetingCheck.Ignore;
}
}
@@ -1,22 +1,13 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Event invoked on <see cref="IntroCutscene.OnDestroy"/> and <see cref="ExileController.WrapUp"/>
/// to determine if it should run the <see cref="RoundStartEvent"/> event or not.
/// Event invoked on <see cref="IntroCutscene.OnDestroy"/> and <see cref="ExileController.WrapUp"/> to determine if it should run the <see cref="RoundStartEvent"/> event or not.
/// </summary>
public class BeforeRoundStartEvent : MiraCancelableEvent
/// <param name="triggeredByIntro">Whether the event was triggered by the intro or not.</param>
public class BeforeRoundStartEvent(bool triggeredByIntro) : MiraCancelableEvent
{
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BeforeRoundStartEvent"/> class.
/// </summary>
/// <param name="triggeredByIntro">Whether the event was triggered by the intro or not.</param>
public BeforeRoundStartEvent(bool triggeredByIntro)
{
TriggeredByIntro = triggeredByIntro;
}
public bool TriggeredByIntro { get; } = triggeredByIntro;
}
@@ -1,21 +1,13 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// The event that is invoked when the end game screen is shown. Non cancelable.
/// The event that is invoked when the end game screen is shown. Non-cancelable.
/// </summary>
public class GameEndEvent : MiraEvent
/// <param name="manager">The <see cref="global::EndGameManager"/> instance.</param>
public class GameEndEvent(EndGameManager manager) : MiraEvent
{
/// <summary>
/// Gets the <see cref="global::EndGameManager"/> instance.
/// </summary>
public EndGameManager EndGameManager { get; }
/// <summary>
/// Initializes a new instance of the <see cref="GameEndEvent"/> class.
/// </summary>
/// <param name="manager">The <see cref="global::EndGameManager"/> instance.</param>
public GameEndEvent(EndGameManager manager)
{
EndGameManager = manager;
}
public EndGameManager EndGameManager { get; } = manager;
}
@@ -1,21 +1,13 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// The event that is invoked when the intro cutscene is shown. Non cancelable.
/// The event that is invoked when the intro cutscene is shown. Non-cancelable.
/// </summary>
public class IntroBeginEvent : MiraEvent
/// <param name="introCutscene">The intro cutscene.</param>
public class IntroBeginEvent(IntroCutscene introCutscene) : MiraEvent
{
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; }
/// <summary>
/// Initializes a new instance of the <see cref="IntroBeginEvent"/> class.
/// </summary>
/// <param name="introCutscene">The intro cutscene.</param>
public IntroBeginEvent(IntroCutscene introCutscene)
{
IntroCutscene = introCutscene;
}
public IntroCutscene IntroCutscene { get; } = introCutscene;
}
@@ -3,6 +3,7 @@
/// <summary>
/// The event that is invoked when the intro cutscene has finished playing.
/// </summary>
/// <param name="introCutscene">The intro cutscene.</param>
public class IntroEndEvent(IntroCutscene introCutscene) : MiraEvent
{
/// <summary>
@@ -1,21 +1,13 @@
namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// The event that is invoked when the player's role is shown on the intro cutscene. Non cancelable.
/// The event that is invoked when the player's role is shown on the intro cutscene. Non-cancelable.
/// </summary>
public class IntroRoleRevealEvent : MiraEvent
/// <param name="introCutscene">The intro cutscene.</param>
public class IntroRoleRevealEvent(IntroCutscene introCutscene) : MiraEvent
{
/// <summary>
/// Gets the <see cref="global::IntroCutscene"/> instance.
/// </summary>
public IntroCutscene IntroCutscene { get; }
/// <summary>
/// Initializes a new instance of the <see cref="IntroRoleRevealEvent"/> class.
/// </summary>
/// <param name="introCutscene">The intro cutscene.</param>
public IntroRoleRevealEvent(IntroCutscene introCutscene)
{
IntroCutscene = introCutscene;
}
public IntroCutscene IntroCutscene { get; } = introCutscene;
}
@@ -4,19 +4,11 @@
/// Start Round event, invoked on <see cref="IntroCutscene.OnDestroy"/> and <see cref="ExileController.WrapUp"/>
/// if the <see cref="BeforeRoundStartEvent"/> isn't cancelled.
/// </summary>
public class RoundStartEvent : MiraEvent
/// <param name="triggeredByIntro">Whether the event was triggered by the intro or not.</param>
public class RoundStartEvent(bool triggeredByIntro) : MiraEvent
{
/// <summary>
/// Gets a value indicating whether the event was triggered by the <see cref="IntroCutscene"/> or <see cref="ExileController"/>.
/// </summary>
public bool TriggeredByIntro { get; }
/// <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;
}
public bool TriggeredByIntro { get; } = triggeredByIntro;
}
@@ -5,26 +5,17 @@ namespace MiraAPI.Events.Vanilla.Gameplay;
/// <summary>
/// Event that is invoked after a player's role is set. This event is not cancelable.
/// </summary>
public class SetRoleEvent : MiraEvent
/// <param name="player">The player.</param>
/// <param name="role">The new role.</param>
public class SetRoleEvent(PlayerControl player, RoleTypes role) : MiraEvent
{
/// <summary>
/// Gets the <see cref="PlayerControl"/> whose role was changed.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the role that the player was set to.
/// </summary>
public RoleTypes Role { get; }
/// <summary>
/// Initializes a new instance of the <see cref="SetRoleEvent"/> class.
/// </summary>
/// <param name="player">The player.</param>
/// <param name="role">The new role.</param>
public SetRoleEvent(PlayerControl player, RoleTypes role)
{
Player = player;
Role = role;
}
public RoleTypes Role { get; } = role;
}
@@ -6,39 +6,24 @@ namespace MiraAPI.Events.Vanilla.Gameplay;
/// Invoked when a Vanilla <see cref="AbilityButton"/> click is cancelled. Do not use for <see cref="CustomActionButton"/>.
/// </summary>
/// <typeparam name="T">The vanilla <see cref="AbilityButton"/> type.</typeparam>
public sealed class VanillaButtonCancelledEvent<T> : MiraEvent where T : AbilityButton
/// <param name="button">The vanilla <see cref="AbilityButton"/> whose click was cancelled.</param>
public sealed class VanillaButtonCancelledEvent<T>(T button) : MiraEvent
where T : AbilityButton
{
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public T Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="VanillaButtonCancelledEvent{T}"/> class.
/// </summary>
/// <param name="button">The vanilla <see cref="AbilityButton"/> whose click was cancelled.</param>
public VanillaButtonCancelledEvent(T button)
{
Button = button;
}
public T Button { get; } = button;
}
/// <summary>
/// Invoked when a Vanilla <see cref="AbilityButton"/> click is cancelled. Do not use for <see cref="CustomActionButton"/>s.
/// </summary>
public sealed class VanillaButtonCancelledEvent : MiraEvent
/// <param name="button">The vanilla <see cref="AbilityButton"/> whose click was cancelled.</param>
public sealed class VanillaButtonCancelledEvent(AbilityButton button) : MiraEvent
{
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> whose click was cancelled.
/// </summary>
public AbilityButton Button { get; }
/// <summary>
/// Initializes a new instance of the <see cref="VanillaButtonCancelledEvent"/> class.
/// </summary>
/// <param name="button">The vanilla <see cref="AbilityButton"/> whose click was cancelled.</param>
public VanillaButtonCancelledEvent(AbilityButton button)
{
Button = button;
}
public AbilityButton Button { get; } = button;
}
@@ -6,60 +6,42 @@ namespace MiraAPI.Events.Vanilla.Gameplay;
/// Button click event for Vanilla <see cref="AbilityButton"/>s only. Do not use for <see cref="CustomActionButton"/>s.
/// </summary>
/// <typeparam name="T">The vanilla <see cref="AbilityButton"/> type.</typeparam>
public sealed class VanillaButtonClickEvent<T> : MiraCancelableEvent where T : AbilityButton
/// <param name="button">The vanilla <see cref="AbilityButton"/> that was clicked.</param>
/// <param name="genericClickEvent">The generic <see cref="VanillaButtonClickEvent"/> invoked before button-specific events.</param>
public sealed class VanillaButtonClickEvent<T>(T button, VanillaButtonClickEvent genericClickEvent) : MiraCancelableEvent
where T : AbilityButton
{
/// <summary>
/// Gets the vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public T Button { get; }
public T Button { get; } = button;
/// <summary>
/// Gets the generic <see cref="VanillaButtonClickEvent"/> that is invoked before this button-specific event.
/// </summary>
public VanillaButtonClickEvent GenericClickEvent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="VanillaButtonClickEvent{T}"/> class.
/// </summary>
/// <param name="button">The vanilla <see cref="AbilityButton"/> that was clicked.</param>
/// <param name="genericClickEvent">The generic <see cref="VanillaButtonClickEvent"/> invoked before button-specific events.</param>
public VanillaButtonClickEvent(T button, VanillaButtonClickEvent genericClickEvent)
{
GenericClickEvent = genericClickEvent;
Button = button;
}
public VanillaButtonClickEvent GenericClickEvent { get; } = genericClickEvent;
}
/// <summary>
/// Button click event for Vanilla <see cref="AbilityButton"/> only. Do not use for <see cref="CustomActionButton"/>s.
/// </summary>
public sealed class VanillaButtonClickEvent : MiraCancelableEvent
/// <param name="button">The Vanilla <see cref="AbilityButton"/> that was clicked.</param>
/// <param name="playerTarget">The <see cref="PlayerControl"/> target, if any.</param>
/// <param name="ventTarget">The <see cref="Vent"/> target, if any.</param>
public sealed class VanillaButtonClickEvent(AbilityButton button, PlayerControl? playerTarget = null, Vent? ventTarget = null) : MiraCancelableEvent
{
/// <summary>
/// Gets the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public AbilityButton Button { get; }
public AbilityButton Button { get; } = button;
/// <summary>
/// Gets the target <see cref="PlayerControl"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public PlayerControl? PlayerTarget { get; }
public PlayerControl? PlayerTarget { get; } = playerTarget;
/// <summary>
/// Gets the target <see cref="Vent"/>, if any, of the Vanilla <see cref="AbilityButton"/> that was clicked.
/// </summary>
public Vent? VentTarget { get; }
/// <summary>
/// Initializes a new instance of the <see cref="VanillaButtonClickEvent"/> class.
/// </summary>
/// <param name="button">The Vanilla <see cref="AbilityButton"/> that was clicked.</param>
/// <param name="playerTarget">The <see cref="PlayerControl"/> target, if any.</param>
/// <param name="ventTarget">The <see cref="Vent"/> target, if any.</param>
public VanillaButtonClickEvent(AbilityButton button, PlayerControl? playerTarget = null, Vent? ventTarget = null)
{
Button = button;
PlayerTarget = playerTarget;
VentTarget = ventTarget;
}
public Vent? VentTarget { get; } = ventTarget;
}
+3 -11
View File
@@ -3,19 +3,11 @@
/// <summary>
/// Event fired when a player closes the doors in a room.
/// </summary>
public class CloseDoorsEvent : MiraCancelableEvent
/// <param name="room">The room that was closed.</param>
public class CloseDoorsEvent(SystemTypes room) : MiraCancelableEvent
{
/// <summary>
/// Gets the room that the doors were closed in.
/// </summary>
public SystemTypes Room { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CloseDoorsEvent"/> class.
/// </summary>
/// <param name="room">The room that was closed.</param>
public CloseDoorsEvent(SystemTypes room)
{
Room = room;
}
public SystemTypes Room { get; } = room;
}
@@ -3,19 +3,11 @@
/// <summary>
/// Sabotage from Vanilla Among Us.
/// </summary>
public class PlayerOpenSabotageEvent : MiraCancelableEvent
/// <param name="mapBehaviour">The <see cref="global::MapBehaviour"/>.</param>
public class PlayerOpenSabotageEvent(MapBehaviour mapBehaviour) : MiraCancelableEvent
{
/// <summary>
/// Gets the <see cref="global::MapBehaviour"/>.
/// </summary>
public MapBehaviour MapBehaviour { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerOpenSabotageEvent"/> class.
/// </summary>
/// <param name="mapBehaviour">The <see cref="global::MapBehaviour"/>.</param>
public PlayerOpenSabotageEvent(MapBehaviour mapBehaviour)
{
MapBehaviour = mapBehaviour;
}
public MapBehaviour MapBehaviour { get; } = mapBehaviour;
}
@@ -3,33 +3,23 @@
/// <summary>
/// <see cref="MiraCancelableEvent"/> that is invoked before a system is updated. Usually used for sabotage events.
/// </summary>
public class UpdateSystemEvent : MiraCancelableEvent
/// <param name="systemType">The <see cref="SystemTypes"/> being updated.</param>
/// <param name="player">The <see cref="PlayerControl"/> that is updating the system.</param>
/// <param name="amount">Amount to update System to.</param>
public class UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byte amount) : MiraCancelableEvent
{
/// <summary>
/// Gets the type of system that will be updated.
/// </summary>
public SystemTypes SystemType { get; }
public SystemTypes SystemType { get; } = systemType;
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is updating the system.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the byte amount the system is being updated by.
/// </summary>
public byte Amount { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSystemEvent"/> class.
/// </summary>
/// <param name="systemType">The <see cref="SystemTypes"/> being updated.</param>
/// <param name="player">The <see cref="PlayerControl"/> that is updating the system.</param>
/// <param name="amount">Amount to update System to.</param>
public UpdateSystemEvent(SystemTypes systemType, PlayerControl player, byte amount)
{
SystemType = systemType;
Player = player;
Amount = amount;
}
public byte Amount { get; } = amount;
}
@@ -3,19 +3,11 @@
/// <summary>
/// The event that is invoked when a player is ejected. Non-cancelable.
/// </summary>
public class EjectionEvent : MiraEvent
/// <param name="controller">The <see cref="global::ExileController"/> instance.</param>
public class EjectionEvent(ExileController controller) : MiraEvent
{
/// <summary>
/// Gets the <see cref="global::ExileController"/> instance.
/// </summary>
public ExileController ExileController { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EjectionEvent"/> class.
/// </summary>
/// <param name="controller">The <see cref="global::ExileController"/> instance.</param>
public EjectionEvent(ExileController controller)
{
ExileController = controller;
}
public ExileController ExileController { get; } = controller;
}
@@ -1,36 +1,26 @@
namespace MiraAPI.Events.Vanilla.Meeting;
/// <summary>
/// The event that is invoked when a body is reported.
/// The event that is invoked when a body is reported.<br/>
/// This is invoked in <see cref="PlayerControl.CmdReportDeadBody(NetworkedPlayerInfo)"/>.
/// </summary>
public class ReportBodyEvent : MiraCancelableEvent
/// <param name="reporter">The player who reported the body.</param>
/// <param name="target">The player being reported.</param>
/// <param name="body">The <see cref="DeadBody"/> being reported.</param>
public class ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target, DeadBody? body) : MiraCancelableEvent
{
/// <summary>
/// Gets the player that is reporting the body.
/// </summary>
public PlayerControl Reporter { get; }
public PlayerControl Reporter { get; } = reporter;
/// <summary>
/// Gets the player that is being reported. Will be <see langword="null"/> for emergency meeting.
/// </summary>
public NetworkedPlayerInfo? Target { get; }
public NetworkedPlayerInfo? Target { get; } = target;
/// <summary>
/// Gets the <see cref="DeadBody"/> that is being reported. Will be <see langword="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 <see cref="DeadBody"/> being reported.</param>
public ReportBodyEvent(PlayerControl reporter, NetworkedPlayerInfo? target, DeadBody? body)
{
Reporter = reporter;
Target = target;
Body = body;
}
public DeadBody? Body { get; } = body;
}
@@ -4,19 +4,11 @@
/// 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 : MiraEvent
/// <param name="meetingHud">The <see cref="global::MeetingHud"/> instance.</param>
public class StartMeetingEvent(MeetingHud meetingHud) : MiraEvent
{
/// <summary>
/// Gets the <see cref="global::MeetingHud"/> instance.
/// </summary>
public MeetingHud MeetingHud { get; }
/// <summary>
/// Initializes a new instance of the <see cref="StartMeetingEvent"/> class.
/// </summary>
/// <param name="meetingHud">The <see cref="global::MeetingHud"/> instance.</param>
public StartMeetingEvent(MeetingHud meetingHud)
{
MeetingHud = meetingHud;
}
public MeetingHud MeetingHud { get; } = meetingHud;
}
@@ -3,26 +3,17 @@
/// <summary>
/// Event that is invoked after the local player successfully votes a player or skips. This event is not cancelable.
/// </summary>
public class AfterVoteEvent : MiraEvent
/// <param name="playerVoteArea">The <see cref="PlayerVoteArea"/> that was voted on.</param>
/// <param name="voter">The player who voted.</param>
public class AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) : MiraEvent
{
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; }
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AfterVoteEvent"/> class.
/// </summary>
/// <param name="playerVoteArea">The <see cref="PlayerVoteArea"/> that was voted on.</param>
/// <param name="voter">The player who voted.</param>
public AfterVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
{
VoteArea = playerVoteArea;
Player = voter;
}
public PlayerControl Player { get; } = voter;
}
@@ -3,26 +3,17 @@
/// <summary>
/// Event that is invoked before the local player confirms a vote on a player or when skipping. This event is cancelable.
/// </summary>
public class BeforeVoteEvent : MiraCancelableEvent
/// <param name="playerVoteArea">The <see cref="PlayerVoteArea"/> that was voted on.</param>
/// <param name="voter">The player who voted.</param>
public class BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter) : MiraCancelableEvent
{
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteArea"/>.
/// </summary>
public PlayerVoteArea VoteArea { get; }
public PlayerVoteArea VoteArea { get; } = playerVoteArea;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BeforeVoteEvent"/> class.
/// </summary>
/// <param name="playerVoteArea">The <see cref="PlayerVoteArea"/> that was voted on.</param>
/// <param name="voter">The player who voted.</param>
public BeforeVoteEvent(PlayerVoteArea playerVoteArea, PlayerControl voter)
{
VoteArea = playerVoteArea;
Player = voter;
}
public PlayerControl Player { get; } = voter;
}
@@ -3,24 +3,16 @@
/// <summary>
/// Checks if voting is complete. If canceled, the default end voting logic will be skipped.
/// </summary>
public class CheckForEndVotingEvent : MiraCancelableEvent
/// <param name="isVotingComplete"><see langword="true"/> if voting is complete, <see langword="false"/> otherwise.</param>
public class CheckForEndVotingEvent(bool isVotingComplete) : MiraCancelableEvent
{
/// <summary>
/// Gets a value indicating whether default voting logic determines that voting is complete.
/// </summary>
public bool IsVotingComplete { get; }
public bool IsVotingComplete { get; } = isVotingComplete;
/// <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"><see langword="true"/> if voting is complete, <see langword="false"/> otherwise.</param>
public CheckForEndVotingEvent(bool isVotingComplete)
{
IsVotingComplete = isVotingComplete;
}
}
@@ -7,38 +7,27 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <summary>
/// Invoked before the dummy selects their vote. If canceled, the dummy won't vote.
/// </summary>
public class DummyVoteEvent : MiraCancelableEvent
/// <param name="dummy">The voting dummy.</param>
public class DummyVoteEvent(DummyBehaviour dummy) : MiraCancelableEvent
{
/// <summary>
/// Gets the dummy that needs to vote.
/// </summary>
public DummyBehaviour Dummy { get; }
public DummyBehaviour Dummy { get; } = dummy;
/// <summary>
/// Gets the instance of the dummy's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; }
public PlayerVoteData VoteData { get; } = dummy.myPlayer.GetVoteData();
/// <summary>
/// Gets or sets a value indicating whether the dummy can vote to skip the meeting.
/// </summary>
public bool CanSkip { get; set; }
public bool CanSkip { get; set; } = true;
/// <summary>
/// Gets or sets a predicate for validating whether the dummy can vote on a player.
/// By default, excludes dead and disconnected players.
/// </summary>
public Predicate<PlayerControl> PlayerIsValid { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DummyVoteEvent"/> class.
/// </summary>
/// <param name="dummy">The voting dummy.</param>
public DummyVoteEvent(DummyBehaviour dummy)
{
Dummy = dummy;
VoteData = dummy.myPlayer.GetVoteData();
CanSkip = true;
PlayerIsValid = x => !x.Data.IsDead && !x.Data.Disconnected;
}
public Predicate<PlayerControl> PlayerIsValid { get; set; } = x => !x.Data.IsDead && !x.Data.Disconnected;
}
@@ -4,68 +4,43 @@ 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 <see cref="PlayerVoteData.Votes"/> list after this event is invoked.
/// </summary>
public class HandleVoteEvent : MiraCancelableEvent
/// <remarks>
/// If you intend on adding custom vote behaviour, cancel the event and do so.<br/>
/// If you are NOT canceling the event, keep in mind that Mira automatically removes a vote and adds the suspect to the <see cref="PlayerVoteData.Votes"/> list after this event is invoked.
/// </remarks>
/// <param name="playerVoteData">The voter's <see cref="PlayerVoteData"/>.</param>
/// <param name="targetId">The target's playerId.</param>
/// <param name="isOverruling">Whether the vote is actually for a Judge.</param>
public class HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool isOverruling = false) : MiraCancelableEvent
{
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; }
public PlayerVoteData VoteData { get; } = playerVoteData;
/// <summary>
/// Gets the player who voted.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = playerVoteData.Owner;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public byte TargetId { get; }
public byte TargetId { get; } = targetId;
/// <summary>
/// Gets or sets a value indicating whether to prevent the vote from commencing.
/// </summary>
public bool PreventVote { get; set; }
public bool PreventVote { get; set; } = false;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
/// </summary>
public NetworkedPlayerInfo TargetPlayerInfo { get; }
public NetworkedPlayerInfo TargetPlayerInfo { get; } = GameData.Instance.GetPlayerById(targetId);
/// <summary>
/// Gets or sets a value indicating whether the vote event is an Overrule caused by a Judge.
/// </summary>
public bool IsOverruling { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="HandleVoteEvent"/> class.
/// </summary>
/// <param name="playerVoteData">The voter's <see cref="PlayerVoteData"/>.</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);
}
/// <summary>
/// Initializes a new instance of the <see cref="HandleVoteEvent"/> class.
/// </summary>
/// <param name="playerVoteData">The voter's <see cref="PlayerVoteData"/>.</param>
/// <param name="targetId">The target's playerId.</param>
/// <param name="isOverruling">Whether the vote is actually for a Judge.</param>
public HandleVoteEvent(PlayerVoteData playerVoteData, byte targetId, bool isOverruling)
{
VoteData = playerVoteData;
Player = playerVoteData.Owner;
TargetId = targetId;
PreventVote = false;
IsOverruling = isOverruling;
TargetPlayerInfo = GameData.Instance.GetPlayerById(targetId);
}
public bool IsOverruling { get; set; } = isOverruling;
}
@@ -5,39 +5,28 @@ 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
/// <param name="playerVoteData">The voter's <see cref="PlayerVoteData"/>.</param>
/// <param name="targetId">The target's playerId.</param>
/// <param name="allowSelect">Whether the player is allowed to select the target.</param>
public class MeetingSelectEvent(PlayerVoteData playerVoteData, int targetId, bool allowSelect) : MiraEvent
{
/// <summary>
/// Gets the instance of the voter's <see cref="PlayerVoteData"/>.
/// </summary>
public PlayerVoteData VoteData { get; }
public PlayerVoteData VoteData { get; } = playerVoteData;
/// <summary>
/// Gets the player id of the target.
/// </summary>
public int TargetId { get; }
public int TargetId { get; } = targetId;
/// <summary>
/// Gets the <see cref="NetworkedPlayerInfo"/> of the target.
/// </summary>
public NetworkedPlayerInfo TargetPlayerInfo { get; }
public NetworkedPlayerInfo TargetPlayerInfo { get; } = GameData.Instance.GetPlayerById((byte)targetId);
/// <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 <see cref="PlayerVoteData"/>.</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;
}
public bool AllowSelect { get; set; } = allowSelect;
}
@@ -5,21 +5,15 @@ namespace MiraAPI.Events.Vanilla.Meeting.Voting;
/// <summary>
/// Called in <see cref="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
/// <remarks>
/// Cancelling is NOT advised but if you do plan on cancelling, please ensure you account for displaying ALL player's votes.
/// </remarks>
/// <param name="votes">The list of <see cref="CustomVote"/>s.</param>
public class PopulateResultsEvent(List<CustomVote> votes) : MiraCancelableEvent
{
/// <summary>
/// Gets a list of networked <see cref="CustomVote"/>s.
/// </summary>
public List<CustomVote> Votes { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PopulateResultsEvent"/> class.
/// </summary>
/// <param name="votes">The list of <see cref="CustomVote"/>s.</param>
public PopulateResultsEvent(List<CustomVote> votes)
{
Votes = votes;
}
public List<CustomVote> Votes { get; } = votes;
}
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using MiraAPI.Voting;
@@ -7,16 +8,11 @@ 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 <see cref="CustomVote"/>s that are being processed.</param>
/// <param name="exiledPlayer">The player to be exiled. Will be <see langword="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;
private readonly List<CustomVote> originalVotes = [.. votes];
/// <summary>
/// Gets a value indicating whether the exiled player has been modified by the event.
@@ -26,7 +22,7 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
/// <summary>
/// Gets a value indicating whether the votes have been modified by the event.
/// </summary>
public bool VotesModified => !Votes.SequenceEqual(_originalVotes);
public bool VotesModified => !Votes.SequenceEqual(originalVotes);
/// <summary>
/// Gets the list of <see cref="CustomVote"/>s that are being processed.
@@ -46,13 +42,15 @@ public class ProcessVotesEvent(List<CustomVote> votes, NetworkedPlayerInfo? exil
/// <summary>
/// Gets or sets the player to be exiled. Will be <see langword="null"/> if no player is to be exiled.
/// </summary>
[SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1513:Closing brace should be followed by blank line", Justification = "Looks weird.")]
public NetworkedPlayerInfo? ExiledPlayer
{
get => _exiledPlayer;
get;
set
{
_exiledPlayer = value;
field = value;
ExiledPlayerModified = true;
}
}
= exiledPlayer;
}
@@ -3,33 +3,23 @@
/// <summary>
/// The event that is invoked when a player completes a task within Hide and Seek. Non-cancelable.
/// </summary>
public class CompleteHnsTaskEvent : MiraEvent
/// <param name="hnsManager">The <see cref="HideAndSeekManager"/> currently active.</param>
/// <param name="player">The player who completed the task.</param>
/// <param name="task">The task that the player completed.</param>
public class CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl player, PlayerTask task) : MiraEvent
{
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; }
public PlayerTask Task { get; } = task;
/// <summary>
/// Gets the instance of the <see cref="HideAndSeekManager"/> attached to the game.
/// </summary>
public HideAndSeekManager HnsManager { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CompleteHnsTaskEvent"/> class.
/// </summary>
/// <param name="hnsManager">The <see cref="HideAndSeekManager"/> currently active.</param>
/// <param name="player">The player who completed the task.</param>
/// <param name="task">The task that the player completed.</param>
public CompleteHnsTaskEvent(HideAndSeekManager hnsManager, PlayerControl player, PlayerTask task)
{
HnsManager = hnsManager;
Player = player;
Task = task;
}
public HideAndSeekManager HnsManager { get; } = hnsManager;
}
@@ -1,28 +1,19 @@
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// The event that is invoked when a player completes a task. Non cancelable.
/// The event that is invoked when a player completes a task. Non-cancelable.
/// </summary>
public class CompleteTaskEvent : MiraEvent
/// <param name="player">The player who completed the task.</param>
/// <param name="task">The task that the player completed.</param>
public class CompleteTaskEvent(PlayerControl player, PlayerTask task) : MiraEvent
{
/// <summary>
/// Gets the instance of the <see cref="PlayerControl"/>.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the instance of the <see cref="PlayerTask"/> that the player completed.
/// </summary>
public PlayerTask Task { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CompleteTaskEvent"/> class.
/// </summary>
/// <param name="player">The player who completed the task.</param>
/// <param name="task">The task that the player completed.</param>
public CompleteTaskEvent(PlayerControl player, PlayerTask task)
{
Player = player;
Task = task;
}
public PlayerTask Task { get; } = task;
}
@@ -1,35 +1,25 @@
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// Event that is invoked when a player dies. Non cancelable.
/// Event that is invoked when a player dies. Non-cancelable.
/// </summary>
public class PlayerDeathEvent : MiraEvent
/// <param name="player">The player who died.</param>
/// <param name="reason">The reason the player died.</param>
/// <param name="deadBody">The player's <see cref="global::DeadBody"/>, if it exists.</param>
public class PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody? deadBody) : MiraEvent
{
/// <summary>
/// Gets the player who died.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the reason the player died.
/// </summary>
public DeathReason DeathReason { get; }
public DeathReason DeathReason { get; } = reason;
/// <summary>
/// Gets the <see cref="global::DeadBody"/> 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>
/// <param name="deadBody">The player's <see cref="global::DeadBody"/>, if it exists.</param>
public PlayerDeathEvent(PlayerControl player, DeathReason reason, DeadBody? deadBody)
{
Player = player;
DeathReason = reason;
DeadBody = deadBody;
}
public DeadBody? DeadBody { get; } = deadBody;
}
@@ -3,21 +3,13 @@
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// Event that is invoked when a player joins the lobby. Non cancelable.
/// Event that is invoked when a player joins the lobby. Non-cancelable.
/// </summary>
public class PlayerJoinEvent : MiraEvent
/// <param name="data">The data of the player who joined.</param>
public class PlayerJoinEvent(ClientData data) : MiraEvent
{
/// <summary>
/// Gets the player who joined.
/// </summary>
public ClientData ClientData { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerJoinEvent"/> class.
/// </summary>
/// <param name="data">The data of the player who joined.</param>
public PlayerJoinEvent(ClientData data)
{
ClientData = data;
}
public ClientData ClientData { get; } = data;
}
@@ -3,28 +3,19 @@
namespace MiraAPI.Events.Vanilla.Player;
/// <summary>
/// Event that is invoked when a player leaves the game. Non cancelable.
/// Event that is invoked when a player leaves the game. Non-cancelable.
/// </summary>
public class PlayerLeaveEvent : MiraEvent
/// <param name="data">The data of the player who left.</param>
/// <param name="reason">The reason why the player left.</param>
public class PlayerLeaveEvent(ClientData data, DisconnectReasons reason) : MiraEvent
{
/// <summary>
/// Gets the player who left.
/// </summary>
public ClientData ClientData { get; }
public ClientData ClientData { get; } = data;
/// <summary>
/// Gets the reason why the player left.
/// </summary>
public DisconnectReasons Reason { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerLeaveEvent"/> class.
/// </summary>
/// <param name="data">The data of the player who left.</param>
/// <param name="reason">The reason why the player left.</param>
public PlayerLeaveEvent(ClientData data, DisconnectReasons reason)
{
ClientData = data;
Reason = reason;
}
public DisconnectReasons Reason { get; } = reason;
}
@@ -3,26 +3,17 @@
/// <summary>
/// Event that is invoked when a player enters a vent. This event is cancelable.
/// </summary>
public class EnterVentEvent : MiraCancelableEvent
/// <param name="player">The <see cref="PlayerControl"/> that is entering the <paramref name="vent"/>.</param>
/// <param name="vent">The <see cref="global::Vent"/> being entered.</param>
public class EnterVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEvent
{
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is entering the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is entering.
/// </summary>
public Vent? Vent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EnterVentEvent"/> class.
/// </summary>
/// <param name="player">The <see cref="PlayerControl"/> that is entering the <paramref name="vent"/>.</param>
/// <param name="vent">The <see cref="global::Vent"/> being entered.</param>
public EnterVentEvent(PlayerControl player, Vent? vent)
{
Player = player;
Vent = vent;
}
public Vent? Vent { get; } = vent;
}
@@ -3,26 +3,17 @@
/// <summary>
/// Event that is invoked when a player exits a vent. This event is cancelable.
/// </summary>
public class ExitVentEvent : MiraCancelableEvent
/// <param name="player">The <see cref="PlayerControl"/> who is exiting the <paramref name="vent"/>.</param>
/// <param name="vent">The <see cref="global::Vent"/> being exited from.</param>
public class ExitVentEvent(PlayerControl player, Vent? vent) : MiraCancelableEvent
{
/// <summary>
/// Gets the <see cref="PlayerControl"/> that is exiting the <see cref="Vent"/>.
/// </summary>
public PlayerControl Player { get; }
public PlayerControl Player { get; } = player;
/// <summary>
/// Gets the <see cref="global::Vent"/> that the <see cref="Player"/> is exiting.
/// </summary>
public Vent? Vent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ExitVentEvent"/> class.
/// </summary>
/// <param name="player">The <see cref="PlayerControl"/> who is exiting the <paramref name="vent"/>.</param>
/// <param name="vent">The <see cref="global::Vent"/> being exited from.</param>
public ExitVentEvent(PlayerControl player, Vent? vent)
{
Player = player;
Vent = vent;
}
public Vent? Vent { get; } = vent;
}
@@ -1,15 +1,7 @@
namespace MiraAPI.Events.Vanilla.Usables;
/// <summary>
/// Event for if a <see cref="PlayerControl"/> can use an <see cref="IUsable"/> from Vanilla Among Us. Will always be ran locally.
/// Event for if a <see cref="PlayerControl"/> can use an <see cref="IUsable"/> from Vanilla Among Us. Will always be run locally.
/// </summary>
public class PlayerCanUseEvent : PlayerUseEvent
{
/// <summary>
/// Initializes a new instance of the <see cref="PlayerCanUseEvent"/> class.
/// </summary>
/// <param name="usable">The <see cref="IUsable"/>.</param>
public PlayerCanUseEvent(IUsable usable) : base(usable)
{
}
}
/// <param name="usable">The <see cref="IUsable"/>.</param>
public class PlayerCanUseEvent(IUsable usable) : PlayerUseEvent(usable);
@@ -1,34 +1,23 @@
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.
/// Event for <see cref="PlayerControl"/> using a <see cref="IUsable"/> from Vanilla Among Us. Will always be run locally.
/// </summary>
public class PlayerUseEvent : MiraCancelableEvent
/// <param name="usable">The <see cref="IUsable"/>.</param>
public class PlayerUseEvent(IUsable usable) : MiraCancelableEvent
{
/// <summary>
/// Gets the instance of <see cref="IUsable"/> that was used.
/// </summary>
public IUsable Usable { get; }
public IUsable Usable { get; } = usable;
/// <summary>
/// Gets a value indicating whether the <see cref="Usable"/> is a <see cref="Console"/>, <see cref="MapConsole"/>, or <see cref="SystemConsole"/>.
/// </summary>
public bool IsPrimaryConsole { get; }
public bool IsPrimaryConsole { get; } = usable.TryCast<Console>() || usable.TryCast<SystemConsole>() || usable.TryCast<MapConsole>();
/// <summary>
/// Gets a value indicating whether the <see cref="Usable"/> is a <see cref="Vent"/>.
/// </summary>
public bool IsVent { get; }
/// <summary>
/// Initializes a new instance of the <see cref="PlayerUseEvent"/> class.
/// </summary>
/// <param name="usable">The <see cref="IUsable"/>.</param>
public PlayerUseEvent(IUsable usable)
{
Usable = usable;
IsPrimaryConsole = usable.TryCast<Console>() || usable.TryCast<SystemConsole>() || usable.TryCast<MapConsole>();
IsVent = usable.TryCast<Vent>();
}
public bool IsVent { get; } = usable.TryCast<Vent>();
}
+4 -2
View File
@@ -48,7 +48,8 @@ public abstract class CustomGameOver
/// </summary>
/// <typeparam name="T">Type of the custom game over.</typeparam>
/// <returns>The <see cref="global::GameOverReason"/> associated with the custom game over.</returns>
public static GameOverReason GameOverReason<T>() where T : CustomGameOver
public static GameOverReason GameOverReason<T>()
where T : CustomGameOver
{
return (GameOverReason)GameOverManager.GetGameOverId<T>();
}
@@ -58,7 +59,8 @@ public abstract class CustomGameOver
/// </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
public static void Trigger<T>(IEnumerable<NetworkedPlayerInfo> winners)
where T : CustomGameOver
{
var reason = GameOverManager.GetGameOverId<T>();
var data = new GameOverData(reason, [.. winners]);
+9 -9
View File
@@ -12,7 +12,7 @@ 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;
private static int nextId = Enum.GetNames<GameOverReason>().Length;
/// <summary>
/// Register a <see cref="CustomGameOver"/>.
@@ -39,9 +39,9 @@ public static class GameOverManager
return false;
}
GameOverIds.Add(gameOverType, _nextId);
GameOverTypes.Add(_nextId, gameOverType);
_nextId++;
GameOverIds.Add(gameOverType, nextId);
GameOverTypes.Add(nextId, gameOverType);
nextId++;
return true;
}
@@ -68,7 +68,8 @@ public static class GameOverManager
/// </summary>
/// <typeparam name="T">Type of the <see cref="CustomGameOver"/>.</typeparam>
/// <returns>The ID of the <see cref="CustomGameOver"/>.</returns>
public static int GetGameOverId<T>() where T : CustomGameOver
public static int GetGameOverId<T>()
where T : CustomGameOver
{
return GetGameOverId(typeof(T));
}
@@ -81,9 +82,8 @@ public static class GameOverManager
/// <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!");
return GameOverIds.TryGetValue(gameOverType, out var id)
? id
: throw new ArgumentException($"{gameOverType.FullName} is not a registered custom game over!");
}
}
-2
View File
@@ -1,2 +0,0 @@
[*.cs]
dotnet_diagnostic.CS1591.severity = none
+51 -31
View File
@@ -84,15 +84,11 @@ public abstract class AbstractGameMode : IOptionable
/// <returns>Resulting body type.</returns>
public virtual PlayerBodyTypes GetBodyType(PlayerControl player)
{
if (AprilFoolsMode.ShouldHorseAround())
{
return PlayerBodyTypes.Horse;
}
if (AprilFoolsMode.ShouldLongAround())
{
return PlayerBodyTypes.Long;
}
return PlayerBodyTypes.Normal;
return AprilFoolsMode.ShouldHorseAround()
? PlayerBodyTypes.Horse
: (AprilFoolsMode.ShouldLongAround()
? PlayerBodyTypes.Long
: PlayerBodyTypes.Normal);
}
/// <summary>
@@ -177,14 +173,17 @@ public abstract class AbstractGameMode : IOptionable
/// Custom winner selection.
/// </summary>
/// <returns>List of winners or null.</returns>
public virtual List<NetworkedPlayerInfo>? CalculateWinners() => null;
public virtual List<NetworkedPlayerInfo>? CalculateWinners()
{
return null;
}
/// <summary>
/// The IEnumerator that plays the intro cutscene for this gamemode.
/// </summary>
/// <param name="__instance">An instance of IntroCutscene.</param>
/// <param name="introCutscene">An instance of IntroCutscene.</param>
/// <returns>An IEnumerator to run the intro cutscene instead of the base game one.</returns>
public virtual IEnumerator IntroCutscene(IntroCutscene __instance)
public virtual IEnumerator IntroCutscene(IntroCutscene introCutscene)
{
yield return new WaitForEndOfFrame();
}
@@ -194,35 +193,50 @@ public abstract class AbstractGameMode : IOptionable
/// </summary>
/// <param name="console">Admin Console.</param>
/// <returns>True if Admin console is enabled.</returns>
public virtual bool CanUseMapConsole(MapConsole console) => true;
public virtual bool CanUseMapConsole(MapConsole console)
{
return true;
}
/// <summary>
/// Can a body be reported in this gamemode.
/// </summary>
/// <param name="body">Target body for reporting.</param>
/// <returns>True if dead bodies can be reported.</returns>
public virtual bool CanReport(DeadBody body) => true;
public virtual bool CanReport(DeadBody body)
{
return true;
}
/// <summary>
/// Can system consoles be used in this gamemode.
/// </summary>
/// <param name="console">System Console.</param>
/// <returns>True if system consoles are enabled in this mode.</returns>
public virtual bool CanUseSystemConsole(SystemConsole console) => true;
public virtual bool CanUseSystemConsole(SystemConsole console)
{
return true;
}
/// <summary>
/// Can tasks be interacted with in this gamemode.
/// </summary>
/// <param name="console">Task console.</param>
/// <returns>True if tasks are enabled in this mode.</returns>
public virtual bool CanUseTasks(Console console) => true;
public virtual bool CanUseTasks(Console console)
{
return true;
}
/// <summary>
/// Should the sabotage map be used when attempting to open sabotage overlay.
/// </summary>
/// <param name="map">MapBehaviour object.</param>
/// <returns>True if the sabotage map should be shown.</returns>
public virtual bool ShouldShowSabotageMap(MapBehaviour map) => true;
public virtual bool ShouldShowSabotageMap(MapBehaviour map)
{
return true;
}
/// <summary>
/// Gets the <see cref="MapOptions"/> to display on the map.
@@ -244,28 +258,36 @@ public abstract class AbstractGameMode : IOptionable
/// <param name="vent">Target vent.</param>
/// <param name="playerInfo">Player attempting to vent.</param>
/// <returns>True if venting is enabled in this mode.</returns>
public virtual bool CanVent(Vent vent, NetworkedPlayerInfo playerInfo) => true;
public virtual bool CanVent(Vent vent, NetworkedPlayerInfo playerInfo)
{
return true;
}
/// <summary>
/// Does the task bar appear in the gamemode.
/// Gets a value indicating whether the task bar appears in the gamemode.
/// </summary>
/// <returns>True if the task bar is enabled in this mode.</returns>
public virtual bool ShowTaskBar => true;
/// <summary>
/// Updates the task panel.
/// </summary>
/// <param name="instance">The task panel to update.</param>
public virtual void UpdateTaskPanel(TaskPanelBehaviour instance)
{
instance.background.transform.localScale = (instance.taskText.textBounds.size.x > 0f)
instance.background.transform.localScale = instance.taskText.textBounds.size.x > 0f
? new Vector3(instance.taskText.textBounds.size.x + 0.2f, instance.taskText.textBounds.size.y + 0.2f, 1f)
: Vector3.zero;
Vector3 vector = instance.background.sprite.bounds.extents;
var vector = instance.background.sprite.bounds.extents;
vector.y = -vector.y;
vector = vector.Mul(instance.background.transform.localScale);
instance.background.transform.localPosition = vector;
Vector3 vector2 = instance.tab.sprite.bounds.extents;
var vector2 = instance.tab.sprite.bounds.extents;
vector2 = vector2.Mul(instance.tab.transform.localScale);
vector2.y = -vector2.y;
vector2.x += vector.x * 2f;
instance.tab.transform.localPosition = vector2;
if (GameManager.Instance == null)
{
return;
@@ -275,14 +297,9 @@ public abstract class AbstractGameMode : IOptionable
var xPos = -instance.background.sprite.bounds.size.x * instance.background.transform.localScale.x;
instance.closedPosition = new Vector3(xPos, yPos, instance.closedPosition.z);
instance.openPosition = new Vector3(instance.openPosition.x, yPos, instance.openPosition.z);
if (instance.open)
{
instance.timer = Mathf.Min(1f, instance.timer + Time.deltaTime / instance.animationTimeSeconds);
}
else
{
instance.timer = Mathf.Max(0f, instance.timer - Time.deltaTime / instance.animationTimeSeconds);
}
instance.timer = instance.open
? Mathf.Min(1f, instance.timer + (Time.deltaTime / instance.animationTimeSeconds))
: Mathf.Max(0f, instance.timer - (Time.deltaTime / instance.animationTimeSeconds));
Vector3 relativePos = new(
Mathf.SmoothStep(instance.closedPosition.x, instance.openPosition.x, instance.timer),
@@ -293,5 +310,8 @@ public abstract class AbstractGameMode : IOptionable
}
/// <inheritdoc/>
public override string ToString() => Name;
public override string ToString()
{
return Name;
}
}
+2 -1
View File
@@ -16,5 +16,6 @@ public class ClassicMode : AbstractGameMode
/// <inheritdoc/>
public override string Description => "MiraApi.Gamemode.Classic.Description";
public override LoadableAsset<Sprite>? Icon => MiraAssets.ClassicGamemodeIcon;
/// <inheritdoc/>
public override LoadableAsset<Sprite> Icon => MiraAssets.ClassicGamemodeIcon;
}
+38 -22
View File
@@ -1,9 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MiraAPI.Translation;
using MiraAPI.PluginLoading;
using Reactor.Utilities;
namespace MiraAPI.GameModes;
@@ -14,7 +12,10 @@ public static class CustomGameModeManager
{
internal static readonly Dictionary<uint, AbstractGameMode> IdToModeMap = [];
private static uint GetNextId() => ++LastId;
private static uint GetNextId()
{
return ++LastId;
}
private static uint LastId { get; set; }
@@ -40,13 +41,13 @@ public static class CustomGameModeManager
return false;
}
if (!mode.HideMode)
{
IdToModeMap.Add(GetNextId(), mode);
pluginInfo.GameModes.Add(LastId, mode);
mode.ID = LastId;
GameModeOption.AddOption(mode);
}
if (mode.HideMode)
return true;
IdToModeMap.Add(GetNextId(), mode);
pluginInfo.GameModes.Add(LastId, mode);
mode.ID = LastId;
GameModeOption.AddOption(mode);
return true;
}
@@ -54,20 +55,30 @@ public static class CustomGameModeManager
/// Checks to see if the current game mode is an instance of the classic mode.
/// </summary>
/// <returns>True if the classic mode is the current one.</returns>
public static bool IsClassic() => ActiveMode != null && ActiveMode.GetType().IsAssignableTo(typeof(ClassicMode));
public static bool IsClassic()
{
return ActiveMode != null && ActiveMode.GetType().IsAssignableTo(typeof(ClassicMode));
}
/// <summary>
/// Checks to see if the current game mode is an instance of the HNS mode.
/// </summary>
/// <returns>True if the Hide n Seek mode is the current one.</returns>
public static bool IsHideNSeek() => ActiveMode != null && ActiveMode.GetType().IsAssignableTo(typeof(HideAndSeekMode));
public static bool IsHideNSeek()
{
return ActiveMode != null && ActiveMode.GetType().IsAssignableTo(typeof(HideAndSeekMode));
}
/// <summary>
/// Checks if a provided GameMode is the current active one.
/// </summary>
/// <typeparam name="T">The AbstractGameMode subclass being checked.</typeparam>
/// <returns>Whether the provided mode is the current active one.</returns>
public static bool IsActiveGameMode<T>() where T : AbstractGameMode => ActiveMode is T;
public static bool IsActiveGameMode<T>()
where T : AbstractGameMode
{
return ActiveMode is T;
}
/// <summary>
/// Gets the current gamemode.
@@ -79,7 +90,10 @@ public static class CustomGameModeManager
/// </summary>
/// <param name="id">The ID of the gamemode to fetch.</param>
/// <returns>The gamemode matching that ID.</returns>
public static AbstractGameMode GetMode(uint id) => IdToModeMap[id];
public static AbstractGameMode GetMode(uint id)
{
return IdToModeMap[id];
}
/// <summary>
/// Finds the parent mod of a custom gamemode.
@@ -95,17 +109,19 @@ public static class CustomGameModeManager
{
var defaultMode = new ClassicMode();
IdToModeMap.Add(0, defaultMode);
// no need to add to game mode option as it already contains it
// because we cannot have the option be created with no values
defaultMode.ID = 0;
var hnsMode = new HideAndSeekMode();
if (!hnsMode.HideMode)
{
IdToModeMap.Add(1, hnsMode);
hnsMode.ID = 1;
GameModeOption.AddOption(hnsMode);
LastId++;
}
if (hnsMode.HideMode)
return;
IdToModeMap.Add(1, hnsMode);
hnsMode.ID = 1;
GameModeOption.AddOption(hnsMode);
LastId++;
}
internal static void GetAndSetGameMode()
@@ -119,6 +135,6 @@ public static class CustomGameModeManager
}
ActiveMode = IdToModeMap[0];
Logger<MiraApiPlugin>.Warning($"Unable to find game mode of id {id}!");
Warning($"Unable to find game mode of id {id}!");
}
}
+32 -34
View File
@@ -1,22 +1,15 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.GameOptions;
using MiraAPI.Networking;
using MiraAPI.Patches;
using MiraAPI.Patches.GameModes;
using MiraAPI.Patches.Options;
using MiraAPI.Translation;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
using Reactor.Networking.Attributes;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.ProBuilder;
using Object = UnityEngine.Object;
namespace MiraAPI.GameModes;
@@ -27,7 +20,7 @@ namespace MiraAPI.GameModes;
public static class GameModeOption
{
/// <summary>
/// Gets the current index of the Game Mode Option
/// Gets the current index of the Game Mode Option.<br/>
/// For the value as an <see cref="AbstractGameMode"/>, see <see cref="CustomGameModeManager.ActiveMode"/>.
/// </summary>
public static int Value
@@ -35,32 +28,37 @@ public static class GameModeOption
get =>
OptionBehaviour != null
? OptionBehaviour.GetInt()
: _lastValue;
: LastValue;
private set
{
_lastValue = value;
LastValue = value;
if (OptionBehaviour == null)
return;
OptionBehaviour.Value = value;
OptionBehaviour.UpdateValue();
_lastValue = value;
LastValue = value;
}
}
internal static StringOption OptionBehaviour { get; set; } = null!;
internal static int _lastValue;
internal static readonly StringNames GamemodeName = MiraLocaleManager.GetOrCreateLocaleString("Gamemode");
internal static readonly StringNames GamemodeName = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.Gamemode");
internal static readonly StringNames CustomName = MiraLocaleManager.GetOrCreateLocaleString("Custom");
internal static readonly Dictionary<uint, StringNames> Values = new()
{
[0] = MiraLocaleManager.GetOrCreateLocaleString("MiraApi.Gamemode.Classic"),
};
internal static StringOption OptionBehaviour { get; set; } = null!;
[SuppressMessage("Critical Code Smell", "S2223:Non-constant static fields should not be visible", Justification = "Internal behaviour that does not need property-level validation.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")] // why so many warnings???
internal static int LastValue;
internal static void AddOption(AbstractGameMode mode)
{
if (!Values.ContainsKey(mode.ID))
Values.Add(mode.ID, MiraLocaleManager.GetOrCreateLocaleString(mode.Name));
}
/*[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.CreateSettings))]
[HarmonyPostfix]
private static void CreateSettingsPatch(GameOptionsMenu __instance)
@@ -112,8 +110,9 @@ public static class GameModeOption
Value = val;
var previousMode = CustomGameModeManager.ActiveMode;
CustomGameModeManager.GetAndSetGameMode();
HudPatches.SetGameModeText(CustomGameModeManager.GetMode(Values.ElementAt(_lastValue).Key).ColoredName);
HudPatches.SetGameModeText(CustomGameModeManager.GetMode(Values.ElementAt(LastValue).Key).ColoredName);
var gm = CustomGameModeManager.ActiveMode!;
if (gm != previousMode)
{
ModdedOptionsManager.AddSettingsChangeMessage(
@@ -121,8 +120,7 @@ public static class GameModeOption
GamemodeName,
gm.ColoredName,
new Color(0.7333f, 0.7333f, 0.7333f, 1),
gm.TmpIcon,
true);
gm.TmpIcon);
if (MenuState.Instance)
{
// should force reset roles for gamemodes properly
@@ -131,29 +129,29 @@ public static class GameModeOption
MenuState.Instance.QueuedRoleMenuRefresh[roleMenu.Key] = true;
}
}
GameOptionsMenuPatch.RefreshForGameMode();
RoleGuidePatches.RefreshSettingsForGameMode();
}
// could make Values a dict of AbstractGameMode too
// TODO: could make Values a dict of AbstractGameMode too
}
[HarmonyPatch(typeof(GameOptionsMenu), nameof(GameOptionsMenu.ValueChanged))]
[HarmonyPrefix]
private static bool ValueChanged(GameOptionsMenu __instance, OptionBehaviour option)
private static bool ValueChanged(OptionBehaviour option)
{
if (OptionBehaviour.Equals(option))
{
Info($"Game mode changed to {option.GetInt()}");
RpcSyncGamemode(PlayerControl.LocalPlayer, option.GetInt());
if (GameSettingMenu.Instance && CustomGameModeManager.ActiveMode != null)
{
GameOptionsMenuPatch.ToggleGamemodeOptions(CustomGameModeManager.ActiveMode, __instance);
GameSettingMenu.Instance.RoleSettingsButton.gameObject.SetActive(CustomGameModeManager.ActiveMode.ShowNormalRoleSettings);
}
return false;
}
return true;
if (!OptionBehaviour.Equals(option))
return true;
Info($"Game mode changed to {option.GetInt()}");
RpcSyncGamemode(PlayerControl.LocalPlayer, option.GetInt());
return false;
}
[MethodRpc((uint) MiraRpc.SyncGamemodeOption)]
[MethodRpc((uint)MiraRpc.SyncGamemodeOption)]
[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Intentionally unused because the main intent is for it to be used by dependent mods to add to a blacklist.")]
internal static void RpcSyncGamemode(PlayerControl host, int data)
{
Set(data);
+241 -233
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using AmongUs.Data;
using AmongUs.GameOptions;
@@ -30,276 +31,287 @@ public class HideAndSeekMode : AbstractGameMode
/// <inheritdoc/>
public override string Description => "MiraApi.Gamemode.HideAndSeek.Description";
/// <inheritdoc/>
// TODO: Once the Hide n Seek port is ready for release, we will remove this.
public override bool HideMode => !MiraApiPlugin.IsDevBuild;
/// <inheritdoc/>
public override Color Color { get; } = new Color32(255, 88, 90, 255);
public override LoadableAsset<Sprite>? Icon => MiraAssets.HnSGamemodeIcon;
public override bool CanReport(DeadBody body) => false;
public override bool ShouldShowSabotageMap(MapBehaviour map) => false;
/// <inheritdoc/>
public override LoadableAsset<Sprite> Icon => MiraAssets.HnSGamemodeIcon;
/// <inheritdoc/>
public override bool ShowGameModeIntroCutscene => true;
/// <inheritdoc/>
public override bool GameModeBodyTypeOverride => true;
/// <inheritdoc/>
public override bool ShowNormalGameSettings => false;
/// <inheritdoc/>
public override bool ShowNormalRoleSettings => false;
/// <inheritdoc/>
public override float DefaultImpostorKillCooldown => 1f;
/// <inheritdoc/>
public override bool ShowTaskBar => false;
public static int ImpostorPlayerID()
/// <inheritdoc/>
public override bool CanReport(DeadBody body)
{
return false;
}
/// <inheritdoc/>
public override bool ShouldShowSabotageMap(MapBehaviour map)
{
return false;
}
private static int ImpostorPlayerID()
{
return OptionGroupSingleton<HnsImpostorOptions>.Instance.SelectedSeeker.Value;
}
public static bool HasImpostorPlayerID()
private static bool HasImpostorPlayerID()
{
return ImpostorPlayerID() > -1;
}
public static bool ValidateImpostorPlayerID(List<NetworkedPlayerInfo> players)
private static bool ValidateImpostorPlayerID(List<NetworkedPlayerInfo> players)
{
return HasImpostorPlayerID() && players.Find((NetworkedPlayerInfo p) => (int)p.PlayerId == ImpostorPlayerID()) != null;
return HasImpostorPlayerID() && players.Find(p => p.PlayerId == ImpostorPlayerID()) != null;
}
/// <inheritdoc/>
public override void AssignRoles(out bool runOriginal, LogicRoleSelectionNormal instance)
{
runOriginal = false;
Il2CppSystem.Collections.Generic.List<ClientData> list = new();
CppCollections.List<ClientData> list = new();
AmongUsClient.Instance.GetAllClients(list);
List<NetworkedPlayerInfo> list2 = list.ToArray()
List<NetworkedPlayerInfo> list2 = [.. list.ToArray()
.Where(c => c.Character != null && c.Character.Data != null && !c.Character.Data.Disconnected &&
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)
.ToList();
!c.Character.Data.IsDead).OrderBy(c => c.Id).Select(c => c.Character.Data)];
foreach (NetworkedPlayerInfo networkedPlayerInfo in GameData.Instance.AllPlayers)
foreach (var networkedPlayerInfo in GameData.Instance.AllPlayers)
{
if (networkedPlayerInfo.Object != null && networkedPlayerInfo.Object.isDummy)
{
list2.Add(networkedPlayerInfo);
}
}
IGameOptions currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions;
int adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count);
var currentGameOptions = GameOptionsManager.Instance.CurrentGameOptions;
var adjustedNumImpostors = GameOptionsManager.Instance.CurrentGameOptions.GetAdjustedNumImpostors(list2.Count);
AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Impostor, Math.Max(adjustedNumImpostors, 1), RoleTypes.Impostor);
AssignRolesForTeam(list2, currentGameOptions, RoleTeamTypes.Crewmate, int.MaxValue, RoleTypes.Engineer);
}
public static void AssignRolesForTeam(
private static void AddGuaranteedRoles(IEnumerable<RoleBehaviour> guaranteedRoles, IGameOptions opts, List<RoleTypes> list)
{
var roleOptions = opts.RoleOptions;
foreach (var roleAssignmentData in guaranteedRoles.Select(x =>
new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100)))
{
while (true)
{
var count = roleAssignmentData.Count;
roleAssignmentData.Count = count - 1;
if (count <= 0) break;
list.Add(roleAssignmentData.Role.Role);
}
}
}
private static void AddPotentialRoles(IEnumerable<RoleBehaviour> source, IGameOptions opts, List<RoleTypes> list)
{
var roleOptions = opts.RoleOptions;
var potentialRoles = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
list.Clear();
foreach (var roleData in potentialRoles)
{
for (var i = 0; i < roleData.Count; i++)
{
if (HashRandom.Next(101) < roleData.Chance)
{
list.Add(roleData.Role.Role);
}
}
}
}
private static void AddFallbackRoles(List<RoleTypes> list, int targetPlayerCount, int teamMax, int rolesAssigned, RoleTypes basicRole)
{
while (list.Count < targetPlayerCount && list.Count + rolesAssigned < teamMax)
{
list.Add(basicRole);
}
}
private static void AssignRolesForTeam(
List<NetworkedPlayerInfo> players,
IGameOptions opts,
RoleTeamTypes team,
int teamMax,
RoleTypes defaultRole)
{
Error($"Hide And Seek Mode - AssignRolesForTeam: Team: {team}, Max: {teamMax}, Players: {players.Count}, DefaultRole: {defaultRole}");
int num = 0;
IRoleOptionsCollection roleOptions = opts.RoleOptions;
Info($"Hide And Seek Mode - AssignRolesForTeam: Team: {team}, Max: {teamMax}, Players: {players.Count}, DefaultRole: {defaultRole}");
var num = 0;
var roleOptions = opts.RoleOptions;
var source = RoleManager.Instance.AllRoles.ToArray()
.Where(role => role.TeamType == team && !RoleManager.IsGhostRole(role.Role) &&
CustomRoleUtils.CanSpawnOnCurrentMode(role));
CustomRoleUtils.CanSpawnOnCurrentMode(role))
.ToList();
var assignmentData = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
var source2 = CustomRoleUtils.GetPossibleRoles(assignmentData, x => x.Chance == 100);
var guaranteedRoles = source.Where(x => source2.Contains(((ushort)x.Role, 100)));
List<RoleTypes> list = new List<RoleTypes>();
if (team == RoleTeamTypes.Crewmate)
var guaranteedRoles = source.Where(x => source2.Contains(((ushort)x.Role, 100))).ToList();
List<RoleTypes> list = [];
switch (team)
{
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment");
foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) =>
new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100)))
{
while (true)
case RoleTeamTypes.Crewmate:
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment");
AddGuaranteedRoles(guaranteedRoles, opts, list);
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment");
AssignRolesFromList(players, teamMax, list, ref num);
AddPotentialRoles(source, opts, list);
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Potential Assignment");
AssignRolesFromList(players, teamMax, list, ref num);
const RoleTypes basicCrewRole = RoleTypes.Engineer;
AddFallbackRoles(list, players.Count, teamMax, num, basicCrewRole);
AssignRolesFromList(players, teamMax, list, ref num);
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Fallback Assignment");
break;
case RoleTeamTypes.Impostor:
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment");
var newImpostors = new List<NetworkedPlayerInfo>();
if (HasImpostorPlayerID() &&
ValidateImpostorPlayerID(players) &&
!AmongUsClient.Instance.IsGamePublic)
{
RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData;
int count = roleAssignmentData2.Count;
roleAssignmentData2.Count = count - 1;
if (count <= 0)
{
break;
}
list.Add(roleAssignmentData.Role.Role);
}
}
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment");
AssignRolesFromList(players, teamMax, list, ref num);
var list2 = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
list.Clear();
foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2)
{
for (int i = 0; i < roleAssignmentData3.Count; i++)
{
if (HashRandom.Next(101) < roleAssignmentData3.Chance)
{
list.Add(roleAssignmentData3.Role.Role);
}
}
}
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Potential Assignment");
AssignRolesFromList(players, teamMax, list, ref num);
var basicRole = RoleTypes.Engineer;
while (list.Count < players.Count && list.Count + num < teamMax)
{
list.Add(basicRole);
}
AssignRolesFromList(players, teamMax, list, ref num);
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Fallback Assignment");
}
else if (team == RoleTeamTypes.Impostor)
{
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Before Guaranteed Assignment");
var newImpostors = new List<NetworkedPlayerInfo>();
// Specified Seeker
if (HasImpostorPlayerID() &&
ValidateImpostorPlayerID(players) &&
!AmongUsClient.Instance.IsGamePublic)
{
NetworkedPlayerInfo networkedPlayerInfo = players.ToArray()
.First(p => p.PlayerId == ImpostorPlayerID());
players.Remove(networkedPlayerInfo);
newImpostors.Add(networkedPlayerInfo);
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}");
}
// Random Seeker
else
{
int num2 = 0;
while (num2 < teamMax && players.Count > 0)
{
PseudoRandomList<NetworkedPlayerInfo> pseudoRandomList = new PseudoRandomList<NetworkedPlayerInfo>(AmongUsClient.Instance.GameId);
players.Do(x => pseudoRandomList.Add(x));
for (int i = 0; i < GameData.RoundsPlayedInSession; i++)
{
pseudoRandomList.PickRandom();
}
NetworkedPlayerInfo networkedPlayerInfo = pseudoRandomList.PickRandom();
// Specified Seeker
var networkedPlayerInfo = players.First(p => p.PlayerId == ImpostorPlayerID());
players.Remove(networkedPlayerInfo);
newImpostors.Add(networkedPlayerInfo);
num2++;
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}");
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}");
}
}
Error($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment");
foreach (RoleManager.RoleAssignmentData roleAssignmentData in guaranteedRoles.Select((x) =>
new RoleManager.RoleAssignmentData(x, roleOptions.GetNumPerGame(x.Role), 100)))
{
while (true)
else
{
RoleManager.RoleAssignmentData roleAssignmentData2 = roleAssignmentData;
int count = roleAssignmentData2.Count;
roleAssignmentData2.Count = count - 1;
if (count <= 0)
// Random Seeker
var num2 = 0;
while (num2 < teamMax && players.Count > 0)
{
break;
}
PseudoRandomList<NetworkedPlayerInfo> pseudoRandomList = new(AmongUsClient.Instance.GameId);
players.Do(pseudoRandomList.Add);
for (var i = 0; i < GameData.RoundsPlayedInSession; i++)
{
pseudoRandomList.PickRandom();
}
list.Add(roleAssignmentData.Role.Role);
}
}
AssignRolesFromList(newImpostors, teamMax, list, ref num);
var list2 = source.Where(x => !x.IsDead).Select(role =>
new RoleManager.RoleAssignmentData(
role,
roleOptions.GetNumPerGame(role.Role),
roleOptions.GetChancePerGame(role.Role))).ToList();
list.Clear();
foreach (RoleManager.RoleAssignmentData roleAssignmentData3 in list2)
{
for (int i = 0; i < roleAssignmentData3.Count; i++)
{
if (HashRandom.Next(101) < roleAssignmentData3.Chance)
{
list.Add(roleAssignmentData3.Role.Role);
var networkedPlayerInfo = pseudoRandomList.PickRandom();
players.Remove(networkedPlayerInfo);
newImpostors.Add(networkedPlayerInfo);
num2++;
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: Seeker is {networkedPlayerInfo.PlayerName}, ID: {networkedPlayerInfo.PlayerId}");
}
}
}
AssignRolesFromList(newImpostors, teamMax, list, ref num);
var basicRole = RoleTypes.Impostor;
while (list.Count < newImpostors.Count && list.Count + num < teamMax)
{
list.Add(basicRole);
}
Info($"MiraAPI.Patches.Roles.LogicRoleSelectionHnsPatch - AssignRolesForTeam: After Guaranteed Assignment");
AssignRolesFromList(newImpostors, teamMax, list, ref num);
AddGuaranteedRoles(guaranteedRoles, opts, list);
AssignRolesFromList(newImpostors, teamMax, list, ref num);
AddPotentialRoles(source, opts, list);
AssignRolesFromList(newImpostors, teamMax, list, ref num);
const RoleTypes basicImpRole = RoleTypes.Impostor;
AddFallbackRoles(list, newImpostors.Count, teamMax, num, basicImpRole);
AssignRolesFromList(newImpostors, teamMax, list, ref num);
break;
default:
throw new ArgumentOutOfRangeException(nameof(team), team, null);
}
}
public static void AssignRolesFromList(List<NetworkedPlayerInfo> players, int teamMax, List<RoleTypes> roleList, ref int rolesAssigned)
private static void AssignRolesFromList(List<NetworkedPlayerInfo> players, int teamMax, List<RoleTypes> roleList, ref int rolesAssigned)
{
while (roleList.Count > 0 && players.Count > 0 && rolesAssigned < teamMax)
{
int index = HashRandom.FastNext(roleList.Count);
RoleTypes roleType = roleList[index];
var index = HashRandom.FastNext(roleList.Count);
var roleType = roleList[index];
roleList.RemoveAt(index);
int index2 = HashRandom.FastNext(players.Count);
players[index2].Object.RpcSetRole(roleType, false);
var index2 = HashRandom.FastNext(players.Count);
players[index2].Object.RpcSetRole(roleType);
players.RemoveAt(index2);
rolesAssigned++;
}
}
public override IEnumerator IntroCutscene(IntroCutscene __instance)
/// <inheritdoc/>
public override IEnumerator IntroCutscene(IntroCutscene introCutscene)
{
SoundManager.Instance.PlaySound(__instance.IntroStinger, false, 1f, null);
Logger.GlobalInstance.Info("IntroCutscene :: CoBegin() :: Game Mode: Hide and Seek (MiraAPI)", null);
__instance.LogPlayerRoleData();
__instance.HideAndSeekPanels.SetActive(true);
SoundManager.Instance.PlaySound(introCutscene.IntroStinger, false);
Logger.GlobalInstance.Info("IntroCutscene :: CoBegin() :: Game Mode: Hide and Seek (MiraAPI)");
introCutscene.LogPlayerRoleData();
introCutscene.HideAndSeekPanels.SetActive(true);
if (PlayerControl.LocalPlayer.Data.Role.IsImpostor)
{
__instance.CrewmateRules.SetActive(false);
__instance.ImpostorRules.SetActive(true);
introCutscene.CrewmateRules.SetActive(false);
introCutscene.ImpostorRules.SetActive(true);
}
else
{
__instance.CrewmateRules.SetActive(true);
__instance.ImpostorRules.SetActive(false);
introCutscene.CrewmateRules.SetActive(true);
introCutscene.ImpostorRules.SetActive(false);
}
__instance.ImpostorName.gameObject.SetActive(true);
__instance.ImpostorTitle.gameObject.SetActive(true);
__instance.BackgroundBar.enabled = false;
__instance.TeamTitle.gameObject.SetActive(false);
introCutscene.ImpostorName.gameObject.SetActive(true);
introCutscene.ImpostorTitle.gameObject.SetActive(true);
introCutscene.BackgroundBar.enabled = false;
introCutscene.TeamTitle.gameObject.SetActive(false);
var impostor = PlayerControl.AllPlayerControls.ToArray().FirstOrDefault(x => x.Data.Role.IsImpostor);
if (impostor == null)
{
Logger.GlobalInstance.Error("IntroCutscene :: CoBegin() :: impostor is NULL", null);
Logger.GlobalInstance.Error("IntroCutscene :: CoBegin() :: impostor is NULL");
}
GameManager.Instance.SetSpecialCosmetics(impostor);
if (impostor != null)
{
__instance.ImpostorName.text = impostor.Data.PlayerName;
}
else
{
__instance.ImpostorName.text = "???";
}
introCutscene.ImpostorName.text = impostor != null ? impostor.Data.PlayerName : "???";
yield return new WaitForSecondsRealtime(0.1f);
if (impostor != null)
{
__instance.ImpostorTitle.text = impostor.Data.Role.GetRoleName();
introCutscene.ImpostorTitle.text = impostor.Data.Role.GetRoleName();
}
PoolablePlayer playerSlot = null;
PoolablePlayer? playerSlot = null;
if (impostor != null)
{
playerSlot = __instance.CreatePlayer(1, 1, impostor.Data, false);
playerSlot = introCutscene.CreatePlayer(1, 1, impostor.Data, false);
playerSlot.SetBodyType(PlayerBodyTypes.Normal);
playerSlot.SetFlipX(false);
playerSlot.transform.localPosition = __instance.impostorPos;
playerSlot.transform.localScale = Vector3.one * __instance.impostorScale;
playerSlot.transform.localPosition = introCutscene.impostorPos;
playerSlot.transform.localScale = Vector3.one * introCutscene.impostorScale;
}
yield return ShipStatus.Instance.CosmeticsCache.PopulateFromPlayers();
@@ -309,45 +321,43 @@ public class HideAndSeekMode : AbstractGameMode
playerSlot.gameObject.SetActive(false);
}
__instance.HideAndSeekPanels.SetActive(false);
__instance.CrewmateRules.SetActive(false);
__instance.ImpostorRules.SetActive(false);
introCutscene.HideAndSeekPanels.SetActive(false);
introCutscene.CrewmateRules.SetActive(false);
introCutscene.ImpostorRules.SetActive(false);
HnsMusicHandler.Instance.StartMusicWithIntro();
var hideTimer = 10f;
if (PlayerControl.LocalPlayer.Data.Role.IsImpostor)
{
__instance.HideAndSeekTimerText.gameObject.SetActive(true);
introCutscene.HideAndSeekTimerText.gameObject.SetActive(true);
PoolablePlayer poolablePlayer;
AnimationClip anim;
if (AprilFoolsMode.ShouldHorseAround())
{
poolablePlayer = __instance.HorseWrangleVisualSuit;
poolablePlayer = introCutscene.HorseWrangleVisualSuit;
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.SetBodyType(PlayerBodyTypes.Seeker);
anim = __instance.HnSSeekerSpawnHorseAnim;
__instance.HorseWrangleVisualPlayer.SetBodyType(PlayerBodyTypes.Normal);
__instance.HorseWrangleVisualPlayer.UpdateFromPlayerData(
anim = introCutscene.HnSSeekerSpawnHorseAnim;
introCutscene.HorseWrangleVisualPlayer.SetBodyType(PlayerBodyTypes.Normal);
introCutscene.HorseWrangleVisualPlayer.UpdateFromPlayerData(
PlayerControl.LocalPlayer.Data,
PlayerControl.LocalPlayer.CurrentOutfitType,
PlayerMaterial.MaskType.None,
false,
null,
false);
}
else if (AprilFoolsMode.ShouldLongAround())
{
poolablePlayer = __instance.HideAndSeekPlayerVisual;
poolablePlayer = introCutscene.HideAndSeekPlayerVisual;
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.SetBodyType(PlayerBodyTypes.LongSeeker);
anim = __instance.HnSSeekerSpawnLongAnim;
anim = introCutscene.HnSSeekerSpawnLongAnim;
}
else
{
poolablePlayer = __instance.HideAndSeekPlayerVisual;
poolablePlayer = introCutscene.HideAndSeekPlayerVisual;
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.SetBodyType(PlayerBodyTypes.Seeker);
anim = __instance.HnSSeekerSpawnAnim;
anim = introCutscene.HnSSeekerSpawnAnim;
}
poolablePlayer.SetBodyCosmeticsVisible(false);
@@ -355,16 +365,14 @@ public class HideAndSeekMode : AbstractGameMode
PlayerControl.LocalPlayer.Data,
PlayerControl.LocalPlayer.CurrentOutfitType,
PlayerMaterial.MaskType.None,
false,
null,
false);
SpriteAnim component = poolablePlayer.GetComponent<SpriteAnim>();
var component = poolablePlayer.GetComponent<SpriteAnim>();
poolablePlayer.gameObject.SetActive(true);
poolablePlayer.ToggleName(false);
component.Play(anim, 1f);
component.Play(anim);
while (hideTimer > 0f)
{
__instance.HideAndSeekTimerText.text = Mathf.RoundToInt(hideTimer).ToString();
introCutscene.HideAndSeekTimerText.text = Mathf.RoundToInt(hideTimer).ToString(CultureInfo.InvariantCulture);
hideTimer -= Time.deltaTime;
yield return null;
}
@@ -376,42 +384,45 @@ public class HideAndSeekMode : AbstractGameMode
{
if (impostor != null)
{
impostor.AnimateCustom(__instance.HnSSeekerSpawnHorseInGameAnim);
impostor.AnimateCustom(introCutscene.HnSSeekerSpawnHorseInGameAnim);
}
}
else if (AprilFoolsMode.ShouldLongAround())
{
if (impostor != null)
{
impostor.AnimateCustom(__instance.HnSSeekerSpawnLongInGameAnim);
impostor.AnimateCustom(introCutscene.HnSSeekerSpawnLongInGameAnim);
}
}
else if (impostor != null)
{
impostor.AnimateCustom(__instance.HnSSeekerSpawnAnim);
impostor.AnimateCustom(introCutscene.HnSSeekerSpawnAnim);
impostor.cosmetics.SetBodyCosmeticsVisible(false);
}
}
ShipStatus.Instance.StartSFX();
HnsMusicHandler.Instance.OnGameStart();
HnsDangerMeter.Instance.OnGameStart();
UnityEngine.Object.Destroy(__instance.gameObject);
UnityEngine.Object.Destroy(introCutscene.gameObject);
}
/// <inheritdoc/>
public override void Initialize()
{
deadPlayerCount = 0;
ShipStatus.Instance.BreakEmergencyButton();
PlayerControl.LocalPlayer.SetKillTimer(0.01f);
if (HudManager.InstanceExists)
{
HudManager.Instance.gameObject.AddComponent<HnsMusicHandler>();
HudManager.Instance.gameObject.AddComponent<HideAndSeekHudHelper>();
HudManager.Instance.gameObject.AddComponent<HnsDangerMeter>();
}
if (!HudManager.InstanceExists) return;
HudManager.Instance.gameObject.AddComponent<HnsMusicHandler>();
HudManager.Instance.gameObject.AddComponent<HideAndSeekHudHelper>();
HudManager.Instance.gameObject.AddComponent<HnsDangerMeter>();
}
/// <inheritdoc/>
public override MapOptions GetMapOptions()
{
MapOptions mapOptions = new MapOptions
MapOptions mapOptions = new()
{
Mode = MapOptions.Modes.Normal,
};
@@ -422,27 +433,34 @@ public class HideAndSeekMode : AbstractGameMode
mapOptions.IncludeDeadBodies = false;
mapOptions.ShowLivePlayerPosition = false;
}
return mapOptions;
}
/// <inheritdoc/>
public override void CheckGameEnd(out bool runOriginal, LogicGameFlowNormal instance)
{
runOriginal = false;
if (Helpers.GetAlivePlayers().Count(x => x.Data.Role.IsImpostor) == 0)
var players = Helpers.GetAlivePlayers();
if (!players.Any(x => x.Data.Role.IsImpostor))
{
instance.Manager.RpcEndGame(GameOverReason.ImpostorDisconnect, !DataManager.Player.Ads.HasPurchasedAdRemoval);
}
if (Helpers.GetAlivePlayers().Count(x => !x.Data.Role.IsImpostor) != 0)
if (players.Any(x => !x.Data.Role.IsImpostor))
{
if (HideAndSeekHudHelper.Instance.AllTimersExpired())
{
instance.Manager.RpcEndGame(GameOverReason.HideAndSeek_CrewmatesByTimer, !DataManager.Player.Ads.HasPurchasedAdRemoval);
}
return;
}
instance.Manager.RpcEndGame(GameOverReason.HideAndSeek_ImpostorsByKills, !DataManager.Player.Ads.HasPurchasedAdRemoval);
}
/// <inheritdoc/>
public override PlayerBodyTypes GetBodyType(PlayerControl player)
{
if (player == null || player.Data == null || player.Data.Role == null)
@@ -451,47 +469,39 @@ public class HideAndSeekMode : AbstractGameMode
{
return PlayerBodyTypes.Horse;
}
if (AprilFoolsMode.ShouldLongAround())
{
return PlayerBodyTypes.Long;
}
return PlayerBodyTypes.Normal;
}
else if (AprilFoolsMode.ShouldHorseAround())
if (AprilFoolsMode.ShouldHorseAround())
{
if (player.Data.Role.IsImpostor)
{
return PlayerBodyTypes.Normal;
}
return PlayerBodyTypes.Horse;
return player.Data.Role.IsImpostor ? PlayerBodyTypes.Normal : PlayerBodyTypes.Horse;
}
else if (AprilFoolsMode.ShouldLongAround())
if (AprilFoolsMode.ShouldLongAround())
{
if (player.Data.Role.IsImpostor)
{
return PlayerBodyTypes.LongSeeker;
}
return PlayerBodyTypes.Long;
}
else
{
if (player.Data.Role.IsImpostor)
{
return PlayerBodyTypes.Seeker;
}
return PlayerBodyTypes.Normal;
return player.Data.Role.IsImpostor ? PlayerBodyTypes.LongSeeker : PlayerBodyTypes.Long;
}
return player.Data.Role.IsImpostor ? PlayerBodyTypes.Seeker : PlayerBodyTypes.Normal;
}
/// <inheritdoc/>
public override void UpdateTaskPanel(TaskPanelBehaviour instance)
{
instance.background.transform.localScale = (instance.taskText.textBounds.size.x > 0f)
? new Vector3(instance.taskText.textBounds.size.x + 0.2f, instance.taskText.textBounds.size.y + 0.2f, 1f)
: Vector3.zero;
Vector3 vector = instance.background.sprite.bounds.extents;
var vector = instance.background.sprite.bounds.extents;
vector.y = -vector.y;
vector = vector.Mul(instance.background.transform.localScale);
instance.background.transform.localPosition = vector;
Vector3 vector2 = instance.tab.sprite.bounds.extents;
var vector2 = instance.tab.sprite.bounds.extents;
vector2 = vector2.Mul(instance.tab.transform.localScale);
vector2.y = -vector2.y;
vector2.x += vector.x * 2f;
@@ -505,14 +515,9 @@ public class HideAndSeekMode : AbstractGameMode
var xPos = -instance.background.sprite.bounds.size.x * instance.background.transform.localScale.x;
instance.closedPosition = new Vector3(xPos, yPos, instance.closedPosition.z);
instance.openPosition = new Vector3(instance.openPosition.x, yPos, instance.openPosition.z);
if (instance.open)
{
instance.timer = Mathf.Min(1f, instance.timer + Time.deltaTime / instance.animationTimeSeconds);
}
else
{
instance.timer = Mathf.Max(0f, instance.timer - Time.deltaTime / instance.animationTimeSeconds);
}
instance.timer = instance.open
? Mathf.Min(1f, instance.timer + (Time.deltaTime / instance.animationTimeSeconds))
: Mathf.Max(0f, instance.timer - (Time.deltaTime / instance.animationTimeSeconds));
Vector3 relativePos = new(
Mathf.SmoothStep(instance.closedPosition.x, instance.openPosition.x, instance.timer),
@@ -521,7 +526,10 @@ public class HideAndSeekMode : AbstractGameMode
instance.transform.localPosition =
AspectPosition.ComputePosition(AspectPosition.EdgeAlignments.LeftTop, relativePos);
}
private int deadPlayerCount;
/// <inheritdoc/>
public override void OnPlayerDeath(PlayerControl player, bool assignGhostRole)
{
base.OnPlayerDeath(player, assignGhostRole);
+61 -15
View File
@@ -1,9 +1,13 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.GameOptions;
@@ -25,6 +29,12 @@ public abstract class AbstractOptionGroup
/// </summary>
public abstract string GroupName { get; }
/// <summary>
/// Gets the sprite of the group that is displayed in the match info guide.
/// </summary>
[HideFromIl2Cpp]
public virtual LoadableAsset<Sprite> Sprite => MiraAssets.IconSettings;
/// <summary>
/// Gets the Optionable type of the group.
/// </summary>
@@ -33,10 +43,9 @@ public abstract class AbstractOptionGroup
/// <summary>
/// Gets a value indicating whether the group should be shown in the modifiers menu.
/// </summary>
// TODO: make this not a boolean
#pragma warning disable S1133
[Obsolete("Use ParentMenu instead.")]
#pragma warning restore S1133
// Completed: make this not a boolean
[Obsolete("Use ParentMenu instead.", true)]
[SuppressMessage("Info Code Smell", "S1133:Deprecated code should be removed", Justification = "Retained.")]
public virtual bool ShowInModifiersMenu => false;
/// <summary>
@@ -47,7 +56,43 @@ public abstract class AbstractOptionGroup
/// <summary>
/// Gets the function that determines whether the group should be visible or not.
/// </summary>
public virtual Func<bool> GroupVisible => () => true;
public virtual Func<bool> GroupVisible => DelegateUtilities.AlwaysTrue;
/// <summary>
/// Gets a value indicating whether this group's options are shown in the Match Info Guide.
/// </summary>
public virtual bool ShowInMatchInfoGuide => ParentMenu is MenuCategory.Game;
/// <summary>
/// Gets the name title of the group when it is in the match info guide.
/// </summary>
public virtual string RoleGuideTitle => GroupName;
/// <summary>
/// Gets the key used to combine this group with other option groups on one Match Info Guide page.
/// Groups are combined only with groups from the same plugin that use the same non-empty key.
/// </summary>
public virtual string? MatchInfoGuidePageKey => null;
/// <summary>
/// Gets the title of the Match Info Guide page. For groups sharing a page key, the first
/// group in menu order supplies the page title.
/// </summary>
public virtual string MatchInfoGuidePageTitle => RoleGuideTitle;
/// <summary>
/// Gets the ordering priority of this Match Info Guide page. Lower values appear first
/// among pages with the same menu category and group priority. Groups sharing a page key
/// use the lowest page-order value among those groups.
/// </summary>
public virtual int MatchInfoGuidePageOrder => int.MaxValue;
/// <summary>
/// Gets the number of columns used to lay out options on this Match Info Guide page.
/// For a combined page, groups are placed into these columns. Values are limited to 1-6;
/// for groups sharing a page key, the first group in menu order supplies this value.
/// </summary>
public virtual int MatchInfoGuidePageColumns => 2;
/// <summary>
/// Gets the group <see cref="Color"/>. This is used to color the group in the options menu.
@@ -76,7 +121,8 @@ public abstract class AbstractOptionGroup
/// 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
public abstract class AbstractOptionGroup<T> : AbstractOptionGroup
where T : IOptionable
{
/// <inheritdoc />
public override Type OptionableType => typeof(T);
@@ -87,14 +133,15 @@ public abstract class AbstractOptionGroup<T> : AbstractOptionGroup where T : IOp
get
{
var type = typeof(T);
if (type == typeof(BaseModifier))
if (typeof(BaseModifier).IsAssignableFrom(type))
{
return MenuCategory.Modifiers;
}
else if (type == typeof(RoleBehaviour))
else if (typeof(RoleBehaviour).IsAssignableFrom(type))
{
return MenuCategory.Roles;
}
return MenuCategory.Game;
}
}
@@ -104,7 +151,8 @@ public abstract class AbstractOptionGroup<T> : AbstractOptionGroup where T : IOp
/// 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 custom role that the group is for.</typeparam>
public abstract class AbstractRoleOptionGroup<T>() : AbstractOptionGroup<T> where T : ICustomRole
public abstract class AbstractRoleOptionGroup<T> : AbstractOptionGroup<T>
where T : ICustomRole
{
/// <inheritdoc />
public override Type OptionableType => typeof(T);
@@ -118,11 +166,9 @@ public abstract class AbstractRoleOptionGroup<T>() : AbstractOptionGroup<T> wher
get
{
var role = CustomRoleManager.CustomMiraRoles.FirstOrDefault(x => x.GetType() == OptionableType);
if (role == null)
{
return new(new Color(0.7333f, 0.7333f, 0.7333f, 1));
}
return new(role.RoleColor, role.Configuration.IconTmp);
return role == null
? new(new Color(0.7333f, 0.7333f, 0.7333f, 1))
: new(role.RoleColor, role.Configuration.IconTmp);
}
}
}
@@ -133,7 +179,7 @@ public abstract class AbstractRoleOptionGroup<T>() : AbstractOptionGroup<T> wher
public enum MenuCategory
{
/// <summary>
/// Placeholder for indexing purposes. Options don't exist in the presset tab.
/// Placeholder for indexing purposes. Options don't exist in the preset tab.
/// </summary>
Preset,
@@ -0,0 +1,50 @@
using System;
using System.Reflection;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute to set the <see cref="IModdedOption.ChangedEvent"/> delegate in a <see cref="ModdedOptionAttribute"/> or <see cref="ModdedOptionListAttribute"/>.
/// </summary>
/// <param name="methodName">The method to get the changed event from.</param>
/// <param name="holderType">The type the method is in.</param>
[AttributeUsage(AttributeTargets.Property)]
public sealed class ModdedOptionChangedAttribute(string? methodName = null, Type? holderType = null)
: ModdedOptionMemberAttribute(methodName, holderType, "Changed")
{
internal Delegate? GetChanged(AbstractOptionGroup group, PropertyInfo property, IModdedOption option)
{
if (ResolveMethod(group, property, out var type, out var instanceGetter, out var notFound) is not { } method)
{
if (notFound)
Error($"Method {MemberName} does not exist in {type.FullName}");
return null;
}
var valueType = option.GetValueType();
if (!ValidateSignature(method, typeof(void), valueType))
return null;
var delegateType = typeof(Action<>).MakeGenericType(valueType);
return CompileDynamicDelegate(type, method, instanceGetter, typeof(void), [valueType], delegateType, "Changed");
}
internal Func<int, Delegate?>? GetListChanged(AbstractOptionGroup group, PropertyInfo property, Type valueType)
{
if (ResolveMethod(group, property, out var type, out var instanceGetter, out var notFound) is not { } method)
{
if (notFound)
Error($"Method {MemberName} does not exist in {type.FullName}");
return null;
}
if (!ValidateListSignature(method, typeof(void), out var hasIndex, valueType))
return null;
var delegateType = typeof(Action<>).MakeGenericType(valueType);
return CompileDynamicListDelegate(type, method, instanceGetter, typeof(void), [valueType], delegateType, "ListChanged", hasIndex);
}
}
@@ -0,0 +1,50 @@
using System;
using System.Reflection;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute to set the <see cref="IModdedOption.Getter"/> delegate in a <see cref="ModdedOptionAttribute"/> or <see cref="ModdedOptionListAttribute"/>.
/// </summary>
/// <param name="methodName">The method to get the getter from.</param>
/// <param name="holderType">The type the method is in.</param>
[AttributeUsage(AttributeTargets.Property)]
public sealed class ModdedOptionGetterAttribute(string? methodName = null, Type? holderType = null)
: ModdedOptionMemberAttribute(methodName, holderType, "Getter")
{
internal Delegate? GetGetter(AbstractOptionGroup group, PropertyInfo property, IModdedOption option)
{
if (ResolveMethod(group, property, out var type, out var instanceGetter, out var notFound) is not { } method)
{
if (notFound)
Error($"Method {MemberName} does not exist in {type.FullName}");
return null;
}
var valueType = option.GetValueType();
if (!ValidateSignature(method, valueType, valueType))
return null;
var delegateType = typeof(Func<,>).MakeGenericType(valueType, valueType);
return CompileDynamicDelegate(type, method, instanceGetter, valueType, [valueType], delegateType, "Getter");
}
internal Func<int, Delegate?>? GetListGetter(AbstractOptionGroup group, PropertyInfo property, Type valueType)
{
if (ResolveMethod(group, property, out var type, out var instanceGetter, out var notFound) is not { } method)
{
if (notFound)
Error($"Method {MemberName} does not exist in {type.FullName}");
return null;
}
if (!ValidateListSignature(method, valueType, out var hasIndex, valueType))
return null;
var delegateType = typeof(Func<,>).MakeGenericType(valueType, valueType);
return CompileDynamicListDelegate(type, method, instanceGetter, valueType, [valueType], delegateType, "ListGetter", hasIndex);
}
}
@@ -0,0 +1,428 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Base attribute for resolving and compiling option delegate members (<see cref="IModdedOption.Visible"/>, <see cref="IModdedOption.Getter"/>, <see cref="IModdedOption.Setter"/>, and <see cref="IModdedOption.ChangedEvent"/>).
/// </summary>
/// <param name="memberName">The name of the target member, or <see langword="null"/> to use the property name with <paramref name="defaultSuffix"/>.</param>
/// <param name="holderType">The type containing the target member, or <see langword="null"/> to use the declaring <see cref="AbstractOptionGroup"/> type.</param>
/// <param name="defaultSuffix">The default suffix appended to the property name when <paramref name="memberName"/> is not specified.</param>
[AttributeUsage(AttributeTargets.Property)]
public abstract class ModdedOptionMemberAttribute(string? memberName, Type? holderType, string defaultSuffix) : Attribute
{
private static readonly Dictionary<MethodInfo, Delegate> DelegateCache = [];
/// <summary>
/// A helper class to bind a specific list index to a dynamically compiled delegate.
/// </summary>
/// <param name="index">The index to bind.</param>
public sealed class DelegateIndexClosure(int index)
{
/// <summary>
/// The bound index.
/// </summary>
[SuppressMessage("Design", "CA1051:Do not declare visible instance fields", Justification = "No need to be private.")]
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", Justification = "Read above.")]
public readonly int Index = index;
}
/// <summary>
/// Exposes the index field so child attributes can emit instructions to read it.
/// </summary>
protected static readonly FieldInfo IndexClosureField = typeof(DelegateIndexClosure).GetField(nameof(DelegateIndexClosure.Index))!;
/// <summary>
/// Gets the resolved name of the target member.
/// </summary>
protected string? MemberName { get; private set; } = memberName;
/// <summary>
/// Validates that a method matches the expected return type and parameter types.
/// </summary>
/// <param name="method">The method to validate.</param>
/// <param name="expectedReturnType">The expected return type of the method.</param>
/// <param name="expectedParamTypes">The expected types of the parameters of the method.</param>
/// <returns><c>true</c> if the method is valid; <c>false</c> otherwise.</returns>
protected bool ValidateSignature(MethodInfo method, Type expectedReturnType, params Type[] expectedParamTypes)
{
if (method.ReturnType != expectedReturnType)
{
Error($"{MemberName}'s return type must be {expectedReturnType.Name}.");
return false;
}
var parameters = method.GetParameters();
if (parameters.Length != expectedParamTypes.Length)
{
Error($"{MemberName} must have exactly {expectedParamTypes.Length} parameter(s).");
return false;
}
for (var i = 0; i < expectedParamTypes.Length; i++)
{
if (parameters[i].ParameterType == expectedParamTypes[i])
continue;
Error($"{MemberName}'s parameter at index {i} must be {expectedParamTypes[i].Name}.");
return false;
}
return true;
}
/// <summary>
/// Validates that a list method matches the expected return type, base parameter types, and an optional integer index.
/// </summary>
/// <param name="method">The method to validate.</param>
/// <param name="expectedReturnType">The expected return type of the method.</param>
/// <param name="hasIndex">When the method returns, a flag that indicates if the method has an index parameter.</param>
/// <param name="expectedParamTypes">The expected types of the parameters of the method.</param>
/// <returns><c>true</c> if the method is valid; <c>false</c> otherwise.</returns>
protected bool ValidateListSignature(MethodInfo method, Type expectedReturnType, out bool hasIndex, params Type[] expectedParamTypes)
{
hasIndex = false;
if (method.ReturnType != expectedReturnType)
{
Error($"{MemberName}'s return type must be {expectedReturnType.Name}.");
return false;
}
var parameters = method.GetParameters();
if (parameters.Length < expectedParamTypes.Length || parameters.Length > expectedParamTypes.Length + 1)
{
Error($"{MemberName} must have {expectedParamTypes.Length} parameter(s), optionally with an extra trailing int parameter.");
return false;
}
for (var i = 0; i < expectedParamTypes.Length; i++)
{
if (parameters[i].ParameterType == expectedParamTypes[i])
continue;
Error($"{MemberName}'s parameter at index {i} must be {expectedParamTypes[i].Name}.");
return false;
}
if (parameters.Length == expectedParamTypes.Length + 1)
{
if (parameters[^1].ParameterType != typeof(int))
{
Error($"{MemberName}'s final parameter must be an int (the list index).");
return false;
}
hasIndex = true;
}
return true;
}
/// <summary>
/// Resolves the target <see cref="MemberInfo"/> (property, field or method) and its associated singleton instance getter, if applicable.
/// </summary>
/// <param name="group">The option group instance the property belongs to.</param>
/// <param name="property">The option property decorated with this attribute.</param>
/// <param name="type">When this method returns, contains the resolved <see cref="Type"/> expected to hold the target member.</param>
/// <param name="instanceGetter">
/// When this method returns, contains the <see cref="OptionGroupSingleton{T}.Instance"/> getter <see cref="MethodInfo"/>
/// if the resolved member is an instance member on an <see cref="AbstractOptionGroup"/>; otherwise, <see langword="null"/>.
/// </param>
/// <param name="notFound">When this method returns, contains a flag that indicates if the member was not found, as null can be returned from other circumstances too.</param>
/// <returns>The resolved <see cref="MemberInfo"/> if found; otherwise, <see langword="null"/>.</returns>
[SuppressMessage("Major Code Smell", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "It is safe.")]
protected MemberInfo? ResolveMember(AbstractOptionGroup group, PropertyInfo property, out Type type, out MethodInfo? instanceGetter, out bool notFound)
{
var groupType = group.GetType();
var flags = BindingFlags.Static | BindingFlags.Public;
MemberName ??= property.Name + defaultSuffix;
type = holderType ?? groupType;
instanceGetter = null;
if (type.IsAssignableTo(typeof(AbstractOptionGroup)))
{
flags |= BindingFlags.Instance;
if (type == groupType)
flags |= BindingFlags.NonPublic;
instanceGetter = typeof(OptionGroupSingleton<>)
.MakeGenericType(type)
.GetProperty(nameof(OptionGroupSingleton<>.Instance))!
.GetGetMethod();
}
else if (!type.IsStatic())
{
flags |= BindingFlags.Instance;
var canSearchPrivates = type.GetCustomAttribute<SearchPrivateAttribute>() != null;
if (canSearchPrivates)
flags |= BindingFlags.NonPublic;
var getterFlags = BindingFlags.Static | BindingFlags.Public | (canSearchPrivates ? BindingFlags.NonPublic : BindingFlags.Default);
foreach (var method in type.GetMethods(getterFlags))
{
if (method.GetParameters().Length > 0 || (method.GetCustomAttribute<InstanceGetterAttribute>() == null && method.Name != "GetInstance"))
continue;
instanceGetter = method;
break;
}
if (instanceGetter == null)
{
foreach (var prop in type.GetProperties(getterFlags))
{
if (prop.GetCustomAttribute<InstanceGetterAttribute>() == null && prop.Name != "Instance")
continue;
var getMethod = prop.GetGetMethod(canSearchPrivates);
if (getMethod == null)
continue;
instanceGetter = getMethod;
break;
}
}
if (instanceGetter == null)
{
Error($"No valid static instance getter (method GetInstance or property Instance) found in instanced type {type.Name}. Try renaming the method/property, or decorate it with InstanceGetterAttribute.");
notFound = false;
return null;
}
if (!instanceGetter.ReturnType.IsAssignableTo(type))
{
Error($"Found instance getter {instanceGetter.Name}, but the return type did not match what was expected ({type.Name}).");
notFound = false;
return null;
}
}
else if (type.GetCustomAttribute<SearchPrivateAttribute>() != null)
{
flags |= BindingFlags.NonPublic;
}
var member = type.GetMember(MemberName, flags).FirstOrDefault();
notFound = true;
if (member == null)
return null;
notFound = false;
if (instanceGetter == null)
return member;
bool isStatic;
if (member is FieldInfo field)
{
isStatic = field.IsStatic;
}
else
{
var method = (member as PropertyInfo)?.GetGetMethod(true) ?? member as MethodInfo;
isStatic = method is { IsStatic: true };
}
if (isStatic)
instanceGetter = null;
return member;
}
/// <summary>
/// Resolves the target <see cref="MethodInfo"/> and its associated singleton instance getter, if applicable.
/// </summary>
/// <param name="group">The option group instance the property belongs to.</param>
/// <param name="property">The option property decorated with this attribute.</param>
/// <param name="type">When this method returns, contains the resolved <see cref="Type"/> expected to hold the target method.</param>
/// <param name="instanceGetter">
/// When this method returns, contains the <see cref="OptionGroupSingleton{T}.Instance"/> getter <see cref="MethodInfo"/>
/// if the resolved method is an instance method on an <see cref="AbstractOptionGroup"/>; otherwise, <see langword="null"/>.
/// </param>
/// <param name="notFound">When this method returns, contains a flag that indicates if the member was not found, as null can be returned from other circumstances too.</param>
/// <returns>The resolved <see cref="MethodInfo"/> if found; otherwise, <see langword="null"/>.</returns>
protected MethodInfo? ResolveMethod(AbstractOptionGroup group, PropertyInfo property, out Type type, out MethodInfo? instanceGetter, out bool notFound)
{
return ResolveMember(group, property, out type, out instanceGetter, out notFound) as MethodInfo;
}
/// <summary>
/// Compiles a <see cref="DynamicMethod"/> using IL generation to invoke the resolved static or instance <paramref name="method"/>.
/// </summary>
/// <param name="ownerType">The <see cref="Type"/> that owns the generated <see cref="DynamicMethod"/> and holds the target method.</param>
/// <param name="method">The target <see cref="MethodInfo"/> to invoke.</param>
/// <param name="instanceGetter">
/// The static getter <see cref="MethodInfo"/> used to push the target instance onto the evaluation stack for instance methods,
/// or <see langword="null"/> if <paramref name="method"/> is static.
/// </param>
/// <param name="returnType">The return <see cref="Type"/> of the generated delegate (or <see cref="void"/> for actions).</param>
/// <param name="paramTypes">The parameter types accepted by the generated delegate.</param>
/// <param name="delegateType">The concrete delegate <see cref="Type"/> to create (e.g., <see cref="Func{T, TResult}"/> or <see cref="Action{T}"/>).</param>
/// <param name="suffix">A descriptive suffix appended to the generated <see cref="DynamicMethod"/> name for debugging and stack traces.</param>
/// <param name="forwardParameters">Whether to push the delegate parameters onto the stack before invoking <paramref name="method"/>.</param>
/// <param name="postProcessCall">An optional callback to emit additional IL instructions before returning.</param>
/// <returns>A compiled <see cref="Delegate"/> of type <paramref name="delegateType"/> bound to the generated IL method.</returns>
protected static Delegate CompileDynamicDelegate(
Type ownerType,
MethodInfo method,
MethodInfo? instanceGetter,
Type returnType,
Type[] paramTypes,
Type delegateType,
string suffix,
bool forwardParameters = true,
Action<ILGenerator>? postProcessCall = null)
{
if (postProcessCall == null && DelegateCache.TryGetValue(method, out var cachedDelegate))
return cachedDelegate;
var dm = new DynamicMethod($"{ownerType.Name}_{method.Name}_{suffix}", returnType, paramTypes, ownerType, true);
var il = dm.GetILGenerator();
if (!method.IsStatic && instanceGetter != null)
il.Emit(OpCodes.Call, instanceGetter);
if (forwardParameters)
{
for (byte i = 0; i < paramTypes.Length; i++)
{
var loadOp = i switch
{
0 => OpCodes.Ldarg_0,
1 => OpCodes.Ldarg_1,
2 => OpCodes.Ldarg_2,
3 => OpCodes.Ldarg_3,
_ => OpCodes.Ldarg_S,
};
if (loadOp == OpCodes.Ldarg_S)
il.Emit(loadOp, i);
else
il.Emit(loadOp);
}
}
var callOp = method.IsStatic ? OpCodes.Call : OpCodes.Callvirt;
il.Emit(callOp, method);
postProcessCall?.Invoke(il);
il.Emit(OpCodes.Ret);
var compiledDelegate = dm.CreateDelegate(delegateType);
if (postProcessCall == null)
DelegateCache[method] = compiledDelegate;
return compiledDelegate;
}
/// <summary>
/// Compiles a factory function that provides a <see cref="Delegate"/> for each index in an option list.
/// If <paramref name="hasIndexParameter"/> is <see langword="false"/> and <paramref name="postProcessListCall"/> is <see langword="null"/>,
/// a single <see cref="Delegate"/> is compiled once and reused for all indices.
/// </summary>
/// <param name="ownerType">The <see cref="Type"/> that owns the generated <see cref="DynamicMethod"/> and holds the target method.</param>
/// <param name="method">The target <see cref="MethodInfo"/> to invoke.</param>
/// <param name="instanceGetter">
/// The static getter <see cref="MethodInfo"/> used to push the target instance onto the evaluation stack for instance methods,
/// or <see langword="null"/> if <paramref name="method"/> is static.
/// </param>
/// <param name="returnType">The return <see cref="Type"/> of the generated delegate (or <see cref="void"/> for actions).</param>
/// <param name="baseParamTypes">The parameter types accepted by the generated delegate.</param>
/// <param name="delegateType">The concrete delegate <see cref="Type"/> to create.</param>
/// <param name="suffix">A descriptive suffix appended to the generated <see cref="DynamicMethod"/> name for debugging and stack traces.</param>
/// <param name="hasIndexParameter">Whether the target <paramref name="method"/> takes the list <see langword="int"/> index as its final parameter.</param>
/// <param name="postProcessCall">An optional index-independent callback to emit additional IL instructions after <paramref name="method"/> is called.</param>
/// <param name="postProcessListCall">An optional index-dependent callback to emit additional IL instructions after <paramref name="method"/> is called.</param>
/// <returns>A factory function that returns a compiled <see cref="Delegate"/> of type <paramref name="delegateType"/> for a given list index.</returns>
protected static Func<int, Delegate> CompileDynamicListDelegate(
Type ownerType,
MethodInfo method,
MethodInfo? instanceGetter,
Type returnType,
Type[] baseParamTypes,
Type delegateType,
string suffix,
bool hasIndexParameter,
Action<ILGenerator>? postProcessCall = null,
Action<ILGenerator>? postProcessListCall = null)
{
if (!hasIndexParameter && postProcessListCall is null)
{
var sharedDelegate = CompileDynamicDelegate(
ownerType,
method,
instanceGetter,
returnType,
baseParamTypes,
delegateType,
suffix,
baseParamTypes.Length > 0,
postProcessCall);
return _ => sharedDelegate;
}
var fullParamTypes = new Type[baseParamTypes.Length + 1];
fullParamTypes[0] = typeof(DelegateIndexClosure);
Array.Copy(baseParamTypes, 0, fullParamTypes, 1, baseParamTypes.Length);
var dm = new DynamicMethod($"{ownerType.Name}_{method.Name}_{suffix}_List", returnType, fullParamTypes, ownerType, true);
var il = dm.GetILGenerator();
if (!method.IsStatic && instanceGetter != null)
il.Emit(OpCodes.Call, instanceGetter);
for (var i = 0; i < baseParamTypes.Length; i++)
{
var argPos = (byte)(i + 1);
var loadOp = argPos switch
{
1 => OpCodes.Ldarg_1,
2 => OpCodes.Ldarg_2,
3 => OpCodes.Ldarg_3,
_ => OpCodes.Ldarg_S,
};
if (loadOp == OpCodes.Ldarg_S)
il.Emit(loadOp, argPos);
else
il.Emit(loadOp);
}
if (hasIndexParameter)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, IndexClosureField);
}
var callOp = method.IsStatic ? OpCodes.Call : OpCodes.Callvirt;
il.Emit(callOp, method);
postProcessCall?.Invoke(il);
postProcessListCall?.Invoke(il);
il.Emit(OpCodes.Ret);
return index => dm.CreateDelegate(delegateType, new DelegateIndexClosure(index));
}
}
@@ -0,0 +1,50 @@
using System;
using System.Reflection;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute to set the <see cref="IModdedOption.Setter"/> delegate in a <see cref="ModdedOptionAttribute"/> or <see cref="ModdedOptionListAttribute"/>.
/// </summary>
/// <param name="methodName">The method to get the setter from.</param>
/// <param name="holderType">The type the method is in.</param>
[AttributeUsage(AttributeTargets.Property)]
public sealed class ModdedOptionSetterAttribute(string? methodName = null, Type? holderType = null)
: ModdedOptionMemberAttribute(methodName, holderType, "Setter")
{
internal Delegate? GetSetter(AbstractOptionGroup group, PropertyInfo property, IModdedOption option)
{
if (ResolveMethod(group, property, out var type, out var instanceGetter, out var notFound) is not { } method)
{
if (notFound)
Error($"Method {MemberName} does not exist in {type.FullName}");
return null;
}
var valueType = option.GetValueType();
if (!ValidateSignature(method, valueType, valueType, valueType))
return null;
var delegateType = typeof(Func<,,>).MakeGenericType(valueType, valueType, valueType);
return CompileDynamicDelegate(type, method, instanceGetter, valueType, [valueType, valueType], delegateType, "Setter");
}
internal Func<int, Delegate?>? GetListSetter(AbstractOptionGroup group, PropertyInfo property, Type valueType)
{
if (ResolveMethod(group, property, out var type, out var instanceGetter, out var notFound) is not { } method)
{
if (notFound)
Error($"Method {MemberName} does not exist in {type.FullName}");
return null;
}
if (!ValidateListSignature(method, valueType, out var hasIndex, valueType, valueType))
return null;
var delegateType = typeof(Func<,,>).MakeGenericType(valueType, valueType, valueType);
return CompileDynamicListDelegate(type, method, instanceGetter, valueType, [valueType, valueType], delegateType, "ListSetter", hasIndex);
}
}
@@ -0,0 +1,257 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute to set the <see cref="IModdedOption.Visible"/> delegate in a <see cref="ModdedOptionAttribute"/> or <see cref="ModdedOptionListAttribute"/>.
/// </summary>
/// <param name="memberName">The member to get the visibility function from.</param>
/// <param name="holderType">The type the member is in.</param>
[AttributeUsage(AttributeTargets.Property)]
public sealed class ModdedOptionVisibilityAttribute(string? memberName = null, Type? holderType = null)
: ModdedOptionMemberAttribute(memberName, holderType, "Visibility")
{
private static readonly MethodInfo ModdedOptionBoolValueGetter = typeof(ModdedOption<bool>).GetProperty(nameof(ModdedOption<>.Value))!.GetGetMethod()!;
private static readonly MethodInfo ListBoolIndexerGetter = typeof(IList<bool>).GetProperty("Item")!.GetGetMethod()!;
internal Func<bool>? GetVisibility(AbstractOptionGroup group, PropertyInfo property)
{
if (ResolveMember(group, property, out Type type, out var instanceGetter, out var notFound) is not { } member)
{
if (notFound)
Error($"Member {MemberName} does not exist in {type.FullName}");
return null;
}
MethodInfo? targetMethod;
Action<ILGenerator>? postProcess = null;
if (member is PropertyInfo vProperty)
{
if (vProperty.PropertyType.IsAssignableTo(typeof(ModdedOption<bool>)))
{
postProcess = il => il.Emit(OpCodes.Callvirt, ModdedOptionBoolValueGetter);
}
else if (!vProperty.PropertyType.IsAssignableTo(typeof(bool)))
{
Error($"Property {MemberName} is not a bool or a bool ModdedOption.");
return null;
}
if (vProperty.GetIndexParameters().Length > 0)
{
Error($"Property {MemberName} cannot be an indexer.");
return null;
}
targetMethod = vProperty.GetGetMethod(true);
if (targetMethod is null)
{
Error($"Property {MemberName} does not have a getter.");
return null;
}
}
else if (member is MethodInfo vMethod)
{
if (vMethod.ReturnType != typeof(bool))
{
Error($"Method {MemberName} does not return a bool.");
return null;
}
if (vMethod.GetParameters().Length > 0)
{
Error($"Method {MemberName} has too many parameters.");
return null;
}
targetMethod = vMethod;
}
else if (member is FieldInfo field)
{
if (field.FieldType != typeof(bool))
{
Error($"Field {MemberName} is not a bool.");
return null;
}
var dynamicMethod = new DynamicMethod($"GetVisibility_{type.Name}_{field.Name}", typeof(bool), Type.EmptyTypes, type, true);
var il = dynamicMethod.GetILGenerator();
if (instanceGetter != null)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, instanceGetter);
il.Emit(OpCodes.Ldfld, field);
}
else
{
il.Emit(OpCodes.Ldsfld, field);
}
il.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate<Func<bool>>();
}
else
{
Error($"Member {MemberName} of {type.FullName} is not valid for Visible function.");
return null;
}
return (Func<bool>)CompileDynamicDelegate(type, targetMethod, instanceGetter, typeof(bool), Type.EmptyTypes, typeof(Func<bool>), "Visibility", false, postProcess);
}
internal Func<int, Delegate?>? GetListVisibility(AbstractOptionGroup group, PropertyInfo property)
{
if (ResolveMember(group, property, out Type type, out var instanceGetter, out var notFound) is not { } member)
{
if (notFound)
Error($"Member {MemberName} does not exist in {type.FullName}");
return null;
}
MethodInfo? targetMethod;
Action<ILGenerator>? postProcess = null;
Action<ILGenerator>? postProcessList = null;
var hasIndexParam = false;
if (member is PropertyInfo vProperty)
{
var isListBool = false;
if (vProperty.PropertyType.IsAssignableTo(typeof(IList<bool>)))
{
isListBool = true;
postProcessList = il =>
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, IndexClosureField);
il.Emit(OpCodes.Callvirt, ListBoolIndexerGetter);
};
}
else if (vProperty.PropertyType.IsAssignableTo(typeof(ModdedOption<bool>)))
{
postProcess = il => il.Emit(OpCodes.Callvirt, ModdedOptionBoolValueGetter);
}
else if (!vProperty.PropertyType.IsAssignableTo(typeof(bool)))
{
Error($"Property {MemberName} is not a bool value or indexer, a list of bools, or a bool ModdedOption.");
return null;
}
var indexParams = vProperty.GetIndexParameters();
if (indexParams.Length > 1)
{
Error($"Indexer {MemberName} has too many parameters.");
return null;
}
if (isListBool && indexParams.Length != 0)
{
Error($"Property {MemberName} cannot be an indexer of lists of bools.");
return null;
}
if (indexParams.Length == 1)
{
if (indexParams[0].ParameterType != typeof(int))
{
Error($"Indexer {MemberName}'s parameter is not an int.");
return null;
}
hasIndexParam = true;
}
targetMethod = vProperty.GetGetMethod(true);
if (targetMethod is null)
{
Error($"Property {MemberName} does not have a getter.");
return null;
}
}
else if (member is MethodInfo vMethod)
{
if (vMethod.ReturnType != typeof(bool))
{
Error($"Method {MemberName} does not return a bool.");
return null;
}
var paramList = vMethod.GetParameters();
if (paramList.Length > 1)
{
Error($"Method {MemberName} has too many parameters.");
return null;
}
if (paramList.Length == 1)
{
if (paramList[0].ParameterType != typeof(int))
{
Error($"Method {MemberName}'s parameter is not an int.");
return null;
}
hasIndexParam = true;
}
targetMethod = vMethod;
}
else if (member is FieldInfo field)
{
if (field.FieldType.IsAssignableTo(typeof(IList<bool>)))
{
postProcess = il =>
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, ListBoolIndexerGetter);
};
}
else if (field.FieldType != typeof(bool))
{
Error($"Field {MemberName} is not a bool or a list of bools.");
return null;
}
var dynamicMethod = new DynamicMethod($"GetListVisibility_{type.Name}_{field.Name}", typeof(bool), [typeof(int)], type, true);
var il = dynamicMethod.GetILGenerator();
if (instanceGetter != null)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, instanceGetter);
il.Emit(OpCodes.Ldfld, field);
}
else
{
il.Emit(OpCodes.Ldsfld, field);
}
postProcess?.Invoke(il);
il.Emit(OpCodes.Ret);
var func = dynamicMethod.CreateDelegate<Func<int, bool>>();
return index => () => func(index);
}
else
{
Error($"Member {MemberName} of {type.FullName} is not valid for Visibility function.");
return null;
}
return CompileDynamicListDelegate(type, targetMethod, instanceGetter, typeof(bool), Type.EmptyTypes, typeof(Func<bool>), "ListVisibility", hasIndexParam, postProcess, postProcessList);
}
}
@@ -0,0 +1,15 @@
using System;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// An attribute used to mark a method or property as one that returns an instance of the class it's declared in.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
public sealed class InstanceGetterAttribute : Attribute;
/// <summary>
/// An attribute used to mark a class as one whose reflection search should include private members.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class SearchPrivateAttribute : Attribute;
@@ -1,20 +1,22 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for creating a <see cref="ModdedEnumOption"/>.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
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.Translate(), (int)(value ?? 0), enumType, values);
var opt = new ModdedEnumOption(Title, (int)(value ?? 0), enumType, values);
return opt;
}
@@ -30,6 +32,39 @@ public class ModdedEnumOptionAttribute(string title, Type enumType, string[]? va
{
return HolderOption is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType ${enumType.FullName} is not a ModdedEnumOption");
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
}
}
/// <summary>
/// Attribute for creating an enum option.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <param name="title">The title of the option.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionAttribute<T>(string title, string[]? values = null)
: ModdedOptionAttribute(title)
where T : struct, Enum
{
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var opt = new ModdedEnumOption<T>(Title, (T)(value ?? 0), values);
return opt;
}
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedEnumOption<T>;
opt?.SetValue((T)value);
}
/// <inheritdoc />
public override object GetValue()
{
return HolderOption is ModdedEnumOption<T> opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{Title}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).Name}>");
}
}
@@ -1,7 +1,6 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.Attributes;
@@ -9,44 +8,97 @@ namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for a <see cref="ModdedNumberOption"/>.
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="zeroBehavior">Determines what is shown for zero.</param>
/// <param name="negativeBehavior">Determines what is shown for negative 1.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="halfIncrements">Whether increments can be split in half (using Shift).</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedNumberOptionAttribute(
string title,
float min,
float max,
float increment = 1,
float increment,
string zeroBehavior,
string negativeBehavior,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false)
bool halfIncrements = false)
: ModdedOptionAttribute(title)
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionAttribute"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
public ModdedNumberOptionAttribute(
string title,
float min,
float max,
float increment = 1,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false)
: this(title, min, max, increment, zeroInfinity ? "∞" : "#", "#", suffixType, formatString, increment == 1f)
{
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var final = value switch
{
null => min + increment,
int integer => integer,
_ => (float)value,
};
return new ModdedNumberOption(
Title.Translate(),
(float)(value ?? min + increment),
Title,
final,
min,
max,
increment,
zeroBehavior,
negativeBehavior,
suffixType,
formatString,
zeroInfinity);
halfIncrements);
}
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedNumberOption;
opt?.SetValue((float)value);
if (HolderOption is not ModdedNumberOption opt)
return;
var final = value switch
{
int integer => integer,
_ => (float)value,
};
opt.SetValue(final);
}
/// <inheritdoc />
public override object GetValue()
{
if (HolderOption is ModdedNumberOption opt)
{
return opt.Value;
}
throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedNumberOption");
if (HolderOption is not ModdedNumberOption opt)
throw new InvalidOperationException($"HolderOption for option \"{Title}\" is not a ModdedNumberOption");
var value = opt.Value;
if (ValueType == typeof(int))
return (int)Math.Round(value);
return value;
}
}
@@ -10,14 +10,15 @@ namespace MiraAPI.GameOptions.Attributes;
/// <param name="roleType">Optional parameter to specify a role Type.</param>
/// <param name="modeType">Optional parameter to specify a game mode Type.</param>
[AttributeUsage(AttributeTargets.Property)]
public abstract class ModdedOptionAttribute(string title, Type? roleType = null, Type? modeType = null) : Attribute
public abstract class ModdedOptionAttribute(string title, Type? roleType = null, Type? modeType = null) : PropertyOptionAttribute
{
internal IModdedOption? HolderOption { get; set; }
internal Type ValueType { get; set; }
/// <summary>
/// Gets the title of the option.
/// </summary>
public string Title { get; private set; } = title;
public string Title => title;
/// <summary>
/// Gets the role type of the option.
@@ -29,17 +30,5 @@ public abstract class ModdedOptionAttribute(string title, Type? roleType = null,
/// </summary>
protected Type? ModeType { get; private set; } = modeType;
/// <summary>
/// Sets the value of the option.
/// </summary>
/// <param name="value">The new value as an <see langword="object"/>.</param>
public abstract void SetValue(object value);
/// <summary>
/// Gets the value of the option.
/// </summary>
/// <returns>The value of the option as an <see langword="object"/>.</returns>
public abstract object GetValue();
internal abstract IModdedOption? CreateOption(object? value, PropertyInfo property);
}
@@ -0,0 +1,49 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for a <see cref="ModdedPlayerOption"/>.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value will return -1.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedPlayerOptionAttribute(
string title,
bool allowNone = true)
: ModdedOptionAttribute(title)
{
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
{
var option = new ModdedPlayerOption(Title, allowNone);
return option;
}
/// <inheritdoc />
public override object GetValue()
{
if (HolderOption is not ModdedPlayerOption opt)
throw new InvalidOperationException($"Holder option for {Title} is not a ModdedPlayerOption.");
if (ValueType == typeof(int))
return opt.Value;
return opt.SelectedPlayer!;
}
/// <inheritdoc />
public override void SetValue(object value)
{
if (HolderOption is not ModdedPlayerOption opt)
return;
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
_ => (int)value,
};
opt?.SetValue(final);
}
}
@@ -0,0 +1,38 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for a <see cref="ModdedStringOption"/>.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="values">An option list of string value.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedStringOptionAttribute(
string title,
string[] values)
: ModdedOptionAttribute(title)
{
internal override IModdedOption? CreateOption(object? value, PropertyInfo property)
{
var option = new ModdedStringOption(Title, (string)(value ?? string.Empty), values);
return option;
}
/// <inheritdoc />
public override object GetValue()
{
return HolderOption is ModdedStringOption opt
? opt.Value
: throw new InvalidOperationException($"Holder option for {Title} is not a ModdedStringOption.");
}
/// <inheritdoc />
public override void SetValue(object value)
{
var opt = HolderOption as ModdedStringOption;
opt?.SetValue((string)value);
}
}
@@ -1,7 +1,6 @@
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
@@ -9,12 +8,27 @@ namespace MiraAPI.GameOptions.Attributes;
/// Attribute for a <see cref="ModdedToggleOption"/>.
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="on">What the option displays when toggled on.</param>
/// <param name="off">What the option displays when toggled off.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedToggleOptionAttribute(string title) : ModdedOptionAttribute(title)
public class ModdedToggleOptionAttribute(
string title,
string on,
string off)
: ModdedOptionAttribute(title)
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionAttribute"/> class.
/// </summary>
/// <param name="title">The option title.</param>
public ModdedToggleOptionAttribute(string title)
: this(title, "On", "Off")
{
}
internal override IModdedOption CreateOption(object? value, PropertyInfo property)
{
var toggleOpt = new ModdedToggleOption(Title.Translate(), (bool)(value ?? false));
var toggleOpt = new ModdedToggleOption(Title, (bool)(value ?? false), on, off);
return toggleOpt;
}
@@ -28,10 +42,8 @@ public class ModdedToggleOptionAttribute(string title) : ModdedOptionAttribute(t
/// <inheritdoc />
public override object GetValue()
{
if (HolderOption is ModdedToggleOption opt)
{
return opt.Value;
}
throw new InvalidOperationException($"Holder option for {Title} is not a ModdedToggleOption.");
return HolderOption is ModdedToggleOption opt
? opt.Value
: throw new InvalidOperationException($"Holder option for {Title} is not a ModdedToggleOption.");
}
}
@@ -0,0 +1,73 @@
using System;
using System.Collections;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for creating a list of enum options.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="enumType">The <see cref="Enum"/> type.</param>
/// <param name="values">An option list of string values to use in place of the <see langword="enum"/> name.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionListAttribute(string title, Type enumType, string[]? values = null)
: ModdedOptionListAttribute(title)
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
var optList = new ModdedOptionList<ModdedEnumOption>(
value.Count, idx => new(GetFormattedTitle(idx), (int)(value[idx] ?? 0), enumType, values));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedEnumOption;
opt?.SetValue((int)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedEnumOption opt
? Enum.ToObject(enumType, opt.Value)
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {enumType.FullName} is not a ModdedEnumOption");
}
}
/// <summary>
/// Attribute for creating a list of enum options.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <param name="title">The option's title.</param>
/// <param name="values">The option's possible values.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedEnumOptionListAttribute<T>(string title, string[]? values = null)
: ModdedOptionListAttribute(title)
where T : struct, Enum
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
var optList = new ModdedOptionList<ModdedEnumOption<T>>(
value.Count, idx => new(GetFormattedTitle(idx), (T)(value[idx] ?? 0), values));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedEnumOption<T>;
opt?.SetValue((T)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedEnumOption<T> opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" with EnumType {typeof(T).FullName} is not a ModdedEnumOption<{typeof(T).FullName}>");
}
}
@@ -0,0 +1,108 @@
using System;
using System.Collections;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for creating a list of number options.
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="zeroBehavior">Determines what is shown for zero.</param>
/// <param name="negativeBehavior">Determines what is shown for negative 1.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
/// <param name="halfIncrements">Whether increments can be split in half (using Shift).</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedNumberOptionListAttribute(
string title,
float min,
float max,
float increment,
string zeroBehavior,
string negativeBehavior,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool halfIncrements = false)
: ModdedOptionListAttribute(title)
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedNumberOptionListAttribute"/> class.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <param name="increment">The increment.</param>
/// <param name="suffixType">The suffix type.</param>
/// <param name="zeroInfinity">Whether zero is infinity or not.</param>
/// <param name="formatString">Optional format string for the option screen.</param>
public ModdedNumberOptionListAttribute(
string title,
float min,
float max,
float increment = 1,
MiraNumberSuffixes suffixType = MiraNumberSuffixes.None,
string? formatString = null,
bool zeroInfinity = false)
: this(title, min, max, increment, zeroInfinity ? "∞" : "#", "#", suffixType, formatString, increment == 1f)
{
}
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
return new ModdedOptionList<ModdedNumberOption>(value.Count, idx =>
{
var final = value[idx] switch
{
null => min + increment,
int integer => integer,
_ => (float)value[idx]!,
};
return new(
GetFormattedTitle(idx),
final,
min,
max,
increment,
zeroBehavior,
negativeBehavior,
suffixType,
formatString,
halfIncrements);
});
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
if (HolderOptionList?[idx] is not ModdedNumberOption opt)
return;
var final = value switch
{
int integer => integer,
_ => (float)value,
};
opt.SetValue(final);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
if (HolderOptionList?[idx] is not ModdedNumberOption opt)
throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedNumberOption");
var value = opt.Value;
if (ValueType == typeof(int))
return (int)Math.Round(value);
return value;
}
}
@@ -0,0 +1,96 @@
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.RegularExpressions;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Represents an attribute that is used to define a list of modded options.
/// </summary>
/// <param name="title">The title of the options.</param>
[AttributeUsage(AttributeTargets.Property)]
public abstract class ModdedOptionListAttribute(string title) : PropertyOptionAttribute
{
internal IModdedOptionList? HolderOptionList { get; set; }
internal IList? Value { get; set; }
internal Type ValueType { get; set; }
/// <summary>
/// Gets the title of the options.
/// If the string contains a format parameter, e.g., <c>{0}</c>, then the option's index will be given to it.
/// The string cannot contain more than one parameter.
/// If no parameter is given, the title will simply append the index to the end of it.
/// </summary>
public string Title => title;
/// <summary>
/// Sets the value of all the options.
/// </summary>
/// <param name="value">The new values as an object.</param>
public override void SetValue(object value)
{
Value = (IList)value;
if (Value.Count != HolderOptionList!.Count)
{
throw new InvalidOperationException($"Value set to option list cannot change the list's length.");
}
for (int i = 0; i < Value.Count; i++)
{
SetValue(i, Value[i]!);
}
}
/// <summary>
/// Sets the value of the specific option.
/// </summary>
/// <param name="idx">The option to set.</param>
/// <param name="value">The new value as an object.</param>
public abstract void SetValue(int idx, object value);
/// <summary>
/// Gets the value of all the options.
/// </summary>
/// <returns>The value of the options as an object.</returns>
public override object GetValue()
{
return Value!;
}
/// <summary>
/// Gets the value of the specific option.
/// </summary>
/// <param name="idx">The option to set.</param>
/// <returns>The value of the option as an object.</returns>
public abstract object GetValue(int idx);
internal abstract IModdedOptionList? CreateOptionList(IList value, PropertyInfo property);
/// <summary>
/// Gets the <see cref="Title"/> formatted with the option's index.
/// </summary>
/// <param name="index">The option's index.</param>
/// <returns>The formatted option's title.</returns>
[SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "I don't even know if this is worth it.")]
protected string GetFormattedTitle(int index)
{
var match = Regex.Match(Title.Translate(), @"\{(\d+)(?::[^}]+)?\}", default, Regex.InfiniteMatchTimeout);
if (!match.Success)
{
return Title + index;
}
if (match.Value == "{0}" && !match.NextMatch().Success)
{
return string.Format(Title, index);
}
Error($"ModdedOptionList Title of {Title} cannot contain more than the first parameter for formatting.");
return Title + index;
}
}
@@ -0,0 +1,52 @@
using System;
using System.Collections;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for creating a list of player options.
/// </summary>
/// <param name="title">The option title.</param>
/// <param name="allowNone">Whether the option includes a none option. If None is selected, value will return -1.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedPlayerOptionListAttribute(
string title,
bool allowNone = true)
: ModdedOptionListAttribute(title)
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
return new ModdedOptionList<ModdedPlayerOption>(value.Count, idx =>
{
return new(GetFormattedTitle(idx), allowNone);
});
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
if (HolderOptionList?[idx] is not ModdedPlayerOption opt)
return;
var final = value switch
{
NetworkedPlayerInfo info => info ? opt.Values.IndexOf(info) : (allowNone ? -1 : 0),
_ => (int)value,
};
opt?.SetValue(final);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
if (HolderOptionList?[idx] is not ModdedPlayerOption opt)
throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedPlayerOption");
if (ValueType == typeof(int))
return opt.Value;
return opt.SelectedPlayer!;
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Translation;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for creating a list of string options.
/// </summary>
/// <param name="title">The title of the option.</param>
/// <param name="values">An option list of string value.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedStringOptionListAttribute(
string title,
string[] values)
: ModdedOptionListAttribute(title)
{
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
return new ModdedOptionList<ModdedStringOption>(value.Count, idx =>
{
return new ModdedStringOption(Title.Translate(), (string)(value[idx] ?? string.Empty), values);
});
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedStringOption;
opt?.SetValue((string)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedStringOption opt
? opt.Value
: throw new InvalidOperationException($"HolderOption for option \"{GetFormattedTitle(idx)}\" is not a ModdedStringOption");
}
}
@@ -0,0 +1,51 @@
using System;
using System.Collections;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Attribute for a list of toggle options.
/// </summary>
/// <param name="title">The option's title.</param>
/// <param name="on">What the option displays when toggled on.</param>
/// <param name="off">What the option displays when toggled off.</param>
[AttributeUsage(AttributeTargets.Property)]
public class ModdedToggleOptionListAttribute(
string title,
string on,
string off)
: ModdedOptionListAttribute(title)
{
/// <summary>
/// Initializes a new instance of the <see cref="ModdedToggleOptionListAttribute"/> class.
/// </summary>
/// <param name="title">The option's title.</param>
public ModdedToggleOptionListAttribute(string title)
: this(title, "On", "Off")
{
}
internal override IModdedOptionList CreateOptionList(IList value, PropertyInfo property)
{
var optList = new ModdedOptionList<ModdedToggleOption>(
value.Count, idx => new(GetFormattedTitle(idx), (bool)(value[idx] ?? false), on, off));
return optList;
}
/// <inheritdoc />
public override void SetValue(int idx, object value)
{
var opt = HolderOptionList?[idx] as ModdedToggleOption;
opt?.SetValue((bool)value);
}
/// <inheritdoc />
public override object GetValue(int idx)
{
return HolderOptionList?[idx] is ModdedToggleOption opt
? opt.Value
: throw new InvalidOperationException($"Holder option for {GetFormattedTitle(idx)} is not a ModdedToggleOption.");
}
}
@@ -0,0 +1,22 @@
using System;
namespace MiraAPI.GameOptions.Attributes;
/// <summary>
/// Represents an attribute that is used to intercept a property's getter and setter.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public abstract class PropertyOptionAttribute : Attribute
{
/// <summary>
/// Sets the value of the option.
/// </summary>
/// <param name="value">The new value as an object.</param>
public abstract void SetValue(object value);
/// <summary>
/// Gets the value of the option.
/// </summary>
/// <returns>The value of the option as an object.</returns>
public abstract object GetValue();
}
+8
View File
@@ -0,0 +1,8 @@
namespace System.Runtime.CompilerServices;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
internal sealed class CollectionBuilderAttribute(Type builderType, string methodName) : Attribute
{
public Type BuilderType { get; } = builderType;
public string MethodName { get; } = methodName;
}
+49
View File
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
@@ -56,6 +57,21 @@ public interface IModdedOption
/// </summary>
Func<bool> Visible { get; set; }
/// <summary>
/// Gets or sets a getter event for the option, allowing for dynamic values based on external circumstances.
/// </summary>
Delegate? Getter { get; set; }
/// <summary>
/// Gets or sets a setter event for the option, allowing for dynamic value changes based on external circumstances.
/// </summary>
Delegate? Setter { get; set; }
/// <summary>
/// Gets or sets the event that is invoked when the value of the option changes.
/// </summary>
Delegate? ChangedEvent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the option should be included with presets.
/// </summary>
@@ -113,4 +129,37 @@ public interface IModdedOption
/// </summary>
/// <param name="presetConfig">The <see cref="ConfigFile"/> representing the preset configuration.</param>
void LoadFromPreset(ConfigFile presetConfig);
/// <summary>
/// Gets the type of the value that the option represents.
/// </summary>
/// <returns>The type of the option value.</returns>
Type GetValueType();
}
/// <summary>
/// Interface for list of modded options.
/// </summary>
public interface IModdedOptionList : IReadOnlyList<IModdedOption>
{
/// <summary>
/// Gets the function to name the keys of the individual options in the configuration file.
/// <para/>
/// Return <see langword="null"/> to use the default of the property's name with its index appended.
/// </summary>
Func<int, string>? ConfigName { get; init; }
}
/// <summary>
/// Interface for list of <typeparamref name="T"/> options.
/// </summary>
/// <typeparam name="T">The type of <see cref="IModdedOption"/>.</typeparam>
public interface IModdedOptionList<out T> : IModdedOptionList
where T : IModdedOption
{
/// <inheritdoc cref="IReadOnlyList{T}.this[int]"/>
new T this[int index] { get; }
/// <inheritdoc cref="IEnumerable{T}.GetEnumerator"/>
new IEnumerator<T> GetEnumerator();
}
Loaded 100 of 354 files, more files were not shown because too many files have changed in this diff. Show more