Compare commits

..
Author SHA1 Message Date
XtraCube 2a3c8feeab fix erorr 2024-09-24 20:50:03 -04:00
ang-xd 833585f15f Make modifier text disappear meetings 2024-09-24 20:36:41 -04:00
XtraCube 66b4976619 mira host option thingy 2024-09-24 09:52:27 -04:00
XtraCube 9c0b874e34 Merge branch 'dev' into feat-addressables
# Conflicts:
#	MiraAPI/Roles/ICustomRole.cs
2024-09-23 16:22:01 -04:00
XtraCube bc756d5c1b real fix for vent 2024-09-23 16:17:58 -04:00
XtraCube bbe7cd5a91 adjust 2024-09-23 16:05:25 -04:00
XtraCube 538ad48d18 modifier didwins 2024-09-23 16:05:24 -04:00
XtraCube 53baac167c custom player menu in mira 2024-09-23 16:05:24 -04:00
XtraCube 167566dc9b fix rpc custom murder 2024-09-23 16:05:23 -04:00
XtraCube 2df1eaa7c0 fix role defaults 2024-09-23 16:05:23 -04:00
XtraCube dd7f643153 only use custom murder 2024-09-23 16:05:23 -04:00
XtraCube 13dd0f4874 fix custom buttons 2024-09-23 16:05:22 -04:00
XtraCube 715d235bdc adjustment to role setting menu 2024-09-23 16:05:22 -04:00
XtraCube 25590242bc fix patch error 2024-09-23 16:05:22 -04:00
XtraCube 49489ff0d1 improvements to custom role (added SetChance and SetCount, improved GetChance and GetCount) 2024-09-23 16:05:21 -04:00
XtraCube aa2350bedf potentially fix mira vent bug 2024-09-23 15:59:42 -04:00
XtraCube ce0662f772 adjust 2024-09-23 06:52:23 -04:00
XtraCube c928eae183 modifier didwins 2024-09-22 20:38:41 -04:00
XtraCube 68afe58678 custom player menu in mira 2024-09-22 10:52:48 -04:00
XtraCube e3b2477cb8 fix rpc custom murder 2024-09-21 19:35:05 -04:00
XtraCube 2b568f933b fix role defaults 2024-09-21 16:20:28 -04:00
XtraCube a0701d582f only use custom murder 2024-09-19 23:19:49 -04:00
XtraCube c42782b157 fix custom buttons 2024-09-19 22:38:55 -04:00
XtraCube f932c4f3ff adjustment to role setting menu 2024-09-19 20:56:28 -04:00
XtraCube 2666aa171d fix patch error 2024-09-19 06:42:47 -04:00
XtraCube 9f99f6abb5 improvements to custom role (added SetChance and SetCount, improved GetChance and GetCount) 2024-09-19 06:40:51 -04:00
XtraCube aa53af112b Merge branch 'dev' into feat-addressables 2024-09-17 20:51:21 -04:00
XtraCube ff2f44fd64 code style stuff and merge 2024-09-17 20:49:15 -04:00
XtraCube d64972a574 Merge branch 'dev' into feat-addressables
# Conflicts:
#	MiraAPI.Example/ExamplePlugin.cs
#	MiraAPI/MiraAPI.csproj
#	MiraAPI/PluginLoading/MiraPluginInfo.cs
#	MiraAPI/PluginLoading/MiraPluginManager.cs
2024-09-17 20:00:09 -04:00
ang-xd 52daf69dfe Fix config disappearing issue 2024-09-17 19:40:14 -04:00
XtraCube 95f78addee oops 2024-09-17 12:33:38 -04:00
XtraCube 12d947748c make plugin manager publicly accessible 2024-09-17 12:31:30 -04:00
XtraCube be28948e7e allow access to plugin information externally 2024-09-17 12:26:01 -04:00
XtraCube d0161ba85c bump version 2024-09-16 16:01:20 -04:00
XtraCube 2411ac28a4 Merge branch 'new-role-configs' into dev 2024-09-16 16:00:59 -04:00
XtraCube 1bc0950acc adjust code 2024-09-14 23:22:19 -04:00
XtraCube 3aecd5a91c fix bug with setting uses of button 2024-09-14 23:22:12 -04:00
XtraCube 836823c477 Merge branch 'master' into dev 2024-09-14 22:56:24 -04:00
XtraCube c24404620b fix bug with modifiers and hud 2024-09-14 19:29:24 -04:00
XtraCube 7471a43d39 fix white button flashing issue 2024-09-14 19:29:14 -04:00
ang-xd dd6d57343e Role singleton 2024-09-14 15:47:02 -04:00
ang-xd fd75c99850 New role options 2024-09-14 14:42:20 -04:00
ang-xd 6e3de08043 New role configs system 2024-09-14 12:55:34 -04:00
MyDragonBreath bb45bab198 Some cleanup 2024-09-14 18:50:34 +10:00
XtraCube 1fa30485b0 bump version 2024-09-13 22:10:45 -04:00
XtraCube faed84d0f6 fix issue with example mod 2024-09-13 22:00:45 -04:00
XtraCube 2f7b0692f3 fix error in Polus Outside tasks in TaskAdder 2024-09-13 21:57:03 -04:00
XtraCube 8123381e1e add some more utility methods to timed modifier 2024-09-13 20:43:45 -04:00
XtraCube 4d36c13c5b use .Instance instead of DestroyableSingleton<>.Instance 2024-09-13 20:35:35 -04:00
XtraCube 91b7901528 generic type thingy :) 2024-09-13 20:33:50 -04:00
XtraCube 9a27a0c3d8 slight modification to caching modifier componenets 2024-09-13 20:24:38 -04:00
XtraCube cda441ee56 vent patch improvements 2024-09-13 20:03:46 -04:00
XtraCube 6ee83f8c7d better canvent stuff 2024-09-13 19:52:55 -04:00
XtraCube 8712a2b4e7 add predicate for selecting players in GetClosestPlayer extension method 2024-09-13 19:45:57 -04:00
MyDragonBreath 1eb13d0513 Base Addressables 2024-09-12 23:26:57 +10:00
XtraCube 30d2edfd9c Merge branch 'master' into dev 2024-09-10 09:46:44 -04:00
XtraCube 76cb2a6a59 adjustment to vent patches 2024-09-08 21:52:03 -04:00
XtraCube f20e7459a4 fix issue with hiding/showing options 2024-09-08 12:25:19 -04:00
XtraCube f462a116d7 fix contactfilter thingy 2024-09-08 12:06:01 -04:00
XtraCube 6f771821c8 update nearestobjectsoftype to specify layermask/contactfilter 2024-09-08 12:03:00 -04:00
XtraCube 754b8ef684 Merge branch 'refs/heads/master' into dev 2024-09-07 18:49:37 -04:00
XtraCube d8eb671b49 add pixels per unit to LoadableResourceAsset.cs 2024-09-07 18:46:32 -04:00
XtraCube 24ebee2743 make timers run on all players 2024-09-07 17:13:24 -04:00
XtraCube 878cf15a20 fix timed modifier auto removing if AutoStart is false 2024-09-07 16:47:52 -04:00
XtraCube 2f7cf4d664 fix double deactivation of modifiers when using ClearModifiers 2024-09-07 16:12:20 -04:00
XtraCube 4fcfb2a9ee fix LobbyViewPanePatches.cs AGAIN 2024-09-07 10:38:37 -04:00
83 changed files with 1879 additions and 419 deletions

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<VersionPrefix>0.1.6</VersionPrefix>
<VersionPrefix>0.1.9</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Authors>All Of Us, XtraCube, Angxl</Authors>
+1 -1
View File
@@ -21,7 +21,7 @@ public class MeetingButton : CustomActionButton
public override bool Enabled(RoleBehaviour? role)
{
return PlayerControl.LocalPlayer.HasModifier<CaptainModifier>();
return PlayerControl.LocalPlayer != null && PlayerControl.LocalPlayer.HasModifier<CaptainModifier>();
}
protected override void OnClick()
@@ -1,10 +1,10 @@
using MiraAPI.Example.Options.Roles;
using System.Collections;
using MiraAPI.Example.Options.Roles;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.Hud;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using System.Collections;
using UnityEngine;
namespace MiraAPI.Example.Buttons.Teleporter;
@@ -40,7 +40,10 @@ public class TeleportButton : CustomActionButton
{
base.FixedUpdate(playerControl);
if (!EffectActive) return;
if (!EffectActive)
{
return;
}
if (Input.GetKey(KeyCode.Mouse0))
{
@@ -0,0 +1,17 @@
using System.Collections.Generic;
using MiraAPI.Cosmetics;
namespace MiraAPI.Example.Cosmetics;
public class ExampleCosmeticGroup : AbstractCosmeticsGroup
{
public override string GroupName => "Example";
[RegisterCustomCosmetic()]
public List<HatData> hats { get; set; } = new();
[RegisterCustomCosmetic()]
public List<NamePlateData> namePlates { get; set;} = new();
[RegisterCustomCosmetic()]
public List<SkinData> skins { get; set; } = new();
[RegisterCustomCosmetic()]
public List<VisorData> visors { get; set; } = new();
}
+11
View File
@@ -2,7 +2,11 @@
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Example.Cosmetics;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using MiraAPI.Utilities.Assets.Addressable;
using Reactor;
using Reactor.Networking;
using Reactor.Networking.Attributes;
@@ -22,5 +26,12 @@ public partial class ExamplePlugin : BasePlugin, IMiraPlugin
public override void Load()
{
Harmony.PatchAll();
AddComponent<MiraDebugWindow>();
new Catalog("Output".ToLocalPath()).LoadCatalog();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.hats = new LoadableAddressableGroupAsset<HatData>(CatalogTools.GetResourceLocation("hatdata")).LoadAsset();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.namePlates = new LoadableAddressableGroupAsset<NamePlateData>(CatalogTools.GetResourceLocation("nameplatedata")).LoadAsset();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.skins = new LoadableAddressableGroupAsset<SkinData>(CatalogTools.GetResourceLocation("skindata")).LoadAsset();
CosmeticGroupSingleton<ExampleCosmeticGroup>.Instance.visors = new LoadableAddressableGroupAsset<VisorData>(CatalogTools.GetResourceLocation("visordata")).LoadAsset();
}
}
@@ -1,7 +1,7 @@
using MiraAPI.Example.Roles;
using System;
using MiraAPI.Example.Roles;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using System;
using MiraAPI.Utilities;
namespace MiraAPI.Example.Options.Roles;
+9 -8
View File
@@ -1,6 +1,4 @@
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using TMPro;
using UnityEngine;
namespace MiraAPI.Example.Roles;
@@ -13,15 +11,18 @@ public class ChameloenRole : CrewmateRole, ICustomRole
public string RoleDescription => RoleLongDescription;
public Color RoleColor => Palette.AcceptedGreen;
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
public LoadableAsset<Sprite> OptionsScreenshot => ExampleAssets.Banner;
public int MaxPlayers => 2;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
OptionsScreenshot = ExampleAssets.Banner,
};
public void PlayerControlFixedUpdate(PlayerControl playerControl)
{
if (playerControl.MyPhysics.Velocity.magnitude > 0)
{
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
TextMeshPro tmp = playerControl.cosmetics.nameText;
var rend = playerControl.cosmetics.currentBodySprite.BodySprite;
var tmp = playerControl.cosmetics.nameText;
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, 1), Time.deltaTime * 4f);
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, 1), Time.deltaTime * 4f);
@@ -32,8 +33,8 @@ public class ChameloenRole : CrewmateRole, ICustomRole
}
else
{
SpriteRenderer rend = playerControl.cosmetics.currentBodySprite.BodySprite;
TextMeshPro tmp = playerControl.cosmetics.nameText;
var rend = playerControl.cosmetics.currentBodySprite.BodySprite;
var tmp = playerControl.cosmetics.nameText;
tmp.color = Color.Lerp(tmp.color, new Color(tmp.color.r, tmp.color.g, tmp.color.b, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
rend.color = Color.Lerp(rend.color, new Color(1, 1, 1, playerControl.AmOwner ? 0.3f : 0), Time.deltaTime * 4f);
+7 -6
View File
@@ -1,6 +1,4 @@
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
@@ -13,7 +11,10 @@ public class FreezerRole : ImpostorRole, ICustomRole
public string RoleDescription => RoleLongDescription;
public Color RoleColor => Palette.Blue;
public ModdedRoleTeams Team => ModdedRoleTeams.Impostor;
[HideFromIl2Cpp]
public LoadableAsset<Sprite> OptionsScreenshot => ExampleAssets.Banner;
public int MaxPlayers => 2;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
OptionsScreenshot = ExampleAssets.Banner,
MaxRoleCount = 2,
};
}
+7 -3
View File
@@ -11,9 +11,13 @@ public class NeutralKillerRole : ImpostorRole, ICustomRole
public string RoleLongDescription => RoleDescription;
public Color RoleColor => Color.magenta;
public ModdedRoleTeams Team => ModdedRoleTeams.Neutral;
public bool UseVanillaKillButton => true;
public bool CanGetKilled => true;
public bool CanUseVent => true;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
UseVanillaKillButton = true,
CanGetKilled = true,
CanUseVent = true,
};
public override void SpawnTaskHeader(PlayerControl playerControl)
{
+9 -5
View File
@@ -1,6 +1,4 @@
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using MiraAPI.Roles;
using UnityEngine;
namespace MiraAPI.Example.Roles;
@@ -13,6 +11,12 @@ public class TeleporterRole : CrewmateRole, ICustomRole
public string RoleDescription => RoleLongDescription;
public Color RoleColor => new Color32(221, 176, 152, 255);
public ModdedRoleTeams Team => ModdedRoleTeams.Crewmate;
[HideFromIl2Cpp]
public LoadableAsset<Sprite> OptionsScreenshot => ExampleAssets.Banner;
public CustomRoleConfiguration Configuration => new CustomRoleConfiguration(this)
{
OptionsScreenshot = ExampleAssets.Banner,
CanModifyChance = false,
DefaultChance = 73,
DefaultRoleCount = 4,
};
}
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.Cosmetics;
public abstract class AbstractCosmeticsGroup
{
public List<HatData> Hats { get; } = [];
public List<SkinData> Skins { get; } = [];
public List<VisorData> Visors { get; } = [];
public List<NamePlateData> Nameplates { get; } = [];
/// <summary>
/// Gets the name of the group. Visible in options menu.
/// </summary>
public abstract string GroupName { get; }
/// <summary>
/// Gets a function that determines whether the group should be visible or not.
/// </summary>
public virtual Func<bool> GroupVisible => () => true;
/// <summary>
/// Gets the sorting mode of individual hats within this group.
/// </summary>
public virtual SortingMode SortingMode => SortingMode.AlphabeticName;
/// <summary>
/// Gets the priority of a group for sorting groups.
/// </summary>
public virtual int SortingPriority { get; }
}
public enum SortingMode
{
Priority,
AlphabeticProductId,
AlphabeticStoreName,
AlphabeticName,
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
namespace MiraAPI.Cosmetics;
internal sealed class AbstractCosmeticsGroupComparer : Comparer<AbstractCosmeticsGroup>
{
public override int Compare(AbstractCosmeticsGroup? x, AbstractCosmeticsGroup? y)
{
switch (x)
{
case not null when y is null:
return 1;
case null when y is null:
return 0;
case null:
return -1;
}
var p = x.SortingPriority - y.SortingPriority;
return p == 0 ? StringComparer.InvariantCultureIgnoreCase.Compare(x.GroupName, y.GroupName) : p;
}
}
+38
View File
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace MiraAPI.Cosmetics;
internal sealed class CosmeticComparer(AbstractCosmeticsGroup group) : Comparer<CosmeticData>
{
internal static readonly string[] NoCosmetics = ["hat_NoHat", "skin_None", "nameplate_NoPlate", "visor_EmptyVisor"];
public override int Compare(CosmeticData? x, CosmeticData? y)
{
if (NoCosmetics.Contains(x?.ProdId))
{
return -1;
}
if (NoCosmetics.Contains(y?.ProdId))
{
return 1;
}
return group.SortingMode switch
{
SortingMode.AlphabeticProductId => StringComparer.InvariantCultureIgnoreCase.Compare(x?.ProductId, y?.ProductId),
SortingMode.Priority => CustomCosmeticManager.CosmeticToPriority[x!] - CustomCosmeticManager.CosmeticToPriority[y!],
SortingMode.AlphabeticStoreName => x switch
{
HatData h1 when y is HatData h2 => StringComparer.InvariantCultureIgnoreCase.Compare(
h1.StoreName,
h2.StoreName),
SkinData s1 when y is SkinData s2 => StringComparer.InvariantCultureIgnoreCase.Compare(
s1.StoreName,
s2.StoreName),
_ => StringComparer.InvariantCultureIgnoreCase.Compare(x?.GetItemName(), y?.GetItemName()),
},
_ => StringComparer.InvariantCultureIgnoreCase.Compare(x?.GetItemName(), y?.GetItemName()),
};
}
}
@@ -0,0 +1,19 @@
using System.Linq;
namespace MiraAPI.Cosmetics;
/// <summary>
/// Used to get access to a CosmeticGroup.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
public static class CosmeticGroupSingleton<T> where T : AbstractCosmeticsGroup
{
private static T? _instance;
/// <summary>
/// Gets instance of the cosmetic group.
/// </summary>
#pragma warning disable CA1000
public static T Instance => _instance ??= CustomCosmeticManager.Groups.OfType<T>().Single();
#pragma warning restore CA1000
}
+127
View File
@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MonoMod.Utils;
using Reactor.Utilities;
namespace MiraAPI.Cosmetics;
public static class CustomCosmeticManager
{
private static readonly Dictionary<PropertyInfo, RegisterCustomCosmeticAttribute> OptionAttributes = [];
private static readonly Dictionary<Type, AbstractCosmeticsGroup> TypeToGroup = [];
internal static readonly Dictionary<CosmeticData, int> CosmeticToPriority = [];
internal static readonly Dictionary<CosmeticData, AbstractCosmeticsGroup> CosmeticToGroup = [];
internal static readonly List<AbstractCosmeticsGroup> Groups = [];
internal static void RegisterVanilla()
{
if (Activator.CreateInstance(typeof(VanillaCosmeticsGroup)) is not AbstractCosmeticsGroup group)
{
Logger<MiraApiPlugin>.Error($"Failed to create group from Vanilla");
return;
}
if (TypeToGroup.ContainsKey(typeof(VanillaCosmeticsGroup)))
{
Logger<MiraApiPlugin>.Error($"Vanilla group already exists.");
return;
}
Groups.Add(group);
TypeToGroup.Add(typeof(VanillaCosmeticsGroup), group);
}
internal static bool RegisterGroup(Type type, MiraPluginInfo pluginInfo)
{
if (Activator.CreateInstance(type) is not AbstractCosmeticsGroup group)
{
Logger<MiraApiPlugin>.Error($"Failed to create group from {type.Name}");
return false;
}
if (TypeToGroup.ContainsKey(type))
{
Logger<MiraApiPlugin>.Error($"Group {type.Name} already exists.");
return false;
}
Groups.Add(group);
TypeToGroup.Add(type, group);
pluginInfo.CosmeticGroups.Add(group);
return true;
}
internal static void RegisterAttributeOption(Type type, RegisterCustomCosmeticAttribute attribute, PropertyInfo property, MiraPluginInfo pluginInfo)
{
if (OptionAttributes.ContainsKey(property))
{
Logger<MiraApiPlugin>.Error($"Property {property.Name} already has an attribute registered.");
return;
}
if (!TypeToGroup.TryGetValue(type, out var group))
{
Logger<MiraApiPlugin>.Error($"Failed to get group for {type.Name}");
return;
}
OptionAttributes.Add(property, attribute);
}
internal static void LoadCosmetic(PropertyInfo property, RegisterCustomCosmeticAttribute attribute)
{
if (!TypeToGroup.TryGetValue(property.DeclaringType, out var group))
{
Logger<MiraApiPlugin>.Error($"Failed to get group for {property.DeclaringType.Name}");
return;
}
if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<HatData>)))
{
group.Hats.AddRange((IEnumerable<HatData>)property.GetValue(group));
}
else if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<SkinData>)))
{
group.Skins.AddRange((IEnumerable<SkinData>)property.GetValue(group));
}
else if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<VisorData>)))
{
group.Visors.AddRange((IEnumerable<VisorData>)property.GetValue(group));
}
else if (property.PropertyType.IsAssignableTo(typeof(IEnumerable<NamePlateData>)))
{
group.Nameplates.AddRange((IEnumerable<NamePlateData>)property.GetValue(group));
}
else
{
Logger<MiraApiPlugin>.Error($"Failed to get enumerable for {property.Name}");
return;
}
CosmeticToPriority.AddRange(((IEnumerable<CosmeticData>)property.GetValue(group)).ToDictionary(y => y, x => attribute.Priority));
CosmeticToGroup.AddRange(((IEnumerable<CosmeticData>)property.GetValue(group)).ToDictionary(y => y, x => group));
}
internal static bool Registered { get; set; }
internal static void LoadAll()
{
CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.runtimeRegister();
if (Registered || !CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.registered)
{
return;
}
Registered = true;
CosmeticToPriority.AddRange(CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.Cosmetics.ToDictionary(y => y, x => 0));
CosmeticToGroup.AddRange(CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance.Cosmetics.ToDictionary(y => y, x => CosmeticGroupSingleton<VanillaCosmeticsGroup>.Instance));
OptionAttributes.Do(x => LoadCosmetic(x.Key, x.Value));
DestroyableSingleton<HatManager>.Instance.allHats = CosmeticToGroup.Keys.OfType<HatData>().ToArray();
DestroyableSingleton<HatManager>.Instance.allVisors = CosmeticToGroup.Keys.OfType<VisorData>().ToArray();
DestroyableSingleton<HatManager>.Instance.allSkins = CosmeticToGroup.Keys.OfType<SkinData>().ToArray();
DestroyableSingleton<HatManager>.Instance.allNamePlates = CosmeticToGroup.Keys.OfType<NamePlateData>().ToArray();
}
}
@@ -0,0 +1,9 @@
using System;
namespace MiraAPI.Cosmetics;
[AttributeUsage(AttributeTargets.Property)]
public class RegisterCustomCosmeticAttribute(int priority = 0) : Attribute
{
public int Priority { get; } = priority;
}
@@ -0,0 +1,40 @@
using System.Collections.Generic;
namespace MiraAPI.Cosmetics;
public class VanillaCosmeticsGroup : AbstractCosmeticsGroup
{
public override string GroupName => "Vanilla";
internal static HatData[] VanillaHats => DestroyableSingleton<HatManager>.Instance.allHats;
internal static VisorData[] VanillaVisors => DestroyableSingleton<HatManager>.Instance.allVisors;
internal static SkinData[] VanillaSkins => DestroyableSingleton<HatManager>.Instance.allSkins;
internal static NamePlateData[] VanillaNameplates => DestroyableSingleton<HatManager>.Instance.allNamePlates;
internal List<CosmeticData> Cosmetics { get; } = [];
internal bool registered { get; set; }
internal bool runtimeRegister()
{
if (registered)
{
return true;
}
if (!DestroyableSingleton<HatManager>.InstanceExists || VanillaHats.Length == 0
|| VanillaVisors.Length == 0 || VanillaSkins.Length == 0
|| VanillaNameplates.Length == 0)
{
return false;
}
registered = true;
Hats.AddRange(VanillaHats);
Visors.AddRange(VanillaVisors);
Skins.AddRange(VanillaSkins);
Nameplates.AddRange(VanillaNameplates);
Cosmetics.AddRange(Hats);
Cosmetics.AddRange(Visors);
Cosmetics.AddRange(Skins);
Cosmetics.AddRange(Nameplates);
return true;
}
}
+4 -4
View File
@@ -1,7 +1,7 @@
using Reactor.Utilities;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using Reactor.Utilities;
namespace MiraAPI.GameModes;
@@ -21,7 +21,7 @@ public static class CustomGameModeManager
}
/// <summary>
/// Current gamemode.
/// Gets current gamemode.
/// </summary>
public static CustomGameMode? ActiveMode { get; internal set; } = new DefaultMode();
@@ -29,7 +29,7 @@ public static class CustomGameModeManager
/// Set current gamemode.
/// </summary>
/// <param name="id">gamemode ID.</param>
public static void SetGameMode(int id)
internal static void SetGameMode(int id)
{
if (GameModes.TryGetValue(id, out var gameMode))
{
@@ -1,6 +1,6 @@
using MiraAPI.GameOptions.OptionTypes;
using System;
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
@@ -1,7 +1,7 @@
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
using System;
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
namespace MiraAPI.GameOptions.Attributes;
@@ -1,6 +1,6 @@
using MiraAPI.GameOptions.OptionTypes;
using System;
using System;
using System.Reflection;
using MiraAPI.GameOptions.OptionTypes;
namespace MiraAPI.GameOptions.Attributes;
+2 -1
View File
@@ -6,7 +6,7 @@ using UnityEngine;
namespace MiraAPI.GameOptions;
internal interface IModdedOption
public interface IModdedOption
{
uint Id { get; }
string Title { get; }
@@ -21,4 +21,5 @@ internal interface IModdedOption
float GetFloatData();
NetData GetNetData();
void HandleNetData(byte[] data);
void ResetToConfig();
}
+4 -2
View File
@@ -45,6 +45,10 @@ public static class ModdedOptionsManager
TypeToGroup.Add(type, group);
pluginInfo.OptionGroups.Add(group);
typeof(OptionGroupSingleton<>).MakeGenericType(type)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, group);
return true;
}
@@ -138,7 +142,6 @@ public static class ModdedOptionsManager
{
// necessary to disable then re-enable this setting
// we dont know how other plugins handle their configs
// this way, all the options are saved at once, instead of one by one
var oldConfigSetting = new Dictionary<MiraPluginInfo, bool>();
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
{
@@ -158,7 +161,6 @@ public static class ModdedOptionsManager
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins())
{
plugin.PluginConfig.Save();
plugin.PluginConfig.SaveOnConfigSet = oldConfigSetting[plugin];
}
@@ -86,7 +86,10 @@ public class ModdedEnumOption : ModdedOption<int>
/// <inheritdoc />
protected override void OnValueChanged(int newValue)
{
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, Data?.GetValueString(newValue), false);
if (HudManager.InstanceExists)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, Data.GetValueString(newValue), false);
}
if (!OptionBehaviour)
{
return;
@@ -1,7 +1,7 @@
using AmongUs.GameOptions;
using System;
using AmongUs.GameOptions;
using MiraAPI.Networking;
using MiraAPI.Utilities;
using System;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -134,10 +134,13 @@ public class ModdedNumberOption : ModdedOption<float>
protected override void OnValueChanged(float newValue)
{
Value = Mathf.Clamp(newValue, Min, Max);
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(
StringName,
Data?.GetValueString(Value),
false);
if (HudManager.InstanceExists)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(
StringName,
Data.GetValueString(Value),
false);
}
if (OptionBehaviour is NumberOption opt)
{
+16 -14
View File
@@ -1,10 +1,10 @@
using BepInEx.Configuration;
using System;
using BepInEx.Configuration;
using MiraAPI.Networking;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using Reactor.Localization.Utilities;
using Reactor.Networking.Rpc;
using System;
using UnityEngine;
namespace MiraAPI.GameOptions.OptionTypes;
@@ -45,7 +45,11 @@ public abstract class ModdedOption<T> : IModdedOption
get => _parentMod;
set
{
if (_parentMod != null || value == null) return;
if (_parentMod != null || value == null)
{
return;
}
_parentMod = value;
var entry = _parentMod.GetConfigFile().Bind(ConfigDefinition, DefaultValue);
Value = entry.Value;
@@ -85,17 +89,7 @@ public abstract class ModdedOption<T> : IModdedOption
/// <summary>
/// Gets or sets the config definition of the option.
/// </summary>
public ConfigDefinition? ConfigDefinition
{
get => _configDefinition;
set
{
if (_configDefinition is not null) return;
_configDefinition = value;
}
}
private ConfigDefinition? _configDefinition;
public ConfigDefinition? ConfigDefinition { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ModdedOption{T}"/> class.
@@ -168,6 +162,14 @@ public abstract class ModdedOption<T> : IModdedOption
/// <param name="data">The NetData's byte array.</param>
public abstract void HandleNetData(byte[] data);
public void ResetToConfig()
{
if (ParentMod?.GetConfigFile().TryGetEntry<T>(ConfigDefinition, out var entry) == true)
{
SetValue(entry.Value);
}
}
/// <summary>
/// Handles the value changed event.
/// </summary>
@@ -1,5 +1,5 @@
using MiraAPI.Networking;
using System;
using System;
using MiraAPI.Networking;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -69,7 +69,10 @@ public class ModdedToggleOption : ModdedOption<bool>
/// <inheritdoc />
protected override void OnValueChanged(bool newValue)
{
DestroyableSingleton<HudManager>.Instance.Notifier.AddSettingsChangeMessage(StringName, newValue ? "On" : "Off", false);
if (HudManager.InstanceExists)
{
HudManager.Instance.Notifier.AddSettingsChangeMessage(StringName, newValue ? "On" : "Off", false);
}
if (!OptionBehaviour)
{
return;
+3 -2
View File
@@ -167,6 +167,7 @@ public abstract class CustomActionButton
public void SetUses(int amount)
{
UsesLeft = Mathf.Clamp(amount, 0, int.MaxValue);
Button?.SetUsesRemaining(MaxUses);
}
/// <summary>
@@ -327,7 +328,7 @@ public abstract class CustomActionButton<T> : CustomActionButton where T : MonoB
/// <returns>True if the target object is valid, false otherwise.</returns>
public virtual bool IsTargetValid(T? target)
{
return target;
return target != null;
}
/// <summary>
@@ -354,6 +355,6 @@ public abstract class CustomActionButton<T> : CustomActionButton where T : MonoB
Target = IsTargetValid(newTarget) ? newTarget : null;
SetOutline(true);
return base.CanUse() && Target;
return base.CanUse() && Target != null;
}
}
+3 -1
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using MiraAPI.PluginLoading;
using Reactor.Utilities;
namespace MiraAPI.Hud;
@@ -9,7 +10,7 @@ internal static class CustomButtonManager
{
internal static readonly List<CustomActionButton> CustomButtons = [];
internal static void RegisterButton(Type buttonType)
internal static void RegisterButton(Type buttonType, MiraPluginInfo pluginInfo)
{
if (!typeof(CustomActionButton).IsAssignableFrom(buttonType))
{
@@ -24,6 +25,7 @@ internal static class CustomButtonManager
}
CustomButtons.Add(button);
pluginInfo.Buttons.Add(button);
typeof(CustomButtonSingleton<>).MakeGenericType(buttonType)
.GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic)!
.SetValue(null, button);
+111
View File
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AmongUs.GameOptions;
using MiraAPI.Patches.Stubs;
using Reactor.Utilities.Attributes;
using Reactor.Utilities.Extensions;
using UnityEngine;
using UnityEngine.Events;
namespace MiraAPI.Hud;
/// <summary>
/// Custom Player Menu using the ShapeshifterPanel as a base.
/// </summary>
/// <param name="il2CppPtr">Used by Il2Cpp. Do not use constructor, this is a MonoBehaviour.</param>
[RegisterInIl2Cpp]
public class CustomPlayerMenu(IntPtr il2CppPtr) : Minigame(il2CppPtr)
{
public ShapeshifterPanel PanelPrefab;
public float XStart = -0.8f;
public float YStart = 2.15f;
public float XOffset = 1.95f;
public float YOffset = -0.65f;
public UiElement BackButton;
public UiElement DefaultButtonSelected;
public List<ShapeshifterPanel> potentialVictims;
/// <summary>
/// Creates a CustomPlayerMenu.
/// </summary>
/// <returns>New CustomPlayerMenu object.</returns>
public static CustomPlayerMenu Create()
{
var shapeShifterRole = RoleManager.Instance.GetRole(RoleTypes.Shapeshifter);
var ogMenu = shapeShifterRole.TryCast<ShapeshifterRole>().ShapeshifterMenu;
var newMenu = Instantiate(ogMenu);
var customMenu = newMenu.gameObject.AddComponent<CustomPlayerMenu>();
customMenu.PanelPrefab = newMenu.PanelPrefab;
customMenu.XStart = newMenu.XStart;
customMenu.YStart = newMenu.YStart;
customMenu.XOffset = newMenu.XOffset;
customMenu.YOffset = newMenu.YOffset;
customMenu.BackButton = newMenu.BackButton;
var back = customMenu.BackButton.GetComponent<PassiveButton>();
back.OnClick.RemoveAllListeners();
back.OnClick.AddListener((UnityAction)(() =>
{
Instance.Close();
}));
customMenu.CloseSound = newMenu.CloseSound;
customMenu.logger = newMenu.logger;
customMenu.OpenSound = newMenu.OpenSound;
newMenu.DestroyImmediate();
customMenu.transform.SetParent(Camera.main.transform, false);
customMenu.transform.localPosition = new Vector3(0f, 0f, -50f);
return customMenu;
}
private void OnDisable()
{
ControllerManager.Instance.CloseOverlayMenu(name);
}
public override void Begin(PlayerTask task)
{
throw new NotImplementedException("Use the other Begin method.");
}
/// <summary>
/// Begins/opens the custom player menu.
/// </summary>
/// <param name="playerMatch">Function to determine if player should show in the custom menu.</param>
/// <param name="onClick">Onclick action for player.</param>
public void Begin(Func<PlayerControl, bool> playerMatch, Action<PlayerControl> onClick)
{
MinigameStubs.Begin(this, null);
DestroyableSingleton<DebugAnalytics>.Instance.Analytics.MinigameOpened(PlayerControl.LocalPlayer.Data, TaskType);
var list = PlayerControl.AllPlayerControls.ToArray().Where(playerMatch).ToList();
potentialVictims = [];
var list2 = new Il2CppSystem.Collections.Generic.List<UiElement>();
for (var i = 0; i < list.Count; i++)
{
var player = list[i];
var num = i % 3;
var num2 = i / 3;
var flag = PlayerControl.LocalPlayer.Data.Role.NameColor == player.Data.Role.NameColor;
var shapeshifterPanel = Instantiate(PanelPrefab, transform);
shapeshifterPanel.transform.localPosition = new Vector3(XStart + num * XOffset, YStart + num2 * YOffset, -1f);
shapeshifterPanel.SetPlayer(i, player.Data, (Il2CppSystem.Action)(() => { onClick(player); }));
shapeshifterPanel.NameText.color = flag ? player.Data.Role.NameColor : Color.white;
potentialVictims.Add(shapeshifterPanel);
list2.Add(shapeshifterPanel.Button);
}
ControllerManager.Instance.OpenOverlayMenu(name, BackButton, DefaultButtonSelected, list2);
}
}
+2 -3
View File
@@ -10,11 +10,10 @@
<ItemGroup>
<None Include="..\README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\**\*.*" />
</ItemGroup>
<Import Project="../AmongUs.props" />
<Import Project="../AmongUs.props" />
</Project>
+2 -2
View File
@@ -75,6 +75,6 @@ public abstract class BaseModifier
/// <summary>
/// Determines whether the player can vent.
/// </summary>
/// <returns>True if the player can vent, false otherwise.</returns>
public virtual bool CanVent() => Player?.Data.Role.CanVent == true;
/// <returns>True if the player can vent, false otherwise. Null for no effect.</returns>
public virtual bool? CanVent() => null;
}
+12 -13
View File
@@ -1,14 +1,14 @@
using System;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
using Reactor.Utilities;
using Reactor.Utilities.Attributes;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Text;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
using Reactor.Utilities;
using Reactor.Utilities.Attributes;
using TMPro;
using UnityEngine;
@@ -39,11 +39,6 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
internal void ClearModifiers()
{
foreach (var modifier in Modifiers)
{
modifier.OnDeactivate();
}
_toRemove.AddRange(Modifiers);
}
@@ -74,7 +69,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
Modifiers.Add(modifier);
modifier.OnActivate();
if (_player?.AmOwner == true && modifier is TimedModifier { AutoStart: true } timer)
if (modifier is TimedModifier { AutoStart: true } timer)
{
timer.StartTimer();
}
@@ -84,7 +79,7 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
{
if (_player?.AmOwner == true)
{
HudManager.Instance?.SetHudActive(true);
HudManager.Instance?.SetHudActive(HudManager.Instance.TaskPanel.isActiveAndEnabled);
}
_toAdd.Clear();
_toRemove.Clear();
@@ -112,6 +107,10 @@ public class ModifierComponent(IntPtr cppPtr) : MonoBehaviour(cppPtr)
var baseModifiers = filteredModifiers as BaseModifier[] ?? filteredModifiers.ToArray();
var inMeeting = MeetingHud.Instance != null;
_modifierText!.gameObject.SetActive(!inMeeting);
if (baseModifiers.Length != 0)
{
var stringBuild = new StringBuilder();
+6
View File
@@ -23,4 +23,10 @@ public abstract class GameModifier : BaseModifier
/// <param name="role">The role to be checked.</param>
/// <returns>True if the modifier is valid on the role, otherwise false.</returns>
public virtual bool IsModifierValidOn(RoleBehaviour role) => true;
/// <summary>
/// Determines whether the player won the game with this modifier.
/// </summary>
/// <returns>True if the player won, false if they lost. Return null to use the player's default win condition.</returns>
public virtual bool? DidWin(GameOverReason reason) => null;
}
+51 -10
View File
@@ -39,6 +39,9 @@ public abstract class TimedModifier : BaseModifier
/// </summary>
public float TimeRemaining { get; protected set; }
/// <inheritdoc />
public override bool HideOnUi => !TimerActive;
/// <summary>
/// Gets the HUD information for Timed Modifier, including the time remaining.
/// </summary>
@@ -53,25 +56,18 @@ public abstract class TimedModifier : BaseModifier
/// </summary>
public override void FixedUpdate()
{
if (Player?.AmOwner == false)
if (!TimerActive)
{
return;
}
if (TimeRemaining > 0 && TimerActive)
if (TimeRemaining > 0)
{
TimeRemaining -= Time.fixedDeltaTime;
}
else
{
TimerActive = false;
TimeRemaining = Duration;
OnTimerComplete();
if (RemoveOnComplete)
{
ModifierComponent?.RemoveModifier(ModifierId);
}
StopTimer();
}
}
@@ -86,7 +82,52 @@ public abstract class TimedModifier : BaseModifier
return;
}
TimeRemaining = Duration;
TimerActive = true;
}
/// <summary>
/// Stops the timer and calls OnTimerComplete().
/// </summary>
public void StopTimer()
{
if (!TimerActive)
{
return;
}
TimerActive = false;
TimeRemaining = Duration;
OnTimerComplete();
if (RemoveOnComplete)
{
ModifierComponent?.RemoveModifier(ModifierId);
}
}
/// <summary>
/// Resets the timer. Does not call OnTimerComplete().
/// </summary>
public void ResetTimer()
{
TimerActive = false;
TimeRemaining = Duration;
}
/// <summary>
/// Pauses the timer.
/// </summary>
public void PauseTimer()
{
TimerActive = false;
}
/// <summary>
/// Pauses the timer.
/// </summary>
public void ResumeTimer()
{
TimerActive = true;
}
}
+7 -6
View File
@@ -4,6 +4,7 @@ using AmongUs.GameOptions;
using Assets.CoreScripts;
using BepInEx.Unity.IL2CPP.Utils;
using Reactor.Networking.Attributes;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using UnityEngine;
@@ -26,7 +27,7 @@ public static class CustomMurderRpc
/// <param name="teleportMurderer">Should the killer be snapped to the dead player.</param>
/// <param name="showKillAnim">Should the kill animation be shown.</param>
/// <param name="playKillSound">Should the kill sound be played.</param>
[MethodRpc((uint)MiraRpc.CustomMurder)]
[MethodRpc((uint)MiraRpc.CustomMurder, LocalHandling = RpcLocalHandling.Before, SendImmediately = true)]
public static void RpcCustomMurder(
this PlayerControl source,
PlayerControl target,
@@ -87,7 +88,7 @@ public static class CustomMurderRpc
if (flag && PlayerControl.LocalPlayer.Data.PlayerId == target.protectedByGuardianId)
{
StatsManager.Instance.IncrementStat(StringNames.StatsGuardianAngelCrewmatesProtected);
DestroyableSingleton<AchievementManager>.Instance.OnProtectACrewmate();
AchievementManager.Instance.OnProtectACrewmate();
}
if (source.AmOwner || flag)
@@ -115,7 +116,7 @@ public static class CustomMurderRpc
return;
}
DestroyableSingleton<DebugAnalytics>.Instance.Analytics.Kill(target.Data, source.Data);
DebugAnalytics.Instance.Analytics.Kill(target.Data, source.Data);
if (source.AmOwner)
{
StatsManager.Instance.IncrementStat(
@@ -139,7 +140,7 @@ public static class CustomMurderRpc
}
}
DestroyableSingleton<UnityTelemetry>.Instance.WriteMurder();
UnityTelemetry.Instance.WriteMurder();
target.gameObject.layer = LayerMask.NameToLayer("Ghost");
if (target.AmOwner)
{
@@ -159,14 +160,14 @@ public static class CustomMurderRpc
if (showKillAnim)
{
DestroyableSingleton<HudManager>.Instance.KillOverlay.ShowKillAnimation(source.Data, data);
HudManager.Instance.KillOverlay.ShowKillAnimation(source.Data, data);
}
target.cosmetics.SetNameMask(false);
target.RpcSetScanner(false);
}
DestroyableSingleton<AchievementManager>.Instance.OnMurder(
AchievementManager.Instance.OnMurder(
source.AmOwner,
target.AmOwner,
source.CurrentOutfitType == PlayerOutfitType.Shapeshifted,
@@ -11,7 +11,7 @@ public static class ScrollingColorsPatch
private static BoxCollider2D? _collider;
/// <summary>
/// Add scrolling to the colors tab
/// Add scrolling to the colors tab.
/// </summary>
[HarmonyPostfix, HarmonyPatch("OnEnable")]
public static void AddScrollingToColorsTabPatch(PlayerTab __instance)
+76
View File
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MonoMod.Utils;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(HatsTab), nameof(HatsTab.OnEnable))]
public static class HatsTabPatch
{
public static bool Prefix(HatsTab __instance)
{
var hatGroups = new SortedList<AbstractCosmeticsGroup, List<HatData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Hats.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<HatData>>(x, x.Hats)).
ToDictionary(x => x.Key, x => x.Value.Where(x=>x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
hatGroups.AddRange<AbstractCosmeticsGroup, List<HatData>>(c);
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
__instance.currentHat = DestroyableSingleton<HatManager>.Instance.GetHatById(DataManager.Player.Customization.Hat);
foreach (var (group, hats) in hatGroups.Where(x=>x.Key.GroupVisible() && x.Key.Hats.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 4) / 5 * 5;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 5;
foreach (var hat in hats)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectHat(hat)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.Inner.SetMaskType(PlayerMaterial.MaskType.SimpleUI);
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, hat);
colorChip.Inner.SetHat(hat, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
colorChip.Inner.transform.localPosition = hat.ChipOffset + new Vector2(0f, -0.3f);
colorChip.Tag = hat;
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
__instance.currentHatIsEquipped = true;
return false;
}
}
@@ -0,0 +1,13 @@
using HarmonyLib;
using MiraAPI.Cosmetics;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(InventoryManager), nameof(InventoryManager.CheckUnlockedItems))]
public static class InventoryManagerPatch
{
public static void Prefix()
{
CustomCosmeticManager.LoadAll();
}
}
@@ -0,0 +1,91 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Utilities.Assets.Addressable;
using MonoMod.Utils;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(NameplatesTab), nameof(NameplatesTab.OnEnable))]
public static class NameplatesTabPatch
{
public static bool Prefix(NameplatesTab __instance)
{
var groups = new SortedList<AbstractCosmeticsGroup, List<NamePlateData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Nameplates.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<NamePlateData>>(x, x.Nameplates)).
ToDictionary(x => x.Key, x => x.Value.Where(x => x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
groups.AddRange<AbstractCosmeticsGroup, List<NamePlateData>>(c);
Logger<MiraApiPlugin>.Info($"{c.Count}");
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
__instance.PlayerPreview.gameObject.SetActive(false);
__instance.StartCoroutine(__instance.CoLoadNameplatePreview());
foreach (var (group, hats) in groups.Where(x => x.Key.GroupVisible() && x.Key.Nameplates.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 1) / 2 * 2;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 2;
foreach (var hat in hats)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectNameplate(hat)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = hat.ProductId;
var handle = Addressables.LoadAssetAsync<NamePlateViewData>(hat.ViewDataRef);
Coroutines.Start(SetupColorChip(colorChip.TryCast<NameplateChip>(), handle));
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.GetDefaultSelectable().PlayerEquippedForeground.SetActive(true);
__instance.plateId = DataManager.Player.Customization.NamePlate;
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
__instance.currentNameplateIsEquipped = true;
return false;
}
private static IEnumerator SetupColorChip(NameplateChip colorChip, AsyncOperationHandle<NamePlateViewData> handle)
{
yield return new WaitForAsyncOperationHandleFinish(handle);
colorChip.image.sprite = handle.Result?.Image;
}
}
@@ -0,0 +1,86 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Utilities.Assets.Addressable;
using MonoMod.Utils;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(SkinsTab), nameof(SkinsTab.OnEnable))]
public static class SkinsTabPatch
{
public static bool Prefix(SkinsTab __instance)
{
var groups = new SortedList<AbstractCosmeticsGroup, List<SkinData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Skins.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<SkinData>>(x, x.Skins)).
ToDictionary(x => x.Key, x => x.Value.Where(x => x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
groups.AddRange<AbstractCosmeticsGroup, List<SkinData>>(c);
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
foreach (var (group, skins) in groups.Where(x => x.Key.GroupVisible() && x.Key.Skins.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 4) / 5 * 5;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 5;
foreach (var skin in skins)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectSkin(skin)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = skin.ProductId;
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, skin);
var handle = Addressables.LoadAssetAsync<SkinViewData>(skin.ViewDataRef);
Coroutines.Start(SetupColorChip(handle, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color, colorChip));
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.skinId = DataManager.Player.Customization.Skin;
__instance.currentSkinIsEquipped = true;
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
return false;
}
internal static IEnumerator SetupColorChip(AsyncOperationHandle<SkinViewData> handle, int colorId, ColorChip colorChip)
{
yield return new WaitForAsyncOperationHandleFinish(handle);
colorChip.Inner.FrontLayer.sprite = handle.Result?.IdleFrame;
PlayerMaterial.SetColors(colorId, colorChip.Inner.FrontLayer);
}
}
@@ -0,0 +1,86 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Cosmetics;
using MiraAPI.Utilities.Assets.Addressable;
using MonoMod.Utils;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Patches.Cosmetics;
[HarmonyPatch(typeof(VisorsTab), nameof(VisorsTab.OnEnable))]
public static class VisorsTabPatch
{
public static bool Prefix(VisorsTab __instance)
{
var groups = new SortedList<AbstractCosmeticsGroup, List<VisorData>>(
new AbstractCosmeticsGroupComparer()
);
CustomCosmeticManager.Groups.Do(x => x.Visors.Sort(new CosmeticComparer(x)));
var c = CustomCosmeticManager.Groups.Select(x => new KeyValuePair<AbstractCosmeticsGroup, List<VisorData>>(x, x.Visors)).
ToDictionary(x => x.Key, x => x.Value.Where(x => x.Free || DataManager.Player.Purchases.GetPurchase(x.ProductId, x.BundleId)).ToList());
groups.AddRange<AbstractCosmeticsGroup, List<VisorData>>(c);
foreach (var colorchip in __instance.ColorChips) colorchip.gameObject.Destroy();
__instance.ColorChips.Clear();
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var hatIdx = 0;
foreach (var (group, visors) in groups.Where(x => x.Key.GroupVisible() && x.Key.Visors.Count > 0))
{
var text = UnityEngine.Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.text = group.GroupName;
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 3f;
text.fontSizeMax = 3f;
text.fontSizeMin = 0f;
hatIdx = (hatIdx + 4) / 5 * 5;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - (hatIdx / __instance.NumPerRow) * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIdx += 5;
foreach (var visor in visors)
{
var num = __instance.XRange.Lerp(hatIdx % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var num2 = __instance.YStart - hatIdx / __instance.NumPerRow * __instance.YOffset;
var colorChip = UnityEngine.Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.transform.localPosition = new Vector3(num, num2, -1f);
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectVisor(visor)));
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = visor.ProductId;
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, visor);
var handle = Addressables.LoadAssetAsync<VisorViewData>(visor.ViewDataRef);
Coroutines.Start(SetupColorChip(handle, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color, colorChip));
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.ColorChips.Add(colorChip);
hatIdx += 1;
}
}
__instance.visorId = DataManager.Player.Customization.Visor;
__instance.currentVisorIsEquipped = true;
__instance.scroller.ContentYBounds.max = -(__instance.YStart - (hatIdx + 1) / __instance.NumPerRow * __instance.YOffset) - 3f;
return false;
}
internal static IEnumerator SetupColorChip(AsyncOperationHandle<VisorViewData> handle, int colorId, ColorChip colorChip)
{
yield return new WaitForAsyncOperationHandleFinish(handle);
colorChip.Inner.FrontLayer.sprite = handle.Result?.IdleFrame;
PlayerMaterial.SetColors(colorId, colorChip.Inner.FrontLayer);
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ using MiraAPI.Hud;
namespace MiraAPI.Patches.Hud;
/// <summary>
/// Reset button patches
/// Reset button patches.
/// </summary>
[HarmonyPatch]
public static class ButtonResetPatches
+2 -2
View File
@@ -1,6 +1,5 @@
using HarmonyLib;
using MiraAPI.Hud;
using MiraAPI.Roles;
using Reactor.Utilities.Extensions;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -89,7 +88,8 @@ public static class HudManagerPatches
[HarmonyPatch(nameof(HudManager.SetHudActive), typeof(PlayerControl), typeof(RoleBehaviour), typeof(bool))]
public static void SetHudActivePostfix(HudManager __instance, PlayerControl localPlayer, RoleBehaviour role, bool isActive)
{
if (!localPlayer.Data)
__instance.AdminButton.ToggleVisible(isActive && role.IsImpostor && GameOptionsManager.Instance.CurrentGameOptions.GameMode == AmongUs.GameOptions.GameModes.HideNSeek);
if (localPlayer.Data == null)
{
return;
}
@@ -0,0 +1,40 @@
using System.Linq;
using HarmonyLib;
using MiraAPI.Modifiers.Types;
using MiraAPI.Utilities;
namespace MiraAPI.Patches.Modifiers;
[HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.CoEndGame))]
public static class EndGameDidWinPatch
{
public static void Prefix()
{
var gameOverReason = EndGameResult.CachedGameOverReason;
EndGameResult.CachedWinners.Clear();
var players = GameData.Instance.AllPlayers.ToArray();
for (var i = 0; i < GameData.Instance.PlayerCount; i++)
{
var networkedPlayerInfo = players[i];
if (networkedPlayerInfo == null)
{
continue;
}
var didWin = networkedPlayerInfo.Role.DidWin(gameOverReason);
var modifierWin = networkedPlayerInfo.Object?.GetModifierComponent()?.ActiveModifiers.OfType<GameModifier>()
.FirstOrDefault(x => x.DidWin(gameOverReason) != null)?.DidWin(gameOverReason);
if (modifierWin != null)
{
didWin = modifierWin.Value;
}
if (didWin)
{
EndGameResult.CachedWinners.Add(new CachedPlayerData(networkedPlayerInfo));
}
}
}
}
-45
View File
@@ -1,45 +0,0 @@
using HarmonyLib;
using MiraAPI.Utilities;
using UnityEngine;
namespace MiraAPI.Patches.Modifiers;
[HarmonyPatch(typeof(Vent))]
public static class VentPatches
{
[HarmonyPostfix]
[HarmonyPatch(nameof(Vent.CanUse))]
public static void CanUseVentPatch(Vent __instance, ref float __result, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] ref bool canUse, [HarmonyArgument(2)] ref bool couldUse)
{
var @object = pc.Object;
var role = @object.Data.Role;
var modifiers = @object.GetModifierComponent()?.ActiveModifiers;
if (modifiers is null || modifiers.Count <= 0)
{
return;
}
switch (role.CanVent)
{
case true when modifiers.Exists(x => !x.CanVent()):
couldUse = canUse = false;
return;
case false when modifiers.Exists(x => x.CanVent()):
couldUse = true;
break;
}
var num = float.MaxValue;
canUse = couldUse;
if (canUse)
{
var center = @object.Collider.bounds.center;
var position = __instance.transform.position;
num = Vector2.Distance(center, position);
canUse &= num <= __instance.UsableDistance && !PhysicsHelpers.AnythingBetween(@object.Collider, center, position, Constants.ShipOnlyMask, false);
}
__result = num;
}
}
@@ -0,0 +1,16 @@
using HarmonyLib;
using MiraAPI.GameOptions;
namespace MiraAPI.Patches.Options;
[HarmonyPatch(typeof(CreateOptionsPicker), nameof(CreateOptionsPicker.Start))]
public static class CreateOptionsPatch
{
public static void Postfix()
{
foreach (var (_, value) in ModdedOptionsManager.ModdedOptions)
{
value.ResetToConfig();
}
}
}
@@ -1,9 +1,9 @@
using HarmonyLib;
using System.Linq;
using HarmonyLib;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Localization.Utilities;
using Reactor.Utilities.Extensions;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
@@ -32,16 +32,25 @@ public static class GameOptionsMenuPatch
var num = 2.1f;
var filteredGroups =
GameSettingMenuPatches.SelectedMod?.OptionGroups.Where(
x => x.GroupVisible.Invoke() && x.AdvancedRole is null) ?? [];
x => x.AdvancedRole is null) ?? [];
foreach (var group in filteredGroups)
{
var filteredOpts = group.Options.Where(x => x.Visible.Invoke()).ToList();
if (filteredOpts.Count == 0 || group.Header is null)
if (group.Options.Count == 0 || group.Header is null)
{
continue;
}
if (!group.GroupVisible.Invoke())
{
group.Header.gameObject.SetActive(false);
foreach (var option in group.Options)
{
option.OptionBehaviour?.gameObject.SetActive(false);
}
continue;
}
group.Header.gameObject.SetActive(true);
group.Header.transform.localScale = Vector3.one * 0.63f;
group.Header.transform.localPosition = new Vector3(-0.903f, num, -2f);
@@ -1,9 +1,9 @@
using HarmonyLib;
using System;
using System.Linq;
using HarmonyLib;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities.Extensions;
using System;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
@@ -6,7 +6,6 @@ using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
@@ -216,7 +215,7 @@ public static class LobbyViewPanePatches
{
var filteredRoles = SelectedMod.CustomRoles.Values
.OfType<ICustomRole>()
.Where(x => !x.HideSettings && x.Team == team).ToList();
.Where(x => !x.Configuration.HideSettings && x.Team == team).ToList();
if (filteredRoles.Count == 0)
{
@@ -285,7 +284,7 @@ public static class LobbyViewPanePatches
chancePerGame,
61,
customRole.RoleColor,
customRole.Icon.LoadAsset(),
customRole.Configuration.Icon.LoadAsset(),
true);
viewSettingsInfoPanelRoleVariant.titleText.color =
@@ -370,7 +369,7 @@ public static class LobbyViewPanePatches
role.StringName,
maskLayer,
role.TeamType == RoleTeamTypes.Crewmate,
customRole.Icon.LoadAsset());
customRole.Configuration.Icon.LoadAsset());
viewPanel.divider.material.SetInt(PlayerMaterial.MaskLayer, maskLayer);
var num = viewPanel.yPosStart;
@@ -390,11 +389,6 @@ public static class LobbyViewPanePatches
var value = option.GetFloatData();
if (baseGameSetting == null)
{
continue;
}
if (baseGameSetting.Type == OptionTypes.Checkbox)
{
viewSettingsInfoPanel.SetInfoCheckbox(baseGameSetting.Title, maskLayer, value > 0f);
@@ -1,7 +1,9 @@
using HarmonyLib;
using System.Linq;
using HarmonyLib;
using Il2CppSystem;
using MiraAPI.Roles;
using System.Linq;
using UnityEngine;
using Object = Il2CppSystem.Object;
namespace MiraAPI.Patches.Options;
@@ -23,16 +25,20 @@ public static class NotificationPopperPatch
return true;
}
var text = teamType == RoleTeamTypes.Crewmate
? Palette.CrewmateSettingChangeText.ToTextColor()
: Palette.ImpostorRed.ToTextColor();
var text = customRole.Team switch
{
ModdedRoleTeams.Crewmate => Palette.CrewmateSettingChangeText.ToTextColor(),
ModdedRoleTeams.Impostor => Palette.ImpostorRed.ToTextColor(),
ModdedRoleTeams.Neutral => Palette.DisabledGrey.ToTextColor(),
_ => Color.white.ToTextColor(),
};
var item = DestroyableSingleton<TranslationController>.Instance.GetString(
var item = TranslationController.Instance.GetString(
StringNames.LobbyChangeSettingNotificationRole,
string.Concat(
"<font=\"Barlow-Black SDF\" material=\"Barlow-Black Outline\">",
text,
DestroyableSingleton<TranslationController>.Instance.GetString(key, Array.Empty<Object>()),
TranslationController.Instance.GetString(key, Array.Empty<Object>()),
"</color></font>"
),
"<font=\"Barlow-Black SDF\" material=\"Barlow-Black Outline\">" + roleCount + "</font>",
+4 -4
View File
@@ -17,7 +17,7 @@ public static class OptionsPatches
}
__instance.TitleText.text =
DestroyableSingleton<TranslationController>.Instance.GetString(__instance.Title, Array.Empty<Object>());
TranslationController.Instance.GetString(__instance.Title, Array.Empty<Object>());
return false;
}
@@ -39,7 +39,7 @@ public static class OptionsPatches
}
__instance.TitleText.text =
DestroyableSingleton<TranslationController>.Instance.GetString(__instance.Title, Array.Empty<Object>());
TranslationController.Instance.GetString(__instance.Title, Array.Empty<Object>());
return false;
}
@@ -61,8 +61,8 @@ public static class OptionsPatches
}
__instance.TitleText.text =
DestroyableSingleton<TranslationController>.Instance.GetString(__instance.Title, Array.Empty<Object>());
__instance.ValueText.text = DestroyableSingleton<TranslationController>.Instance.GetString(
TranslationController.Instance.GetString(__instance.Title, Array.Empty<Object>());
__instance.ValueText.text = TranslationController.Instance.GetString(
__instance.Values[__instance.Value],
Array.Empty<Object>());
@@ -1,4 +1,6 @@
using HarmonyLib;
using System;
using System.Linq;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using MiraAPI.Networking;
using MiraAPI.Roles;
@@ -7,8 +9,6 @@ using MiraAPI.Utilities.Assets;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using System;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
@@ -56,7 +56,7 @@ public static class RoleSettingMenuPatches
var crewRoles = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role is { Team: ModdedRoleTeams.Crewmate, HideSettings: false })
.Where(role => role is { Team: ModdedRoleTeams.Crewmate, Configuration.HideSettings: false })
.ToList() ?? [];
if (crewRoles is { Count: > 0 })
@@ -82,7 +82,7 @@ public static class RoleSettingMenuPatches
var impRoles = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role is { Team: ModdedRoleTeams.Impostor, HideSettings: false })
.Where(role => role is { Team: ModdedRoleTeams.Impostor, Configuration.HideSettings: false })
.ToList() ?? [];
if (impRoles is { Count: > 0 })
@@ -109,7 +109,7 @@ public static class RoleSettingMenuPatches
var neutRoles = GameSettingMenuPatches.SelectedMod?.CustomRoles.Values
.OfType<ICustomRole>()
.Where(role => role is { Team: ModdedRoleTeams.Neutral, HideSettings: false })
.Where(role => role is { Team: ModdedRoleTeams.Neutral, Configuration.HideSettings: false })
.ToList() ?? [];
if (neutRoles is { Count: > 0 })
@@ -159,18 +159,22 @@ public static class RoleSettingMenuPatches
{
var roleSetting = obj.Cast<RoleOptionSetting>();
var role = roleSetting.Role as ICustomRole;
if (role is null or { HideSettings: true })
if (role is null or { Configuration.HideSettings: true })
{
return;
}
try
{
role.ParentMod.PluginConfig.TryGetEntry<int>(role.NumConfigDefinition, out var numEntry);
numEntry.Value = roleSetting.RoleMaxCount;
if (role.Configuration.MaxRoleCount != 0)
{
role.SetCount(roleSetting.RoleMaxCount);
}
role.ParentMod.PluginConfig.TryGetEntry<int>(role.ChanceConfigDefinition, out var chanceEntry);
chanceEntry.Value = roleSetting.RoleChance;
if (role.Configuration.CanModifyChance)
{
role.SetChance(roleSetting.RoleChance);
}
}
catch (Exception e)
{
@@ -178,7 +182,7 @@ public static class RoleSettingMenuPatches
}
roleSetting.UpdateValuesAndText(GameOptionsManager.Instance.CurrentGameOptions.RoleOptions);
DestroyableSingleton<HudManager>.Instance.Notifier.AddRoleSettingsChangeMessage(
HudManager.Instance.Notifier.AddRoleSettingsChangeMessage(
roleSetting.Role.StringName,
roleSetting.RoleMaxCount,
roleSetting.RoleChance,
@@ -228,7 +232,7 @@ public static class RoleSettingMenuPatches
renderer.material.SetInt(PlayerMaterial.MaskLayer, 20);
}
foreach (var fontMat in newOpt.GetComponentsInChildren<TextMeshPro>(true).Select(x=>x.fontMaterial))
foreach (var fontMat in newOpt.GetComponentsInChildren<TextMeshPro>(true).Select(x => x.fontMaterial))
{
fontMat.SetFloat(ShaderID.StencilComp, 3f);
fontMat.SetFloat(ShaderID.Stencil, 20);
@@ -254,11 +258,11 @@ public static class RoleSettingMenuPatches
}
__instance.roleDescriptionText.text = customRole.RoleLongDescription;
__instance.roleTitleText.text = DestroyableSingleton<TranslationController>.Instance.GetString(
__instance.roleTitleText.text = TranslationController.Instance.GetString(
role.StringName,
new Il2CppReferenceArray<Il2CppSystem.Object>(0));
__instance.roleScreenshot.sprite = Sprite.Create(
customRole.OptionsScreenshot.LoadAsset().texture,
customRole.Configuration.OptionsScreenshot.LoadAsset().texture,
new Rect(0, 0, 370, 230),
Vector2.one / 2,
100);
@@ -305,6 +309,7 @@ public static class RoleSettingMenuPatches
Quaternion.identity,
__instance.RoleChancesSettings.transform);
roleOptionSetting.transform.localPosition = new Vector3(-0.15f, yPos, -2f);
roleOptionSetting.SetRole(GameOptionsManager.Instance.CurrentGameOptions.RoleOptions, role, 20);
roleOptionSetting.labelSprite.color = customRole.RoleColor;
roleOptionSetting.OnValueChanged = new Action<OptionBehaviour>(ValueChanged);
@@ -336,6 +341,18 @@ public static class RoleSettingMenuPatches
passiveButton.OnClick.AddListener((UnityAction)(() => { ChangeTab(role, __instance); }));
}
if (customRole.Configuration is { MaxRoleCount: 0 })
{
roleOptionSetting.CountMinusBtn.gameObject.SetActive(false);
roleOptionSetting.CountPlusBtn.gameObject.SetActive(false);
}
if (!customRole.Configuration.CanModifyChance)
{
roleOptionSetting.ChanceMinusBtn.gameObject.SetActive(false);
roleOptionSetting.ChancePlusBtn.gameObject.SetActive(false);
}
if (index < GameSettingMenuPatches.SelectedMod?.CustomRoles.Count - 1)
{
yPos += -0.43f;
+1 -1
View File
@@ -39,7 +39,7 @@ public static class SettingPatches
MiraNumberSuffixes.None => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo),
MiraNumberSuffixes.Multiplier => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "x",
MiraNumberSuffixes.Percent => value.ToString(__instance.FormatString, NumberFormatInfo.InvariantInfo) + "%",
_ => DestroyableSingleton<TranslationController>.Instance.GetString(
_ => TranslationController.Instance.GetString(
StringNames.GameSecondsAbbrev,
(Il2CppSystem.Object[])[value.ToString(__instance.FormatString, CultureInfo.InvariantCulture)]),
};
+15
View File
@@ -15,6 +15,7 @@ public static class PlayerControlPatches
/// <summary>
/// Adds the modifier component to the player on start.
/// </summary>
/// <param name="__instance">PlayerControl instance.</param>
[HarmonyPrefix]
[HarmonyPatch(nameof(PlayerControl.Start))]
public static void PlayerControlStartPostfix(PlayerControl __instance)
@@ -30,6 +31,8 @@ public static class PlayerControlPatches
/// <summary>
/// Calls the OnDeath method for all active modifiers.
/// </summary>
/// <param name="__instance">PlayerControl instance.</param>
/// <param name="reason">The death reason.</param>
[HarmonyPostfix]
[HarmonyPatch(nameof(PlayerControl.Die))]
public static void PlayerControlDiePostfix(PlayerControl __instance, DeathReason reason)
@@ -45,6 +48,7 @@ public static class PlayerControlPatches
/// <summary>
/// FixedUpdate handler for custom roles and custom buttons.
/// </summary>
/// <param name="__instance">PlayerControl instance.</param>
[HarmonyPostfix]
[HarmonyPatch(nameof(PlayerControl.FixedUpdate))]
public static void PlayerControlFixedUpdatePostfix(PlayerControl __instance)
@@ -74,4 +78,15 @@ public static class PlayerControlPatches
button.FixedUpdateHandler(__instance);
}
}
/// <summary>
/// Clear from modifier component cache.
/// </summary>
/// <param name="__instance">PlayerControl instance.</param>
[HarmonyPrefix]
[HarmonyPatch(nameof(PlayerControl.OnDestroy))]
public static void PlayerControlOnDestroyPrefix(PlayerControl __instance)
{
Utilities.Extensions.ModifierComponents.Remove(__instance);
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ public static class GameStartupPatch
private static bool _runOnce;
/// <summary>
/// This is used for registering roles when the game opens, might be a janky solution, but it works
/// This is used for registering roles when the game opens, might be a janky solution, but it works.
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(nameof(MainMenuManager.Start))]
+8 -4
View File
@@ -17,6 +17,10 @@ public static class HudManagerPatches
/// <summary>
/// Fixes Kill Button not showing for Neutral killing role.
/// </summary>
/// <param name="__instance">HudManager instance.</param>
/// <param name="localPlayer">The local PlayerControl.</param>
/// <param name="role">The player's RoleBehaviour.</param>
/// <param name="isActive">Whether the Hud should be set active or not.</param>
[HarmonyPostfix]
[HarmonyPatch(nameof(HudManager.SetHudActive), typeof(PlayerControl), typeof(RoleBehaviour), typeof(bool))]
public static void SetHudActivePostfix(
@@ -29,9 +33,9 @@ public static class HudManagerPatches
if (role is ICustomRole customRole)
{
__instance.KillButton.ToggleVisible(isActive && role.CanUseKillButton && !flag);
__instance.ImpostorVentButton.ToggleVisible(isActive && role.CanVent && !flag);
__instance.SabotageButton.gameObject.SetActive(isActive && customRole.CanUseSabotage);
__instance.KillButton.ToggleVisible(isActive && customRole.Configuration.UseVanillaKillButton && !flag);
__instance.ImpostorVentButton.ToggleVisible(isActive && customRole.Configuration.CanUseVent && !flag);
__instance.SabotageButton.gameObject.SetActive(isActive && customRole.Configuration.CanUseSabotage);
}
if (_roleTab)
@@ -56,7 +60,7 @@ public static class HudManagerPatches
var role = local?.Data?.Role;
if (role is ICustomRole { RoleHintType: RoleHintType.RoleTab } customRole)
if (role is ICustomRole { Configuration.RoleHintType: RoleHintType.RoleTab } customRole)
{
customRole.HudUpdate(__instance);
+1 -6
View File
@@ -36,7 +36,7 @@ public static class KillButtonPatches
__instance.currentTarget = target;
if (__instance.currentTarget)
{
__instance.currentTarget.cosmetics.SetOutline(true, new Nullable<Color>(customRole.KillButtonOutlineColor));
__instance.currentTarget.cosmetics.SetOutline(true, new Nullable<Color>(customRole.Configuration.KillButtonOutlineColor));
__instance.SetEnabled();
return false;
}
@@ -52,11 +52,6 @@ public static class KillButtonPatches
[HarmonyPatch(nameof(KillButton.DoClick))]
public static bool DoClickPrefix(KillButton __instance)
{
if (PlayerControl.LocalPlayer.Data.Role is not ICustomRole)
{
return true;
}
if (!__instance.isActiveAndEnabled || !__instance.currentTarget || __instance.isCoolingDown ||
PlayerControl.LocalPlayer.Data.IsDead || !PlayerControl.LocalPlayer.CanMove)
{
+1 -1
View File
@@ -4,7 +4,7 @@ using UnityEngine;
namespace MiraAPI.Patches.Roles;
/// <summary>
/// Set nametag color depending on option
/// Set nametag color depending on option.
/// </summary>
[HarmonyPatch(typeof(PlayerNameColor))]
public static class NameTagPatch
@@ -8,7 +8,7 @@ namespace MiraAPI.Patches.Roles;
public static class RoleBehaviourPatches
{
/// <summary>
/// Update TeamColor text for Launchpad roles
/// Update TeamColor text for custom roles.
/// </summary>
[HarmonyPrefix]
[HarmonyPatch(nameof(RoleBehaviour.TeamColor), MethodType.Getter)]
+4 -4
View File
@@ -1,8 +1,8 @@
using AmongUs.GameOptions;
using System.Linq;
using AmongUs.GameOptions;
using HarmonyLib;
using MiraAPI.Modifiers;
using MiraAPI.Roles;
using System.Linq;
namespace MiraAPI.Patches.Roles;
@@ -37,12 +37,12 @@ public static class RoleManagerPatches
return true;
}
if (role.GhostRole is RoleTypes.CrewmateGhost or RoleTypes.ImpostorGhost)
if (role.Configuration.GhostRole is RoleTypes.CrewmateGhost or RoleTypes.ImpostorGhost)
{
return true;
}
plr.RpcSetRole(role.GhostRole);
plr.RpcSetRole(role.Configuration.GhostRole);
return false;
}
}
@@ -1,55 +1,73 @@
using AmongUs.GameOptions;
using HarmonyLib;
using MiraAPI.Roles;
using Reactor.Utilities;
namespace MiraAPI.Patches.Roles;
/// <summary>
/// Patches to return the correct role counts.
/// </summary>
[HarmonyPatch(typeof(RoleOptionsCollectionV08))]
public static class RoleOptionsCollectionPatch
{
/// <summary>
/// Set the role chance for custom Launchpad roles based on config
/// Set the role chance for custom Launchpad roles based on config.
/// </summary>
/// <returns>Return false to skip original method, true to not.</returns>
[HarmonyPrefix]
[HarmonyPatch(nameof(RoleOptionsCollectionV08.GetChancePerGame))]
public static bool GetChancePrefix([HarmonyArgument(0)] RoleTypes roleType, ref int __result)
public static bool GetChancePrefix(RoleTypes role, ref int __result)
{
if (!CustomRoleManager.GetCustomRoleBehaviour(roleType, out var customRole) || customRole == null)
if (!CustomRoleManager.GetCustomRoleBehaviour(role, out var customRole) || customRole == null)
{
return true;
}
if (customRole.HideSettings)
if (customRole.Configuration.HideSettings)
{
__result = 0;
return false;
}
customRole.ParentMod.PluginConfig.TryGetEntry<int>(customRole.ChanceConfigDefinition, out var entry);
__result = entry.Value;
var chance = customRole.GetChance();
if (chance == null)
{
Logger<MiraApiPlugin>.Error($"Chance is null, defaulting to zero.");
chance = 0;
}
__result = chance.Value;
return false;
}
/// <summary>
/// Set the amount for custom Launchpad roles based on config
/// Set the amount for custom Launchpad roles based on config.
/// </summary>
/// <returns>Return false to skip original method, true to not.</returns>
[HarmonyPrefix]
[HarmonyPatch(nameof(RoleOptionsCollectionV08.GetNumPerGame))]
public static bool GetNumPrefix([HarmonyArgument(0)] RoleTypes roleType, ref int __result)
public static bool GetNumPrefix(RoleTypes role, ref int __result)
{
if (!CustomRoleManager.GetCustomRoleBehaviour(roleType, out var customRole) || customRole == null)
if (!CustomRoleManager.GetCustomRoleBehaviour(role, out var customRole) || customRole == null)
{
return true;
}
if (customRole.HideSettings)
if (customRole.Configuration.HideSettings)
{
__result = 0;
return false;
}
customRole.ParentMod.PluginConfig.TryGetEntry<int>(customRole.NumConfigDefinition, out var entry);
__result = entry.Value;
var count = customRole.GetCount();
if (count == null)
{
Logger<MiraApiPlugin>.Error($"Count is null, defaulting to zero.");
count = 0;
}
__result = count.Value;
return false;
}
}
+4 -4
View File
@@ -4,7 +4,7 @@ using MiraAPI.Roles;
namespace MiraAPI.Patches.Roles;
[HarmonyPatch(typeof(SabotageButton))]
public class SabotageButtonPatch
public static class SabotageButtonPatch
{
/// <summary>
/// Patches the Sabotage button to check if the player's custom role can use sabotage.
@@ -20,12 +20,12 @@ public class SabotageButtonPatch
return true;
}
if (!customRole.CanUseSabotage || PlayerControl.LocalPlayer.inVent || !GameManager.Instance.SabotagesEnabled())
if (!customRole.Configuration.CanUseSabotage || PlayerControl.LocalPlayer.inVent || !GameManager.Instance.SabotagesEnabled())
{
return false;
}
DestroyableSingleton<HudManager>.Instance.ToggleMapVisible(
HudManager.Instance.ToggleMapVisible(
new MapOptions
{
Mode = MapOptions.Modes.Sabotage,
@@ -52,7 +52,7 @@ public class SabotageButtonPatch
if (player.inVent || !GameManager.Instance.SabotagesEnabled() || player.petting)
{
__instance.ToggleVisible(customRole.CanUseSabotage && GameManager.Instance.SabotagesEnabled());
__instance.ToggleVisible(customRole.Configuration.CanUseSabotage && GameManager.Instance.SabotagesEnabled());
__instance.SetDisabled();
return false;
}
+21 -25
View File
@@ -1,21 +1,24 @@
using AmongUs.GameOptions;
using System;
using System.Collections.Generic;
using System.Linq;
using AmongUs.GameOptions;
using HarmonyLib;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using MiraAPI.Utilities.Assets;
using System.Linq;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Roles;
/// <summary>
/// Patch TaskAdder for organizing Roles and adding scroller.
/// </summary>
[HarmonyPatch]
public static class TaskAdderPatch
{
private static readonly System.Collections.Generic.Dictionary<string, string> ModsFolders = [];
private static readonly Dictionary<string, string> ModsFolders = [];
private static Scroller? _scroller;
[HarmonyPostfix]
@@ -167,19 +170,14 @@ public static class TaskAdderPatch
ControllerManager.Instance.AddSelectableUiElement(taskFolder2.Button);
if (!string.IsNullOrEmpty(__instance.restorePreviousSelectionByFolderName) &&
taskFolder2.FolderName.Equals(__instance.restorePreviousSelectionByFolderName, System.StringComparison.Ordinal))
taskFolder2.FolderName.Equals(__instance.restorePreviousSelectionByFolderName, StringComparison.Ordinal))
{
__instance.restorePreviousSelectionFound = taskFolder2.Button;
}
}
var flag = false;
var list = new List<PlayerTask>();
foreach (var item in taskFolder.Children)
{
list.Add(item);
}
var list = taskFolder.Children.ToArray().OrderBy(t => t.TaskType).ToList();
for (var l = 0; l < list.Count; l++)
{
@@ -190,26 +188,24 @@ public static class TaskAdderPatch
case TaskTypes.DivertPower:
{
var targetSystem = taskAddButton.MyTask.Cast<DivertPowerTask>().TargetSystem;
taskAddButton.Text.text = DestroyableSingleton<TranslationController>.Instance.GetString(
taskAddButton.Text.text = TranslationController.Instance.GetString(
StringNames.DivertPowerTo,
DestroyableSingleton<TranslationController>.Instance.GetString(targetSystem));
TranslationController.Instance.GetString(targetSystem));
break;
}
case TaskTypes.FixWeatherNode:
{
var nodeId = ((WeatherNodeTask)taskAddButton.MyTask).NodeId;
var nodeId = taskAddButton.MyTask.Cast<WeatherNodeTask>().NodeId;
taskAddButton.Text.text =
DestroyableSingleton<TranslationController>.Instance.GetString(
StringNames.FixWeatherNode,
Array.Empty<Il2CppSystem.Object>()) + " " +
DestroyableSingleton<TranslationController>.Instance.GetString(
WeatherSwitchGame.ControlNames[nodeId],
Array.Empty<Il2CppSystem.Object>());
TranslationController.Instance.GetString(
StringNames.FixWeatherNode) + " " +
TranslationController.Instance.GetString(
WeatherSwitchGame.ControlNames[nodeId]);
break;
}
default:
taskAddButton.Text.text =
DestroyableSingleton<TranslationController>.Instance.GetString(taskAddButton.MyTask.TaskType);
TranslationController.Instance.GetString(taskAddButton.MyTask.TaskType);
break;
}
@@ -238,9 +234,9 @@ public static class TaskAdderPatch
if (taskFolder.FolderName == "Roles")
{
for (var m = 0; m < DestroyableSingleton<RoleManager>.Instance.AllRoles.Length; m++)
for (var m = 0; m < RoleManager.Instance.AllRoles.Length; m++)
{
var roleBehaviour = DestroyableSingleton<RoleManager>.Instance.AllRoles[m];
var roleBehaviour = RoleManager.Instance.AllRoles[m];
if (roleBehaviour.Role == RoleTypes.ImpostorGhost || roleBehaviour.Role == RoleTypes.CrewmateGhost ||
CustomRoleManager.CustomRoles.ContainsKey((ushort)roleBehaviour.Role))
{
@@ -275,7 +271,7 @@ public static class TaskAdderPatch
if (ModsFolders.TryGetValue(taskFolder.FolderName, out var guid))
{
var plugin = MiraPluginManager.Instance.GetPluginByGuid(guid);
var plugin = MiraPluginManager.GetPluginByGuid(guid);
for (var m = 0; m < plugin.CustomRoles.Count; m++)
{
var roleBehaviour = plugin.CustomRoles.ElementAt(m).Value;
@@ -6,12 +6,17 @@ using UnityEngine;
namespace MiraAPI.Patches.Roles;
/// <summary>
/// Set vent outline color based on the player's role.
/// Vent patches for Roles.
/// </summary>
[HarmonyPatch(typeof(Vent), nameof(Vent.SetOutline))]
public static class VentOutlinePatch
[HarmonyPatch(typeof(Vent))]
public static class VentPatches
{
public static void Postfix(Vent __instance, bool on, bool mainTarget)
/// <summary>
/// Set outline to player's custom role color.
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(nameof(Vent.SetOutline))]
public static void SetOutlinePostfix(Vent __instance, bool on, bool mainTarget)
{
if (PlayerControl.LocalPlayer.Data.Role is not ICustomRole customRole)
{
+24
View File
@@ -0,0 +1,24 @@
using System.Runtime.CompilerServices;
using HarmonyLib;
namespace MiraAPI.Patches.Stubs;
/// <summary>
/// Reverse patches for Minigames.
/// </summary>
[HarmonyPatch]
public static class MinigameStubs
{
/// <summary>
/// Reverse patch for Minigame.Begin.
/// </summary>
/// <param name="instance">The Minigame instance.</param>
/// <param name="task">Associated PlayerTask.</param>
[HarmonyReversePatch]
[HarmonyPatch(typeof(Minigame), nameof(Minigame.Begin))]
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Begin(Minigame instance, PlayerTask? task)
{
// nothing needed
}
}
+55
View File
@@ -0,0 +1,55 @@
using System.Linq;
using HarmonyLib;
using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI.Patches;
/// <summary>
/// Vent patches to make sure the player is able to use the vent.
/// </summary>
[HarmonyPatch(typeof(Vent))]
public static class VentPatches
{
/// <summary>
/// CanUse patch.
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(nameof(Vent.CanUse))]
public static void VentCanUsePostfix(Vent __instance, ref float __result, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] ref bool canUse, [HarmonyArgument(2)] ref bool couldUse)
{
var @object = pc.Object;
var role = @object.Data.Role;
var canVent = role is ICustomRole customRole ? customRole.Configuration.CanUseVent : role.CanVent;
couldUse = canVent;
var modifiers = @object.GetModifierComponent()?.ActiveModifiers;
if (modifiers is { Count: > 0 })
{
switch (canVent)
{
case true when modifiers.Exists(x => x.CanVent().HasValue && x.CanVent()==false):
couldUse = canUse = false;
return;
case false when modifiers.Exists(x => x.CanVent().HasValue && x.CanVent()==true):
couldUse = true;
break;
}
}
var num = float.MaxValue;
canUse = couldUse;
if (canUse)
{
var center = @object.Collider.bounds.center;
var position = __instance.transform.position;
num = Vector2.Distance(center, position);
canUse &= num <= __instance.UsableDistance && !PhysicsHelpers.AnythingBetween(@object.Collider, center, position, Constants.ShipOnlyMask, false);
}
__result = num;
}
}
+53 -2
View File
@@ -1,8 +1,10 @@
using BepInEx;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using BepInEx;
using BepInEx.Configuration;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using System.Collections.Generic;
using MiraAPI.Hud;
namespace MiraAPI.PluginLoading;
@@ -19,14 +21,63 @@ public class MiraPluginInfo
PluginId = info.Metadata.GUID;
}
/// <summary>
/// Get a read only collection of this plugin's Option Groups.
/// </summary>
/// <returns>Readonly collection of option groups.</returns>
public IReadOnlyCollection<AbstractOptionGroup> GetOptionGroups()
{
return OptionGroups.AsReadOnly();
}
/// <summary>
/// Gets a read only collection of this plugin's options.
/// </summary>
/// <returns>Read only collection of options.</returns>
public IReadOnlyCollection<IModdedOption> GetOptions()
{
return Options.AsReadOnly();
}
/// <summary>
/// Gets a read only dictionary of Role IDs and the RoleBehaviour object they are associated with.
/// </summary>
/// <returns>Read only dictionary of IDs and Roles.</returns>
public ReadOnlyDictionary<ushort, RoleBehaviour> GetRoles()
{
return new ReadOnlyDictionary<ushort, RoleBehaviour>(CustomRoles);
}
/// <summary>
/// Gets a read only collection of this plugin's custom buttons.
/// </summary>
/// <returns>Read only collection of buttons.</returns>
public IReadOnlyCollection<CustomActionButton> GetButtons()
{
return Buttons.AsReadOnly();
}
/// <summary>
/// Gets a read only collection of this plugin's custom buttons.
/// </summary>
/// <returns>Read only collection of buttons.</returns>
public IReadOnlyCollection<Cosmetics.AbstractCosmeticsGroup> GetCosmetics()
{
return CosmeticGroups.AsReadOnly();
}
internal List<AbstractOptionGroup> OptionGroups { get; } = [];
internal List<IModdedOption> Options { get; } = [];
internal List<Cosmetics.AbstractCosmeticsGroup> CosmeticGroups { get; } = [];
internal Dictionary<ushort, RoleBehaviour> CustomRoles { get; } = [];
internal Dictionary<int, CustomGameMode> GameModes { get; } = [];
internal List<CustomActionButton> Buttons { get; } = [];
/// <summary>
/// Gets the plugin's ID, as defined in the plugin's BepInEx metadata.
/// </summary>
+42 -7
View File
@@ -4,6 +4,7 @@ using System.Linq;
using System.Reflection;
using BepInEx.Unity.IL2CPP;
using MiraAPI.Colors;
using MiraAPI.Cosmetics;
using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.Hud;
@@ -15,17 +16,21 @@ using Reactor.Utilities;
namespace MiraAPI.PluginLoading;
internal sealed class MiraPluginManager
/// <summary>
/// Mira Plugin manager.
/// </summary>
public sealed class MiraPluginManager
{
private readonly Dictionary<Assembly, MiraPluginInfo> _registeredPlugins = [];
internal MiraPluginInfo[] RegisteredPlugins() => [.. _registeredPlugins.Values];
public static MiraPluginManager Instance { get; private set; } = new();
internal static MiraPluginManager Instance { get; private set; } = new();
internal void Initialize()
{
Instance = this;
CustomCosmeticManager.RegisterVanilla();
IL2CPPChainloader.Instance.PluginLoad += (pluginInfo, assembly, plugin) =>
{
if (plugin is not IMiraPlugin miraPlugin)
@@ -37,9 +42,10 @@ internal sealed class MiraPluginManager
RegisterModifierAttribute(assembly);
RegisterAllOptions(assembly, info);
RegisterAllCosmetics(assembly, info);
RegisterRoleAttribute(assembly, info);
RegisterButtonAttribute(assembly);
RegisterButtonAttribute(assembly, info);
RegisterColorClasses(assembly);
@@ -50,9 +56,14 @@ internal sealed class MiraPluginManager
IL2CPPChainloader.Instance.Finished += PaletteManager.RegisterAllColors;
}
public MiraPluginInfo GetPluginByGuid(string guid)
/// <summary>
/// Get a mira plugin by its GUID.
/// </summary>
/// <param name="uniqueId">The plugin GUID.</param>
/// <returns>A MiraPluginInfo.</returns>
public static MiraPluginInfo GetPluginByGuid(string uniqueId)
{
return _registeredPlugins.Values.First(plugin => plugin.PluginId == guid);
return Instance._registeredPlugins.Values.First(plugin => plugin.PluginId == uniqueId);
}
private static void RegisterAllOptions(Assembly assembly, MiraPluginInfo pluginInfo)
@@ -87,6 +98,30 @@ internal sealed class MiraPluginManager
pluginInfo.OptionGroups.Sort((x, y) => x.GroupPriority.CompareTo(y.GroupPriority));
}
private static void RegisterAllCosmetics(Assembly assembly, MiraPluginInfo pluginInfo)
{
var filteredTypes = assembly.GetTypes().Where(type => type.IsAssignableTo(typeof(AbstractCosmeticsGroup)));
foreach (var type in filteredTypes)
{
if (!CustomCosmeticManager.RegisterGroup(type, pluginInfo))
{
continue;
}
foreach (var property in type.GetProperties())
{
var attribute = property.GetCustomAttribute<RegisterCustomCosmeticAttribute>();
if (attribute == null)
{
continue;
}
CustomCosmeticManager.RegisterAttributeOption(type, attribute, property, pluginInfo);
}
}
}
private static void RegisterRoleAttribute(Assembly assembly, MiraPluginInfo pluginInfo)
{
List<Type> roles = [];
@@ -161,14 +196,14 @@ internal sealed class MiraPluginManager
}
}
private static void RegisterButtonAttribute(Assembly assembly)
private static void RegisterButtonAttribute(Assembly assembly, MiraPluginInfo pluginInfo)
{
foreach (var type in assembly.GetTypes())
{
var attribute = type.GetCustomAttribute<RegisterButtonAttribute>();
if (attribute != null)
{
CustomButtonManager.RegisterButton(type);
CustomButtonManager.RegisterButton(type, pluginInfo);
}
}
}
+130
View File
@@ -0,0 +1,130 @@
using AmongUs.GameOptions;
using MiraAPI.Utilities.Assets;
using UnityEngine;
namespace MiraAPI.Roles;
/// <summary>
/// Used to configure the specific settings of a role.
/// </summary>
public struct CustomRoleConfiguration
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomRoleConfiguration"/> struct.
/// </summary>
/// <param name="role">The role in which you are configuring.</param>
public CustomRoleConfiguration(ICustomRole role)
{
MaxRoleCount = 15;
DefaultRoleCount = 0;
DefaultChance = 0;
OptionsScreenshot = Icon = MiraAssets.Empty;
AffectedByLightOnAirship = role.Team == ModdedRoleTeams.Crewmate;
KillButtonOutlineColor = role.Team switch
{
ModdedRoleTeams.Impostor => Palette.ImpostorRed,
ModdedRoleTeams.Crewmate => Palette.CrewmateBlue,
_ => role.RoleColor,
};
RoleHintType = RoleHintType.RoleTab;
GhostRole = role.Team is ModdedRoleTeams.Impostor ? RoleTypes.ImpostorGhost : RoleTypes.CrewmateGhost;
CanGetKilled = !IsGhostRole && role.Team is not ModdedRoleTeams.Impostor;
UseVanillaKillButton = role.Team is ModdedRoleTeams.Impostor;
CanUseVent = role.Team is ModdedRoleTeams.Impostor;
CanUseSabotage = role.Team is ModdedRoleTeams.Impostor;
TasksCountForProgress = role.Team is ModdedRoleTeams.Crewmate;
IsGhostRole = false;
HideSettings = IsGhostRole;
CanModifyChance = true;
}
#pragma warning disable S1104
#pragma warning disable CA1051
/// <summary>
/// Gets the hard limit of players that can have this role. This property is used to set a limit in the Role Options menu. If set to 0, the role will not be assigned at start.
/// </summary>
public int MaxRoleCount;
/// <summary>
/// Gets the default role count.
/// </summary>
public int DefaultRoleCount;
/// <summary>
/// Gets the default role chance.
/// </summary>
public int DefaultChance;
/// <summary>
/// Whether the chance option can be changed or not.
/// </summary>
public bool CanModifyChance;
/// <summary>
/// Gets the Sprite used for the Role Options menu screenshot.
/// </summary>
public LoadableAsset<Sprite> OptionsScreenshot;
/// <summary>
/// Gets the Sprite used for the Role Icon.
/// </summary>
public LoadableAsset<Sprite> Icon;
/// <summary>
/// Gets a value indicating whether the role is affected by light affectors on Airship.
/// </summary>
public bool AffectedByLightOnAirship;
/// <summary>
/// Gets a value indicating whether the role can be killed by vanilla murder system.
/// </summary>
public bool CanGetKilled;
/// <summary>
/// Gets a value indicating whether the role should use the vanilla kill button.
/// </summary>
public bool UseVanillaKillButton;
/// <summary>
/// Gets a value indicating whether the role can use vents.
/// </summary>
public bool CanUseVent;
/// <summary>
/// Gets a value indicating whether the role can use the sabotage button.
/// </summary>
public bool CanUseSabotage;
/// <summary>
/// Gets a value indicating whether the role's tasks count towards task progress.
/// </summary>
public bool TasksCountForProgress;
/// <summary>
/// Gets a value indicating whether the role is a Ghost.
/// </summary>
public bool IsGhostRole;
/// <summary>
/// Gets a value indicating whether the role should show up in the Role Options menu.
/// </summary>
public bool HideSettings;
/// <summary>
/// Gets the outline color for the KillButton if <see cref="UseVanillaKillButton"/> is true.
/// </summary>
public Color KillButtonOutlineColor;
/// <summary>
/// Gets the role hint style. See <see cref="RoleHintType"/> enum for all options.
/// </summary>
public RoleHintType RoleHintType;
/// <summary>
/// Gets the Ghost role that is applied when the player is killed.
/// </summary>
public RoleTypes GhostRole;
#pragma warning restore S1104
#pragma warning restore CA1051
}
+23 -30
View File
@@ -1,4 +1,7 @@
using AmongUs.GameOptions;
using System;
using System.Collections.Generic;
using System.Linq;
using AmongUs.GameOptions;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using MiraAPI.Networking;
@@ -8,9 +11,6 @@ using Reactor.Localization.Utilities;
using Reactor.Networking.Rpc;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -36,7 +36,7 @@ public static class CustomRoleManager
{
RoleManager.Instance.AllRoles = RoleManager.Instance.AllRoles.Concat(CustomRoles.Values).ToArray();
foreach (var role in CustomRoles.Values.Where(x=>x.IsDead))
foreach (var role in CustomRoles.Values.Where(x => x.IsDead))
{
RoleManager.GhostRoles.Add(role.Role);
}
@@ -84,21 +84,21 @@ public static class CustomRoleManager
roleBehaviour.StringName = CustomStringName.CreateAndRegister(customRole.RoleName);
roleBehaviour.BlurbName = CustomStringName.CreateAndRegister(customRole.RoleDescription);
roleBehaviour.BlurbNameLong = CustomStringName.CreateAndRegister(customRole.RoleLongDescription);
roleBehaviour.AffectedByLightAffectors = customRole.AffectedByLightOnAirship;
roleBehaviour.CanBeKilled = customRole.CanGetKilled;
roleBehaviour.CanUseKillButton = customRole.UseVanillaKillButton;
roleBehaviour.TasksCountTowardProgress = customRole.TasksCountForProgress;
roleBehaviour.CanVent = customRole.CanUseVent;
roleBehaviour.DefaultGhostRole = customRole.GhostRole;
roleBehaviour.MaxCount = customRole.MaxPlayers;
roleBehaviour.RoleScreenshot = customRole.OptionsScreenshot.LoadAsset();
roleBehaviour.AffectedByLightAffectors = customRole.Configuration.AffectedByLightOnAirship;
roleBehaviour.CanBeKilled = customRole.Configuration.CanGetKilled;
roleBehaviour.CanUseKillButton = customRole.Configuration.UseVanillaKillButton;
roleBehaviour.TasksCountTowardProgress = customRole.Configuration.TasksCountForProgress;
roleBehaviour.CanVent = customRole.Configuration.CanUseVent;
roleBehaviour.DefaultGhostRole = customRole.Configuration.GhostRole;
roleBehaviour.MaxCount = customRole.Configuration.MaxRoleCount;
roleBehaviour.RoleScreenshot = customRole.Configuration.OptionsScreenshot.LoadAsset();
if (customRole.IsGhostRole)
if (customRole.Configuration.IsGhostRole)
{
RoleManager.GhostRoles.Add(roleBehaviour.Role);
}
var useTaskHint = customRole.RoleHintType is RoleHintType.TaskHint;
var useTaskHint = customRole.Configuration.RoleHintType is RoleHintType.TaskHint;
var overridesTaskText = customRole.GetType().GetMethod("SpawnTaskHeader")?.DeclaringType == customRole.GetType();
if (useTaskHint && !overridesTaskText)
@@ -108,14 +108,14 @@ public static class CustomRoleManager
CustomRoles.Add(roleId, roleBehaviour);
if (customRole.HideSettings)
if (customRole.Configuration.HideSettings)
{
return roleBehaviour;
}
var config = parentMod.PluginConfig;
config.Bind(customRole.NumConfigDefinition, 1);
config.Bind(customRole.ChanceConfigDefinition, 100);
config.Bind(customRole.NumConfigDefinition, Mathf.Clamp(customRole.Configuration.DefaultRoleCount, 0, customRole.Configuration.MaxRoleCount));
config.Bind(customRole.ChanceConfigDefinition, Mathf.Clamp(customRole.Configuration.DefaultChance, 0, 100));
return roleBehaviour;
}
@@ -186,7 +186,7 @@ public static class CustomRoleManager
internal static void SyncAllRoleSettings(int targetId = -1)
{
var data = CustomRoles.Values
.Where(x => x is ICustomRole { HideSettings: false })
.Where(x => x is ICustomRole { Configuration.HideSettings: false })
.Select(x => ((ICustomRole)x).GetNetData())
.ChunkNetData(1000);
@@ -216,7 +216,7 @@ public static class CustomRoleManager
}
var customRole = role as ICustomRole;
if (customRole is null or { HideSettings: true })
if (customRole is null or { Configuration.HideSettings: true })
{
continue;
}
@@ -224,19 +224,12 @@ public static class CustomRoleManager
var num = BitConverter.ToInt32(netData.Data, 0);
var chance = BitConverter.ToInt32(netData.Data, 4);
DestroyableSingleton<HudManager>.Instance.Notifier.AddRoleSettingsChangeMessage(role.StringName, num, chance, role.TeamType, false);
HudManager.Instance.Notifier.AddRoleSettingsChangeMessage(role.StringName, num, chance, role.TeamType, false);
try
{
customRole.ParentMod.PluginConfig.TryGetEntry<int>(
customRole.NumConfigDefinition,
out var numEntry);
customRole.ParentMod.PluginConfig.TryGetEntry<int>(
customRole.ChanceConfigDefinition,
out var chanceEntry);
numEntry.Value = num;
chanceEntry.Value = chance;
customRole.SetCount(num);
customRole.SetChance(chance);
}
catch (Exception e)
{
+19
View File
@@ -0,0 +1,19 @@
using System.Linq;
namespace MiraAPI.Roles;
/// <summary>
/// A utility class to get the instance of a custom role.
/// </summary>
/// <typeparam name="T">The role you are trying to access.</typeparam>
public static class CustomRoleSingleton<T> where T : ICustomRole
{
private static T? _instance;
/// <summary>
/// Gets the instance of the role.
/// </summary>
#pragma warning disable CA1000
public static ICustomRole Instance => _instance ??= CustomRoleManager.CustomRoles.Values.OfType<T>().Single();
#pragma warning restore CA1000
}
+75 -87
View File
@@ -1,11 +1,9 @@
using System.Text;
using AmongUs.GameOptions;
using BepInEx.Configuration;
using Il2CppInterop.Runtime.Attributes;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI.Roles;
@@ -41,91 +39,9 @@ public interface ICustomRole
ModdedRoleTeams Team { get; }
/// <summary>
/// Gets the hard limit of players that can have this role. This property is used to set a limit in the Role Options menu.
/// Gets the advanced settings of the role.
/// </summary>
int MaxPlayers => 15;
/// <summary>
/// Gets the Sprite used for the Role Options menu screenshot.
/// </summary>
[HideFromIl2Cpp]
LoadableAsset<Sprite> OptionsScreenshot => MiraAssets.Empty;
/// <summary>
/// Gets the Sprite used for the Role Icon.
/// </summary>
[HideFromIl2Cpp]
LoadableAsset<Sprite> Icon => MiraAssets.Empty;
/// <summary>
/// Gets a value indicating whether the role is affected by light affectors on Airship.
/// </summary>
bool AffectedByLightOnAirship => Team == ModdedRoleTeams.Crewmate;
/// <summary>
/// Gets a value indicating whether the role can be killed by vanilla murder system.
/// </summary>
bool CanGetKilled => Team == ModdedRoleTeams.Crewmate;
/// <summary>
/// Gets a value indicating whether the role should use the vanilla kill button.
/// </summary>
bool UseVanillaKillButton => Team == ModdedRoleTeams.Impostor;
/// <summary>
/// Gets a value indicating whether the role can use vents.
/// </summary>
bool CanUseVent => Team == ModdedRoleTeams.Impostor;
/// <summary>
/// Gets a value indicating whether the role can use the sabotage button.
/// </summary>
bool CanUseSabotage => Team == ModdedRoleTeams.Impostor;
/// <summary>
/// Gets a value indicating whether the role's tasks count towards task progress.
/// </summary>
bool TasksCountForProgress => Team == ModdedRoleTeams.Crewmate;
/// <summary>
/// Gets a value indicating whether the role is a Ghost.
/// </summary>
bool IsGhostRole => false;
/// <summary>
/// Gets a value indicating whether the role should show up in the Role Options menu.
/// </summary>
bool HideSettings => IsGhostRole;
/// <summary>
/// Gets the outline color for the KillButton if <see cref="UseVanillaKillButton"/> is true.
/// </summary>
Color KillButtonOutlineColor => Team switch
{
ModdedRoleTeams.Impostor => Palette.ImpostorRed,
ModdedRoleTeams.Crewmate => Palette.CrewmateBlue,
_ => RoleColor,
};
/// <summary>
/// Gets the role hint style. See <see cref="RoleHintType"/> enum for all options.
/// </summary>
RoleHintType RoleHintType => RoleHintType.RoleTab;
/// <summary>
/// Gets the Ghost role that is applied when the player is killed.
/// </summary>
RoleTypes GhostRole => Team == ModdedRoleTeams.Impostor ? RoleTypes.ImpostorGhost : RoleTypes.CrewmateGhost;
/// <summary>
/// Gets the BepInEx ConfigDefinition for the amount of players that can have this role.
/// </summary>
ConfigDefinition NumConfigDefinition => new("Roles", $"Num {GetType().FullName}");
/// <summary>
/// Gets the BepInEx ConfigDefinition for the chance of this role being selected.
/// </summary>
ConfigDefinition ChanceConfigDefinition => new("Roles", $"Chance {GetType().FullName}");
CustomRoleConfiguration Configuration { get; }
/// <summary>
/// Gets the parent mod of this role.
@@ -140,6 +56,78 @@ public interface ICustomRole
{
}
internal ConfigDefinition NumConfigDefinition => new("Roles", $"Num {GetType().FullName}");
internal ConfigDefinition ChanceConfigDefinition => new("Roles", $"Chance {GetType().FullName}");
/// <summary>
/// Gets the role chance option.
/// </summary>
/// <returns>The role chance option.</returns>
public int? GetChance()
{
if (!Configuration.CanModifyChance)
{
return Configuration.DefaultChance;
}
if (ParentMod.PluginConfig.TryGetEntry(ChanceConfigDefinition, out ConfigEntry<int> entry))
{
return Mathf.Clamp(entry.Value, 0, 100);
}
return null;
}
/// <summary>
/// Gets the role count option.
/// </summary>
/// <returns>The role count option.</returns>
public int? GetCount()
{
if (ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry<int> entry))
{
return Mathf.Clamp(entry.Value, 0, Configuration.MaxRoleCount);
}
return null;
}
/// <summary>
/// Sets the role chance option.
/// </summary>
/// <param name="chance">The chance between 0 and 100.</param>
public void SetChance(int chance)
{
if (!Configuration.CanModifyChance)
{
Logger<MiraApiPlugin>.Error($"Cannot modify chance for role: {RoleName}");
return;
}
if (ParentMod.PluginConfig.TryGetEntry(ChanceConfigDefinition, out ConfigEntry<int> entry))
{
entry.Value = Mathf.Clamp(chance, 0, 100);
return;
}
Logger<MiraApiPlugin>.Error($"Error getting chance configuration for role: {RoleName}");
}
/// <summary>
/// Sets the role count option.
/// </summary>
/// <param name="count">The amount of this role between zero and its MaxRoleCount in the Configuration.</param>
public void SetCount(int count)
{
if (ParentMod.PluginConfig.TryGetEntry(NumConfigDefinition, out ConfigEntry<int> entry))
{
entry.Value = Mathf.Clamp(count, 0, Configuration.MaxRoleCount);
return;
}
Logger<MiraApiPlugin>.Error($"Error getting count configuration for role: {RoleName}");
}
/// <summary>
/// This method runs on the HudManager.Update method ONLY when the LOCAL player has this role.
/// </summary>
+1 -1
View File
@@ -16,7 +16,7 @@ public enum RoleHintType
TaskHint,
/// <summary>
/// Use custom role tab.
/// Use Mira's custom role tab.
/// </summary>
RoleTab,
}
@@ -0,0 +1,52 @@
using System.Collections;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using Reactor.Utilities;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Utilities.Assets.Addressable;
/// <summary>
/// Catalogs are a representation of resource locators for the Unity Addressables api.
/// </summary>
public class Catalog(string CatalogPath)
{
/// <summary>
/// Loads the catalog asynchronously.
/// </summary>
public void LoadCatalogAsync()
{
Coroutines.Start(LoadCatalogAsynchronously());
}
/// <summary>
/// Loads the catalog. This must be done before you can call any addressables.
/// </summary>
public void LoadCatalog()
{
Addressables.LoadContentCatalog(CatalogPath).WaitForCompletion();
}
/// <summary>
/// Updates the network catalogs.
/// </summary>
public void UpdateNetworkCatalog()
{
Coroutines.Start(UpdateCatalog());
}
protected IEnumerator LoadCatalogAsynchronously()
{
AsyncOperationHandle<IResourceLocator> handle = Addressables.LoadContentCatalogAsync(CatalogPath, true);
yield return handle;
}
protected IEnumerator UpdateCatalog()
{
string[] toUpdate = { CatalogPath };
var catalogs = toUpdate.WrapToIl2Cpp().Cast<Il2CppSystem.Collections.Generic.IEnumerable<string>>();
var updateHandle = Addressables.UpdateCatalogs(catalogs);
yield return updateHandle;
updateHandle.Release();
}
}
@@ -0,0 +1,42 @@
using System.IO;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using UnityEngine.AddressableAssets;
namespace MiraAPI.Utilities.Assets.Addressable;
/// <summary>
/// A utility class for various catalog-related operations.
/// </summary>
public static class CatalogTools
{
/// <summary>
/// Converts string filenames to catalog paths within the plugins folder.
/// </summary>
/// <param name="fileName">A string of the catalog file without the extension.</param>
/// <returns>The path to the catalog file.</returns>
public static string ToLocalPath(this string fileName)
{
return Path.GetDirectoryName(typeof(MiraApiPlugin).Assembly.Location) + $"\\{fileName}.catalog";
}
/// <summary>
/// Finds the resource locations of a specific label.
/// </summary>
/// <param name="label">The label of the addressables assets.</param>
/// <returns>An IList of IResourceLocation.</returns>
public static Il2CppSystem.Collections.Generic.IList<UnityEngine.ResourceManagement.ResourceLocations.IResourceLocation> GetResourceLocation(string label)
{
return Addressables.LoadResourceLocationsAsync(label).WaitForCompletion();
}
/// <summary>
/// Finds the resource locations of multiple specific labels.
/// </summary>
/// <param name="labels">The label of the addressables assets.</param>
/// <returns>An IList of IResourceLocation.</returns>
public static Il2CppSystem.Collections.Generic.IList<UnityEngine.ResourceManagement.ResourceLocations.IResourceLocation> GetResourceLocations(string[] labels)
{
var il2CPPLabels = new Il2CppSystem.Collections.Generic.IList<Il2CppSystem.Object>(labels.WrapToIl2Cpp().Pointer);
return Addressables.LoadResourceLocationsAsync(il2CPPLabels, Addressables.MergeMode.Union).WaitForCompletion();
}
}
@@ -0,0 +1,21 @@
using System.Collections;
using UnityEngine;
using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Utilities.Assets.Addressable;
/// <summary>
/// An IEnumerator for awaiting an AsyncOperationHandle.
/// </summary>.
/// <param name="handle">The AsyncOperationHandle being awaited.</param>
public class WaitForAsyncOperationHandleFinish(AsyncOperationHandle handle) : IEnumerator
{
public object Current => null;
public bool MoveNext()
{
return !Mathf.Approximately(handle.PercentComplete, 1.0f) && !handle.IsDone;
}
public void Reset()
{
}
}
@@ -0,0 +1,34 @@
using System;
using UnityEngine.AddressableAssets;
namespace MiraAPI.Utilities.Assets;
/// <summary>
/// A utility class for loading assets from the addressables api.
/// </summary>
/// <param name="name">The name/identifier of the asset.</param>
/// <typeparam name="T">The type of the asset to be loaded.</typeparam>
public class LoadableAddressableAsset<T>(string name) : LoadableAsset<T> where T : UnityEngine.Object
{
/// <summary>
/// Loads the asset from the addressables api.
/// </summary>
/// <returns>The asset.</returns>
/// <exception cref="Exception">The asset did not load properly.</exception>
public override T LoadAsset()
{
if (LoadedAsset != null)
{
return LoadedAsset;
}
LoadedAsset = Addressables.LoadAssetAsync<T>(name).WaitForCompletion();
if (LoadedAsset == null)
{
throw new InvalidOperationException($"INVALID ASSET: {name}");
}
return LoadedAsset;
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using UnityEngine.AddressableAssets;
namespace MiraAPI.Utilities.Assets;
/// <summary>
/// A utility class for loading multiple assets from the addressables api.
/// </summary>
/// <param name="locations">A list of IResourceLocations that locate the assets.</param>
/// <typeparam name="T">The type of the assets to be loaded.</typeparam>
public class LoadableAddressableGroupAsset<T>(Il2CppSystem.Collections.Generic.IList<UnityEngine.ResourceManagement.ResourceLocations.IResourceLocation> locations) where T : UnityEngine.Object
{
/// <summary>
/// Gets or sets a reference to the loaded assets. Intended to be used for caching purposes.
/// </summary>
protected List<T> LoadedAsset { get; set; } = [];
/// <summary>
/// Loads the assets from the addressables api.
/// </summary>
/// <returns>The assets.</returns>
/// <exception cref="Exception">The asset did not load properly.</exception>
public List<T> LoadAsset()
{
if (LoadedAsset.Count != 0)
{
return LoadedAsset;
}
var assets = Addressables.LoadAssetsAsync<T>(locations, null, false).WaitForCompletion();
var array = new Il2CppSystem.Collections.Generic.List<T>(assets.Pointer);
LoadedAsset = [..array.ToArray()];
if (LoadedAsset is null || LoadedAsset.Count == 0)
{
throw new InvalidOperationException("INVALID ASSET LOCATION/s");
}
return LoadedAsset;
}
}
@@ -7,7 +7,7 @@ namespace MiraAPI.Utilities.Assets;
/// A utility class for loading assets from embedded resources.
/// </summary>
/// <param name="path">The path to the embedded resource.</param>
public class LoadableResourceAsset(string path) : LoadableAsset<Sprite>
public class LoadableResourceAsset(string path, float pixelsPerUnit=100f) : LoadableAsset<Sprite>
{
private readonly Assembly _assembly = Assembly.GetCallingAssembly();
@@ -19,6 +19,6 @@ public class LoadableResourceAsset(string path) : LoadableAsset<Sprite>
return LoadedAsset;
}
return LoadedAsset = SpriteTools.LoadSpriteFromPath(path, _assembly);
return LoadedAsset = SpriteTools.LoadSpriteFromPath(path, _assembly, pixelsPerUnit);
}
}
+2 -2
View File
@@ -39,7 +39,7 @@ public static class SpriteTools
/// <param name="resourcePath">The path to the resource.</param>
/// <returns>A sprite made from the resource.</returns>
/// <exception cref="Exception">The resource cannot be found.</exception>
public static Sprite LoadSpriteFromPath(string resourcePath, Assembly assembly)
public static Sprite LoadSpriteFromPath(string resourcePath, Assembly assembly, float pixelsPerUnit)
{
var tex = new Texture2D(1, 1, TextureFormat.ARGB32, false);
var myStream = assembly.GetManifestResourceStream(resourcePath);
@@ -53,6 +53,6 @@ public static class SpriteTools
Logger<MiraApiPlugin>.Error($"Resource not found: {resourcePath}\nReturning empty sprite!");
}
return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), pixelsPerUnit);
}
}
+56 -17
View File
@@ -19,10 +19,24 @@ public static class Extensions
{
internal static NetData GetNetData(this ICustomRole role)
{
role.ParentMod.PluginConfig.TryGetEntry<int>(role.NumConfigDefinition, out var numEntry);
role.ParentMod.PluginConfig.TryGetEntry<int>(role.ChanceConfigDefinition, out var chanceEntry);
var count = role.GetCount();
var chance = role.GetChance();
return new NetData(RoleId.Get(role.GetType()), BitConverter.GetBytes(numEntry.Value).AddRangeToArray(BitConverter.GetBytes(chanceEntry.Value)));
if (count == null)
{
Logger<MiraApiPlugin>.Error("Couldn't get role count for NetData, defaulting to zero.");
count = 0;
}
if (chance == null)
{
Logger<MiraApiPlugin>.Error("Couldn't get role chance for NetData, defaulting to zero.");
chance = 0;
}
return new NetData(
RoleId.Get(role.GetType()),
BitConverter.GetBytes(count.Value).AddRangeToArray(BitConverter.GetBytes(chance.Value)));
}
/// <summary>
@@ -112,10 +126,11 @@ public static class Extensions
/// <returns>True if the OptionBehaviour is for a custom options, false otherwise.</returns>
public static bool IsCustom(this OptionBehaviour optionBehaviour)
{
return ModdedOptionsManager.ModdedOptions.Values.Any(opt => opt.OptionBehaviour && opt.OptionBehaviour == optionBehaviour);
return ModdedOptionsManager.ModdedOptions.Values.Any(
opt => opt.OptionBehaviour && opt.OptionBehaviour == optionBehaviour);
}
private static readonly Dictionary<PlayerControl, ModifierComponent> ModifierComponents = [];
internal static Dictionary<PlayerControl, ModifierComponent> ModifierComponents { get; } = [];
/// <summary>
/// Gets the ModifierComponent for a player.
@@ -130,11 +145,12 @@ public static class Extensions
}
component = player.GetComponent<ModifierComponent>();
if (component)
if (component == null)
{
ModifierComponents[player] = component;
return null;
}
ModifierComponents[player] = component;
return component;
}
@@ -154,6 +170,7 @@ public static class Extensions
randomizedList.Add(list[index]);
list.RemoveAt(index);
}
return randomizedList;
}
@@ -176,7 +193,8 @@ public static class Extensions
/// <returns>True if the Modifier is present, false otherwise.</returns>
public static bool HasModifier<T>(this PlayerControl? player) where T : BaseModifier
{
return player?.GetModifierComponent() != null && player.GetModifierComponent()!.ActiveModifiers.Exists(x => x is T);
return player?.GetModifierComponent() != null &&
player.GetModifierComponent()!.ActiveModifiers.Exists(x => x is T);
}
/// <summary>
@@ -187,7 +205,8 @@ public static class Extensions
/// <returns>True if the Modifier is present, false otherwise.</returns>
public static bool HasModifier(this PlayerControl? player, uint id)
{
return player?.GetModifierComponent() != null && player.GetModifierComponent()!.ActiveModifiers.Exists(x => x.ModifierId == id);
return player?.GetModifierComponent() != null &&
player.GetModifierComponent()!.ActiveModifiers.Exists(x => x.ModifierId == id);
}
/// <summary>
@@ -233,6 +252,7 @@ public static class Extensions
Logger<MiraApiPlugin>.Error($"Cannot add modifier with id {modifierId} because it is not registered.");
return;
}
target.GetModifierComponent()?.AddModifier(type);
}
@@ -304,7 +324,9 @@ public static class Extensions
/// <returns>The dead body if it is found, or null there is none within the radius.</returns>
public static DeadBody? GetNearestDeadBody(this PlayerControl playerControl, float radius)
{
return Helpers.GetNearestDeadBodies(playerControl.GetTruePosition(), radius).Find(component => component && !component.Reported);
return Helpers
.GetNearestDeadBodies(playerControl.GetTruePosition(), radius, Helpers.CreateFilter(Constants.NotShipMask))
.Find(component => component && !component.Reported);
}
/// <summary>
@@ -312,29 +334,46 @@ public static class Extensions
/// </summary>
/// <param name="playerControl">The player object.</param>
/// <param name="radius">The radius to search within.</param>
/// <param name="filter">The contact filter.</param>
/// <param name="colliderTag">An optional collider tag.</param>
/// <param name="predicate">Optional predicate to test if the object is valid.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The object if it was found, or null if there is none within the radius.</returns>
public static T? GetNearestObjectOfType<T>(this PlayerControl playerControl, float radius, string? colliderTag = null, Predicate<T>? predicate = null) where T : Component
public static T? GetNearestObjectOfType<T>(
this PlayerControl playerControl,
float radius,
ContactFilter2D filter,
string? colliderTag = null,
Predicate<T>? predicate = null) where T : Component
{
return Helpers.GetNearestObjectsOfType<T>(playerControl.GetTruePosition(), radius, colliderTag).Find(predicate ?? (component => component));
return Helpers.GetNearestObjectsOfType<T>(playerControl.GetTruePosition(), radius, filter, colliderTag)
.Find(predicate ?? (component => component));
}
/// <summary>
/// Gets the nearest player to a player.
/// Gets the closest player that matches the given criteria.
/// </summary>
/// <param name="playerControl">The player object.</param>
/// <param name="includeImpostors">Whether impostors should be included in the search.</param>
/// <param name="distance">The radius to search within.</param>
/// <param name="ignoreColliders">Whether colliders should be ignored when searching.</param>
/// <param name="predicate">Optional predicate to test if the object is valid.</param>
/// <returns>The closest player if there is one, false otherwise.</returns>
public static PlayerControl? GetClosestPlayer(this PlayerControl playerControl, bool includeImpostors, float distance, bool ignoreColliders = false)
public static PlayerControl? GetClosestPlayer(
this PlayerControl playerControl,
bool includeImpostors,
float distance,
bool ignoreColliders = false,
Predicate<PlayerControl>? predicate = null)
{
var filteredPlayers = Helpers.GetClosestPlayers(playerControl, distance, ignoreColliders)
.Where(playerInfo => !playerInfo.Data.Disconnected && playerInfo.PlayerId != playerControl.PlayerId && !playerInfo.Data.IsDead &&
(includeImpostors || !playerInfo.Data.Role.IsImpostor));
.Where(
playerInfo => !playerInfo.Data.Disconnected &&
playerInfo.PlayerId != playerControl.PlayerId &&
!playerInfo.Data.IsDead &&
(includeImpostors || !playerInfo.Data.Role.IsImpostor))
.ToList();
return filteredPlayers.FirstOrDefault();
return predicate != null ? filteredPlayers.Find(predicate) : filteredPlayers.FirstOrDefault();
}
}
+16 -12
View File
@@ -1,8 +1,8 @@
using MiraAPI.Roles;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using MiraAPI.Roles;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
@@ -15,12 +15,14 @@ namespace MiraAPI.Utilities;
public static class Helpers
{
/// <summary>
/// NotShipMask filter for collisions.
/// Creates a ContactFilter2D from a layer mask.
/// </summary>
public static readonly ContactFilter2D Filter = ContactFilter2D.CreateLegacyFilter(
Constants.NotShipMask,
float.MinValue,
float.MaxValue);
/// <param name="layerMask">The layer mask.</param>
/// <returns>A new ContactFilter2D that represents the layer mask.</returns>
public static ContactFilter2D CreateFilter(int layerMask)
{
return ContactFilter2D.CreateLegacyFilter(layerMask, float.MinValue, float.MaxValue);
}
/// <summary>
/// Get the room at a specific position.
@@ -37,11 +39,12 @@ public static class Helpers
/// </summary>
/// <param name="source">The source location.</param>
/// <param name="radius">The radius to search in.</param>
/// <param name="filter">The contact filter.</param>
/// <returns>A list of dead bodies.</returns>
public static List<DeadBody> GetNearestDeadBodies(Vector2 source, float radius)
public static List<DeadBody> GetNearestDeadBodies(Vector2 source, float radius, ContactFilter2D filter)
{
var results = new Il2CppSystem.Collections.Generic.List<Collider2D>();
Physics2D.OverlapCircle(source, radius, Filter, results);
Physics2D.OverlapCircle(source, radius, filter, results);
return results.ToArray()
.Where(collider2D => collider2D.CompareTag("DeadBody"))
.Select(collider2D => collider2D.GetComponent<DeadBody>()).ToList();
@@ -52,14 +55,15 @@ public static class Helpers
/// </summary>
/// <param name="source">The source point.</param>
/// <param name="radius">The radius to search in.</param>
/// <param name="filter">The contact filter.</param>
/// <param name="colliderTag">An optional collider tag.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>A list of objects of type T.</returns>
public static List<T> GetNearestObjectsOfType<T>(Vector2 source, float radius, string? colliderTag = null)
public static List<T> GetNearestObjectsOfType<T>(Vector2 source, float radius, ContactFilter2D filter, string? colliderTag = null)
where T : Component
{
var results = new Il2CppSystem.Collections.Generic.List<Collider2D>();
Physics2D.OverlapCircle(source, radius, Filter, results);
Physics2D.OverlapCircle(source, radius, filter, results);
return results.ToArray()
.Where(collider2D => colliderTag == null || collider2D.CompareTag(colliderTag))
.Select(collider2D => collider2D.GetComponent<T>()).ToList();
@@ -77,7 +81,7 @@ public static class Helpers
float radius,
bool ignoreColliders = true)
{
var newList = GetNearestObjectsOfType<PlayerControl>(source, radius);
var newList = GetNearestObjectsOfType<PlayerControl>(source, radius, CreateFilter(Constants.NotShipMask));
if (!ignoreColliders)
{