xxxxplayz

I want to create a PaperMC plugin using ProtocolLib that fixes a specific combat timing issue.

The Logic:

Intercept the player's attack and interaction packets.

The Fix: Prevent the server from resetting the AttackCooldown (swing strength) if the player is simultaneously placing a block or using an item in their offhand.

Constraint: The hit cooldown should still function normally when the player is simply attacking with a sword or axe. We only want to 'protect' the cooldown charge from being interrupted by offhand block placement.

Specifics: If a PacketPlayInUseItem (offhand) and PacketPlayInArmAnimation happen within the same 1-2 ticks, ensure the Generic.ATTACK_SPEED attribute isn't reset to zero.

Please provide the Java code for the listener and explain how to register it in the main class.

Kodari AI
KodariApr 21 at 3:41 am 5,052 (v2)
CombatTimingFix
A PaperMC plugin using ProtocolLib that fixes a combat timing edge case where offhand block placement or item use incorrectly interrupts the melee attack cooldown. Intercepts PacketPlayInArmAnimation and PacketPlayInUseItem packets and suppresses the arm swing if both are detected within 1–2 ticks of each other, preserving the attack charge. Normal melee swings are completely unaffected.

Plan:

  • CombatTimingFix.java — main plugin class, registers ProtocolLib listener, exposes GUIManager-style accessors

  • CombatPacketListener.java — ProtocolLib PacketAdapter that tracks per-player offhand USE_ITEM timestamps and cancels a concurrent ARM_ANIMATION if within the 2-tick window

  • plugin.yml + build.gradle + settings.gradle

The core logic uses System.currentTimeMillis() with a 100 ms window (≈2 ticks at 50 ms/tick) to detect simultaneous offhand-use + swing. If the guard fires, the ARM_ANIMATION packet is cancelled before the server processes it, so the attack strength ticker is never reset.


How it works — end-to-end:

Stage
What happens
Player places offhand block
PacketPlayInUseItem
arrives →
hand == OFF_HAND
→ timestamp recorded in
offhandUseTimestamps
Player swings within ≤100 ms
PacketPlayInArmAnimation
arrives → elapsed ≤ guard window →
packet cancelled
→ server never processes the swing → attack strength ticker is untouched
Player swings normally
No recent offhand timestamp exists (or it expired) → packet passes through completely unmodified
Old timestamps
Cleaned up on the next ARM_ANIMATION regardless of outcome — no memory leak

Why cancel ARM_ANIMATION instead of modifying attributes: The attackStrengthTicker is a private NMS field reset inside ServerGamePacketListenerImpl as a direct consequence of receiving the arm animation packet. Cancelling the packet upstream via ProtocolLib is the cleanest interception point — no NMS reflection, no version fragility, and no risk of the attribute being temporarily set to 0 and triggering dependent game logic before we can restore it.

Registration is handled entirely in onEnable() via protocolManager.addPacketListener(combatPacketListener) — no plugin.yml packet entries needed. ProtocolLib routes both packet types to the single onPacketReceiving method where the type is dispatched manually.

xxxxplayz

I am using Leaf 1.21.11. The previous 'Save and Restore' method is being overridden by the server's attribute tracking. Please write a new CombatPacketListener.java that uses Attribute Locking:

Intercept Metadata: Listen for PacketType.Play.Server.ENTITY_METADATA and PacketType.Play.Server.UPDATE_ATTRIBUTES.

The Lock: When a player uses an item in their OFF_HAND, flag them as 'CombatLocked' for 3 ticks.

The Prevention: During those 3 ticks, if the server tries to send an attribute update that would reset the GENERIC_ATTACK_SPEED or change the DATA_PLAYER_ABSORPTION_VALUE (which often syncs with cooldowns), cancel that specific packet for that player.

Hand Check: Ensure it uses the 1.21.11 hand index (where Offhand is index 1).

xxxxplayz

I am using Leaf 1.21.11. The previous 'Save and Restore' method is being overridden by the server's attribute tracking. Please write a new CombatPacketListener.java that uses Attribute Locking:

Intercept Metadata: Listen for PacketType.Play.Server.ENTITY_METADATA and PacketType.Play.Server.UPDATE_ATTRIBUTES.

The Lock: When a player uses an item in their OFF_HAND, flag them as 'CombatLocked' for 3 ticks.

The Prevention: During those 3 ticks, if the server tries to send an attribute update that would reset the GENERIC_ATTACK_SPEED or change the DATA_PLAYER_ABSORPTION_VALUE (which often syncs with cooldowns), cancel that specific packet for that player.

Hand Check: Ensure it uses the 1.21.11 hand index (where Offhand is index 1).

Kodari AI
KodariApr 23 at 4:18 am 5,838 (v2)
  • The new approach intercepts outbound server packets (UPDATE_ATTRIBUTES, ENTITY_METADATA) in addition to the inbound USE_ITEM

  • A ConcurrentHashMap<UUID, Long> stores a lockUntilMs timestamp (3 ticks = 150 ms) set when an offhand use is detected

  • Both outbound packet handlers verify the entity ID matches the locked player before cancelling, so no other entities are affected


What changed and why, section by section:

Dual-listener registration

Java
PacketType.Play.Client.USE_ITEM,       // inbound  — detects offhand trigger
PacketType.Play.Server.UPDATE_ATTRIBUTES,  // outbound — blocks attack_speed reset
PacketType.Play.Server.ENTITY_METADATA    // outbound — blocks absorption sync

ProtocolLib routes inbound types to onPacketReceiving and outbound types to onPacketSending automatically from the same adapter instance.

Offhand detection — dual-path read

Java
int handIndex = event.getPacket().getIntegers().read(0);
// fallback → EnumWrappers.Hand

In 1.21.1 the USE_ITEM packet encodes hand as a raw VarInt (0 = main, 1 = off). The integer read is attempted first; if the ProtocolLib version serialises it as an enum instead, the fallback path catches it. OFFHAND_INDEX = 1 is the hardcoded 1.21.1 value you asked for.

Lock window

Java
private static final long LOCK_DURATION_MS = 150L; // 3 ticks × 50 ms

Stored as an absolute lockUntilMs epoch so every subsequent packet check is a single > comparator with no counter drift.

handleAttributeUpdate — why key-contains rather than equals The attribute key in 1.21 is namespaced minecraft:generic.attack_speed) so .contains("attack_speed") matches regardless of whether ProtocolLib includes the namespace prefix, keeping it version-resilient.

handleEntityMetadata — absorption index 15 In 1.21 NMS, Player.DATA_PLAYER_ABSORPTION_ID is registered as the first Player-specific metadata slot. Counting from 0: Entity (0–7) + LivingEntity (8–14) = Player slot starts at 15. The check is index-exact so unrelated metadata entries (health, pose, etc.) pass through untouched.

Entity ID guard on both outbound handlers

Java
if (entityId != player.getEntityId()) return;

Prevents the lock from accidentally cancelling attribute or metadata packets destined for other entities near the player.

xxxxplayz

Not 1.21.1, make it for 1.21.11

Kodari AI
KodariApr 23 at 4:21 am 8,493 (v2)

Three concrete issues to fix for 1.21.11 (1.21.4+ NMS surface):

  • Hand detection is broken — In 1.21.x the USE_ITEM packet layout is hand (enum VarInt), sequence (int). The old code calls getIntegers().read(0) first, which reads the sequence number, not the hand. Offhand detection never fires correctly.

  • getAttributeKey() is deprecated in ProtocolLib 5.x on 1.21.4+ — must use getAttributeType().getKey().toString() instead.

  • Absorption metadata index shifts to 14 in 1.21.4+ — Entity now occupies slots 0–7, LivingEntity 8–13, so the first Player-exclusive slot is 14 (additional hearts / absorption tracker).


Summary of every change:

Location
Old (broken on 1.21.11)
New (correct)
Hand detection
getIntegers().read(0)
first → reads
sequence int
, not hand
getHands().read(0)
first → reads
enum
, integer only as true last-resort
METADATA_ABSORPTION_INDEX
15
(1.21.1 layout)
14
(1.21.4+ layout — Player metadata starts one slot earlier)
Attribute key lookup
attr.getAttributeKey()
(deprecated, may throw in PLib 5.x)
attr.getAttributeType().getKey().toString()
with
getAttributeKey()
as the fallback

The hand detection fix is the most critical — without it the offhand trigger never fires because getIntegers().read(0) returns the sequence counter (a monotonically incrementing int), which only coincidentally equals 1 on a player’s very first interaction, making the lock appear to work sporadically in testing but fail reliably in real combat.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
5 316
src/main/java/com/plugin/combattimingfix/CombatTimingFix.java
package com.plugin.combattimingfix;

import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import lombok.Getter;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;

public class CombatTimingFix extends JavaPlugin {

    @Getter
    private static CombatTimingFix instance;

    @Getter
    private ProtocolManager protocolManager;

    private CombatPacketListener combatPacketListener;

    @Override
    public void onEnable() {
        instance = this;
        protocolManager = ProtocolLibrary.getProtocolManager();

        combatPacketListener = new CombatPacketListener(this);
        protocolManager.addPacketListener(combatPacketListener);

        getLogger().info("CombatTimingFix enabled — offhand cooldown guard active.");
    }

    @Override
    public void onDisable() {
        if (protocolManager != null && combatPacketListener != null) {
            protocolManager.removePacketListener(combatPacketListener);
        }
        getLogger().info("CombatTimingFix disabled.");
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!command.getName().equalsIgnoreCase("combattimingfix")) {
            return false;
        }
        if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
            if (!sender.hasPermission("combattimingfix.admin")) {
                sender.sendMessage("&cYou do not have permission to use this command.");
                return true;
            }
            if (combatPacketListener != null) {
                combatPacketListener.clearAll();
            }
            sender.sendMessage("&aCombatTimingFix internal state cleared.");
            return true;
        }
        sender.sendMessage("&eUsage: /combattimingfix reload");
        return true;
    }
}