diff --git a/codex-api/src/main/java/studio/magemonkey/codex/api/damage/FinalDamageEvent.java b/codex-api/src/main/java/studio/magemonkey/codex/api/damage/FinalDamageEvent.java new file mode 100644 index 0000000..4094ea7 --- /dev/null +++ b/codex-api/src/main/java/studio/magemonkey/codex/api/damage/FinalDamageEvent.java @@ -0,0 +1,449 @@ +package studio.magemonkey.codex.api.damage; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Predicate; + +/** + * The final numbers of a hit, as a damage plugin has calculated them, just before it writes them to the + * Bukkit damage event. + *

+ * A damage plugin (a provider, such as Divinity) fires this event from its own + * {@link EntityDamageEvent} handler, after it has worked out dodge, critical hits, blocking, defenses and + * the like, and before it sets the damage of the Bukkit event. Other plugins can then read and change the + * damage of the hit by type, without depending on the provider. A skill plugin such as Fabled, for + * example, runs its on-hit triggers and buffs here instead of changing the Bukkit event's damage itself. + *

+ * Codex never fires this event. It only defines it, so that plugins which cannot see each other's classes + * can share it. + * + *

Damage by type

+ * The damage is kept per damage type, keyed by the provider's type id ({@code physical}, {@code fire} and + * so on; what the ids are is up to the provider). The total is always the sum of the types: + * + * After the event, the provider deals {@link #getTotalDamage()} (and may run its own after-hit effects, + * such as life steal, on the per-type amounts). + * + *

Cancelling

+ * Cancelling this event cancels the hit: the provider cancels the Bukkit event and deals no damage. Codex + * only keeps the flag; acting on it is the provider's job. + * + *

Knowing whether the event will fire

+ * A plugin that changes Bukkit damage itself when no provider is around needs to know whether this event + * will come for a hit, so that it does not apply its changes twice. Providers announce themselves with + * {@link #registerProvider(Plugin, Predicate)}; ask with {@link #willFire(EntityDamageEvent)}. See there. + * + *

Subclassing

+ * A provider may fire this class as it is, or a subclass of its own that adds what only it knows. Listeners + * of {@code FinalDamageEvent} receive the subclass too, and listeners of the subclass keep working: + * + *

+ * This event is fired, read and changed on the server thread only. It uses nothing newer than the oldest + * Minecraft version Codex supports. + */ +public class FinalDamageEvent extends Event implements Cancellable { + /** + * The type that {@link #setTotalDamage(double)} puts the damage in when the hit has no damage types at + * all. + */ + public static final String DEFAULT_TYPE = "default"; + + private static final HandlerList HANDLERS = new HandlerList(); + + /** Registered providers, in the order they registered. */ + private static final Map> PROVIDERS = new LinkedHashMap<>(); + + @NotNull + private final LivingEntity victim; + @Nullable + private final LivingEntity attacker; + @Nullable + private final Projectile projectile; + @NotNull + private final DamageCause cause; + @NotNull + private final EntityDamageEvent damageEvent; + @Nullable + private final DamageRequest request; + @NotNull + private final DamageOrigin origin; + @NotNull + private final WeaponStatsMode weaponStatsMode; + @NotNull + private final Map damages; + private boolean cancelled; + + /** + * Creates the event. Only a provider creates it, right before it calls it. + * + * @param victim the entity that is hit + * @param attacker the entity the hit is attributed to: the shooter of a projectile, the caster of a + * skill. Null if there is none. + * @param projectile the projectile that hit, or null if it was not a projectile + * @param cause the cause of the hit. Usually that of the Bukkit event, or the one the + * {@link DamageRequest} asks for. + * @param damageEvent the Bukkit event being handled + * @param request the request that describes the hit (see {@link DamageContexts#claim}), or null if + * the hit was not announced + * @param origin what deals the damage: the request's origin, or the provider's best guess when + * there is no request + * @param weaponStatsMode how the attacker's equipment took part: the request's mode, or + * {@link WeaponStatsMode#ADD} when there is no request + * @param damages the final damage by type id, in the order the provider wants them listed. The map + * is copied. Amounts must be finite numbers and not negative. A subclass with storage of + * its own passes an empty map (see the class description). + */ + public FinalDamageEvent(@NotNull LivingEntity victim, + @Nullable LivingEntity attacker, + @Nullable Projectile projectile, + @NotNull DamageCause cause, + @NotNull EntityDamageEvent damageEvent, + @Nullable DamageRequest request, + @NotNull DamageOrigin origin, + @NotNull WeaponStatsMode weaponStatsMode, + @NotNull Map damages) { + super(false); + this.victim = Objects.requireNonNull(victim, "victim"); + this.attacker = attacker; + this.projectile = projectile; + this.cause = Objects.requireNonNull(cause, "cause"); + this.damageEvent = Objects.requireNonNull(damageEvent, "damageEvent"); + this.request = request; + this.origin = Objects.requireNonNull(origin, "origin"); + this.weaponStatsMode = Objects.requireNonNull(weaponStatsMode, "weaponStatsMode"); + this.damages = new LinkedHashMap<>(); + Objects.requireNonNull(damages, "damages").forEach((type, amount) -> { + Objects.requireNonNull(type, "damage type"); + this.damages.put(type, checkAmount(amount == null ? Double.NaN : amount)); + }); + } + + /** + * @return the entity that is hit + */ + @NotNull + public LivingEntity getVictim() { + return victim; + } + + /** + * @return the entity the hit is attributed to (the shooter of a projectile, the caster of a skill), or + * null if there is none + */ + @Nullable + public LivingEntity getAttacker() { + return attacker; + } + + /** + * @return the projectile that hit, or null if the hit was not from a projectile + */ + @Nullable + public Projectile getProjectile() { + return projectile; + } + + /** + * @return the cause of the hit + */ + @NotNull + public DamageCause getCause() { + return cause; + } + + /** + * The Bukkit event the provider is handling. Read it, but leave its damage alone: the provider sets it + * from this event's total when this event is over. To stop the hit, cancel this event. + * + * @return the Bukkit damage event of the hit + */ + @NotNull + public EntityDamageEvent getDamageEvent() { + return damageEvent; + } + + /** + * @return the request that describes the hit, or null if the hit was not announced through + * {@link DamageContexts} + */ + @Nullable + public DamageRequest getRequest() { + return request; + } + + /** + * @return what deals the damage: the request's origin, or the provider's best guess when there is no + * request + */ + @NotNull + public DamageOrigin getOrigin() { + return origin; + } + + /** + * @return how the attacker's equipment took part in the hit: the request's mode, or + * {@link WeaponStatsMode#ADD} when there is no request + */ + @NotNull + public WeaponStatsMode getWeaponStatsMode() { + return weaponStatsMode; + } + + /** + * The amounts the dealer asked for, as opposed to the final amounts of {@link #getDamages()}. + * + * @return the request's amounts by type, or an empty map if there is no request + */ + @NotNull + public Map getRequestedAmounts() { + return request == null ? Collections.emptyMap() : request.getAmounts(); + } + + /** + * The final damage of the hit by type id, in the provider's order. Types with an amount of 0 may be + * listed. + *

+ * A subclass with storage of its own overrides this together with {@link #getDamage(String)} and + * {@link #setDamage(String, double)}. + * + * @return the damage by type. The map cannot be changed; use {@link #setDamage(String, double)}. + */ + @NotNull + public Map getDamages() { + return Collections.unmodifiableMap(damages); + } + + /** + * @param type a damage type id + * @return the final damage of that type, or 0 if the hit has none of it + */ + public double getDamage(@NotNull String type) { + Double amount = damages.get(type); + return amount == null ? 0 : amount; + } + + /** + * Sets the final damage of one type. The total changes by the difference. A type the hit did not have + * is added. Setting a type to 0 removes its damage but may keep it listed. + *

+ * Which ids a provider knows is up to it. A provider may ignore, or map, an id it does not know. + * + * @param type a damage type id + * @param amount the amount, which must be a finite number and not negative + * @throws IllegalArgumentException if the amount is negative, infinite or not a number + */ + public void setDamage(@NotNull String type, double amount) { + Objects.requireNonNull(type, "type"); + damages.put(type, checkAmount(amount)); + } + + /** + * @return the final damage of the hit: the sum of {@link #getDamages()} + */ + public double getTotalDamage() { + double total = 0; + for (double amount : getDamages().values()) { + total += amount; + } + return total; + } + + /** + * Sets the final damage of the hit by scaling every type by the same factor, so that each keeps its + * share. Setting 0 sets every type to 0. + *

+ * A hit whose total is 0 has no shares to keep. Then the new total is split evenly between the listed + * types, or, if there are none, given to {@link #DEFAULT_TYPE}. + * + * @param total the new total, which must be a finite number and not negative + * @throws IllegalArgumentException if the total is negative, infinite or not a number + */ + public void setTotalDamage(double total) { + checkAmount(total); + // Copy first: setDamage may change the map getDamages() is a view of. + List> types = new ArrayList<>(new LinkedHashMap<>(getDamages()).entrySet()); + double current = 0; + for (Map.Entry entry : types) { + current += entry.getValue(); + } + + if (current > 0) { + double factor = total / current; + for (Map.Entry entry : types) { + setDamage(entry.getKey(), entry.getValue() * factor); + } + } else if (!types.isEmpty()) { + double share = total / types.size(); + for (Map.Entry entry : types) { + setDamage(entry.getKey(), share); + } + } else if (total > 0) { + setDamage(DEFAULT_TYPE, total); + } + } + + /** + * @return whether the hit is cancelled. The provider then cancels the Bukkit event and deals no damage. + */ + @Override + public boolean isCancelled() { + return cancelled; + } + + /** + * Cancels the hit, or lets it through again. A cancelled hit deals no damage: the provider cancels the + * Bukkit event and skips its after-hit effects. + * + * @param cancel whether to cancel the hit + */ + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Final, so that every subclass shares this class's handler list. See the class description. + */ + @Override + @NotNull + public final HandlerList getHandlers() { + return HANDLERS; + } + + /** + * The handler list Bukkit registers listeners of this event, and of every subclass, with. + * + * @return the handler list + */ + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } + + // ------------------------------------------------------------------------------------------------------ + // Providers + // ------------------------------------------------------------------------------------------------------ + + /** + * Announces a plugin that fires this event. Call it from {@code onEnable}, and call + * {@link #unregisterProvider(Plugin)} from {@code onDisable}. Registering again replaces the earlier + * predicate. + *

+ * The predicate answers, for a Bukkit damage event, whether the provider will fire this event for it, + * should the hit still be going (not cancelled) when the provider's handler runs. It is asked from other + * plugins' damage handlers, possibly before the provider's handler has run, so it must not change + * anything, must be cheap, and must not rely on what the provider works out during the hit. It should + * answer true for every hit the provider calculates; answering true for a hit the provider then leaves + * alone means the asking plugin skips it entirely. + *

+ * Use {@link #registerProvider(Plugin)} if the provider fires the event for every hit. + * + * @param provider the plugin that fires the event + * @param fires whether the provider fires the event for a given Bukkit damage event + */ + public static void registerProvider(@NotNull Plugin provider, + @NotNull Predicate fires) { + PROVIDERS.put(Objects.requireNonNull(provider, "provider"), Objects.requireNonNull(fires, "fires")); + } + + /** + * Announces a plugin that fires this event for every damage event it sees that is still going when its + * handler runs. Same as {@code registerProvider(provider, event -> true)}. + * + * @param provider the plugin that fires the event + */ + public static void registerProvider(@NotNull Plugin provider) { + registerProvider(provider, event -> true); + } + + /** + * Withdraws a provider. Doing so for a plugin that is not registered does nothing. + * + * @param provider the plugin that no longer fires the event + */ + public static void unregisterProvider(@NotNull Plugin provider) { + PROVIDERS.remove(provider); + } + + /** + * @return whether any enabled plugin has registered as a provider + */ + public static boolean hasProvider() { + for (Plugin provider : PROVIDERS.keySet()) { + if (provider.isEnabled()) return true; + } + return false; + } + + /** + * Whether a provider will fire this event for a hit, should the hit not be cancelled before the + * provider's handler runs. + *

+ * This is what a plugin that otherwise changes the Bukkit event's damage itself asks, from its own damage + * handler, to decide between the two ways: + *

{@code
+     * @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
+     * public void onDamage(EntityDamageByEntityEvent event) {
+     *     if (FinalDamageEvent.willFire(event)) return; // handled in onFinalDamage instead
+     *     event.setDamage(applyBuffs(event.getDamage()));
+     * }
+     *
+     * @EventHandler(ignoreCancelled = true)
+     * public void onFinalDamage(FinalDamageEvent event) {
+     *     event.setTotalDamage(applyBuffs(event.getTotalDamage()));
+     * }
+     * }
+ * A provider that has been disabled without unregistering is not counted. + * + * @param event the Bukkit damage event of the hit + * @return whether an enabled provider says it fires this event for the hit + */ + public static boolean willFire(@NotNull EntityDamageEvent event) { + Objects.requireNonNull(event, "event"); + for (Map.Entry> entry : PROVIDERS.entrySet()) { + if (entry.getKey().isEnabled() && entry.getValue().test(event)) return true; + } + return false; + } + + private static double checkAmount(double amount) { + if (!Double.isFinite(amount) || amount < 0) { + throw new IllegalArgumentException("Damage must be a finite number, 0 or more, got " + amount); + } + return amount; + } +} diff --git a/codex-api/src/test/java/studio/magemonkey/codex/api/damage/FinalDamageEventTest.java b/codex-api/src/test/java/studio/magemonkey/codex/api/damage/FinalDamageEventTest.java new file mode 100644 index 0000000..4a9e993 --- /dev/null +++ b/codex-api/src/test/java/studio/magemonkey/codex/api/damage/FinalDamageEventTest.java @@ -0,0 +1,438 @@ +package studio.magemonkey.codex.api.damage; + +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.SimplePluginManager; +import org.bukkit.plugin.java.JavaPluginLoader; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class FinalDamageEventTest { + private static final double EPSILON = 1e-9; + + private final LivingEntity victim = mock(LivingEntity.class); + private final LivingEntity attacker = mock(LivingEntity.class); + private final EntityDamageEvent bukkit = mock(EntityDamageEvent.class); + private final List registered = new ArrayList<>(); + + @AfterEach + void unregisterProviders() { + registered.forEach(FinalDamageEvent::unregisterProvider); + } + + private static Map damages(Object... typeAndAmount) { + Map map = new LinkedHashMap<>(); + for (int i = 0; i < typeAndAmount.length; i += 2) { + map.put((String) typeAndAmount[i], ((Number) typeAndAmount[i + 1]).doubleValue()); + } + return map; + } + + private FinalDamageEvent event(Map damages) { + return new FinalDamageEvent(victim, attacker, null, DamageCause.ENTITY_ATTACK, bukkit, null, + DamageOrigin.WEAPON_MELEE, WeaponStatsMode.ADD, damages); + } + + private Plugin plugin(boolean enabled) { + Plugin plugin = mock(Plugin.class); + when(plugin.isEnabled()).thenReturn(enabled); + registered.add(plugin); + return plugin; + } + + // --- Values --------------------------------------------------------------------------------------------- + + @Test + void getters_returnWhatTheProviderGave() { + DamageRequest request = DamageRequest.builder() + .origin(DamageOrigin.SKILL) + .weaponStats(WeaponStatsMode.REPLACE) + .amount("fire", 3) + .build(); + FinalDamageEvent event = new FinalDamageEvent(victim, attacker, null, DamageCause.MAGIC, bukkit, + request, DamageOrigin.SKILL, WeaponStatsMode.REPLACE, damages("fire", 2.5)); + + assertSame(victim, event.getVictim()); + assertSame(attacker, event.getAttacker()); + assertNull(event.getProjectile()); + assertEquals(DamageCause.MAGIC, event.getCause()); + assertSame(bukkit, event.getDamageEvent()); + assertSame(request, event.getRequest()); + assertEquals(DamageOrigin.SKILL, event.getOrigin()); + assertEquals(WeaponStatsMode.REPLACE, event.getWeaponStatsMode()); + assertEquals(Collections.singletonMap("fire", 3.0), event.getRequestedAmounts()); + assertEquals(2.5, event.getTotalDamage(), EPSILON); + assertFalse(event.isAsynchronous()); + } + + @Test + void getRequestedAmounts_withoutRequest_isEmpty() { + assertTrue(event(damages("physical", 1)).getRequestedAmounts().isEmpty()); + } + + @Test + void constructor_copiesTheMap() { + Map map = damages("physical", 4); + FinalDamageEvent event = event(map); + map.put("fire", 10.0); + + assertEquals(Collections.singletonMap("physical", 4.0), event.getDamages()); + } + + @Test + void constructor_rejectsBadAmounts() { + assertThrows(IllegalArgumentException.class, () -> event(damages("physical", -1))); + assertThrows(IllegalArgumentException.class, () -> event(damages("physical", Double.NaN))); + Map withNull = new HashMap<>(); + withNull.put("physical", null); + assertThrows(IllegalArgumentException.class, () -> event(withNull)); + } + + @Test + void getDamages_cannotBeChanged() { + FinalDamageEvent event = event(damages("physical", 4)); + assertThrows(UnsupportedOperationException.class, () -> event.getDamages().put("fire", 1.0)); + } + + // --- Per-type and total ------------------------------------------------------------------------------- + + @Test + void getDamage_ofAMissingType_isZero() { + assertEquals(0, event(damages("physical", 4)).getDamage("fire"), EPSILON); + } + + @Test + void setDamage_changesTheTypeAndTheTotalByTheDifference() { + FinalDamageEvent event = event(damages("physical", 6, "fire", 2)); + + event.setDamage("fire", 5); + + assertEquals(6, event.getDamage("physical"), EPSILON); + assertEquals(5, event.getDamage("fire"), EPSILON); + assertEquals(11, event.getTotalDamage(), EPSILON); + } + + @Test + void setDamage_ofANewType_addsItAtTheEnd() { + FinalDamageEvent event = event(damages("physical", 6)); + + event.setDamage("ice", 1); + + assertEquals(List.of("physical", "ice"), new ArrayList<>(event.getDamages().keySet())); + assertEquals(7, event.getTotalDamage(), EPSILON); + } + + @Test + void setDamage_rejectsBadAmounts() { + FinalDamageEvent event = event(damages("physical", 6)); + assertThrows(IllegalArgumentException.class, () -> event.setDamage("physical", -0.5)); + assertThrows(IllegalArgumentException.class, () -> event.setDamage("physical", Double.NaN)); + assertThrows(IllegalArgumentException.class, () -> event.setDamage("physical", Double.POSITIVE_INFINITY)); + assertEquals(6, event.getTotalDamage(), EPSILON); + } + + @Test + void setTotalDamage_scalesEveryTypeProportionally() { + FinalDamageEvent event = event(damages("physical", 6, "fire", 2)); + + event.setTotalDamage(4); + + assertEquals(3, event.getDamage("physical"), EPSILON); + assertEquals(1, event.getDamage("fire"), EPSILON); + assertEquals(4, event.getTotalDamage(), EPSILON); + } + + @Test + void setTotalDamage_toZero_zeroesEveryType() { + FinalDamageEvent event = event(damages("physical", 6, "fire", 2)); + + event.setTotalDamage(0); + + assertEquals(0, event.getDamage("physical"), EPSILON); + assertEquals(0, event.getDamage("fire"), EPSILON); + assertEquals(0, event.getTotalDamage(), EPSILON); + } + + @Test + void setTotalDamage_whenEveryTypeIsZero_splitsEvenly() { + FinalDamageEvent event = event(damages("physical", 0, "fire", 0)); + + event.setTotalDamage(5); + + assertEquals(2.5, event.getDamage("physical"), EPSILON); + assertEquals(2.5, event.getDamage("fire"), EPSILON); + } + + @Test + void setTotalDamage_withNoTypes_usesTheDefaultType() { + FinalDamageEvent event = event(Collections.emptyMap()); + + event.setTotalDamage(3); + + assertEquals(Collections.singletonMap(FinalDamageEvent.DEFAULT_TYPE, 3.0), event.getDamages()); + + FinalDamageEvent empty = event(Collections.emptyMap()); + empty.setTotalDamage(0); + assertTrue(empty.getDamages().isEmpty()); + } + + @Test + void setTotalDamage_rejectsBadAmounts() { + FinalDamageEvent event = event(damages("physical", 6)); + assertThrows(IllegalArgumentException.class, () -> event.setTotalDamage(-1)); + assertThrows(IllegalArgumentException.class, () -> event.setTotalDamage(Double.NaN)); + assertEquals(6, event.getTotalDamage(), EPSILON); + } + + @Test + void setTotalDamage_goesThroughASubclassStorage() { + StorageEvent event = new StorageEvent(victim, bukkit, 6, 2); + + event.setTotalDamage(4); + + assertEquals(3, event.physical, EPSILON); + assertEquals(1, event.fire, EPSILON); + assertEquals(4, event.getTotalDamage(), EPSILON); + assertEquals(damages("physical", 3, "fire", 1), event.getDamages()); + + event.setDamage("fire", 2); + assertEquals(2, event.fire, EPSILON); + assertEquals(5, event.getTotalDamage(), EPSILON); + } + + // --- Cancelling --------------------------------------------------------------------------------------- + + @Test + void cancel_isOffByDefault_andCanBeUndone() { + FinalDamageEvent event = event(damages("physical", 6)); + assertFalse(event.isCancelled()); + + event.setCancelled(true); + assertTrue(event.isCancelled()); + + event.setCancelled(false); + assertFalse(event.isCancelled()); + } + + @Test + void cancel_leavesTheBukkitEventToTheProvider() { + FinalDamageEvent event = event(damages("physical", 6)); + + event.setCancelled(true); + + org.mockito.Mockito.verifyNoInteractions(bukkit); + assertEquals(6, event.getTotalDamage(), EPSILON); + } + + // --- Handler list ------------------------------------------------------------------------------------- + + @Test + void handlerList_isSharedBySubclasses() { + StorageEvent sub = new StorageEvent(victim, bukkit, 1, 1); + assertSame(FinalDamageEvent.getHandlerList(), sub.getHandlers()); + assertSame(FinalDamageEvent.getHandlerList(), event(damages()).getHandlers()); + } + + /** + * Registers listeners through a real {@link SimplePluginManager} and {@link JavaPluginLoader}, the way a + * server does, to check Bukkit's rule on this API version: a listener of a subclass that does not declare + * {@code getHandlerList()} is registered with the base class's list. + */ + @Test + void bukkit_deliversSubclassEventsToBaseListeners_andOnlySubclassEventsToSubclassListeners() throws Exception { + Server server = mock(Server.class); + when(server.getLogger()).thenReturn(Logger.getLogger("test")); + when(server.isPrimaryThread()).thenReturn(true); + SimplePluginManager manager = new SimplePluginManager(server, new SimpleCommandMap(server)); + when(server.getPluginManager()).thenReturn(manager); + + JavaPluginLoader loader = new JavaPluginLoader(server); + Plugin plugin = mock(Plugin.class); + when(plugin.isEnabled()).thenReturn(true); + when(plugin.getDescription()).thenReturn(new PluginDescriptionFile("Test", "1.0", "test.Main")); + when(plugin.getLogger()).thenReturn(Logger.getLogger("test")); + when(plugin.getPluginLoader()).thenReturn(loader); + + // Spigot's timings, which the plugin loader's executor starts, look the plugin manager up through + // the static Bukkit server. Install the mock for this test only. + Field serverField = Bukkit.class.getDeclaredField("server"); + serverField.setAccessible(true); + assertNull(serverField.get(null), "another test left a Bukkit server behind"); + serverField.set(null, server); + + RecordingListener listener = new RecordingListener(); + try { + manager.registerEvents(listener, plugin); + + FinalDamageEvent base = event(damages("physical", 6)); + StorageEvent sub = new StorageEvent(victim, bukkit, 4, 0); + manager.callEvent(base); + manager.callEvent(sub); + + assertEquals(List.of(base, sub), listener.base); + assertEquals(List.of(sub), listener.sub); + // The base listener ran first and halved the subclass event; the subclass listener saw that. + assertEquals(2, sub.physical, EPSILON); + // Both handlers, the subclass one included, sit in the base class's list. + assertEquals(2, FinalDamageEvent.getHandlerList().getRegisteredListeners().length); + } finally { + HandlerList.unregisterAll(listener); + serverField.set(null, null); + } + assertEquals(0, FinalDamageEvent.getHandlerList().getRegisteredListeners().length); + } + + public static class RecordingListener implements Listener { + final List base = new ArrayList<>(); + final List sub = new ArrayList<>(); + + @EventHandler(priority = org.bukkit.event.EventPriority.LOW) + public void onFinal(FinalDamageEvent event) { + base.add(event); + if (event instanceof StorageEvent) event.setTotalDamage(event.getTotalDamage() / 2); + } + + @EventHandler(priority = org.bukkit.event.EventPriority.HIGH) + public void onSub(StorageEvent event) { + sub.add(event); + } + } + + // --- Providers ---------------------------------------------------------------------------------------- + + @Test + void providers_noneRegistered() { + assertFalse(FinalDamageEvent.hasProvider()); + assertFalse(FinalDamageEvent.willFire(bukkit)); + } + + @Test + void providers_registerAndUnregister() { + Plugin provider = plugin(true); + + FinalDamageEvent.registerProvider(provider); + assertTrue(FinalDamageEvent.hasProvider()); + assertTrue(FinalDamageEvent.willFire(bukkit)); + + FinalDamageEvent.unregisterProvider(provider); + assertFalse(FinalDamageEvent.hasProvider()); + assertFalse(FinalDamageEvent.willFire(bukkit)); + + // Unregistering twice does nothing. + FinalDamageEvent.unregisterProvider(provider); + } + + @Test + void providers_predicateDecidesPerHit() { + Plugin provider = plugin(true); + EntityDamageEvent fall = mock(EntityDamageEvent.class); + when(fall.getCause()).thenReturn(DamageCause.FALL); + when(bukkit.getCause()).thenReturn(DamageCause.ENTITY_ATTACK); + + FinalDamageEvent.registerProvider(provider, e -> e.getCause() == DamageCause.ENTITY_ATTACK); + + assertTrue(FinalDamageEvent.hasProvider()); + assertTrue(FinalDamageEvent.willFire(bukkit)); + assertFalse(FinalDamageEvent.willFire(fall)); + } + + @Test + void providers_registeringAgainReplacesThePredicate() { + Plugin provider = plugin(true); + FinalDamageEvent.registerProvider(provider, e -> false); + assertFalse(FinalDamageEvent.willFire(bukkit)); + + FinalDamageEvent.registerProvider(provider); + assertTrue(FinalDamageEvent.willFire(bukkit)); + } + + @Test + void providers_aDisabledProviderDoesNotCount() { + Plugin provider = plugin(false); + FinalDamageEvent.registerProvider(provider); + + assertFalse(FinalDamageEvent.hasProvider()); + assertFalse(FinalDamageEvent.willFire(bukkit)); + } + + @Test + void providers_anyOneProviderIsEnough() { + FinalDamageEvent.registerProvider(plugin(true), e -> false); + FinalDamageEvent.registerProvider(plugin(true), e -> true); + + assertTrue(FinalDamageEvent.willFire(bukkit)); + } + + /** + * A provider's own event, the way Divinity's would look: it keeps the damage in fields of its own and + * overrides only the three storage methods, and it does not declare {@code getHandlerList()}. + */ + static class StorageEvent extends FinalDamageEvent { + double physical; + double fire; + + StorageEvent(LivingEntity victim, EntityDamageEvent bukkit, double physical, double fire) { + super(victim, null, null, DamageCause.ENTITY_ATTACK, bukkit, null, DamageOrigin.WEAPON_MELEE, + WeaponStatsMode.ADD, Collections.emptyMap()); + this.physical = physical; + this.fire = fire; + } + + @Override + public Map getDamages() { + Map map = new LinkedHashMap<>(); + map.put("physical", physical); + map.put("fire", fire); + return Collections.unmodifiableMap(map); + } + + @Override + public double getDamage(String type) { + switch (type) { + case "physical": + return physical; + case "fire": + return fire; + default: + return 0; + } + } + + @Override + public void setDamage(String type, double amount) { + if (amount < 0) throw new IllegalArgumentException(); + switch (type) { + case "physical": + physical = amount; + break; + case "fire": + fire = amount; + break; + default: + break; + } + } + } +}