From 891c130ebd738e0ec902e90067bc0d12923c7a7f Mon Sep 17 00:00:00 2001 From: 40 Cakes <16377135+40Cakes@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:44:57 +1100 Subject: [PATCH 1/6] Publish attack cooldowns to event bus --- .../java/com/attacktimer/AttackTimerMetronomePlugin.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java index 9270083..4947c95 100644 --- a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java +++ b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java @@ -68,8 +68,10 @@ import net.runelite.api.gameval.VarPlayerID; import net.runelite.api.gameval.VarbitID; import net.runelite.client.config.ConfigManager; +import net.runelite.client.eventbus.EventBus; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; +import net.runelite.client.events.PluginMessage; import net.runelite.client.game.ItemManager; import net.runelite.client.game.NPCManager; import net.runelite.client.plugins.Plugin; @@ -119,6 +121,9 @@ public enum AttackState @Inject private NPCManager npcManager; + @Inject + private EventBus eventBus; + public int tickPeriod = 0; private int uiHideDebounceTickCount = 0; @@ -471,6 +476,10 @@ public void onGameTick(GameTick tick) // clamp the attackDelayHoldoffTicks at -20, this is so we correctly account for eats even when not // attacking, but don't count down forever. attackDelayHoldoffTicks = Math.max(-20, attackDelayHoldoffTicks - 1); + + final int ticksRemaining = getTicksUntilNextAttack(); + eventBus.post(new PluginMessage("attacktimer", "cooldown", Map.of("ticksRemaining", ticksRemaining))); + ATTACK_SPEED.onTick(); } From a3229015310ccc1860af38832cddce7a2fee2c1c Mon Sep 17 00:00:00 2001 From: 40 Cakes <16377135+40Cakes@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:09:19 +1100 Subject: [PATCH 2/6] Revert "Publish attack cooldowns to event bus" This reverts commit 891c130ebd738e0ec902e90067bc0d12923c7a7f. --- .../java/com/attacktimer/AttackTimerMetronomePlugin.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java index 4947c95..9270083 100644 --- a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java +++ b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java @@ -68,10 +68,8 @@ import net.runelite.api.gameval.VarPlayerID; import net.runelite.api.gameval.VarbitID; import net.runelite.client.config.ConfigManager; -import net.runelite.client.eventbus.EventBus; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; -import net.runelite.client.events.PluginMessage; import net.runelite.client.game.ItemManager; import net.runelite.client.game.NPCManager; import net.runelite.client.plugins.Plugin; @@ -121,9 +119,6 @@ public enum AttackState @Inject private NPCManager npcManager; - @Inject - private EventBus eventBus; - public int tickPeriod = 0; private int uiHideDebounceTickCount = 0; @@ -476,10 +471,6 @@ public void onGameTick(GameTick tick) // clamp the attackDelayHoldoffTicks at -20, this is so we correctly account for eats even when not // attacking, but don't count down forever. attackDelayHoldoffTicks = Math.max(-20, attackDelayHoldoffTicks - 1); - - final int ticksRemaining = getTicksUntilNextAttack(); - eventBus.post(new PluginMessage("attacktimer", "cooldown", Map.of("ticksRemaining", ticksRemaining))); - ATTACK_SPEED.onTick(); } From b5c269b1e371b9785bd013b3ed40f9e69665b316 Mon Sep 17 00:00:00 2001 From: 40 Cakes <16377135+40Cakes@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:45:14 +1100 Subject: [PATCH 3/6] Create AttackTimerEventPublisher worker --- README-EventPublisher.md | 85 ++++++++ .../AttackTimerEventPublisher.java | 200 ++++++++++++++++++ .../AttackTimerMetronomePlugin.java | 14 +- 3 files changed, 298 insertions(+), 1 deletion(-) create mode 100644 README-EventPublisher.md create mode 100644 src/main/java/com/attacktimer/AttackTimerEventPublisher.java diff --git a/README-EventPublisher.md b/README-EventPublisher.md new file mode 100644 index 0000000..8d66f29 --- /dev/null +++ b/README-EventPublisher.md @@ -0,0 +1,85 @@ +# EventPublish reference +## Information for plugin developers + +Attack Timer posts its current state to the RuneLite event bus so other plugins can react to it without re-implementing attack detection. + +> **⚠️ Note: use the events as supplemental information only, your plugin should never depend on Attack Timer.** +> +> Attack Timer works by inferring attacks from animations, sounds, experience drops and worn equipment. RuneLite does not expose when the game actually considers you to have attacked. It is sometimes wrong, late or missing, for example with unusual when the game changes. +> +> Don't build anything where an incorrect or missing value would cause an issue in your plugin. Always have a sensible fallback when the data is absent or implausible. +> +> Don't assume the events are posted at a specific moment in the game tick or in a timely manner. Events should never be assumed guaranteed to be delivered. + +## The `attackTimerUpdate` message + +Namespace: `attacktimer`, name: `attackTimerUpdate`. Each message is a full snapshot, and is sent when any of +the values below changes, so during an attack cooldown you will get one message per game tick. + +Treat every key as optional (a missing key is `null`), future versions of Attack Timer may add, or change keys without notice. + +| Key | Type | Description | +|------------------------|-----------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| `ticksUntilNextAttack` | `Integer` | Game ticks until the player can attack again, `1` means they can attack on the next tick. `0` or lower means the cooldown elapsed without a new attack being detected: `0` is one tick late, `-1` two ticks late, and so on. It keeps counting down to a floor of `-19`. | +| `weaponPeriod` | `Integer` | The attack speed in game ticks which the current cooldown started with (e.g. `4` for a whip, `5` for a Tumeken's shadow). | +| `cooldownPending` | `Boolean` | `true` while Attack Timer is showing an attack cooldown. When `false` the player isn't considered to be attacking, and the tick values are leftovers from the last attack. | +| `lastTargetName` | `String` | Name of the target of the last detected attack, `null` if there hasn't been one. It is not cleared when the fight ends. | +| `lastTargetNpcId` | `Integer` | NPC id of that target, `-1` if there isn't one or it wasn't an NPC. | +| `lastTargetNpcIndex` | `Integer` | NPC index of that target (distinguishes two NPCs with the same id/name), `-1` if there isn't one or it wasn't an NPC. | + +## Event delivery + +- Updates are only sent when something changes. During a cooldown that is every game tick, and `ticksUntilNextAttack` keeps counting down after the cooldown ends, so expect up to ~20 more messages after an attack sequence finishes, then silence until the next attack. +- Nothing is sent when Attack Timer is disabled. If `cooldownPending` was `true` and the messages stop arriving, treat the data as stale. +- Messages are queued. If your subscriber (or any other plugins that share the thread) are too slow, the **oldest** queued messages are dropped. You can miss intermediate ticks, but because each message is a full snapshot the latest one you receive is still complete. +- Only the messages posted after your plugin starts are received, there's no replay. To catch up, wait for the next message. + +## How to subscribe to events + +The data is sent as a [`PluginMessage`](https://static.runelite.net/runelite-client/apidocs/net/runelite/client/events/PluginMessage.html), the RuneLite event for plugin hub plugins to send data to each other. + +You don't need to depend on Attack Timer, just subscribe to `PluginMessage` and filter on the namespace and name. See `TestSubscriber` in [`AttackTimerEventPublisher.java`](src/main/java/com/attacktimer/AttackTimerEventPublisher.java) for a code example, or set `TEST_SUBSCRIBER_ENABLED` true to test without the need of a second plugin. + +Output example: +``` +18:09:07: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=5, weaponPeriod=5} +18:09:08: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=4, weaponPeriod=5} +18:09:08: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=3, weaponPeriod=5} +18:09:09: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=2, weaponPeriod=5} +18:09:09: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=1, weaponPeriod=5} +18:09:10: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=5, weaponPeriod=5} +18:09:11: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=4, weaponPeriod=5} +18:09:11: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=7, weaponPeriod=5} +18:09:11: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=6, weaponPeriod=5} +18:09:12: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=5, weaponPeriod=5} +18:09:12: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=4, weaponPeriod=5} +18:09:13: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=3, weaponPeriod=5} +18:09:14: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=2, weaponPeriod=5} +18:09:14: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=1, weaponPeriod=5} +18:09:15: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=5, weaponPeriod=5} +18:09:15: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=4, weaponPeriod=5} +18:09:16: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=3, weaponPeriod=5} +18:09:17: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=2, weaponPeriod=5} +18:09:17: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=1, weaponPeriod=5} +18:09:18: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=0, weaponPeriod=5} +18:09:18: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-1, weaponPeriod=5} +18:09:19: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-2, weaponPeriod=5} +18:09:20: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-3, weaponPeriod=5} +18:09:20: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-4, weaponPeriod=5} +18:09:21: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-5, weaponPeriod=5} +18:09:21: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-5, weaponPeriod=5} +18:09:21: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-6, weaponPeriod=5} +18:09:22: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-7, weaponPeriod=5} +18:09:23: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-8, weaponPeriod=5} +18:09:23: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-9, weaponPeriod=5} +18:09:24: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-10, weaponPeriod=5} +18:09:24: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-11, weaponPeriod=5} +18:09:25: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-12, weaponPeriod=5} +18:09:26: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-13, weaponPeriod=5} +18:09:26: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-14, weaponPeriod=5} +18:09:27: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-15, weaponPeriod=5} +18:09:27: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-16, weaponPeriod=5} +18:09:28: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-17, weaponPeriod=5} +18:09:29: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-18, weaponPeriod=5} +18:09:29: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-19, weaponPeriod=5} +``` \ No newline at end of file diff --git a/src/main/java/com/attacktimer/AttackTimerEventPublisher.java b/src/main/java/com/attacktimer/AttackTimerEventPublisher.java new file mode 100644 index 0000000..9aabf9d --- /dev/null +++ b/src/main/java/com/attacktimer/AttackTimerEventPublisher.java @@ -0,0 +1,200 @@ +package com.attacktimer; + +/* + * Copyright (c) 2026, 40 Cakes + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Actor; +import net.runelite.api.NPC; +import net.runelite.client.eventbus.EventBus; +import net.runelite.client.eventbus.Subscribe; +import net.runelite.client.events.PluginMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + // AttackTimerEventPublisher shares the plugin's attack timer state with other plugins by posting + // PluginMessages to the RuneLite event bus. See README-EventPublisher.md for more information. +@Singleton +class AttackTimerEventPublisher +{ + private static final Logger log = LoggerFactory.getLogger(AttackTimerEventPublisher.class); + + static final String NAMESPACE = "attacktimer"; + static final String UPDATE_MESSAGE_NAME = "attackTimerUpdate"; + static final String KEY_TICKS_UNTIL_NEXT_ATTACK = "ticksUntilNextAttack"; + static final String KEY_WEAPON_PERIOD = "weaponPeriod"; + static final String KEY_COOLDOWN_PENDING = "cooldownPending"; + static final String KEY_LAST_TARGET_NAME = "lastTargetName"; + static final String KEY_LAST_TARGET_NPC_ID = "lastTargetNpcId"; + static final String KEY_LAST_TARGET_NPC_INDEX = "lastTargetNpcIndex"; + + static final int NOT_AN_NPC = -1; + static final int QUEUE_CAPACITY = 8; + private static final String THREAD_NAME = "attacktimer-event-publisher"; + + // Debug: set true to enable a subscriber inside this plugin that listens to what is posted and logs it + static final boolean TEST_SUBSCRIBER_ENABLED = true; + + private final EventBus eventBus; + private final TestSubscriber testSubscriber = new TestSubscriber(); + private ThreadPoolExecutor executor; + + private boolean hasPublished = false; + private int lastTicksUntilNextAttack; + private int lastWeaponPeriod; + private boolean lastCooldownPending; + private String lastTargetName; + private int lastTargetNpcId; + private int lastTargetNpcIndex; + + @Inject + AttackTimerEventPublisher(final EventBus eventBus) + { + this.eventBus = eventBus; + } + + // Create the worker thread. Until it is called, `publish` is a no-op + synchronized void start() + { + if (executor != null) + { + return; + } + + executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(QUEUE_CAPACITY), + runnable -> + { + final Thread thread = new Thread(runnable, THREAD_NAME); + thread.setDaemon(true); + return thread; + }, + new ThreadPoolExecutor.DiscardOldestPolicy()); + hasPublished = false; + if (TEST_SUBSCRIBER_ENABLED) + { + eventBus.register(testSubscriber); + } + } + + + // Discard anything still queued and interrupt the worker + synchronized void stop() + { + if (executor == null) + { + return; + } + if (TEST_SUBSCRIBER_ENABLED) + { + eventBus.unregister(testSubscriber); + } + executor.shutdownNow(); + executor = null; + } + + // Post the given state to the bus if it differs from the last state which was posted + synchronized void publish(final int ticksUntilNextAttack, final int weaponPeriod, final boolean cooldownPending, + @Nullable final Actor lastTarget) + { + if (executor == null) + { + return; + } + try + { + final String targetName = lastTarget == null ? null : lastTarget.getName(); + final int npcId = lastTarget instanceof NPC ? ((NPC) lastTarget).getId() : NOT_AN_NPC; + final int npcIndex = lastTarget instanceof NPC ? ((NPC) lastTarget).getIndex() : NOT_AN_NPC; + + if (hasPublished + && ticksUntilNextAttack == lastTicksUntilNextAttack + && weaponPeriod == lastWeaponPeriod + && cooldownPending == lastCooldownPending + && npcId == lastTargetNpcId + && npcIndex == lastTargetNpcIndex + && Objects.equals(targetName, lastTargetName)) + { + return; + } + hasPublished = true; + lastTicksUntilNextAttack = ticksUntilNextAttack; + lastWeaponPeriod = weaponPeriod; + lastCooldownPending = cooldownPending; + lastTargetName = targetName; + lastTargetNpcId = npcId; + lastTargetNpcIndex = npcIndex; + + final Map data = new HashMap<>(); + data.put(KEY_TICKS_UNTIL_NEXT_ATTACK, ticksUntilNextAttack); + data.put(KEY_WEAPON_PERIOD, weaponPeriod); + data.put(KEY_COOLDOWN_PENDING, cooldownPending); + data.put(KEY_LAST_TARGET_NAME, targetName); + data.put(KEY_LAST_TARGET_NPC_ID, npcId); + data.put(KEY_LAST_TARGET_NPC_INDEX, npcIndex); + + final PluginMessage message = new PluginMessage(NAMESPACE, UPDATE_MESSAGE_NAME, + Collections.unmodifiableMap(data)); + + executor.execute(() -> post(message)); + } + catch (RuntimeException e) + { + log.debug("Failed to publish attack timer update", e); + } + } + + private void post(final PluginMessage message) + { + try + { + eventBus.post(message); + } + catch (RuntimeException e) + { + log.warn("Failed to post attack timer update", e); + } + } + + public static final class TestSubscriber + { + @Subscribe + public void onPluginMessage(final PluginMessage message) + { + if (!NAMESPACE.equals(message.getNamespace()) || !UPDATE_MESSAGE_NAME.equals(message.getName())) + { + return; + } + log.info("[attacktimer test subscriber] {}/{} on thread '{}': {}", message.getNamespace(), + message.getName(), Thread.currentThread().getName(), new TreeMap<>(message.getData())); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java index 9270083..131a1ed 100644 --- a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java +++ b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java @@ -119,6 +119,9 @@ public enum AttackState @Inject private NPCManager npcManager; + @Inject + private AttackTimerEventPublisher eventPublisher; + public int tickPeriod = 0; private int uiHideDebounceTickCount = 0; @@ -472,12 +475,19 @@ public void onGameTick(GameTick tick) // attacking, but don't count down forever. attackDelayHoldoffTicks = Math.max(-20, attackDelayHoldoffTicks - 1); ATTACK_SPEED.onTick(); + publishState(); + } + + private void publishState() + { + eventPublisher.publish(getTicksUntilNextAttack(), getWeaponPeriod(), isAttackCooldownPending(), lastTarget); } @Override protected void startUp() throws Exception { trackingLostTicks = false; + eventPublisher.start(); overlayManager.add(overlay); overlay.setPreferredSize(DEFAULT_SIZE); overlayManager.add(barOverlayAboveScene); @@ -492,6 +502,7 @@ protected void shutDown() throws Exception overlayManager.remove(barOverlayAboveScene); overlayManager.remove(barOverlayUnderWidgets); overlayManager.remove(barOverlayAboveWidgets); + eventPublisher.stop(); attackDelayHoldoffTicks = 0; trackingLostTicks = false; } @@ -555,6 +566,7 @@ public void onRender() performAttack(); } checkForLateWeaponSwaps(); + publishState(); } public void checkForLateWeaponSwaps() @@ -594,4 +606,4 @@ public static void reset() ATTACK_SPEED.reset(); } -} +} \ No newline at end of file From 138ae833b93c633c4390582e2c2f49596ddb4c0b Mon Sep 17 00:00:00 2001 From: 40 Cakes <16377135+40Cakes@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:59:38 +1100 Subject: [PATCH 4/6] Default TEST_SUBSCRIBER_ENABLED to false --- src/main/java/com/attacktimer/AttackTimerEventPublisher.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/attacktimer/AttackTimerEventPublisher.java b/src/main/java/com/attacktimer/AttackTimerEventPublisher.java index 9aabf9d..381d3ff 100644 --- a/src/main/java/com/attacktimer/AttackTimerEventPublisher.java +++ b/src/main/java/com/attacktimer/AttackTimerEventPublisher.java @@ -61,7 +61,7 @@ class AttackTimerEventPublisher private static final String THREAD_NAME = "attacktimer-event-publisher"; // Debug: set true to enable a subscriber inside this plugin that listens to what is posted and logs it - static final boolean TEST_SUBSCRIBER_ENABLED = true; + static final boolean TEST_SUBSCRIBER_ENABLED = false; private final EventBus eventBus; private final TestSubscriber testSubscriber = new TestSubscriber(); From d06994b25d672f74568631b7929b5b4bebd62840 Mon Sep 17 00:00:00 2001 From: 40 Cakes <16377135+40Cakes@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:30:10 +1100 Subject: [PATCH 5/6] Fix bug where event would publish null target if NPC was in dying anim --- .../AttackTimerMetronomePlugin.java | 80 ++++++++++--------- 1 file changed, 41 insertions(+), 39 deletions(-) diff --git a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java index 131a1ed..2005a1b 100644 --- a/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java +++ b/src/main/java/com/attacktimer/AttackTimerMetronomePlugin.java @@ -138,6 +138,7 @@ public enum AttackState private Spellbook currentSpellBook = Spellbook.STANDARD; private int lastUsedWeaponId = -1; private Actor lastTarget = null; + private AttackTimerEventPublisher.Target lastTargetSnapshot = null; private boolean trackingLostTicks = false; private boolean isUsingMagic = false; @@ -319,6 +320,7 @@ private void performAttack() tickPeriod = attackDelayHoldoffTicks; uiHideDebounceTickCount = UI_HIDE_DEBOUNCE_TICKS_MAX; lastTarget = client.getLocalPlayer().getInteracting(); + lastTargetSnapshot = AttackTimerEventPublisher.Target.of(lastTarget); // Use the existing attack detection, including NPCs without a normal health ratio. trackingLostTicks = attackDelayHoldoffTicks > 0; } @@ -397,21 +399,21 @@ public void onInteractingChanged(InteractingChanged interactingChanged) { switch (attackState) { - case NOT_ATTACKING: - isUsingMagic = false; - // If not previously attacking, this action can result in a queued attack or - // an instant attack. If its queued, don't trigger the cooldown yet. - if (Attacking.isPlayerAttacking(client, npcManager, sailingCannons)) - { - logStateTrace("onInteractingChanged"); - performAttack(); - } - break; - case DELAYED_FIRST_TICK: - // fallthrough - case DELAYED: - // Don't reset tick counter or tick period. - break; + case NOT_ATTACKING: + isUsingMagic = false; + // If not previously attacking, this action can result in a queued attack or + // an instant attack. If its queued, don't trigger the cooldown yet. + if (Attacking.isPlayerAttacking(client, npcManager, sailingCannons)) + { + logStateTrace("onInteractingChanged"); + performAttack(); + } + break; + case DELAYED_FIRST_TICK: + // fallthrough + case DELAYED: + // Don't reset tick counter or tick period. + break; } } @@ -432,36 +434,36 @@ public void onGameTick(GameTick tick) final boolean isAttacking = Attacking.isPlayerAttacking(client, npcManager, sailingCannons); switch (attackState) { - case NOT_ATTACKING: - if (isAttacking) - { - logStateTrace("onGameTick"); - performAttack(); // Sets state to DELAYED_FIRST_TICK. - } - else - { - uiHideDebounceTickCount = Math.max(-20, uiHideDebounceTickCount - 1); - } - break; - case DELAYED_FIRST_TICK: - // we stay in this state for one tick to allow for 0-ticking - logStateTrace("onGameTick DELAYED_FIRST_TICK"); - attackState = AttackState.DELAYED; - // fallthrough - case DELAYED: - logStateTrace("onGameTick DELAYED"); - if (attackDelayHoldoffTicks <= 0) - { // Eligible for a new attack + case NOT_ATTACKING: if (isAttacking) { logStateTrace("onGameTick"); - performAttack(); + performAttack(); // Sets state to DELAYED_FIRST_TICK. } else { - attackState = AttackState.NOT_ATTACKING; + uiHideDebounceTickCount = Math.max(-20, uiHideDebounceTickCount - 1); + } + break; + case DELAYED_FIRST_TICK: + // we stay in this state for one tick to allow for 0-ticking + logStateTrace("onGameTick DELAYED_FIRST_TICK"); + attackState = AttackState.DELAYED; + // fallthrough + case DELAYED: + logStateTrace("onGameTick DELAYED"); + if (attackDelayHoldoffTicks <= 0) + { // Eligible for a new attack + if (isAttacking) + { + logStateTrace("onGameTick"); + performAttack(); + } + else + { + attackState = AttackState.NOT_ATTACKING; + } } - } } // This needs to come after performAttack as it's an additive affect @@ -480,7 +482,7 @@ public void onGameTick(GameTick tick) private void publishState() { - eventPublisher.publish(getTicksUntilNextAttack(), getWeaponPeriod(), isAttackCooldownPending(), lastTarget); + eventPublisher.publish(getTicksUntilNextAttack(), getWeaponPeriod(), isAttackCooldownPending(), lastTargetSnapshot); } @Override From 2b6f5e57a9454823df04d09c1effc30593a499c6 Mon Sep 17 00:00:00 2001 From: 40 Cakes <16377135+40Cakes@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:30:43 +1100 Subject: [PATCH 6/6] Add event publisher versioning v1 --- README-EventPublisher.md | 45 ++-- .../AttackTimerEventPublisher.java | 222 +++++++++++++----- 2 files changed, 189 insertions(+), 78 deletions(-) diff --git a/README-EventPublisher.md b/README-EventPublisher.md index 8d66f29..f4ffda7 100644 --- a/README-EventPublisher.md +++ b/README-EventPublisher.md @@ -1,32 +1,43 @@ -# EventPublish reference +# Event publisher reference ## Information for plugin developers Attack Timer posts its current state to the RuneLite event bus so other plugins can react to it without re-implementing attack detection. > **⚠️ Note: use the events as supplemental information only, your plugin should never depend on Attack Timer.** > -> Attack Timer works by inferring attacks from animations, sounds, experience drops and worn equipment. RuneLite does not expose when the game actually considers you to have attacked. It is sometimes wrong, late or missing, for example with unusual when the game changes. +> Attack Timer works by inferring attacks from animations, sounds, experience drops and worn equipment. RuneLite does not expose when the game actually considers you to have attacked. It is sometimes wrong, late or missing, for example with unusual weapons, special attacks, lag or after the game changes. > > Don't build anything where an incorrect or missing value would cause an issue in your plugin. Always have a sensible fallback when the data is absent or implausible. -> +> > Don't assume the events are posted at a specific moment in the game tick or in a timely manner. Events should never be assumed guaranteed to be delivered. -## The `attackTimerUpdate` message +## The `attackTimerUpdate.v1` message -Namespace: `attacktimer`, name: `attackTimerUpdate`. Each message is a full snapshot, and is sent when any of +Namespace: `attacktimer`, name: `attackTimerUpdate.v1`. Each message is a full snapshot, and is sent when any of the values below changes, so during an attack cooldown you will get one message per game tick. -Treat every key as optional (a missing key is `null`), future versions of Attack Timer may add, or change keys without notice. +Within a version, keys are never removed, renamed or given a different type or meaning, but new keys may be added at any time. Ignore keys you don't know, and treat every key as optional (a missing key is `null`). | Key | Type | Description | |------------------------|-----------|------------------------------------------------------------------------------------------------------------------------------------------------------| | `ticksUntilNextAttack` | `Integer` | Game ticks until the player can attack again, `1` means they can attack on the next tick. `0` or lower means the cooldown elapsed without a new attack being detected: `0` is one tick late, `-1` two ticks late, and so on. It keeps counting down to a floor of `-19`. | | `weaponPeriod` | `Integer` | The attack speed in game ticks which the current cooldown started with (e.g. `4` for a whip, `5` for a Tumeken's shadow). | | `cooldownPending` | `Boolean` | `true` while Attack Timer is showing an attack cooldown. When `false` the player isn't considered to be attacking, and the tick values are leftovers from the last attack. | -| `lastTargetName` | `String` | Name of the target of the last detected attack, `null` if there hasn't been one. It is not cleared when the fight ends. | +| `lastTargetName` | `String` | Name of the target of the last detected attack, `null` if there hasn't been one. It is not cleared when the fight ends, or when the target dies. | | `lastTargetNpcId` | `Integer` | NPC id of that target, `-1` if there isn't one or it wasn't an NPC. | | `lastTargetNpcIndex` | `Integer` | NPC index of that target (distinguishes two NPCs with the same id/name), `-1` if there isn't one or it wasn't an NPC. | +## Versioning + +The version is part of the message name (`attackTimerUpdate.v1`, `attackTimerUpdate.v2`, ...), so you choose the version your plugin is written for by matching that exact name. Subscribe to `PluginMessage` as usual and ignore any name you don't recognise, you won't be affected by newer versions. + +- A new version is only made for a breaking change: removing or renaming a key, or changing the type, unit or meaning of one. Adding keys isn't breaking, it doesn't need a new version. +- Old versions are kept for a deprecation period. When a new version is added the previous one is still posted next to it, until the removal date listed in the table below. + +| Version | Message name | Status | Removal | +|---------|------------------------|---------|---------| +| v1 | `attackTimerUpdate.v1` | Current | - | + ## Event delivery - Updates are only sent when something changes. During a cooldown that is every game tick, and `ticksUntilNextAttack` keeps counting down after the cooldown ends, so expect up to ~20 more messages after an attack sequence finishes, then silence until the next attack. @@ -38,9 +49,9 @@ Treat every key as optional (a missing key is `null`), future versions of Attack The data is sent as a [`PluginMessage`](https://static.runelite.net/runelite-client/apidocs/net/runelite/client/events/PluginMessage.html), the RuneLite event for plugin hub plugins to send data to each other. -You don't need to depend on Attack Timer, just subscribe to `PluginMessage` and filter on the namespace and name. See `TestSubscriber` in [`AttackTimerEventPublisher.java`](src/main/java/com/attacktimer/AttackTimerEventPublisher.java) for a code example, or set `TEST_SUBSCRIBER_ENABLED` true to test without the need of a second plugin. +You don't need to depend on Attack Timer, just subscribe to `PluginMessage` and filter on the namespace and the full versioned name (see [Versioning](#versioning)). See `TestSubscriber` in [`AttackTimerEventPublisher.java`](src/main/java/com/attacktimer/AttackTimerEventPublisher.java) for a code example, or set `TEST_SUBSCRIBER_ENABLED` true to test without the need of a second plugin. -Output example: +Output example (`attackTimerUpdate.v1`): ``` 18:09:07: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=5, weaponPeriod=5} 18:09:08: {cooldownPending=true, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=4, weaponPeriod=5} @@ -67,19 +78,5 @@ Output example: 18:09:20: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-3, weaponPeriod=5} 18:09:20: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-4, weaponPeriod=5} 18:09:21: {cooldownPending=false, lastTargetName=Kalphite Queen, lastTargetNpcId=965, lastTargetNpcIndex=42259, ticksUntilNextAttack=-5, weaponPeriod=5} -18:09:21: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-5, weaponPeriod=5} -18:09:21: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-6, weaponPeriod=5} -18:09:22: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-7, weaponPeriod=5} -18:09:23: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-8, weaponPeriod=5} -18:09:23: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-9, weaponPeriod=5} -18:09:24: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-10, weaponPeriod=5} -18:09:24: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-11, weaponPeriod=5} -18:09:25: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-12, weaponPeriod=5} -18:09:26: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-13, weaponPeriod=5} -18:09:26: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-14, weaponPeriod=5} -18:09:27: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-15, weaponPeriod=5} -18:09:27: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-16, weaponPeriod=5} -18:09:28: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-17, weaponPeriod=5} -18:09:29: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-18, weaponPeriod=5} -18:09:29: {cooldownPending=false, lastTargetName=null, lastTargetNpcId=-1, lastTargetNpcIndex=42259, ticksUntilNextAttack=-19, weaponPeriod=5} +... ``` \ No newline at end of file diff --git a/src/main/java/com/attacktimer/AttackTimerEventPublisher.java b/src/main/java/com/attacktimer/AttackTimerEventPublisher.java index 381d3ff..a0803e0 100644 --- a/src/main/java/com/attacktimer/AttackTimerEventPublisher.java +++ b/src/main/java/com/attacktimer/AttackTimerEventPublisher.java @@ -29,6 +29,7 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; @@ -40,15 +41,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - // AttackTimerEventPublisher shares the plugin's attack timer state with other plugins by posting - // PluginMessages to the RuneLite event bus. See README-EventPublisher.md for more information. +// AttackTimerEventPublisher shares the plugin's attack timer state with other plugins by posting +// PluginMessages to the RuneLite event bus. See README-EventPublisher.md for more information. @Singleton class AttackTimerEventPublisher { private static final Logger log = LoggerFactory.getLogger(AttackTimerEventPublisher.class); static final String NAMESPACE = "attacktimer"; - static final String UPDATE_MESSAGE_NAME = "attackTimerUpdate"; + // The name of a message is ".", e.g. "attackTimerUpdate.v1", consumers pick the + // version they were written against by matching the full name. See "Versioning" in README-EventPublisher.md + static final String UPDATE_MESSAGE_BASE_NAME = "attackTimerUpdate"; + static final String UPDATE_V1_NAME = UPDATE_MESSAGE_BASE_NAME + ".v1"; + + // v1 keys static final String KEY_TICKS_UNTIL_NEXT_ATTACK = "ticksUntilNextAttack"; static final String KEY_WEAPON_PERIOD = "weaponPeriod"; static final String KEY_COOLDOWN_PENDING = "cooldownPending"; @@ -63,25 +69,120 @@ class AttackTimerEventPublisher // Debug: set true to enable a subscriber inside this plugin that listens to what is posted and logs it static final boolean TEST_SUBSCRIBER_ENABLED = false; + // The state of the plugin which gets published, every version of the message is built from this + static final class State + { + final int ticksUntilNextAttack; + final int weaponPeriod; + final boolean cooldownPending; + @Nullable + final Target lastTarget; + + State(final int ticksUntilNextAttack, final int weaponPeriod, final boolean cooldownPending, + @Nullable final Target lastTarget) + { + this.ticksUntilNextAttack = ticksUntilNextAttack; + this.weaponPeriod = weaponPeriod; + this.cooldownPending = cooldownPending; + this.lastTarget = lastTarget; + } + + boolean matches(final int ticksUntilNextAttack, final int weaponPeriod, final boolean cooldownPending, + @Nullable final Target lastTarget) + { + return this.ticksUntilNextAttack == ticksUntilNextAttack + && this.weaponPeriod == weaponPeriod + && this.cooldownPending == cooldownPending + && Objects.equals(this.lastTarget, lastTarget); + } + } + + static final class Target + { + @Nullable + final String name; + final int npcId; + final int npcIndex; + + Target(@Nullable final String name, final int npcId, final int npcIndex) + { + this.name = name; + this.npcId = npcId; + this.npcIndex = npcIndex; + } + + @Nullable + static Target of(@Nullable final Actor actor) + { + if (actor == null) + { + return null; + } + final boolean isNpc = actor instanceof NPC; + return new Target(actor.getName(), isNpc ? ((NPC) actor).getId() : NOT_AN_NPC, + isNpc ? ((NPC) actor).getIndex() : NOT_AN_NPC); + } + + @Override + public boolean equals(final Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof Target)) + { + return false; + } + final Target other = (Target) o; + return npcId == other.npcId && npcIndex == other.npcIndex && Objects.equals(name, other.name); + } + + @Override + public int hashCode() + { + return Objects.hash(name, npcId, npcIndex); + } + } + + static final class MessageVersion + { + final String name; + final Function> encoder; + + MessageVersion(final String name, final Function> encoder) + { + this.name = name; + this.encoder = encoder; + } + } + + // Every version in here is posted on every change. To make a breaking change to the message add a new + // version to this list (keeping the old one for the deprecation period), don't change an existing one + static final List SUPPORTED_VERSIONS = Collections.unmodifiableList(Arrays.asList( + new MessageVersion(UPDATE_V1_NAME, AttackTimerEventPublisher::encodeV1))); + private final EventBus eventBus; + private final List versions; private final TestSubscriber testSubscriber = new TestSubscriber(); private ThreadPoolExecutor executor; - private boolean hasPublished = false; - private int lastTicksUntilNextAttack; - private int lastWeaponPeriod; - private boolean lastCooldownPending; - private String lastTargetName; - private int lastTargetNpcId; - private int lastTargetNpcIndex; + private State lastState = null; + private final Map> lastPosted = new HashMap<>(); @Inject AttackTimerEventPublisher(final EventBus eventBus) + { + this(eventBus, SUPPORTED_VERSIONS); + } + + AttackTimerEventPublisher(final EventBus eventBus, final List versions) { this.eventBus = eventBus; + this.versions = versions; } - // Create the worker thread. Until it is called, `publish` is a no-op + // Create the worker thread. Until it is called, `publish` is a no-op synchronized void start() { if (executor != null) @@ -98,7 +199,7 @@ synchronized void start() return thread; }, new ThreadPoolExecutor.DiscardOldestPolicy()); - hasPublished = false; + resetPublished(); if (TEST_SUBSCRIBER_ENABLED) { eventBus.register(testSubscriber); @@ -106,7 +207,7 @@ synchronized void start() } - // Discard anything still queued and interrupt the worker + // Discard anything still queued and interrupt the worker synchronized void stop() { if (executor == null) @@ -121,9 +222,9 @@ synchronized void stop() executor = null; } - // Post the given state to the bus if it differs from the last state which was posted + // Post the given state to the bus if it differs from the last state which was posted, in every version synchronized void publish(final int ticksUntilNextAttack, final int weaponPeriod, final boolean cooldownPending, - @Nullable final Actor lastTarget) + @Nullable final Target lastTarget) { if (executor == null) { @@ -131,56 +232,69 @@ synchronized void publish(final int ticksUntilNextAttack, final int weaponPeriod } try { - final String targetName = lastTarget == null ? null : lastTarget.getName(); - final int npcId = lastTarget instanceof NPC ? ((NPC) lastTarget).getId() : NOT_AN_NPC; - final int npcIndex = lastTarget instanceof NPC ? ((NPC) lastTarget).getIndex() : NOT_AN_NPC; - - if (hasPublished - && ticksUntilNextAttack == lastTicksUntilNextAttack - && weaponPeriod == lastWeaponPeriod - && cooldownPending == lastCooldownPending - && npcId == lastTargetNpcId - && npcIndex == lastTargetNpcIndex - && Objects.equals(targetName, lastTargetName)) + if (lastState != null && lastState.matches(ticksUntilNextAttack, weaponPeriod, cooldownPending, lastTarget)) { return; } - hasPublished = true; - lastTicksUntilNextAttack = ticksUntilNextAttack; - lastWeaponPeriod = weaponPeriod; - lastCooldownPending = cooldownPending; - lastTargetName = targetName; - lastTargetNpcId = npcId; - lastTargetNpcIndex = npcIndex; - - final Map data = new HashMap<>(); - data.put(KEY_TICKS_UNTIL_NEXT_ATTACK, ticksUntilNextAttack); - data.put(KEY_WEAPON_PERIOD, weaponPeriod); - data.put(KEY_COOLDOWN_PENDING, cooldownPending); - data.put(KEY_LAST_TARGET_NAME, targetName); - data.put(KEY_LAST_TARGET_NPC_ID, npcId); - data.put(KEY_LAST_TARGET_NPC_INDEX, npcIndex); - - final PluginMessage message = new PluginMessage(NAMESPACE, UPDATE_MESSAGE_NAME, - Collections.unmodifiableMap(data)); - - executor.execute(() -> post(message)); + final State state = new State(ticksUntilNextAttack, weaponPeriod, cooldownPending, lastTarget); + + final List messages = new ArrayList<>(versions.size()); + for (final MessageVersion version : versions) + { + final Map data = version.encoder.apply(state); + if (data.equals(lastPosted.get(version.name))) + { + continue; + } + lastPosted.put(version.name, data); + messages.add(new PluginMessage(NAMESPACE, version.name, Collections.unmodifiableMap(data))); + } + lastState = state; + + if (!messages.isEmpty()) + { + executor.execute(() -> post(messages)); + } } catch (RuntimeException e) { + resetPublished(); log.debug("Failed to publish attack timer update", e); } } - private void post(final PluginMessage message) + private void resetPublished() { - try - { - eventBus.post(message); - } - catch (RuntimeException e) + lastState = null; + lastPosted.clear(); + } + + private static Map encodeV1(final State state) + { + // v1 + final Target target = state.lastTarget; + final Map data = new HashMap<>(); + data.put(KEY_TICKS_UNTIL_NEXT_ATTACK, state.ticksUntilNextAttack); + data.put(KEY_WEAPON_PERIOD, state.weaponPeriod); + data.put(KEY_COOLDOWN_PENDING, state.cooldownPending); + data.put(KEY_LAST_TARGET_NAME, target == null ? null : target.name); + data.put(KEY_LAST_TARGET_NPC_ID, target == null ? NOT_AN_NPC : target.npcId); + data.put(KEY_LAST_TARGET_NPC_INDEX, target == null ? NOT_AN_NPC : target.npcIndex); + return data; + } + + private void post(final List messages) + { + for (final PluginMessage message : messages) { - log.warn("Failed to post attack timer update", e); + try + { + eventBus.post(message); + } + catch (RuntimeException e) + { + log.warn("Failed to post attack timer update", e); + } } } @@ -189,7 +303,7 @@ public static final class TestSubscriber @Subscribe public void onPluginMessage(final PluginMessage message) { - if (!NAMESPACE.equals(message.getNamespace()) || !UPDATE_MESSAGE_NAME.equals(message.getName())) + if (!NAMESPACE.equals(message.getNamespace()) || !UPDATE_V1_NAME.equals(message.getName())) { return; }