diff --git a/MiraAPI/Events/MiraEventHandle.cs b/MiraAPI/Events/MiraEventHandle.cs
index 451e6a2a..19482f41 100644
--- a/MiraAPI/Events/MiraEventHandle.cs
+++ b/MiraAPI/Events/MiraEventHandle.cs
@@ -3,7 +3,8 @@
namespace MiraAPI.Events;
///
-/// Event handle to use when unregistering a .
+/// Wrapper for handlers.
+/// Also used when unregistering a .
///
public class MiraEventHandle
{
@@ -12,11 +13,37 @@ public class MiraEventHandle
///
public Type EventType { get; }
- internal MiraEventWrapper EventWrapper { get; }
+ ///
+ /// Gets the priority of the handler. Lower values are called first.
+ ///
+ public int Priority { get; }
- internal MiraEventHandle(Type type, MiraEventWrapper eventWrapper)
+ ///
+ /// Gets the event handler delegate.
+ ///
+ public Delegate EventHandler { get; }
+
+ ///
+ /// Gets a value indicating whether the event handler should also be
+ /// triggered by subclasses of .
+ ///
+ public bool InvokeOnSubtype { get; }
+
+ internal MiraEventHandle(Delegate eventHandler, int priority, Type type, bool invokeOnSubtype)
{
+ EventHandler = eventHandler;
+ Priority = priority;
EventType = type;
- EventWrapper = eventWrapper;
+ InvokeOnSubtype = invokeOnSubtype;
+ }
+
+ internal bool IsTriggeredBy(Type type)
+ {
+ if (InvokeOnSubtype)
+ {
+ return EventType.IsAssignableTo(type);
+ }
+
+ return EventType == type;
}
}
diff --git a/MiraAPI/Events/MiraEventManager.cs b/MiraAPI/Events/MiraEventManager.cs
index a19bda9f..a3cd0e7f 100644
--- a/MiraAPI/Events/MiraEventManager.cs
+++ b/MiraAPI/Events/MiraEventManager.cs
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
using System.Reflection;
using MiraAPI.PluginLoading;
using MiraAPI.Utilities;
@@ -11,7 +13,21 @@ namespace MiraAPI.Events;
///
public static class MiraEventManager
{
- private static readonly Dictionary> EventWrappers = [];
+ private static readonly Dictionary> EventHandlers = [];
+ private static readonly Dictionary> EventHandlersToLoad = [];
+ private static readonly Comparer EventComparer = Comparer.Create((a, b) => a.Priority.CompareTo(b.Priority));
+
+ ///
+ /// Gets the list of all registered types.
+ /// Generic event types are registered as their generic type definitions.
+ ///
+ public static IReadOnlyList EventTypes { get; internal set; } = [];
+
+ internal static List InternalEventTypes { get; } = [];
+
+ private static readonly Dictionary> TrackedEventTypes = [];
+
+ private static bool loadFinalized = false;
///
/// Invoke a .
@@ -22,26 +38,7 @@ public static class MiraEventManager
public static bool InvokeEvent(this T eventInstance)
where T : MiraEvent
{
- EventWrappers.TryGetValue(typeof(T), out var handlers);
-
- if (handlers == null || handlers.Count == 0)
- {
- return false;
- }
-
- foreach (var handler in handlers)
- {
- try
- {
- ((Action)handler.EventHandler).Invoke(eventInstance);
- }
- catch (Exception ex)
- {
- Error($"Error invoking event handler for {typeof(T).Name}: {ex}");
- }
- }
-
- return true;
+ return eventInstance.InvokeEvent(typeof(T));
}
///
@@ -52,14 +49,27 @@ public static class MiraEventManager
/// If there was an event handler invoked for this event, return . Otherwise, return .
public static bool InvokeEvent(this MiraEvent eventInstance, Type type)
{
- EventWrappers.TryGetValue(type, out var handlers);
+ var trackedType = type.GetTrackedType();
+ var callableHandlers = new List();
- if (handlers == null || handlers.Count == 0)
+ if (EventHandlers.TryGetValue(trackedType, out var handlers))
+ {
+ callableHandlers.AddRange(handlers.Where(x => x.IsTriggeredBy(type)));
+ }
+
+ if (!loadFinalized && EventHandlersToLoad.TryGetValue(trackedType, out var pendingHandlers))
+ {
+ callableHandlers.AddRange(pendingHandlers.Where(x => x.IsTriggeredBy(type)));
+ }
+
+ if (callableHandlers.Count == 0)
{
return false;
}
- foreach (var handler in handlers)
+ callableHandlers.Sort(EventComparer);
+
+ foreach (var handler in callableHandlers)
{
try
{
@@ -74,35 +84,113 @@ public static class MiraEventManager
return true;
}
+ internal static bool RegisterEventType(in MiraPluginManager.RegistrationContext context)
+ {
+ var eventType = context.Type;
+ var pluginInfo = context.PluginInfo;
+
+ if (eventType.IsAbstract || !eventType.IsSubclassOf(typeof(MiraEvent)))
+ {
+ return false;
+ }
+
+ AddTypeToTracked(eventType);
+
+ // subtypes are added to their supertypes, regardless of which were added first
+ TrackedEventTypes[eventType].UnionWith(InternalEventTypes.Where(x => x.IsSubclassOfWithGeneric(eventType)));
+ foreach (var supertype in InternalEventTypes.Where(x => eventType.IsSubclassOfWithGeneric(x)))
+ {
+ AddTypeToTracked(supertype, eventType);
+ }
+
+ pluginInfo.InternalEventTypes.Add(eventType);
+ InternalEventTypes.Add(eventType);
+
+ return true;
+ }
+
+ private static void AddTypeToTracked(Type eventType, Type trackedAs = null!)
+ {
+ if (eventType.IsAbstract)
+ {
+ return;
+ }
+
+ if (!TrackedEventTypes.TryGetValue(eventType, out var trackedEvents))
+ {
+ trackedEvents = [];
+ TrackedEventTypes.Add(eventType, trackedEvents);
+ }
+
+ trackedAs ??= eventType;
+ trackedEvents.Add(trackedAs);
+ }
+
///
/// Register a handler.
///
/// The type of event.
/// The of the event handler.
/// The priority of the event handler. Lower values are called first.
+ /// Whether the event handler should also be triggered by subclasses of the type of the handler.
/// A to use when unregistering the event.
- public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority = 0)
+ public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority, bool invokeOnSubtype)
{
- if (!type.IsSubclassOf(typeof(MiraEvent)))
+ if (!type.IsAssignableTo(typeof(MiraEvent)))
{
throw new InvalidOperationException($"Type must be a subclass of MiraEvent: {type.FullName}");
}
- EventWrappers.TryAdd(type, []);
- var handlers = EventWrappers[type];
-
var @delegate = Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(type), methodInfo);
- var eventWrapper = new MiraEventWrapper(@delegate, priority);
+ return RegisterEventHandler(type, @delegate, priority, invokeOnSubtype);
+ }
- var index = handlers.BinarySearch(eventWrapper, Comparer.Create((a, b) => a.Priority.CompareTo(b.Priority)));
+ ///
+ public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, int priority)
+ {
+ return RegisterEventHandler(type, methodInfo, priority, false);
+ }
- if (index < 0)
- {
- index = ~index;
- }
+ ///
+ public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo, bool invokeOnSubtype)
+ {
+ return RegisterEventHandler(type, methodInfo, 0, invokeOnSubtype);
+ }
- handlers.Insert(index, eventWrapper);
- return new MiraEventHandle(type, eventWrapper);
+ ///
+ public static MiraEventHandle RegisterEventHandler(Type type, MethodInfo methodInfo)
+ {
+ return RegisterEventHandler(type, methodInfo, 0, false);
+ }
+
+ ///
+ /// Register a handler.
+ ///
+ /// The of the event handler.
+ /// The priority of the event handler. Lower values are called first.
+ /// Whether the event handler should also be triggered by subclasses of the type of the handler.
+ /// A to use when unregistering the event.
+ public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo, int priority, bool invokeOnSubtype)
+ {
+ return RegisterEventHandler(methodInfo.GetParameters()[0].ParameterType, methodInfo, priority, invokeOnSubtype);
+ }
+
+ ///
+ public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo, int priority)
+ {
+ return RegisterEventHandler(methodInfo, priority, false);
+ }
+
+ ///
+ public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo, bool invokeOnSubtype)
+ {
+ return RegisterEventHandler(methodInfo, 0, invokeOnSubtype);
+ }
+
+ ///
+ public static MiraEventHandle RegisterEventHandler(MethodInfo methodInfo)
+ {
+ return RegisterEventHandler(methodInfo, 0, false);
}
///
@@ -110,25 +198,87 @@ public static class MiraEventManager
///
/// The callback method/handler for the event.
/// The priority of the event handler. Lower values are called first.
+ /// Whether the event handler should also be triggered by subclasses of the type of the handler.
/// Type of event.
/// A to use when unregistering the event.
- public static MiraEventHandle RegisterEventHandler(Action handler, int priority = 0)
+ public static MiraEventHandle RegisterEventHandler(Action handler, int priority, bool invokeOnSubtype)
where T : MiraEvent
{
- EventWrappers.TryAdd(typeof(T), []);
+ return RegisterEventHandler(typeof(T), handler, priority, invokeOnSubtype);
+ }
- var handlers = EventWrappers[typeof(T)];
- var eventWrapper = new MiraEventWrapper(handler, priority);
+ ///
+ public static MiraEventHandle RegisterEventHandler(Action handler, int priority)
+ where T : MiraEvent
+ {
+ return RegisterEventHandler(handler, priority, false);
+ }
- var index = handlers.BinarySearch(eventWrapper, Comparer.Create((a, b) => a.Priority.CompareTo(b.Priority)));
+ ///
+ public static MiraEventHandle RegisterEventHandler(Action handler, bool invokeOnSubtype)
+ where T : MiraEvent
+ {
+ return RegisterEventHandler(handler, 0, invokeOnSubtype);
+ }
- if (index < 0)
+ ///
+ public static MiraEventHandle RegisterEventHandler(Action handler)
+ where T : MiraEvent
+ {
+ return RegisterEventHandler(handler, 0, false);
+ }
+
+ ///
+ /// Register a handler.
+ ///
+ /// The type of event.
+ /// The method/handler for the event.
+ /// The priority of the event handler. Lower values are called first.
+ /// Whether the event handler should also be triggered by subclasses of the type of the handler.
+ /// A to use when unregistering the event.
+ private static MiraEventHandle RegisterEventHandler(Type type, Delegate @delegate, int priority, bool invokeOnSubtype)
+ {
+ var eventHandler = new MiraEventHandle(@delegate, priority, type, invokeOnSubtype);
+ EventHandlerAdded(type, eventHandler);
+ return eventHandler;
+ }
+
+ private static Type GetTrackedType(this Type type)
+ {
+ if (type.IsGenericType)
{
- index = ~index;
+ return type.GetGenericTypeDefinition();
}
- handlers.Insert(index, eventWrapper);
- return new MiraEventHandle(typeof(T), eventWrapper);
+ return type;
+ }
+
+ private static void EventHandlerAdded(Type type, MiraEventHandle eventHandler)
+ {
+ if (!loadFinalized)
+ {
+ EventHandlersToLoad.TryAdd(type, []);
+ EventHandlersToLoad[type].Add(eventHandler);
+ return;
+ }
+
+ if (!TrackedEventTypes.TryGetValue(type.GetTrackedType(), out var trackedEvents))
+ {
+ return;
+ }
+
+ foreach (Type eventType in trackedEvents)
+ {
+ var handlers = EventHandlers[eventType];
+ var index = handlers.BinarySearch(eventHandler, EventComparer);
+
+ if (index < 0)
+ {
+ index = ~index;
+ }
+
+ handlers.Insert(index, eventHandler);
+ }
}
///
@@ -138,22 +288,59 @@ public static class MiraEventManager
/// if the event was unregistered successfully, otherwise.
public static bool UnregisterEventHandler(MiraEventHandle eventHandle)
{
- if (!EventWrappers.TryGetValue(eventHandle.EventType, out var handlers))
+ if (!loadFinalized)
+ {
+ if (!EventHandlersToLoad.TryGetValue(eventHandle.EventType, out var handlersToLoad))
+ {
+ return false;
+ }
+
+ if (!handlersToLoad.Remove(eventHandle))
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ if (!TrackedEventTypes.TryGetValue(eventHandle.EventType.GetTrackedType(), out var eventTypes))
{
return false;
}
- if (!handlers.Remove(eventHandle.EventWrapper))
+ var removed = false;
+ foreach (var type in eventTypes)
{
- return false;
+ if (EventHandlers.TryGetValue(type, out var handlers))
+ {
+ removed |= handlers.Remove(eventHandle);
+ }
}
- if (handlers.Count == 0)
+ return removed;
+ }
+
+ internal static void OnLoadFinalize()
+ {
+ loadFinalized = true;
+ EventTypes = new ReadOnlyCollection(InternalEventTypes);
+
+ foreach (var eventType in EventTypes)
{
- EventWrappers.Remove(eventHandle.EventType);
+ EventHandlers.Add(eventType, []);
}
- return true;
+ foreach (var (concreteType, eventHandlers) in EventHandlersToLoad)
+ {
+ foreach (var eventHandler in eventHandlers)
+ {
+ EventHandlerAdded(concreteType, eventHandler);
+ }
+
+ eventHandlers.Clear();
+ }
+
+ EventHandlersToLoad.Clear();
}
internal static bool RegisterEvents(in MiraPluginManager.RegistrationContext context)
@@ -181,8 +368,7 @@ public static class MiraEventManager
continue;
}
- var paramType = parameters[0].ParameterType;
- RegisterEventHandler(paramType, method, eventAttribute.Priority);
+ RegisterEventHandler(method, eventAttribute.Priority, eventAttribute.InvokeOnSubtype);
}
return hasContainerAttribute;
diff --git a/MiraAPI/Events/MiraEventWrapper.cs b/MiraAPI/Events/MiraEventWrapper.cs
index 469a98d3..8b0300c3 100644
--- a/MiraAPI/Events/MiraEventWrapper.cs
+++ b/MiraAPI/Events/MiraEventWrapper.cs
@@ -7,6 +7,7 @@ namespace MiraAPI.Events;
///
/// The action for the event handler.
/// The priority of the handler.
+[Obsolete("Use MiraEventHandle instead. This will be removed in a future version.")]
public class MiraEventWrapper(Delegate eventHandler, int priority)
{
///
diff --git a/MiraAPI/Events/RegisterEventAttribute.cs b/MiraAPI/Events/RegisterEventAttribute.cs
index 494d7689..29737a0c 100644
--- a/MiraAPI/Events/RegisterEventAttribute.cs
+++ b/MiraAPI/Events/RegisterEventAttribute.cs
@@ -6,11 +6,36 @@ namespace MiraAPI.Events;
/// Register a handler.
///
/// The priority of the event. Lower values are called first.
+/// Whether the event handler should also be triggered by subclasses of the type of the handler.
[AttributeUsage(AttributeTargets.Method)]
-public class RegisterEventAttribute(int priority = 0) : Attribute
+public class RegisterEventAttribute(int priority, bool invokeOnSubtype) : Attribute
{
///
/// Gets the priority of the event. Lower values are called first.
///
public int Priority => priority;
+
+ ///
+ /// Gets a value indicating whether the event handler should also be
+ /// triggered by subclasses of the type of the handler.
+ ///
+ public bool InvokeOnSubtype => invokeOnSubtype;
+
+ ///
+ public RegisterEventAttribute(int priority)
+ : this(priority, false)
+ {
+ }
+
+ ///
+ public RegisterEventAttribute(bool invokeOnSubtype)
+ : this(0, invokeOnSubtype)
+ {
+ }
+
+ ///
+ public RegisterEventAttribute()
+ : this(0, false)
+ {
+ }
}
diff --git a/MiraAPI/Events/RegisterEventsAttribute.cs b/MiraAPI/Events/RegisterEventContainerAttribute.cs
similarity index 100%
rename from MiraAPI/Events/RegisterEventsAttribute.cs
rename to MiraAPI/Events/RegisterEventContainerAttribute.cs
diff --git a/MiraAPI/Hud/CustomActionButton.cs b/MiraAPI/Hud/CustomActionButton.cs
index ce91ad57..7763aac0 100644
--- a/MiraAPI/Hud/CustomActionButton.cs
+++ b/MiraAPI/Hud/CustomActionButton.cs
@@ -165,28 +165,22 @@ public abstract class CustomActionButton
{
// Invoke the generic button click event.
var genericEvent = new MiraButtonClickEvent(this);
- MiraEventManager.InvokeEvent(genericEvent);
- if (genericEvent.IsCancelled) MiraEventManager.InvokeEvent(new MiraButtonCancelledEvent(this));
+ genericEvent.InvokeEvent();
+ if (genericEvent.IsCancelled) new MiraButtonCancelledEvent(this).InvokeEvent();
// Invoke the button click event for specific button.
var eventType = CustomButtonManager.ButtonEventTypes[GetType()];
var @event = (MiraCancelableEvent)Activator.CreateInstance(eventType, this, genericEvent)!;
- var specificInvoked = MiraEventManager.InvokeEvent(@event, eventType);
+ var specificInvoked = @event.InvokeEvent(eventType);
if (@event.IsCancelled)
{
var cancelEventType = CustomButtonManager.ButtonCancelledEventTypes[GetType()];
var cancelEvent = (MiraEvent)Activator.CreateInstance(cancelEventType, this)!;
- MiraEventManager.InvokeEvent(cancelEvent, cancelEventType);
+ cancelEvent.InvokeEvent(cancelEventType);
}
- if (specificInvoked)
- {
- if (!@event.IsCancelled) ClickHandler();
- }
- else
- {
- if (!genericEvent.IsCancelled) ClickHandler();
- }
+ MiraCancelableEvent eventCheck = specificInvoked ? @event : genericEvent;
+ if (!eventCheck.IsCancelled) ClickHandler();
}));
if (Keybind == null) return;
diff --git a/MiraAPI/MiraApiSettings.cs b/MiraAPI/MiraApiSettings.cs
index e39a6294..c6dcb0b3 100644
--- a/MiraAPI/MiraApiSettings.cs
+++ b/MiraAPI/MiraApiSettings.cs
@@ -96,10 +96,10 @@ public class MiraApiSettings(ConfigFile config) : LocalSettingsTab(config)
return;
var genericEvent = new UiButtonResetEvent();
- MiraEventManager.InvokeEvent(genericEvent);
+ genericEvent.InvokeEvent();
var genericEvent2 = new UiButtonPostResetEvent(topUi, extraTopUi);
- MiraEventManager.InvokeEvent(genericEvent2);
+ genericEvent2.InvokeEvent();
MiraHudHelper.UiGrid.ArrangeChilds();
MiraHudHelper.ExtraUiGrid.ArrangeChilds();
}
diff --git a/MiraAPI/Networking/CustomMurderRpc.cs b/MiraAPI/Networking/CustomMurderRpc.cs
index 8a5a701a..2099cb3c 100644
--- a/MiraAPI/Networking/CustomMurderRpc.cs
+++ b/MiraAPI/Networking/CustomMurderRpc.cs
@@ -85,7 +85,7 @@ public static class CustomMurderRpc
var murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError;
var beforeMurderEvent = new BeforeMurderEvent(source, target, inMeeting);
- MiraEventManager.InvokeEvent(beforeMurderEvent);
+ beforeMurderEvent.InvokeEvent();
var defenseFlag = beforeMurderEvent.IgnoreDefense;
var indirectFlag = beforeMurderEvent.IsIndirectAttack;
var isMeetingActive = MeetingHud.Instance != null || ExileController.Instance != null;
@@ -227,7 +227,7 @@ public static class CustomMurderRpc
var murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError;
var beforeMurderEvent = new BeforeMurderEvent(source, target, isIndirect, ignoreDefense, inMeeting);
- MiraEventManager.InvokeEvent(beforeMurderEvent);
+ beforeMurderEvent.InvokeEvent();
var defenseFlag = beforeMurderEvent.IgnoreDefense;
var indirectFlag = beforeMurderEvent.IsIndirectAttack;
var isMeetingActive = MeetingHud.Instance != null || ExileController.Instance != null;
@@ -357,7 +357,7 @@ public static class CustomMurderRpc
var murderResultFlags = didSucceed ? MurderResultFlags.Succeeded : MurderResultFlags.FailedError;
var beforeMurderEvent = new BeforeMurderEvent(source, target, framed, isIndirect, ignoreDefense, inMeeting);
- MiraEventManager.InvokeEvent(beforeMurderEvent);
+ beforeMurderEvent.InvokeEvent();
var defenseFlag = beforeMurderEvent.IgnoreDefense;
var indirectFlag = beforeMurderEvent.IsIndirectAttack;
var isMeetingActive = MeetingHud.Instance != null || ExileController.Instance != null;
@@ -821,7 +821,7 @@ public static class CustomMurderRpc
}
var afterMurderEvent = framed != null ? new AfterMurderEvent(source, target, framed, deadBody, isIndirect, ignoreDefense) : new AfterMurderEvent(source, target, deadBody, isIndirect, ignoreDefense);
- MiraEventManager.InvokeEvent(afterMurderEvent);
+ afterMurderEvent.InvokeEvent();
if (!isParticipant)
{
diff --git a/MiraAPI/Patches/AmongUsClientSyncPatch.cs b/MiraAPI/Patches/AmongUsClientSyncPatch.cs
index 9fb6cbb6..a80d15ac 100644
--- a/MiraAPI/Patches/AmongUsClientSyncPatch.cs
+++ b/MiraAPI/Patches/AmongUsClientSyncPatch.cs
@@ -31,7 +31,7 @@ internal static class AmongUsClientSyncPatch
var wrapper = new StateMachineWrapper(__instance);
var clientData = wrapper.GetParameter("clientData");
var joinEvent = new PlayerJoinEvent(clientData);
- MiraEventManager.InvokeEvent(joinEvent);
+ joinEvent.InvokeEvent();
if (!AmongUsClient.Instance.AmHost)
{
@@ -56,6 +56,6 @@ internal static class AmongUsClientSyncPatch2
public static void PlayerLeftPatch(ClientData data, DisconnectReasons reason)
{
var leftEvent = new PlayerLeaveEvent(data, reason);
- MiraEventManager.InvokeEvent(leftEvent);
+ leftEvent.InvokeEvent();
}
}
diff --git a/MiraAPI/Patches/Events/CanUsePatches.cs b/MiraAPI/Patches/Events/CanUsePatches.cs
index f99d2b90..a8aa67fd 100644
--- a/MiraAPI/Patches/Events/CanUsePatches.cs
+++ b/MiraAPI/Patches/Events/CanUsePatches.cs
@@ -35,7 +35,7 @@ public static class CanUsePatches
var usable = __instance.TryCast();
if (usable == null) return true;
var @event = new PlayerCanUseEvent(usable);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return !@event.IsCancelled;
}
diff --git a/MiraAPI/Patches/Events/EndGamePatches.cs b/MiraAPI/Patches/Events/EndGamePatches.cs
index aa475397..d158d3fd 100644
--- a/MiraAPI/Patches/Events/EndGamePatches.cs
+++ b/MiraAPI/Patches/Events/EndGamePatches.cs
@@ -13,7 +13,7 @@ internal static class EndGamePatches
public static bool Prefix(GameOverReason endReason)
{
var @event = new BeforeGameEndEvent(endReason);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return !@event.IsCancelled;
}
@@ -42,7 +42,7 @@ internal static class EndGamePatches
}
var @event = new GameEndEvent(__instance);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
}
}
}
diff --git a/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs b/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs
index 8427679d..a05bb936 100644
--- a/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs
+++ b/MiraAPI/Patches/Events/FreeplayRoundStartPatch.cs
@@ -19,6 +19,6 @@ public static class FreeplayRoundStartPatch
{
if (__result) return;
MeetingButtonManager.OnGameStart();
- MiraEventManager.InvokeEvent(new RoundStartEvent(true));
+ new RoundStartEvent(true).InvokeEvent();
}
}
diff --git a/MiraAPI/Patches/Events/HnsFinishTaskPatch.cs b/MiraAPI/Patches/Events/HnsFinishTaskPatch.cs
index 41b193f5..0d837e54 100644
--- a/MiraAPI/Patches/Events/HnsFinishTaskPatch.cs
+++ b/MiraAPI/Patches/Events/HnsFinishTaskPatch.cs
@@ -12,6 +12,6 @@ public static class HnsFinishTaskPatch
public static void FinishTaskPostfix(HideAndSeekManager __instance, PlayerTask task)
{
var completeTaskEvent = new CompleteHnsTaskEvent(__instance, task.Owner, task);
- MiraEventManager.InvokeEvent(completeTaskEvent);
+ completeTaskEvent.InvokeEvent();
}
}
diff --git a/MiraAPI/Patches/Events/KillAnimationMurderEventPatch.cs b/MiraAPI/Patches/Events/KillAnimationMurderEventPatch.cs
index d102664c..3c2808e7 100644
--- a/MiraAPI/Patches/Events/KillAnimationMurderEventPatch.cs
+++ b/MiraAPI/Patches/Events/KillAnimationMurderEventPatch.cs
@@ -30,6 +30,6 @@ public static class KillAnimationMurderEventPatch
var target = wrapper.GetParameter("target");
var afterMurderEvent = new AfterMurderEvent(source, target, Helpers.GetBodyById(target.PlayerId));
- MiraEventManager.InvokeEvent(afterMurderEvent);
+ afterMurderEvent.InvokeEvent();
}
}
diff --git a/MiraAPI/Patches/Events/MapBehaviourPatches.cs b/MiraAPI/Patches/Events/MapBehaviourPatches.cs
index 246b6e59..abca6561 100644
--- a/MiraAPI/Patches/Events/MapBehaviourPatches.cs
+++ b/MiraAPI/Patches/Events/MapBehaviourPatches.cs
@@ -15,7 +15,7 @@ public static class MapBehaviourPatches
public static bool MapShowSabotagePatch(MapBehaviour __instance)
{
var @event = new PlayerOpenSabotageEvent(__instance);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return !@event.IsCancelled;
}
}
diff --git a/MiraAPI/Patches/Events/ReportBodyEventPatch.cs b/MiraAPI/Patches/Events/ReportBodyEventPatch.cs
index 3eb1c291..781d5cc3 100644
--- a/MiraAPI/Patches/Events/ReportBodyEventPatch.cs
+++ b/MiraAPI/Patches/Events/ReportBodyEventPatch.cs
@@ -15,7 +15,7 @@ public static class ReportBodyEventPatch
var body = target != null ? Helpers.GetBodyById(target.PlayerId) : null;
var @event = new ReportBodyEvent(source, target, body);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return !@event.IsCancelled;
}
diff --git a/MiraAPI/Patches/Events/SabotageEventPatches.cs b/MiraAPI/Patches/Events/SabotageEventPatches.cs
index 0717d6f8..2aaaa571 100644
--- a/MiraAPI/Patches/Events/SabotageEventPatches.cs
+++ b/MiraAPI/Patches/Events/SabotageEventPatches.cs
@@ -15,7 +15,7 @@ public static class SabotageEventPatches
public static bool ShipStatusUpdateSystemPrefix(SystemTypes systemType, byte amount)
{
var @event = new UpdateSystemEvent(systemType, PlayerControl.LocalPlayer, amount);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return !@event.IsCancelled;
}
@@ -24,7 +24,7 @@ public static class SabotageEventPatches
public static bool ShipStatusCloseDoorsOfTypePrefix(SystemTypes type)
{
var @event = new CloseDoorsEvent(type);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return !@event.IsCancelled;
}
}
diff --git a/MiraAPI/Patches/Events/UsePatches.cs b/MiraAPI/Patches/Events/UsePatches.cs
index 4d783f39..679ac46e 100644
--- a/MiraAPI/Patches/Events/UsePatches.cs
+++ b/MiraAPI/Patches/Events/UsePatches.cs
@@ -29,7 +29,7 @@ public static class UsePatches
public static bool UsePatch(MonoBehaviour __instance)
{
var @event = new PlayerUseEvent(__instance.Cast());
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return !@event.IsCancelled;
}
diff --git a/MiraAPI/Patches/Events/VanillaButtonPatches.cs b/MiraAPI/Patches/Events/VanillaButtonPatches.cs
index 70a218be..92946439 100644
--- a/MiraAPI/Patches/Events/VanillaButtonPatches.cs
+++ b/MiraAPI/Patches/Events/VanillaButtonPatches.cs
@@ -1,4 +1,5 @@
-using AmongUs.GameOptions;
+using System;
+using AmongUs.GameOptions;
using HarmonyLib;
using MiraAPI.Events;
using MiraAPI.Events.Vanilla.Gameplay;
@@ -40,14 +41,7 @@ public static class VanillaButtonPatches
ventTarget = role.Cast().currentTarget;
}
- var genericEvent = new VanillaButtonClickEvent(__instance, playerTarget, ventTarget);
- MiraEventManager.InvokeEvent(genericEvent);
- if (genericEvent.IsCancelled)
- {
- MiraEventManager.InvokeEvent(new VanillaButtonCancelledEvent(__instance));
- }
-
- return !genericEvent.IsCancelled;
+ return InvokeEvents(__instance, playerTarget, ventTarget);
}
[HarmonyPrefix]
@@ -66,13 +60,29 @@ public static class VanillaButtonPatches
playerTarget = role.Cast().currentTarget;
}
- var genericEvent = new VanillaButtonClickEvent(__instance, playerTarget);
- MiraEventManager.InvokeEvent(genericEvent);
+ return InvokeEvents(__instance, playerTarget);
+ }
+
+ private static bool InvokeEvents(AbilityButton __instance, PlayerControl? playerTarget, Vent? ventTarget = null)
+ {
+ var genericEvent = new VanillaButtonClickEvent(__instance, playerTarget, ventTarget);
+ genericEvent.InvokeEvent();
if (genericEvent.IsCancelled)
{
- MiraEventManager.InvokeEvent(new VanillaButtonCancelledEvent(__instance));
+ new VanillaButtonCancelledEvent(__instance).InvokeEvent();
}
- return !genericEvent.IsCancelled;
+ var eventType = typeof(VanillaButtonClickEvent<>).MakeGenericType(__instance.GetType());
+ var @event = (MiraCancelableEvent)Activator.CreateInstance(eventType, [__instance])!;
+ var specificInvoked = @event.InvokeEvent(eventType);
+ if (@event.IsCancelled)
+ {
+ var cancelEventType = typeof(VanillaButtonCancelledEvent<>).MakeGenericType(__instance.GetType());
+ var cancelEvent = (MiraEvent)Activator.CreateInstance(cancelEventType, [__instance])!;
+ cancelEvent.InvokeEvent(cancelEventType);
+ }
+
+ MiraCancelableEvent eventCheck = specificInvoked ? @event : genericEvent;
+ return !eventCheck.IsCancelled;
}
}
diff --git a/MiraAPI/Patches/Events/VentEventPatches.cs b/MiraAPI/Patches/Events/VentEventPatches.cs
index 737d221f..c1852015 100644
--- a/MiraAPI/Patches/Events/VentEventPatches.cs
+++ b/MiraAPI/Patches/Events/VentEventPatches.cs
@@ -29,7 +29,7 @@ public static class VentEventPatches
var vent = ShipStatus.Instance.AllVents.FirstOrDefault(v => v.Id == ventId);
var @event = new EnterVentEvent(pc, vent);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (pc.AmOwner)
{
@@ -47,7 +47,7 @@ public static class VentEventPatches
var vent = ShipStatus.Instance.AllVents.First(v => v.Id == ventId);
var @event = new ExitVentEvent(pc, vent);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (pc.AmOwner)
{
diff --git a/MiraAPI/Patches/IntroCutscenePatches.cs b/MiraAPI/Patches/IntroCutscenePatches.cs
index 8abbefbe..dfd668c8 100644
--- a/MiraAPI/Patches/IntroCutscenePatches.cs
+++ b/MiraAPI/Patches/IntroCutscenePatches.cs
@@ -31,7 +31,7 @@ public static class IntroCutscenePatches
public static void IntroBeginPatch(IntroCutscene __instance)
{
var @event = new IntroBeginEvent(__instance);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (CustomGameModeManager.ActiveMode != null)
{
@@ -61,7 +61,7 @@ public static class IntroCutscenePatches
Info("IntroCutscene ShowRole reached");
var @event = new IntroRoleRevealEvent(introCutscene);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
}
}
@@ -135,13 +135,13 @@ public static class IntroCutscenePatches
Info("IntroCutscene ended");
MeetingButtonManager.OnGameStart();
- MiraEventManager.InvokeEvent(new IntroEndEvent(introCutscene));
+ new IntroEndEvent(introCutscene).InvokeEvent();
var @event = new BeforeRoundStartEvent(true);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (@event.IsCancelled) return;
- MiraEventManager.InvokeEvent(new RoundStartEvent(true));
+ new RoundStartEvent(true).InvokeEvent();
}
}
}
diff --git a/MiraAPI/Patches/PlayerControlPatches.cs b/MiraAPI/Patches/PlayerControlPatches.cs
index 89c78e36..74292e0b 100644
--- a/MiraAPI/Patches/PlayerControlPatches.cs
+++ b/MiraAPI/Patches/PlayerControlPatches.cs
@@ -41,7 +41,7 @@ internal static class PlayerControlPatches
public static void PlayerControlDiePostfix(PlayerControl __instance, DeathReason reason)
{
var deathEvent = new PlayerDeathEvent(__instance, reason, Helpers.GetBodyById(__instance.PlayerId));
- MiraEventManager.InvokeEvent(deathEvent);
+ deathEvent.InvokeEvent();
var modifiersComponent = __instance.GetComponent();
@@ -59,7 +59,7 @@ internal static class PlayerControlPatches
if (playerTask != null)
{
var completeTaskEvent = new CompleteTaskEvent(__instance, playerTask);
- MiraEventManager.InvokeEvent(completeTaskEvent);
+ completeTaskEvent.InvokeEvent();
}
}
@@ -102,7 +102,7 @@ internal static class PlayerControlPatches
}
var beforeMurderEvent = new BeforeMurderEvent(__instance, target);
- MiraEventManager.InvokeEvent(beforeMurderEvent);
+ beforeMurderEvent.InvokeEvent();
if (beforeMurderEvent.IsCancelled)
{
diff --git a/MiraAPI/Patches/Roles/EjectionPatches.cs b/MiraAPI/Patches/Roles/EjectionPatches.cs
index d37b550f..5aec4fb9 100644
--- a/MiraAPI/Patches/Roles/EjectionPatches.cs
+++ b/MiraAPI/Patches/Roles/EjectionPatches.cs
@@ -17,7 +17,7 @@ internal static class EjectionPatches
public static void BeginPostfix(ExileController __instance)
{
var @event = new EjectionEvent(__instance);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (!__instance.initData.networkedPlayer || !__instance.initData.networkedPlayer.Role ||
__instance.initData.networkedPlayer.Role is not ICustomRole role)
@@ -39,12 +39,12 @@ internal static class EjectionPatches
public static void Postfix()
{
var @event = new BeforeRoundStartEvent(false);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (@event.IsCancelled) return;
var @event2 = new RoundStartEvent(false);
- MiraEventManager.InvokeEvent(@event2);
+ @event2.InvokeEvent();
}
}
}
diff --git a/MiraAPI/Patches/Roles/RoleManagerPatches.cs b/MiraAPI/Patches/Roles/RoleManagerPatches.cs
index 82cf9911..a9071e47 100644
--- a/MiraAPI/Patches/Roles/RoleManagerPatches.cs
+++ b/MiraAPI/Patches/Roles/RoleManagerPatches.cs
@@ -61,7 +61,7 @@ public static class RoleManagerPatches
}
var @event = new SetRoleEvent(targetPlayer, roleType);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return false;
}
diff --git a/MiraAPI/Patches/VentCanUsePatch.cs b/MiraAPI/Patches/VentCanUsePatch.cs
index cc4e9e5a..3b94441a 100644
--- a/MiraAPI/Patches/VentCanUsePatch.cs
+++ b/MiraAPI/Patches/VentCanUsePatch.cs
@@ -17,7 +17,7 @@ internal static class VentCanUsePatch
public static void Postfix(Vent __instance, ref float __result, [HarmonyArgument(0)] NetworkedPlayerInfo pc, [HarmonyArgument(1)] ref bool canUse, [HarmonyArgument(2)] ref bool couldUse)
{
var @event = new PlayerCanUseEvent(__instance.Cast());
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (@event.IsCancelled)
{
diff --git a/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs b/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs
index a893d516..1d392b64 100644
--- a/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs
+++ b/MiraAPI/Patches/Voting/DummyBehaviourPatch.cs
@@ -43,7 +43,7 @@ internal static class DummyBehaviourPatches
yield return new WaitForSeconds(dummy.voteTime.Next());
var dummyVoteEvent = new DummyVoteEvent(dummy);
- MiraEventManager.InvokeEvent(dummyVoteEvent);
+ dummyVoteEvent.InvokeEvent();
if (dummyVoteEvent.IsCancelled)
{
diff --git a/MiraAPI/Patches/Voting/MeetingHudPatches.cs b/MiraAPI/Patches/Voting/MeetingHudPatches.cs
index d9232f38..71d2c518 100644
--- a/MiraAPI/Patches/Voting/MeetingHudPatches.cs
+++ b/MiraAPI/Patches/Voting/MeetingHudPatches.cs
@@ -24,7 +24,7 @@ internal static class MeetingHudPatches
public static bool VotePatch(PlayerVoteArea __instance)
{
var beforeVoteEvent = new BeforeVoteEvent(__instance, PlayerControl.LocalPlayer);
- MiraEventManager.InvokeEvent(beforeVoteEvent);
+ beforeVoteEvent.InvokeEvent();
if (beforeVoteEvent.IsCancelled)
{
@@ -32,7 +32,7 @@ internal static class MeetingHudPatches
}
var afterVoteEvent = new AfterVoteEvent(__instance, PlayerControl.LocalPlayer);
- MiraEventManager.InvokeEvent(afterVoteEvent);
+ afterVoteEvent.InvokeEvent();
return true;
}
@@ -99,7 +99,7 @@ internal static class MeetingHudPatches
}
var @event = new StartMeetingEvent(__instance);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
}
[HarmonyPostfix]
@@ -107,7 +107,7 @@ internal static class MeetingHudPatches
public static void OnDestroyPatch(MeetingHud __instance)
{
MeetingVoteAreaVisibility.RestoreAll();
- MiraEventManager.InvokeEvent(new EndMeetingEvent(__instance));
+ new EndMeetingEvent(__instance).InvokeEvent();
}
[HarmonyPostfix]
@@ -125,7 +125,7 @@ internal static class MeetingHudPatches
}
}
- MiraEventManager.InvokeEvent(new VotingCompleteEvent(__instance));
+ new VotingCompleteEvent(__instance).InvokeEvent();
}
// this is necessary because the actual ForceSkipAll method is inlined.
@@ -179,7 +179,7 @@ internal static class MeetingHudPatches
var hasVotedFor = voteData.VotedFor((byte)suspectStateIdx);
var @event = new MeetingSelectEvent(voteData, suspectStateIdx, hasVotes && !hasVotedFor);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
return @event.AllowSelect;
}
@@ -231,7 +231,7 @@ internal static class MeetingHudPatches
var shouldEnd = !Helpers.GetAlivePlayers().Exists(plr => plr.GetVoteData().VotesRemaining > 0);
var checkEndEvent = new CheckForEndVotingEvent(shouldEnd);
- MiraEventManager.InvokeEvent(checkEndEvent);
+ checkEndEvent.InvokeEvent();
shouldEnd = checkEndEvent.ForceEndVoting || checkEndEvent is { IsCancelled: false, IsVotingComplete: true };
if (!shouldEnd)
@@ -243,7 +243,7 @@ internal static class MeetingHudPatches
var exiled = VotingUtils.GetExiled(votes, out var isTie);
var @event = new ProcessVotesEvent(votes, exiled);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (@event.VotesModified)
{
diff --git a/MiraAPI/PluginLoading/MiraPluginInfo.cs b/MiraAPI/PluginLoading/MiraPluginInfo.cs
index 4bbfe363..a8914df5 100644
--- a/MiraAPI/PluginLoading/MiraPluginInfo.cs
+++ b/MiraAPI/PluginLoading/MiraPluginInfo.cs
@@ -1,8 +1,10 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using BepInEx;
using BepInEx.Configuration;
+using MiraAPI.Events;
using MiraAPI.GameModes;
using MiraAPI.GameOptions;
using MiraAPI.Hud;
@@ -93,10 +95,15 @@ public class MiraPluginInfo
public IReadOnlyCollection MeetingButtons { get; private set; } = null!;
///
- /// Gets a of this 's s.
+ /// Gets a of this 's s.
///
public IReadOnlyCollection Presets { get; internal set; } = null!;
+ ///
+ /// Gets a of this 's types.
+ ///
+ public IReadOnlyCollection EventTypes { get; internal set; } = null!;
+
///
/// Gets a read only dictionary of Game Mode IDs and the AbstractGameMode object they are associated with.
///
@@ -116,6 +123,7 @@ public class MiraPluginInfo
Buttons = [.. InternalButtons];
MeetingButtons = [.. InternalMeetingButtons];
TargetedMeetingButtons = [.. InternalTargetedMeetingButtons];
+ EventTypes = [.. InternalEventTypes];
}
internal List InternalPresets { get; } = [];
@@ -125,6 +133,7 @@ public class MiraPluginInfo
internal List InternalOptionGroups { get; } = [];
internal List InternalMeetingButtons { get; } = [];
internal List InternalTargetedMeetingButtons { get; } = [];
+ internal List InternalEventTypes { get; } = [];
internal Dictionary GameModes { get; } = [];
internal Dictionary InternalRoles { get; } = [];
diff --git a/MiraAPI/PluginLoading/MiraPluginManager.cs b/MiraAPI/PluginLoading/MiraPluginManager.cs
index a1869c93..526b96f1 100644
--- a/MiraAPI/PluginLoading/MiraPluginManager.cs
+++ b/MiraAPI/PluginLoading/MiraPluginManager.cs
@@ -55,6 +55,7 @@ public sealed class MiraPluginManager
private static readonly (string LogContext, TypeRegistrationHandler Handler)[] RegistrationHandlers =
[
("events in", MiraEventManager.RegisterEvents),
+ ("event type", MiraEventManager.RegisterEventType),
("options for", ModdedOptionsManager.RegisterGroup),
("options for", LocalSettingsManager.RegisterLocalTabs),
("color class", PaletteManager.RegisterColors),
@@ -113,6 +114,7 @@ public sealed class MiraPluginManager
PaletteManager.RegisterAllColors();
CustomButtonManager.RegisterAllButtons();
ModifierManager.RegisterAllModifiers();
+ MiraEventManager.OnLoadFinalize();
// Cache all the registered plugins into an array for easy access
RegisteredPlugins = [.. _registeredPlugins.Values];
diff --git a/MiraAPI/Utilities/Extensions.cs b/MiraAPI/Utilities/Extensions.cs
index 1df8dbf9..53ce0d8f 100644
--- a/MiraAPI/Utilities/Extensions.cs
+++ b/MiraAPI/Utilities/Extensions.cs
@@ -602,6 +602,35 @@ public static class Extensions
return type is { IsClass: true, IsAbstract: true, IsSealed: true };
}
+ ///
+ /// Checks if is a subclass of , including
+ /// account for generics, or given generic type definitions.
+ ///
+ /// The type to check.
+ /// The type to compare against.
+ /// if is a sublass of , otherwise.
+ public static bool IsSubclassOfWithGeneric(this Type? type, Type super)
+ {
+ if (type == null || type == typeof(object))
+ {
+ return false;
+ }
+
+ if (type == super)
+ {
+ return true;
+ }
+
+ if (super.IsGenericTypeDefinition &&
+ type.IsGenericType &&
+ type.GetGenericTypeDefinition() == super)
+ {
+ return true;
+ }
+
+ return type.BaseType.IsSubclassOfWithGeneric(super);
+ }
+
///
/// Gets a darkened version of a .
///
diff --git a/MiraAPI/Voting/VotingUtils.cs b/MiraAPI/Voting/VotingUtils.cs
index ec62225c..4db434aa 100644
--- a/MiraAPI/Voting/VotingUtils.cs
+++ b/MiraAPI/Voting/VotingUtils.cs
@@ -47,7 +47,7 @@ public static class VotingUtils
private static void HandleVote(PlayerVoteData voteData, byte suspectIdx, bool byJudge, out bool cancelVote)
{
var @event = new HandleVoteEvent(voteData, suspectIdx, byJudge);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
cancelVote = @event.PreventVote;
@@ -290,7 +290,7 @@ public static class VotingUtils
public static void HandlePopulateResults(List votes)
{
var @event = new PopulateResultsEvent(votes);
- MiraEventManager.InvokeEvent(@event);
+ @event.InvokeEvent();
if (@event.IsCancelled)
{