0x2F S2FPacketSetSlot
Sets a single slot in an inventory window. Used for cursor updates, specific slot changes, and armor slot updates.
Published 2026-06-18 · Updated 2026-10-14
Fields
| Field | Type | Description |
|---|---|---|
| windowId | byte | Window ID (-1 = cursor, 0 = player inv) |
| slot | short | Slot index (-1 = cursor) |
| item | Slot (ItemStack) | ItemStack to place in slot (null = clear) |
Wire Encoding
| Field | Type | Notes |
|---|---|---|
| Window ID | byte | -1=cursor, 0=player inventory |
| Slot | short | Slot index |
| Slot Data | Slot | ItemStack or null |
MCP References
NetHandlerPlayClient.handleSetSlot()Handler Interface
INetHandlerPlayClientNotes
Vanilla Source
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
Deobfuscated MCP 1.8.9 source of S2FPacketSetSlot, fetched directly from Marcelektro/MavenMCP-1.8.9 (net/minecraft/network/play/server/S2FPacketSetSlot.java) at build time and verified present.
Deep Dive
Role in the protocol
S2FPacketSetSlot is the single-slot inventory sync packet, the fine-grained counterpart to the S30 full-window dump. The server emits it for every slot mutation: EntityPlayerMP.updateCraftingInventory pushes windowId/slot/stack on each container change, the cursor is synced with the (-1, -1) variant after clicks settle (lines 760, 774, 805), NetHandlerPlayServer line 554 re-sends the held hotbar slot after a swap, and ItemEditableBook pushes the signed book back into slot 0. windowId -1 means the cursor, 0 means the player inventory, anything else the open container.
Vanilla handling
NetHandlerPlayClient.handleSetSlot resolves the target container from the window id: -1 sets the player's cursor stack, 0 and the player inventory window id write into inventoryContainer, otherwise the open container receives the slot. The matching GuiScreen is notified so the renderer updates. There is no validation: the client trusts the server's slot content unconditionally, which is exactly the trust that cancel-based modules exploit. The vanilla client never sends S2F; it is strictly clientbound.
Why clients touch it
Four distinct uses in the 8 clients. Rise 5.99 Auto sniffs S2F for the Redesky captcha item and clicks it with a crafted C0E. Rise 5.99 Scaffold and Spicy BlockFly cancel every S2F so the server cannot correct the hotbar while they place blocks. Tenacity 6.0 NoSlowModule cancels window-0 slot updates while using a non-sword item, keeping the ghost-item no-slow state alive. Rise 6.x AdaptiveRefreshRateComponent treats S2F as a significant packet that forces a HUD cache redraw, and PacketUtil exposes a wrapper for the script API.
Exploit surface
Cancelling S2F is a local lie that only survives until the next window resync: the server owns slot state, and a rejected click (S32 accepted=false) triggers a full S30 dump that snaps the client back. That makes S2F cancellation a short-horizon trick, useful inside a single click loop, not a persistent desync. For inventory modules the packet is a cheap signal: an armor swap or a hotbar change arrives as one small packet, so AutoArmor-style logic can react without parsing a window. The trade-off is ordering: any module that cancels S2F upstream silently blinds every other module that reads it.
Server-Side Handling
EntityPlayerMP.updateCraftingInventory sends S2F(windowId, slot, stack) per slot change and the cursor variant (-1, -1) after click processing (lines 760, 774, 805 in the bundled sources). NetHandlerPlayServer line 554 re-sends the held item slot after a hotbar swap; ItemEditableBook line 116 pushes the signed book into slot 0. There is no rate limit and no client-side validation: handleSetSlot writes the slot into the resolved container and notifies the open GUI.
Protocol Analysis
Wire layout: byte windowId, short slot, then a Slot encoding (short item id, byte count, short damage, optional NBT; item id -1 encodes null). windowId -1 (0xFF) targets the cursor, 0 the player inventory, other values the open container. S2F is PLAY-state only and always carries exactly one slot, which is what makes it the cheapest way for a module to detect an armor equip or hotbar change. The cursor variant pairs slot -1 with windowId -1.
Anti-Cheat Landscape
No anti-cheat measures S2F: it is server-authoritative display state. The abuse is purely client-side view desync, and the detection surface is the eventual resync: a server that rejects a click re-sends S30, and any client that still behaves as if the old slot content exists is visibly desynced. Cancel-heavy movement modules (Scaffold, BlockFly) therefore risk inventory desync that manifests as phantom hotbar items rather than a flag.
implementation Implementation Cases
The single-slot sync packet and the cheapest inventory signal on the wire. Rise's Auto reads it to click captcha items, Scaffold and Spicy's BlockFly cancel it to freeze the hotbar, Tenacity's NoSlow cancels window-0 updates to preserve a ghost item, and Rise 6.x treats it as a HUD-significant packet. The server always owns slot truth; cancelling only delays the client's view.
Automated Redesky captcha solving: detect a captcha item in a container slot via S2F and click it before the server times it out.
PacketReceiveEvent; on S2F, skip window 0 (player inventory), then check the item's display name case-insensitively for 'aqui'. On match, send C0EPacketClickWindow(windowId, slot, 0, 0, item, (short) 1919): button 0, mode 0, and an absurdly large action number the server ignores. Runs only while the redeskyAutoCaptcha setting is on.
// ===== FILE: Rise 5.99, dev/rise/module/impl/other/Auto.java =====
/*
Copyright Alan Wood 2021
None of this code to be reused without my written permission
Intellectual Rights owned by Alan Wood
*/
package dev.rise.module.impl.other;
import dev.rise.event.impl.motion.PreMotionEvent;
import dev.rise.event.impl.packet.PacketReceiveEvent;
import dev.rise.module.Module;
import dev.rise.module.api.ModuleInfo;
import dev.rise.module.enums.Category;
import dev.rise.setting.impl.BooleanSetting;
import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C0EPacketClickWindow;
import net.minecraft.network.play.server.S2FPacketSetSlot;
@ModuleInfo(name = "Auto", description = "Automatically does things for you", category = Category.OTHER)
public final class Auto extends Module {
private final BooleanSetting redeskyAutoCaptcha = new BooleanSetting("Redesky Auto Captcha", this, false);
private final BooleanSetting redeskyAutoRegister = new BooleanSetting("Redesky Auto Register", this, false);
boolean sentReg, sentLogin;
int ticks;
int amountFlagged;
@Override
public void onPacketReceive(final PacketReceiveEvent event) {
final Packet packet = event.getPacket();
if (redeskyAutoCaptcha.isEnabled()) {
if (packet instanceof S2FPacketSetSlot) {
final S2FPacketSetSlot S2F = (S2FPacketSetSlot) packet;
if (S2F.func_149175_c() == 0) {
return;
}
final ItemStack item = S2F.func_149174_e();
if (item != null && item.getDisplayName().toLowerCase().contains("aqui")) {
mc.thePlayer.sendQueue.addToSendQueue(new C0EPacketClickWindow(S2F.func_149175_c(), S2F.func_149173_d(), 0, 0, item, (short) 1919));
}
}
}
}
@Override
public void onPreMotion(final PreMotionEvent event) {
if (mc.thePlayer.ticksExisted % 20 == 0)
amountFlagged--;
if (amountFlagged < 0)
amountFlagged = 0;
if (redeskyAutoRegister.isEnabled()) {
if (mc.thePlayer.ticksExisted == 1) {
sentLogin = sentReg = false;
}
if (mc.currentScreen == null) {
ticks++;
if (ticks > 30) {
if (!sentReg) {
mc.thePlayer.sendChatMessage("/register Lolxd00 Lolxd00");
sentReg = true;
} else if (!sentLogin) {
mc.thePlayer.sendChatMessage("/login Lolxd00");
sentLogin = true;
}
}
} else {
ticks = 0;
}
}
}
}
// NOTE (AI): The Redesky captcha item is matched case-insensitively against 'aqui' in the display name and clicked with action number 1919, a deliberately large value the server tolerates. Window 0 (player inventory) slots are skipped by the early return so only open-container slots are scanned.
Cancel all incoming slot sync so the server cannot correct the client's hotbar view during the block placement loop.
onPacketReceive: if the packet is S2FPacketSetSlot, event.setCancelled(true). Every slot update is dropped while scaffolding, keeping the client's own view of the hotbar authoritative for the placement loop.
Block-fly movement that cancels S2F so the server cannot correct the fake block placement state.
EventPacket pre-phase: if the packet is S2FPacketSetSlot, setCanceled(true), unless killaura has a target, in which case the handler returns early so weapon switching stays synced. The module also freezes yaw and pitch on C03 and EventMotion and places blocks below the player via onPlayerRightClick.
// ===== FILE: Spicy, info/spicyclient/modules/movement/BlockFly.java =====
package info.spicyclient.modules.movement;
import java.util.Comparator;
import java.util.Random;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.tests.xml.ItemContainer;
import info.spicyclient.SpicyClient;
import info.spicyclient.chatCommands.Command;
import info.spicyclient.events.Event;
import info.spicyclient.events.listeners.EventMotion;
import info.spicyclient.events.listeners.EventPacket;
import info.spicyclient.events.listeners.EventRender3D;
import info.spicyclient.events.listeners.EventSendPacket;
import info.spicyclient.events.listeners.EventSneaking;
import info.spicyclient.events.listeners.EventUpdate;
import info.spicyclient.modules.Module;
import info.spicyclient.settings.BooleanSetting;
import info.spicyclient.settings.ModeSetting;
import info.spicyclient.settings.NumberSetting;
import info.spicyclient.settings.SettingChangeEvent;
import info.spicyclient.settings.SettingChangeEvent.type;
import info.spicyclient.util.MovementUtils;
import info.spicyclient.util.RenderUtils;
import info.spicyclient.util.RotationUtils;
import info.spicyclient.util.Timer;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C02PacketUseEntity;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
import net.minecraft.network.play.client.C09PacketHeldItemChange;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
public class BlockFly extends Module {
public BlockFly() {
super("Block Fly", Keyboard.KEY_NONE, Category.MOVEMENT);
}
public void onEnable() {
lastYaw = mc.thePlayer.rotationYaw;
lastPitch = mc.thePlayer.rotationPitch;
}
public void onDisable() {
}
public static transient float lastYaw = 0, lastPitch = 0;
public static transient Timer timer = new Timer();
public void onEvent(Event e) {
if (e instanceof EventSneaking) {
if (e.isPre()) {
if (SpicyClient.config.killaura.isEnabled() && SpicyClient.config.killaura.target != null) {
return;
}
EventSneaking sneak = (EventSneaking) e;
if (sneak.entity.onGround && sneak.entity instanceof EntityPlayer) {
sneak.sneaking = true;
}else {
sneak.sneaking = false;
}
sneak.offset = -1D;
sneak.revertFlagAfter = true;
}
}
if (e instanceof EventPacket && e.isPre()) {
if (SpicyClient.config.killaura.isEnabled() && SpicyClient.config.killaura.target != null) {
return;
}
if (((EventPacket)e).packet instanceof S2FPacketSetSlot) {
e.setCanceled(true);
}
}
if (e instanceof EventSendPacket & e.isPre()) {
if (SpicyClient.config.killaura.isEnabled() && SpicyClient.config.killaura.target != null) {
return;
}
if (((EventSendPacket)e).packet instanceof C03PacketPlayer) {
((C03PacketPlayer)((EventSendPacket)e).packet).setYaw(lastYaw);
((C03PacketPlayer)((EventSendPacket)e).packet).setPitch(lastPitch);
}
}
if (e instanceof EventRender3D && e.isPre()) {
BlockPos below = new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 1D, mc.thePlayer.posZ);
for (int i = 0; i < 5; i++) {
RenderUtils.drawLine(below.getX(), below.getY(), below.getZ(), below.getX() + 1, below.getY(), below.getZ());
RenderUtils.drawLine(below.getX(), below.getY() + 1, below.getZ(), below.getX() + 1, below.getY() + 1, below.getZ());
RenderUtils.drawLine(below.getX(), below.getY(), below.getZ(), below.getX(), below.getY(), below.getZ() + 1);
RenderUtils.drawLine(below.getX(), below.getY() + 1, below.getZ(), below.getX(), below.getY() + 1, below.getZ() + 1);
RenderUtils.drawLine(below.getX(), below.getY(), below.getZ(), below.getX(), below.getY() + 1, below.getZ());
RenderUtils.drawLine(below.getX(), below.getY() + 1, below.getZ(), below.getX(), below.getY() + 1, below.getZ());
RenderUtils.drawLine(below.getX() + 1, below.getY(), below.getZ(), below.getX() + 1, below.getY() + 1, below.getZ());
RenderUtils.drawLine(below.getX() + 1, below.getY() + 1, below.getZ(), below.getX() + 1, below.getY() + 1, below.getZ());
RenderUtils.drawLine(below.getX(), below.getY(), below.getZ() + 1, below.getX(), below.getY() + 1, below.getZ() + 1);
RenderUtils.drawLine(below.getX(), below.getY() + 1, below.getZ() + 1, below.getX(), below.getY() + 1, below.getZ() + 1);
RenderUtils.drawLine(below.getX() + 1, below.getY(), below.getZ() + 1, below.getX(), below.getY(), below.getZ() + 1);
RenderUtils.drawLine(below.getX() + 1, below.getY() + 1, below.getZ() + 1, below.getX(), below.getY() + 1, below.getZ() + 1);
RenderUtils.drawLine(below.getX() + 1, below.getY(), below.getZ() + 1, below.getX() + 1, below.getY() + 1, below.getZ() + 1);
RenderUtils.drawLine(below.getX() + 1, below.getY() + 1, below.getZ(), below.getX() + 1, below.getY() + 1, below.getZ() + 1);
RenderUtils.drawLine(below.getX() + 1, below.getY(), below.getZ(), below.getX() + 1, below.getY(), below.getZ() + 1);
}
}
if (e instanceof EventUpdate && e.isPre() && MovementUtils.isOnGround(0.4)) {
if (SpicyClient.config.killaura.isEnabled() && SpicyClient.config.killaura.target != null) {
return;
}
//mc.thePlayer.onGround = false;
EventUpdate update = (EventUpdate)e;
double motionX = mc.thePlayer.motionX, motionZ = mc.thePlayer.motionZ;
if (motionX < 0)
motionX *= -1;
if (motionZ < 0)
motionZ *= -1;
if (motionX < 0.05 && motionZ < 0.05 && MovementUtils.isOnGround(0.3) && mc.gameSettings.keyBindJump.isKeyDown()) {
if (mc.gameSettings.keyBindJump.isKeyDown() && MovementUtils.isOnGround(0.25)) {
//mc.thePlayer.motionX = 0.0D;
//mc.thePlayer.motionZ = 0.0D;
//mc.thePlayer.motionY = 0.375;
if (timer.hasTimeElapsed(1500, true)) {
//mc.thePlayer.motionY = -0.28D;
}
}
}
}
if (e instanceof EventMotion && e.isPost()) {
if (SpicyClient.config.killaura.isEnabled() && SpicyClient.config.killaura.target != null) {
return;
}
EventMotion event = (EventMotion) e;
//mc.thePlayer.setSprinting(false);
event.setYaw(lastYaw);
event.setYaw(lastPitch);
ItemStack i = mc.thePlayer.getCurrentEquippedItem();
BlockPos below = new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 1D, mc.thePlayer.posZ);
if (mc.theWorld.getBlockState(below).getBlock() == Blocks.air) {
for (EnumFacing facing : EnumFacing.VALUES) {
switch (facing) {
case UP:
BlockPos underBelow = new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 2D, mc.thePlayer.posZ);
if (mc.theWorld.getBlockState(underBelow).getBlock() != Blocks.air) {
ItemStack block = mc.thePlayer.getCurrentEquippedItem();
for (int g = 0; g < 9; g++) {
if (mc.thePlayer.inventoryContainer.getSlot(g + 36).getHasStack() && mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem() instanceof ItemBlock && mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().stackSize > 0 && !((ItemBlock)mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem()).getBlock().getLocalizedName().toLowerCase().contains("chest") && !((ItemBlock)mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem()).getBlock().getLocalizedName().toLowerCase().contains("table")) {
InventoryPlayer inventoryplayer = mc.thePlayer.inventory;
inventoryplayer.setCurrentItem(mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem(), 0, false, true);
}
}
if (mc.playerController.onPlayerRightClick(mc.thePlayer, mc.theWorld, block, underBelow, EnumFacing.UP, RotationUtils.getVectorForRotation(getRotationsHypixel(underBelow, EnumFacing.UP)[1], getRotationsHypixel(underBelow, EnumFacing.UP)[1])) || true) {
mc.thePlayer.swingItem();
event.setYaw(getRotationsHypixel(underBelow, facing)[0]);
event.setPitch(getRotationsHypixel(underBelow, facing)[1]);
lastYaw = event.yaw;
lastPitch = event.pitch;
return;
}
return;
}
break;
case NORTH:
case EAST:
case SOUTH:
case WEST:
BlockInfo defaultPos = findFacingAndBlockPosForBlock(new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 1D, mc.thePlayer.posZ + mc.thePlayer.motionZ));
if (defaultPos == null)
return;
if (mc.theWorld.getBlockState(defaultPos.pos).getBlock() != Blocks.air) {
ItemStack block = mc.thePlayer.getCurrentEquippedItem();
for (int g = 0; g < 9; g++) {
if (mc.thePlayer.inventoryContainer.getSlot(g + 36).getHasStack() && mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem() instanceof ItemBlock && mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().stackSize > 0 && !((ItemBlock)mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem()).getBlock().getLocalizedName().toLowerCase().contains("chest") && !((ItemBlock)mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem()).getBlock().getLocalizedName().toLowerCase().contains("table")) {
InventoryPlayer inventoryplayer = mc.thePlayer.inventory;
inventoryplayer.setCurrentItem(mc.thePlayer.inventoryContainer.getSlot(g + 36).getStack().getItem(), 0, false, true);
}
}
if (mc.playerController.onPlayerRightClick(mc.thePlayer, mc.theWorld, block, defaultPos.pos, defaultPos.facing, RotationUtils.getVectorForRotation(getRotationsHypixel(defaultPos.targetPos, defaultPos.facing)[0], getRotationsHypixel(defaultPos.targetPos, defaultPos.facing)[1])) || true) {
mc.thePlayer.swingItem();
event.setYaw(getRotationsHypixel(defaultPos.pos.offset(defaultPos.facing), defaultPos.facing)[0]);
event.setPitch(getRotationsHypixel(defaultPos.pos.offset(defaultPos.facing), defaultPos.facing)[1]);
lastYaw = event.yaw;
lastPitch = event.pitch;
return;
}
return;
}
break;
}
}
}
}
}
private BlockInfo findFacingAndBlockPosForBlock(BlockPos input) {
BlockInfo output = new BlockInfo();
output.pos = input;
for (EnumFacing face : EnumFacing.VALUES) {
if (mc.theWorld.getBlockState(output.pos.offset(face)).getBlock() != Blocks.air) {
output.pos = output.pos.offset(face);
output.facing = face.getOpposite();
output.targetPos = new BlockPos(mc.thePlayer.posX, mc.thePlayer.posY - 1D, mc.thePlayer.posZ);
return output;
}
}
for (EnumFacing face : EnumFacing.VALUES) {
if (mc.theWorld.getBlockState(output.pos.offset(face)).getBlock() == Blocks.air) {
for (EnumFacing face1 : EnumFacing.VALUES) {
if (mc.theWorld.getBlockState(output.pos.offset(face).offset(face1)).getBlock() != Blocks.air) {
output.pos = output.pos.offset(face).offset(face1);
output.facing = face.getOpposite();
output.targetPos = output.pos.offset(face);
return output;
}
}
}
}
return null;
}
public float[] getRotationsHypixel(BlockPos paramBlockPos, EnumFacing paramEnumFacing) {
double offset = 0.5;
offset = 1;
double d1 = (double)paramBlockPos.getX() + offset - mc.thePlayer.posX + (double)paramEnumFacing.getFrontOffsetX() / 2.0D;
double d2 = (double)paramBlockPos.getZ() + offset - mc.thePlayer.posZ + (double)paramEnumFacing.getFrontOffsetZ() / 2.0D;
double d3 = mc.thePlayer.posY + (double)mc.thePlayer.getEyeHeight() - ((double)paramBlockPos.getY() + 0.5D);
double d4 = (double)MathHelper.sqrt_double(d1 * d1 + d2 * d2);
float f1 = (float)(Math.atan2(d2, d1) * 180.0D / 3.141592653589793D) - 90.0F;
float f2 = (float)(Math.atan2(d3, d4) * 180.0D / 3.141592653589793D);
if (f1 < 0.0F) {
f1 += 360.0F;
}
//f1 += 180;
f1 = MathHelper.wrapAngleTo180_float(f1);
f2 += 30;
if (f2 > 90)
f2 = 90;
if (f2 < -90)
f2 = -90;
//Command.sendPrivateChatMessage(f1 + " : " + f2);
return new float[]{f1, f2};
}
private class BlockInfo {
BlockPos pos, targetPos;
EnumFacing facing;
}
}
// NOTE (AI): The S2F cancel only fires while killaura has no target; the early return exists because killaura needs accurate slot state for weapon switching. The module also freezes yaw and pitch on C03 and EventMotion while it places blocks below the player.
No-slow that preserves a ghost item by cancelling window-0 slot updates while using a non-sword item.
Vanilla mode: on MotionEvent pre, if no ghost exists call sendBypass (C0D close window 0, then C0E shift-click of the held item into its own slot to create the ghost). Then on PacketReceiveEvent, cancel every S2F whose window id is 0 while the player is using a non-sword item with no screen open, so the server's slot corrections never remove the ghost. isItemGhost resets when the player stops using the item.
// ===== FILE: Tenacity 6.0, dev/tenacity/module/impl/movement/NoSlowModule.java =====
package dev.tenacity.module.impl.movement;
import dev.tenacity.event.Event;
import dev.tenacity.event.IEventListener;
import dev.tenacity.event.impl.packet.PacketReceiveEvent;
import dev.tenacity.event.impl.player.MotionEvent;
import dev.tenacity.event.impl.player.SlowDownEvent;
import dev.tenacity.module.Module;
import dev.tenacity.module.ModuleCategory;
import java.util.ArrayList;
import java.util.Arrays;
import dev.tenacity.setting.impl.ModeSetting;
import net.minecraft.item.ItemSword;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C0DPacketCloseWindow;
import net.minecraft.network.play.client.C0EPacketClickWindow;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import net.minecraft.world.gen.layer.GenLayerEdge;
public final class NoSlowModule extends Module {
private boolean isItemGhost;
private final ModeSetting mode = new ModeSetting("Mode", "Vanilla", "Watchdog");
public NoSlowModule() {
super("NoSlow", "Makes you not take slow down", ModuleCategory.MOVEMENT);
initializeSettings(mode);
}
private final IEventListener<SlowDownEvent> onSlowDownEvent = Event::cancel;
private final IEventListener<MotionEvent> onMotionEvent = event -> {
switch (mode.getCurrentMode()) {
case "Vanilla": {
if (event.isPre() && mc.thePlayer != null) {
if (!isItemGhost)
sendBypass();
if (!mc.thePlayer.isUsingItem())
isItemGhost = false;
}
}
case "Watchdog": {
if (mc.thePlayer.isUsingItem()) {
if (mc.currentScreen == null && mc.thePlayer.getHeldItem() != null) {
}
}
break;
}
}
};
private final IEventListener<PacketReceiveEvent> onPacketReceiveEvent = event -> {
if (event.getPacket() instanceof S2FPacketSetSlot && mc.thePlayer != null) {
final S2FPacketSetSlot s2f = (S2FPacketSetSlot) event.getPacket();
if (s2f.func_149175_c() == 0 && mc.thePlayer.isUsingItem() && mc.currentScreen == null && mc.thePlayer.getHeldItem() != null && !(mc.thePlayer.getHeldItem().getItem() instanceof ItemSword)) {
event.cancel();
//isItemGhost = false;
}
}
};
private void sendBypass() {
if (mc.thePlayer.isUsingItem() && mc.currentScreen == null && mc.thePlayer.getHeldItem() != null && !(mc.thePlayer.getHeldItem().getItem() instanceof ItemSword)) {
mc.getNetHandler().addToSendQueue(new C0DPacketCloseWindow(0));
mc.getNetHandler().addToSendQueue(new C0EPacketClickWindow(0, 36 + mc.thePlayer.inventory.currentItem, 0, 6, null, mc.thePlayer.inventoryContainer.getNextTransactionID(mc.thePlayer.inventory)));
isItemGhost = true;
}
}
}
// NOTE (AI): The ghost item is created by sendBypass (C0D close window 0, then C0E shift-click of the held item); cancelling S2F for window 0 stops the server's slot corrections from removing it. The commented-out isItemGhost reset and the empty Watchdog branch show the module is unfinished.
HUD performance component: S2F (and S30, chat, collect-item) mark significant events that force a GuiIngameCache redraw.
PacketReceiveEvent: on S2F, reset the StopWatch and set the cache dirty so the next frame re-renders the HUD. PreMotionEvent re-evaluates dirty state every 100 ticks, on player-list/debug key changes, or while the component is disabled for a few ticks after health changes.
// ===== FILE: Rise 6.2.4, Client-release2/Client/src/main/java/com/alan/clients/component/impl/hud/AdaptiveRefreshRateComponent.java =====
package com.alan.clients.component.impl.hud;
import com.alan.clients.component.Component;
import com.alan.clients.event.Listener;
import com.alan.clients.event.annotations.EventLink;
import com.alan.clients.event.impl.motion.PreMotionEvent;
import com.alan.clients.event.impl.packet.PacketReceiveEvent;
import com.alan.clients.event.impl.render.Render2DEvent;
import com.alan.clients.ui.ingame.GuiIngameCache;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S02PacketChat;
import net.minecraft.network.play.server.S0DPacketCollectItem;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import net.minecraft.network.play.server.S30PacketWindowItems;
import rip.vantage.commons.util.time.StopWatch;
public class AdaptiveRefreshRateComponent extends Component {
private boolean playerList, debugInfo;
private boolean setDirty;
private int disabledFor;
private float health;
public final StopWatch stopWatch = new StopWatch();
@EventLink
public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
if (mc.thePlayer.ticksExisted % 100 == 0 || setDirty ||
mc.gameSettings.keyBindPlayerList.isKeyDown() != playerList || mc.gameSettings.showDebugInfo != debugInfo ||
mc.thePlayer.ticksExisted <= 10 || disabledFor > 0) {
GuiIngameCache.dirty = true;
playerList = mc.gameSettings.keyBindPlayerList.isKeyDown();
debugInfo = mc.gameSettings.showDebugInfo;
setDirty = false;
}
if (health != mc.thePlayer.getHealth()) {
disabledFor = 3;
health = mc.thePlayer.getHealth();
}
disabledFor--;
};
@EventLink
public final Listener<Render2DEvent> onRender2D = event -> {
if (mc.currentScreen != null) {
setDirty = true;
GuiIngameCache.dirty = true;
}
};
@EventLink
public final Listener<PacketReceiveEvent> onPacketReceiveEvent = event -> {
Packet packet = event.getPacket();
if (packet instanceof S02PacketChat || packet instanceof S30PacketWindowItems || packet instanceof S2FPacketSetSlot) {
stopWatch.reset();
setDirty = true;
}
if (packet instanceof S0DPacketCollectItem) {
disabledFor = 5;
}
};
}
// NOTE (AI): S2F and S30 are grouped with S02PacketChat as significant packets that force a HUD cache redraw; S0D collect-item disables adaptive refresh for 5 ticks. The component is byte-identical in 6.1.30 under com/alan/clients.
anticheat Anti-Cheat Checks
The set-slot packet is the server's single-slot inventory correction: window id, slot, and the item placed there. It is server-authoritative display state, so anticheats do not validate it, but simulation anticheats must consume it to keep their compensated copy of the player inventory honest. The only real corpus hits are Grim's replication listener, which reads S2F to detect held-item and offhand changes, and Grim's check listener, which manufactures S2F packets to resync the client after a cancelled interaction. Everyone else ignores it.
Apply the server's single-slot corrections to the compensated inventory and end stale item-use state when the held item changes.
PacketEntityReplication wraps SET_SLOT and, for window id 0 (the player inventory), schedules a transaction-sandwiched task: if the slot is the selected hotbar slot (36 + lastSlotSelected) or the offhand (45) and the item type differs from the compensated inventory, it clears the slowed-by-using-item state and resets item usage through the item reset handler. The task runs for the current and the next transaction to cover 1.8 clients that fail to send release-item packets.
// ===== FILE: GrimAnticheat-Grim, common/src/main/java/ac/grim/grimac/events/packets/PacketEntityReplication.java =====
package ac.grim.grimac.events.packets;
import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.api.config.ConfigManager;
import ac.grim.grimac.checks.Check;
import ac.grim.grimac.checks.type.PacketReceiveListener;
import ac.grim.grimac.checks.type.PacketSendListener;
import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.utils.anticheat.LogUtil;
import ac.grim.grimac.utils.data.SprintingState;
import ac.grim.grimac.utils.data.TrackerData;
import ac.grim.grimac.utils.data.packetentity.DashableEntity;
import ac.grim.grimac.utils.data.packetentity.PacketEntity;
import ac.grim.grimac.utils.data.packetentity.PacketEntityHook;
import ac.grim.grimac.utils.data.packetentity.PacketEntityTrackXRot;
import ac.grim.grimac.utils.enums.Pose;
import ac.grim.grimac.utils.nmsutil.EntityMetadataPoseUtil;
import ac.grim.grimac.utils.viaversion.ViaVersionUtil;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.entity.EntityPositionData;
import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
import com.github.retrooper.packetevents.protocol.player.UserProfile;
import com.github.retrooper.packetevents.protocol.potion.PotionType;
import com.github.retrooper.packetevents.util.Vector3d;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAttachEntity;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEffect;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityPositionSync;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMoveAndRotation;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoRemove;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerRemoveEntityEffect;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPainting;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPlayer;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowItems;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
public class PacketEntityReplication extends Check implements PacketReceiveListener, PacketSendListener {
private final AtomicBoolean hasSentPreWavePacket = new AtomicBoolean(true);
// Let's imagine the player is on a boat.
// The player breaks this boat
// If we were to despawn the boat without an extra transaction, then the boat would disappear before
// it disappeared on the client side, creating a ghost boat to flag checks with
//
// If we were to despawn the tick after, spawning must occur the transaction before to stop the same exact
// problem with ghost boats in reverse.
//
// Therefore, we despawn the transaction after, and spawn the tick before.
//
// If we despawn then spawn an entity in the same transaction, then this solution would despawn the new entity
// instead of the old entity, so we wouldn't see the boat at all
//
// Therefore, if the server sends a despawn and then a spawn in the same transaction for the same entity,
// We should simply add a transaction (which will clear this list!)
//
// Another valid solution is to simply spam more transactions, but let's not waste bandwidth.
private final List<Integer> despawnedEntitiesThisTransaction = new ArrayList<>();
// Maximum ping when a firework boost is removed from the player.
private int maxFireworkBoostPing = 1000;
public PacketEntityReplication(GrimPlayer player) {
super(player);
}
@Override
public void onPacketReceive(PacketReceiveEvent event) {
// Teleports don't interpolate, duplicate 1.17 packets don't interpolate
if (!isTickPacket(event.getPacketType())) return;
player.compensatedEntities.entitiesRemovedThisTick.clear();
boolean isTickingReliably = player.isTickingReliablyFor(3);
PacketEntity playerVehicle = player.compensatedEntities.self.getRiding();
for (PacketEntity entity : player.compensatedEntities.entityMap.values()) {
if (entity == playerVehicle && !player.vehicleData.lastDummy) {
// The player has this as their vehicle, so they aren't interpolating it.
// And it isn't a dummy position
entity.setPositionRaw(player, entity.getPossibleLocationBoxes());
} else {
entity.onMovement(isTickingReliably);
}
}
if (player.vehicleData.camelSprintingState == SprintingState.STOPPING) {
player.vehicleData.camelSprintingState = SprintingState.STOPPED;
} else if (player.vehicleData.camelSprintingState == SprintingState.STOPPED && player.isSprinting) { // For sprint desyncs
player.vehicleData.camelSprintingState = SprintingState.STARTED;
}
}
@Override
public void onPacketSend(PacketSendEvent event) {
// ensure grim is the one that sent the transaction
if ((event.getPacketType() == PacketType.Play.Server.PING || event.getPacketType() == PacketType.Play.Server.WINDOW_CONFIRMATION) && player.packetStateData.lastServerTransWasValid) {
despawnedEntitiesThisTransaction.clear();
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_LIVING_ENTITY) {
WrapperPlayServerSpawnLivingEntity packetOutEntity = new WrapperPlayServerSpawnLivingEntity(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getEntityUUID(), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_ENTITY) {
WrapperPlayServerSpawnEntity packetOutEntity = new WrapperPlayServerSpawnEntity(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID().orElse(null), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), null, packetOutEntity.getData());
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PLAYER) {
WrapperPlayServerSpawnPlayer packetOutEntity = new WrapperPlayServerSpawnPlayer(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PLAYER, packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PAINTING) {
WrapperPlayServerSpawnPainting packetOutEntity = new WrapperPlayServerSpawnPainting(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PAINTING, packetOutEntity.getPosition().toVector3d(), 0, 0f, null, packetOutEntity.getDirection().getHorizontalIndex());
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE) {
WrapperPlayServerEntityRelativeMove move = new WrapperPlayServerEntityRelativeMove(event);
handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), null, null, true, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE_AND_ROTATION) {
WrapperPlayServerEntityRelativeMoveAndRotation move = new WrapperPlayServerEntityRelativeMoveAndRotation(event);
handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_TELEPORT) {
WrapperPlayServerEntityTeleport move = new WrapperPlayServerEntityTeleport(event);
Vector3d pos = move.getPosition();
handleMoveEntity(event, move.getEntityId(), pos.getX(), pos.getY(), pos.getZ(), move.getYaw(), move.getPitch(), false, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_POSITION_SYNC) {
// ENTITY_TELEPORT but without relative flags
WrapperPlayServerEntityPositionSync move = new WrapperPlayServerEntityPositionSync(event);
final EntityPositionData values = move.getValues();
final Vector3d pos = values.getPosition();
// TODO this isn't technically correct
// If the position sync is to a pos > 4096 from the entity pos, client does some special stuff without interpolation
handleMoveEntity(event, move.getId(), pos.getX(), pos.getY(), pos.getZ(), values.getYaw(), values.getPitch(), false, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_ROTATION) { // Affects interpolation
WrapperPlayServerEntityRotation move = new WrapperPlayServerEntityRotation(event);
handleMoveEntity(event, move.getEntityId(), 0, 0, 0, move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, false);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_METADATA) {
WrapperPlayServerEntityMetadata entityMetadata = new WrapperPlayServerEntityMetadata(event);
schedulePoseTransition(entityMetadata, event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityMetadata(entityMetadata.getEntityId(), entityMetadata.getEntityMetadata()));
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EQUIPMENT) {
WrapperPlayServerEntityEquipment equipment = new WrapperPlayServerEntityEquipment(event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityEquipment(equipment.getEntityId(), equipment.getEquipment()));
}
// 1.19.3+
else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_UPDATE) {
WrapperPlayServerPlayerInfoUpdate info = new WrapperPlayServerPlayerInfoUpdate(event);
if (info.getActions().contains(WrapperPlayServerPlayerInfoUpdate.Action.ADD_PLAYER)) {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
for (WrapperPlayServerPlayerInfoUpdate.PlayerInfo entry : info.getEntries()) {
final UserProfile gameProfile = entry.getGameProfile();
final UUID uuid = gameProfile.getUUID();
player.compensatedEntities.profiles.put(uuid, gameProfile);
}
});
}
} else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_REMOVE) {
WrapperPlayServerPlayerInfoRemove remove = new WrapperPlayServerPlayerInfoRemove(event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> remove.getProfileIds().forEach(player.compensatedEntities.profiles::remove));
} else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO) {
WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo(event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
if (info.getAction() == WrapperPlayServerPlayerInfo.Action.ADD_PLAYER) {
for (WrapperPlayServerPlayerInfo.PlayerData entry : info.getPlayerDataList()) {
final UserProfile gameProfile = entry.getUserProfile();
final UUID uuid = gameProfile.getUUID();
player.compensatedEntities.profiles.put(uuid, gameProfile);
}
} else if (info.getAction() == WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER) {
info.getPlayerDataList().forEach(profile -> player.compensatedEntities.profiles.remove(profile.getUserProfile().getUUID()));
}
});
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EFFECT) {
WrapperPlayServerEntityEffect effect = new WrapperPlayServerEntityEffect(event);
PotionType type = effect.getPotionType();
// ViaVersion tries faking levitation effects and fails badly lol, flagging the anticheat
// Block other effects just in case ViaVersion gets any ideas
//
// Set to 24 so ViaVersion blocks it
// 24 is the levitation effect
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) > 23) {
event.setCancelled(true);
return;
}
// ViaVersion dolphin's grace also messes us up, set it to a potion effect that doesn't exist on 1.12
// Effect 31 is bad omen
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_13) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) == 30) {
event.setCancelled(true);
return;
}
if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
if (entity == null) return;
entity.addPotionEffect(type, effect.getEffectAmplifier());
});
} else if (event.getPacketType() == PacketType.Play.Server.REMOVE_ENTITY_EFFECT) {
WrapperPlayServerRemoveEntityEffect effect = new WrapperPlayServerRemoveEntityEffect(event);
if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
if (entity == null) return;
entity.removePotionEffect(effect.getPotionType());
});
} else if (event.getPacketType() == PacketType.Play.Server.UPDATE_ATTRIBUTES) {
WrapperPlayServerUpdateAttributes attributes = new WrapperPlayServerUpdateAttributes(event);
int entityID = attributes.getEntityId();
// The attributes for this entity is active, currently
if (isDirectlyAffectingPlayer(player, entityID)) player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(),
() -> player.compensatedEntities.updateAttributes(entityID, attributes.getProperties()));
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_STATUS) {
WrapperPlayServerEntityStatus status = new WrapperPlayServerEntityStatus(event);
// This hasn't changed from 1.7.2 to 1.17
// Needed to exempt players on dead vehicles, as dead entities have strange physics.
if (status.getStatus() == 3) {
PacketEntity entity = player.compensatedEntities.getEntity(status.getEntityId());
if (entity == null) return;
entity.isDead = true;
}
if (status.getStatus() == 9) {
if (status.getEntityId() != player.entityID) return;
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
}
if (status.getStatus() == 31) {
PacketEntity hook = player.compensatedEntities.getEntity(status.getEntityId());
if (!(hook instanceof PacketEntityHook hookEntity)) return;
if (hookEntity.attached == player.entityID) {
player.sendTransaction();
// We don't transaction sandwich this, it's too rare to be a real problem.
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.uncertaintyHandler.fishingRodPulls.add(hookEntity.owner));
}
}
if (status.getStatus() >= 24 && status.getStatus() <= 28 && status.getEntityId() == player.entityID) {
player.compensatedEntities.self.opLevel = status.getStatus() - 24;
}
} else if (event.getPacketType() == PacketType.Play.Server.SET_SLOT) {
WrapperPlayServerSetSlot slot = new WrapperPlayServerSetSlot(event);
if (slot.getWindowId() == 0) {
Runnable task = () -> {
if (slot.getSlot() - 36 == player.packetStateData.lastSlotSelected && (
!player.inventory.getHeldItem().is(slot.getItem().getType()) || player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)
) || slot.getSlot() == 45 && !player.inventory.getOffHand().is(slot.getItem().getType())) {
InteractionHand hand = slot.getSlot() == 45 ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;
if (hand == player.packetStateData.itemInUseHand) {
player.packetStateData.setSlowedByUsingItem(false);
}
if (player.isResetItemUsageOnItemUpdate() && hand == GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer)) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
}
};
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
}
} else if (event.getPacketType() == PacketType.Play.Server.WINDOW_ITEMS) {
WrapperPlayServerWindowItems items = new WrapperPlayServerWindowItems(event);
if (items.getWindowId() == 0) { // Player inventory
Runnable task = () -> {
if (player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)) {
player.packetStateData.setSlowedByUsingItem(false);
if (player.isResetItemUsageOnItemUpdate()) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
} else {
if (items.getItems().size() > 45 && !player.inventory.getOffHand().is(items.getItems().get(45).getType())) {
if (player.packetStateData.itemInUseHand == InteractionHand.OFF_HAND) {
player.packetStateData.setSlowedByUsingItem(false);
}
if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.OFF_HAND) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
}
if (!player.inventory.getHeldItem().is(items.getItems().get(player.packetStateData.lastSlotSelected + 36).getType())) {
if (player.packetStateData.itemInUseHand == InteractionHand.MAIN_HAND) {
player.packetStateData.setSlowedByUsingItem(false);
}
if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.MAIN_HAND) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
}
}
};
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
}
}
// 1.8 clients fail to send the RELEASE_USE_ITEM packet when a window is opened client sided while using an item
else if (event.getPacketType() == PacketType.Play.Server.OPEN_WINDOW) {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
} else if (event.getPacketType() == PacketType.Play.Server.OPEN_HORSE_WINDOW) {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
} else if (event.getPacketType() == PacketType.Play.Server.SET_PASSENGERS) {
WrapperPlayServerSetPassengers mount = new WrapperPlayServerSetPassengers(event);
int vehicleID = mount.getEntityId();
int[] passengers = mount.getPassengers();
handleMountVehicle(event, vehicleID, passengers);
} else if (event.getPacketType() == PacketType.Play.Server.ATTACH_ENTITY) {
WrapperPlayServerAttachEntity attach = new WrapperPlayServerAttachEntity(event);
// This packet was replaced by the mount packet on 1.9+ servers - to support multiple passengers on one vehicle
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))
return;
// If this is mounting rather than leashing
if (!attach.isLeash()) {
// Alright, let's convert this to the 1.9+ format to make it easier for grim
int vehicleID = attach.getHoldingId();
int attachID = attach.getAttachedId();
TrackerData trackerData = player.compensatedEntities.getTrackedEntity(attachID);
if (trackerData != null) {
// 1.8 sends a vehicle ID of -1 to dismount the entity from its vehicle
// This is opposite of the 1.9+ format, which sends the vehicle ID and then an empty array.
if (vehicleID == -1) { // Dismounting
vehicleID = trackerData.getLegacyPointEightMountedUpon();
handleMountVehicle(event, vehicleID, new int[]{}); // The vehicle is empty
} else { // Mounting
trackerData.setLegacyPointEightMountedUpon(vehicleID);
handleMountVehicle(event, vehicleID, new int[]{attachID});
}
} else {
// I don't think we can recover from this... warn and move on as this shouldn't happen.
LogUtil.warn("Server sent an invalid attach entity packet for entity " + attach.getHoldingId() + " with passenger " + attach.getAttachedId() + "! The client ignores this.");
}
}
} else if (event.getPacketType() == PacketType.Play.Server.DESTROY_ENTITIES) {
WrapperPlayServerDestroyEntities destroy = new WrapperPlayServerDestroyEntities(event);
int[] destroyEntityIds = destroy.getEntityIds();
for (int entityID : destroyEntityIds) {
despawnedEntitiesThisTransaction.add(entityID);
player.compensatedEntities.serverPositionsMap.remove(entityID);
// Remove the tracked vehicle (handling tracking knockback) if despawned
if (player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == entityID) {
player.compensatedEntities.serverPlayerVehicle = null;
}
}
final int destroyTransaction = player.lastTransactionSent.get() + 1;
player.latencyUtils.addRealTimeTask(destroyTransaction, () -> {
for (int entityId : destroyEntityIds) {
player.compensatedEntities.removeEntity(entityId);
player.dashableEntities.removeEntity(entityId);
player.fireworks.removeFirework(entityId);
player.compensatedEntities.entitiesRemovedThisTick.add(entityId);
}
});
// Don't let the player freeze transactions to keep the firework boost velocity + uncertainty
// Also generally prevents people with high ping gaining too high an advantage in firework use
if (maxFireworkBoostPing > 0) {
player.runNettyTaskInMs(() -> {
if (player.lastTransactionReceived.get() >= destroyTransaction) return;
for (int entityID : destroyEntityIds) {
// If the player has a firework boosting them, setback
if (player.fireworks.hasFirework(entityID)) {
player.getSetbackTeleportUtil().executeViolationSetback();
break;
}
}
}, maxFireworkBoostPing);
}
}
}
private void handleMountVehicle(PacketSendEvent event, int vehicleID, int[] passengers) {
boolean wasInVehicle = player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == vehicleID;
boolean inThisVehicle = false;
for (int passenger : passengers) {
inThisVehicle = passenger == player.entityID;
if (inThisVehicle) break;
}
if (inThisVehicle && !wasInVehicle) {
player.handleMountVehicle(vehicleID);
}
if (!inThisVehicle && wasInVehicle) {
player.handleDismountVehicle(event);
}
// Better lag compensation if we were affected by this
if (wasInVehicle || inThisVehicle) {
player.sendTransaction();
}
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity vehicle = player.compensatedEntities.getEntity(vehicleID);
// Vanilla likes sending null vehicles, so we must ignore those like the client ignores them
if (vehicle == null) return;
// Eject existing passengers for this vehicle
for (PacketEntity passenger : new ArrayList<>(vehicle.passengers)) {
passenger.eject();
}
// Add the entities as vehicles
for (int entityID : passengers) {
PacketEntity passenger = player.compensatedEntities.getEntity(entityID);
if (passenger == null) continue;
passenger.mount(vehicle);
}
});
}
private void handleMoveEntity(PacketSendEvent event, int entityId, double deltaX, double deltaY, double deltaZ, Float yaw, Float pitch, boolean isRelative, boolean hasPos) {
TrackerData data = player.compensatedEntities.getTrackedEntity(entityId);
final boolean didNotSendPreWave = hasSentPreWavePacket.compareAndSet(false, true);
if (didNotSendPreWave) player.sendTransaction();
if (data != null) {
// Update the tracked server's entity position
if (isRelative) {
// There is a bug where vehicles may start flying due to mojang setting packet position on the client
// (Works at 0 ping but causes funny bugs at any higher ping)
// As we don't want vehicles to fly, we need to replace it with a teleport if it is player vehicle
//
// Don't bother with client controlled vehicles though
boolean vanillaVehicleFlight = player.compensatedEntities.serverPlayerVehicle != null
&& player.compensatedEntities.serverPlayerVehicle == entityId
&& player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_9)
// TODO: https://discord.com/channels/721686193061888071/721686193515003966/1310659538831020123
// Why does the server now send an entity rel move packet matching the player's vehicle movement every time?
&& PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_21_2)
&& PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9);
// ViaVersion sends two relative packets when moving more than 4 blocks
// This is broken and causes the client to interpolate like (0, 4) and (1, 3) instead of (1, 7)
// This causes impossible hits, so grim must replace this with a teleport entity packet
// Not ideal, but neither is 1.8 players on a 1.9+ server.
if (vanillaVehicleFlight ||
((Math.abs(deltaX) >= 3.9375 || Math.abs(deltaY) >= 3.9375 || Math.abs(deltaZ) >= 3.9375) && player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))) {
player.user.writePacket(new WrapperPlayServerEntityTeleport(entityId, new Vector3d(data.getX() + deltaX, data.getY() + deltaY, data.getZ() + deltaZ), yaw == null ? data.getXRot() : yaw, pitch == null ? data.getYRot() : pitch, false));
event.setCancelled(true);
return;
}
data.setX(data.getX() + deltaX);
data.setY(data.getY() + deltaY);
data.setZ(data.getZ() + deltaZ);
} else {
data.setX(deltaX);
data.setY(deltaY);
data.setZ(deltaZ);
}
if (yaw != null) {
data.setXRot(yaw);
data.setYRot(pitch);
}
// We can't hang two relative moves on one transaction
if (data.getLastTransactionHung() == player.lastTransactionSent.get()) {
player.sendTransaction();
}
data.setLastTransactionHung(player.lastTransactionSent.get());
}
int lastTrans = player.lastTransactionSent.get();
player.latencyUtils.addRealTimeTask(lastTrans, () -> {
PacketEntity entity = player.compensatedEntities.getEntity(entityId);
if (entity == null) return;
if (entity instanceof PacketEntityTrackXRot xRotEntity && yaw != null) {
xRotEntity.packetYaw = yaw;
xRotEntity.steps = entity.isBoat ? 10 : 3;
}
entity.onFirstTransaction(isRelative, hasPos, deltaX, deltaY, deltaZ, player);
});
player.latencyUtils.addRealTimeTask(lastTrans + 1, () -> {
PacketEntity entity = player.compensatedEntities.getEntity(entityId);
if (entity == null) return;
entity.onSecondTransaction();
});
}
public void addEntity(int entityID, UUID uuid, EntityType type, Vector3d position, float xRot, float yRot, List<EntityData<?>> entityMetadata, int extraData) {
if (despawnedEntitiesThisTransaction.contains(entityID)) {
player.sendTransaction();
}
player.compensatedEntities.serverPositionsMap.put(entityID, new TrackerData(position.getX(), position.getY(), position.getZ(), xRot, yRot, type, player.lastTransactionSent.get()));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity entity = player.compensatedEntities.addEntity(entityID, uuid, type, position, xRot, extraData);
if (entity instanceof DashableEntity dashable) {
player.dashableEntities.addEntity(entityID, dashable);
}
if (entityMetadata != null) {
if (EntityMetadataPoseUtil.usesPoseMetadata(entity) && player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_14)) {
Pose initialPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata);
if (initialPose != null) {
entity.currentPose = initialPose;
}
}
player.compensatedEntities.updateEntityMetadata(entityID, entityMetadata);
}
});
}
private void schedulePoseTransition(WrapperPlayServerEntityMetadata entityMetadata, PacketSendEvent event) {
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_14)) return;
int entityId = entityMetadata.getEntityId();
if (entityId == player.entityID) return;
Pose newPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata.getEntityMetadata());
if (newPose == null) return;
boolean shouldTrackPoseTransition = false;
PacketEntity entity = player.compensatedEntities.getEntity(entityId);
if (entity != null) {
shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(entity);
} else {
// If the client didn't respond to the spawn packet yet, we need to check if we should track the pose transition based on the entity type
// is there a better way to do this?
TrackerData trackedEntity = player.compensatedEntities.getTrackedEntity(entityId);
if (trackedEntity != null) {
shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(trackedEntity.getEntityType());
}
}
if (!shouldTrackPoseTransition) return;
player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity target = player.compensatedEntities.getEntity(entityId);
if (target == null) {
return;
}
target.beginPoseTransition(newPose);
});
event.getTasksAfterSend().add(() -> {
player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity target = player.compensatedEntities.getEntity(entityId);
if (target == null) {
return;
}
target.completePoseTransition(newPose);
});
});
}
private boolean isDirectlyAffectingPlayer(GrimPlayer player, int entityID) {
// The attributes for this entity is active, currently
return (player.compensatedEntities.serverPlayerVehicle == null && entityID == player.entityID) ||
(player.compensatedEntities.serverPlayerVehicle != null && entityID == player.compensatedEntities.serverPlayerVehicle);
}
public void onEndOfTickEvent(boolean async, boolean flush) {
// Only send a transaction at the end of the tick if we are tracking players
player.sendTransaction(async);
if (flush) player.user.flushPackets();
}
public void tickStartTick() {
hasSentPreWavePacket.set(false);
}
@Override
public void onReload(@NotNull ConfigManager config) {
maxFireworkBoostPing = config.getIntElse("max-ping-firework-boost", 1000);
}
}
// NOTE (AI): The file is the general entity and item replication listener; the S2F branch is the SET_SLOT case near the end (window id 0 only). The double scheduling exists because a 1.8 client can act on the slot change one tick later.Re-send the authoritative held-item slot to the client after a block place is cancelled, so the client's view cannot desync from the server.
CheckManagerListener handles the block-place packet; when the placement is cancelled the server-side inventory no longer matches what the client predicted, so the listener sends a WrapperPlayServerSetSlot for the main hand (slot 36 + selected) or the offhand (slot 45) carrying the platform player's actual item. The code comment calls this 'stop inventory desync from cancelling place'.
// ===== FILE: GrimAnticheat-Grim, common/src/main/java/ac/grim/grimac/events/packets/CheckManagerListener.java =====
package ac.grim.grimac.events.packets;
import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.checks.impl.badpackets.BadPacketsB;
import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.utils.anticheat.update.*;
import ac.grim.grimac.utils.blockplace.BlockPlaceResult;
import ac.grim.grimac.utils.blockplace.ConsumesBlockPlace;
import ac.grim.grimac.utils.change.BlockModification;
import ac.grim.grimac.utils.data.*;
import ac.grim.grimac.utils.inventory.Inventory;
import ac.grim.grimac.utils.latency.CompensatedWorld;
import ac.grim.grimac.utils.math.VectorUtils;
import ac.grim.grimac.utils.nmsutil.*;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
import com.github.retrooper.packetevents.event.PacketListenerPriority;
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.ConnectionState;
import com.github.retrooper.packetevents.protocol.item.ItemStack;
import com.github.retrooper.packetevents.protocol.item.type.ItemType;
import com.github.retrooper.packetevents.protocol.item.type.ItemTypes;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.DiggingAction;
import com.github.retrooper.packetevents.protocol.player.GameMode;
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
import com.github.retrooper.packetevents.protocol.world.BlockFace;
import com.github.retrooper.packetevents.protocol.world.Location;
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
import com.github.retrooper.packetevents.protocol.world.states.defaulttags.BlockTags;
import com.github.retrooper.packetevents.protocol.world.states.type.StateType;
import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes;
import com.github.retrooper.packetevents.protocol.world.states.type.StateValue;
import com.github.retrooper.packetevents.util.Vector3d;
import com.github.retrooper.packetevents.util.Vector3f;
import com.github.retrooper.packetevents.util.Vector3i;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import com.github.retrooper.packetevents.wrapper.play.client.*;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAcknowledgeBlockChanges;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot;
import org.jetbrains.annotations.NotNull;
import java.util.function.Predicate;
public class CheckManagerListener extends PacketListenerAbstract {
// Manual filter on FINISH_DIGGING to prevent clients setting non-breakable blocks to air
private static final Predicate<StateType> BREAKABLE = type -> !type.isAir() && type.getHardness() != -1.0f && type != StateTypes.WATER && type != StateTypes.LAVA;
public CheckManagerListener() {
super(PacketListenerPriority.LOW);
}
private static void placeWaterLavaSnowBucket(GrimPlayer player, ItemStack held, StateType toPlace, InteractionHand hand, int sequence) {
HitData data = WorldRayTrace.getNearestBlockHitResult(player, StateTypes.AIR, false, true, true);
if (data != null) {
BlockPlace blockPlace = new BlockPlace(player, hand, data.position(), data.closestDirection().getFaceValue(), data.closestDirection(), held, data, sequence);
boolean didPlace = false;
// Powder snow, lava, and water all behave like placing normal blocks after checking for waterlogging (replace clicked always false though)
// If we hit a waterloggable block, then the bucket is directly placed
// Otherwise, use the face to determine where to place the bucket
if (Materials.isPlaceableWaterBucket(blockPlace.itemStack.getType()) && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_13)) {
blockPlace.replaceClicked = true; // See what's in the existing place
WrappedBlockState existing = blockPlace.getExistingBlockData();
if (existing.hasProperty(StateValue.WATERLOGGED) && !existing.isWaterlogged()) {
// Strangely, the client does not predict waterlogged placements
didPlace = true;
}
}
if (!didPlace) {
// Powder snow, lava, and water all behave like placing normal blocks after checking for waterlogging (replace clicked always false though)
blockPlace.replaceClicked = false;
blockPlace.set(toPlace);
}
if (player.gamemode != GameMode.CREATIVE) {
player.inventory.markSlotAsResyncing(blockPlace);
if (hand == InteractionHand.MAIN_HAND) {
player.inventory.inventory.setHeldItem(ItemStack.builder().type(ItemTypes.BUCKET).amount(1).build());
} else {
player.inventory.inventory.setPlayerInventoryItem(Inventory.SLOT_OFFHAND, ItemStack.builder().type(ItemTypes.BUCKET).amount(1).build());
}
}
}
}
public static void handleQueuedPlaces(GrimPlayer player, boolean hasLook, float pitch, float yaw, long now) {
// Handle queue'd block places
BlockPlaceSnapshot snapshot;
while ((snapshot = player.placeUseItemPackets.poll()) != null) {
double lastX = player.x;
double lastY = player.y;
double lastZ = player.z;
player.x = player.packetStateData.lastClaimedPosition.getX();
player.y = player.packetStateData.lastClaimedPosition.getY();
player.z = player.packetStateData.lastClaimedPosition.getZ();
boolean lastSneaking = player.isSneaking;
player.isSneaking = snapshot.sneaking();
if (player.inVehicle()) {
Vector3d posFromVehicle = BoundingBoxSize.getRidingOffsetFromVehicle(player.compensatedEntities.self.getRiding(), player);
player.x = posFromVehicle.getX();
player.y = posFromVehicle.getY();
player.z = posFromVehicle.getZ();
}
// Less than 15 milliseconds ago means this is likely (fix all look vectors being a tick behind server sided)
// Or mojang had the idle packet... for the 1.7/1.8 clients
// No idle packet on 1.9+
if ((now - player.lastBlockPlaceUseItem < 15 || player.getClientVersion().isOlderThan(ClientVersion.V_1_9)) && hasLook) {
player.yaw = yaw;
player.pitch = pitch;
}
player.compensatedWorld.startPredicting();
handleBlockPlaceOrUseItem(snapshot.wrapper(), player);
player.compensatedWorld.stopPredicting(snapshot.wrapper());
player.x = lastX;
player.y = lastY;
player.z = lastZ;
player.isSneaking = lastSneaking;
}
}
public static void handleQueuedBreaks(GrimPlayer player, boolean hasLook, float pitch, float yaw, long now) {
BlockBreak blockBreak;
while ((blockBreak = player.queuedBreaks.poll()) != null) {
double lastX = player.x;
double lastY = player.y;
double lastZ = player.z;
player.x = player.packetStateData.lastClaimedPosition.getX();
player.y = player.packetStateData.lastClaimedPosition.getY();
player.z = player.packetStateData.lastClaimedPosition.getZ();
if (player.inVehicle()) {
Vector3d posFromVehicle = BoundingBoxSize.getRidingOffsetFromVehicle(player.compensatedEntities.self.getRiding(), player);
player.x = posFromVehicle.getX();
player.y = posFromVehicle.getY();
player.z = posFromVehicle.getZ();
}
// Less than 15 milliseconds ago means this is likely (fix all look vectors being a tick behind server sided)
// Or mojang had the idle packet... for the 1.7/1.8 clients
// No idle packet on 1.9+
if ((now - player.lastBlockBreak < 15 || player.getClientVersion().isOlderThan(ClientVersion.V_1_9)) && hasLook) {
player.yaw = yaw;
player.pitch = pitch;
}
player.checkManager.onPostFlyingBlockBreak(blockBreak);
player.x = lastX;
player.y = lastY;
player.z = lastZ;
}
}
private static void handleUseItem(GrimPlayer player, ItemStack placedWith, InteractionHand hand, int sequence) {
// Lilypads are USE_ITEM (THIS CAN DESYNC, WTF MOJANG)
if (placedWith.getType() == ItemTypes.LILY_PAD) {
placeLilypad(player, hand, sequence); // Pass a block place because lily pads have a hitbox
return;
}
StateType toBucketMat = Materials.transformBucketMaterial(placedWith.getType());
if (toBucketMat != null) {
placeWaterLavaSnowBucket(player, placedWith, toBucketMat, hand, sequence);
}
if (placedWith.getType() == ItemTypes.BUCKET) {
placeBucket(player, hand, sequence);
}
}
private static void handleBlockPlaceOrUseItem(PacketWrapper<?> packet, GrimPlayer player) {
// Legacy "use item" packet
if (packet instanceof WrapperPlayClientPlayerBlockPlacement place &&
PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_9)) {
if (player.gamemode == GameMode.SPECTATOR || player.gamemode == GameMode.ADVENTURE)
return;
if (place.getFace() == BlockFace.OTHER) {
ItemStack placedWith = player.inventory.getHeldItem();
if (place.getHand() == InteractionHand.OFF_HAND) {
placedWith = player.inventory.getOffHand();
}
handleUseItem(player, placedWith, place.getHand(), place.getSequence());
return;
}
}
if (packet instanceof WrapperPlayClientUseItem place) {
if (player.gamemode == GameMode.SPECTATOR || player.gamemode == GameMode.ADVENTURE)
return;
ItemStack placedWith = player.inventory.getHeldItem();
if (place.getHand() == InteractionHand.OFF_HAND) {
placedWith = player.inventory.getOffHand();
}
handleUseItem(player, placedWith, place.getHand(), place.getSequence());
}
// Check for interactable first (door, etc)
if (packet instanceof WrapperPlayClientPlayerBlockPlacement place) {
ItemStack placedWith = player.inventory.getHeldItem();
ItemStack offhand = player.inventory.getOffHand();
boolean onlyAir = placedWith.isEmpty() && offhand.isEmpty();
// The offhand is unable to interact with blocks like this... try to stop some desync points before they happen
if ((!player.isSneaking || onlyAir) && place.getHand() == InteractionHand.MAIN_HAND) {
Vector3i blockPosition = place.getBlockPosition();
BlockPlace blockPlace = new BlockPlace(player, place.getHand(), blockPosition, place.getFaceId(), place.getFace(), placedWith, WorldRayTrace.getNearestBlockHitResult(player, null, true, false, false), place.getSequence());
// Right-clicking a trapdoor/door/etc.
StateType placedAgainst = blockPlace.getPlacedAgainstMaterial();
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_11) && (placedAgainst == StateTypes.IRON_TRAPDOOR
|| placedAgainst == StateTypes.IRON_DOOR || BlockTags.FENCES.contains(placedAgainst))
|| player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8) && BlockTags.CAULDRONS.contains(placedAgainst)
|| Materials.isClientSideInteractable(placedAgainst)) {
player.checkManager.onPostFlyingBlockPlace(blockPlace);
Vector3i location = blockPlace.position;
player.compensatedWorld.tickOpenable(location.x, location.y, location.z);
return;
}
// This also has side effects
// This method is for when the block doesn't always consume the click
// This causes a ton of desync's but mojang doesn't seem to care...
if (ConsumesBlockPlace.consumesPlace(player, player.compensatedWorld.getBlock(blockPlace.position), blockPlace)) {
player.checkManager.onPostFlyingBlockPlace(blockPlace);
return;
}
}
}
if (packet instanceof WrapperPlayClientPlayerBlockPlacement place) {
if (player.gamemode == GameMode.SPECTATOR || player.gamemode == GameMode.ADVENTURE)
return;
Vector3i blockPosition = place.getBlockPosition();
BlockFace face = place.getFace();
ItemStack placedWith = player.inventory.getHeldItem();
if (place.getHand() == InteractionHand.OFF_HAND) {
placedWith = player.inventory.getOffHand();
}
BlockPlace blockPlace = new BlockPlace(player, place.getHand(), blockPosition, place.getFaceId(), face, placedWith, WorldRayTrace.getNearestBlockHitResult(player, null, true, false, false), place.getSequence());
// At this point, it is too late to cancel, so we can only flag, and cancel subsequent block places more aggressively
player.checkManager.onPostFlyingBlockPlace(blockPlace);
blockPlace.isInside = place.getInsideBlock().orElse(false);
if (placedWith.getType().getPlacedType() != null || placedWith.getType() == ItemTypes.FLINT_AND_STEEL || placedWith.getType() == ItemTypes.FIRE_CHARGE) {
BlockPlaceResult.getMaterialData(placedWith.getType()).applyBlockPlaceToWorld(player, blockPlace);
}
}
}
private static void placeBucket(GrimPlayer player, InteractionHand hand, int sequence) {
HitData data = WorldRayTrace.getNearestBlockHitResult(player, null, true, false, true);
if (data != null) {
BlockPlace blockPlace = new BlockPlace(player, hand, data.position(), data.closestDirection().getFaceValue(), data.closestDirection(), ItemStack.EMPTY, data, sequence);
blockPlace.replaceClicked = true; // Replace the block clicked, not the block in the direction
boolean placed = false;
ItemType type = null;
if (data.state().getType() == StateTypes.POWDER_SNOW) {
blockPlace.set(StateTypes.AIR);
type = ItemTypes.POWDER_SNOW_BUCKET;
placed = true;
}
if (data.state().getType() == StateTypes.LAVA) {
blockPlace.set(StateTypes.AIR);
type = ItemTypes.LAVA_BUCKET;
placed = true;
}
// We didn't hit fluid source
if (!placed && !player.compensatedWorld.isWaterSourceBlock(data.position().getX(), data.position().getY(), data.position().getZ()))
return;
// We can't replace plants with a water bucket
if (data.state().getType() == StateTypes.KELP || data.state().getType() == StateTypes.SEAGRASS || data.state().getType() == StateTypes.TALL_SEAGRASS) {
return;
}
if (!placed) {
type = ItemTypes.WATER_BUCKET;
}
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_13)) {
WrappedBlockState existing = blockPlace.getExistingBlockData();
if (existing.hasProperty(StateValue.WATERLOGGED)) { // waterloggable
existing.setWaterlogged(false);
blockPlace.set(existing);
placed = true;
}
}
// Therefore, not waterlogged and is a fluid, and is therefore a source block
if (!placed) {
blockPlace.set(StateTypes.AIR);
}
if (player.gamemode != GameMode.CREATIVE) {
player.inventory.markSlotAsResyncing(blockPlace);
setPlayerItem(player, hand, type);
}
}
}
public static void setPlayerItem(GrimPlayer player, InteractionHand hand, ItemType type) {
// Give the player a water bucket
if (player.gamemode != GameMode.CREATIVE) {
if (hand == InteractionHand.MAIN_HAND) {
if (player.inventory.getHeldItem().getAmount() == 1) {
player.inventory.inventory.setHeldItem(ItemStack.builder().type(type).amount(1).build());
} else { // Give the player a water bucket
player.inventory.inventory.add(ItemStack.builder().type(type).amount(1).build());
// and reduce the held item
player.inventory.getHeldItem().setAmount(player.inventory.getHeldItem().getAmount() - 1);
}
} else {
if (player.inventory.getOffHand().getAmount() == 1) {
player.inventory.inventory.setPlayerInventoryItem(Inventory.SLOT_OFFHAND, ItemStack.builder().type(type).amount(1).build());
} else { // Give the player a water bucket
player.inventory.inventory.add(Inventory.SLOT_OFFHAND, ItemStack.builder().type(type).amount(1).build());
// and reduce the held item
player.inventory.getOffHand().setAmount(player.inventory.getOffHand().getAmount() - 1);
}
}
}
}
private static void placeLilypad(GrimPlayer player, InteractionHand hand, int sequence) {
HitData data = WorldRayTrace.getNearestBlockHitResult(player, null, true, false, true);
if (data != null) {
// A lilypad cannot replace a fluid
if (player.compensatedWorld.getFluidLevelAt(data.position().getX(), data.position().getY() + 1, data.position().getZ()) > 0)
return;
BlockPlace blockPlace = new BlockPlace(player, hand, data.position(), data.closestDirection().getFaceValue(), data.closestDirection(), ItemStack.EMPTY, data, sequence);
blockPlace.replaceClicked = false; // Not possible with use item
// We checked for a full fluid block below here.
if (player.compensatedWorld.getWaterFluidLevelAt(data.position().getX(), data.position().getY(), data.position().getZ()) > 0
|| data.state().getType() == StateTypes.ICE || data.state().getType() == StateTypes.FROSTED_ICE) {
Vector3i pos = data.position();
pos = pos.add(0, 1, 0);
blockPlace.set(pos, StateTypes.LILY_PAD.createBlockState(CompensatedWorld.blockVersion));
if (player.gamemode != GameMode.CREATIVE) {
player.inventory.markSlotAsResyncing(blockPlace);
if (hand == InteractionHand.MAIN_HAND) {
player.inventory.inventory.getHeldItem().setAmount(player.inventory.inventory.getHeldItem().getAmount() - 1);
} else {
player.inventory.getOffHand().setAmount(player.inventory.getOffHand().getAmount() - 1);
}
}
}
}
}
@Override
public void onPacketReceive(PacketReceiveEvent event) {
GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getUser());
if (player == null) return;
if (event.getConnectionState() != ConnectionState.PLAY) {
// Allow checks to listen to configuration packets
if (event.getConnectionState() != ConnectionState.CONFIGURATION) return;
player.checkManager.onPacketReceive(event);
return;
}
// Determine if teleport BEFORE we call the pre-prediction vehicle
if (event.getPacketType() == PacketType.Play.Client.VEHICLE_MOVE) {
WrapperPlayClientVehicleMove move = new WrapperPlayClientVehicleMove(event);
Vector3d position = move.getPosition();
player.packetStateData.lastPacketWasTeleport = player.getSetbackTeleportUtil().checkVehicleTeleportQueue(position.getX(), position.getY(), position.getZ());
}
TeleportAcceptData teleportData = null;
if (WrapperPlayClientPlayerFlying.isFlying(event.getPacketType())) {
player.serverOpenedInventoryThisTick = false;
WrapperPlayClientPlayerFlying flying = new WrapperPlayClientPlayerFlying(event);
Location location = flying.getLocation();
Vector3d position = VectorUtils.clampVector(location.getPosition());
// Teleports must be POS LOOK
teleportData = flying.hasPositionChanged() && flying.hasRotationChanged() ? player.getSetbackTeleportUtil().checkTeleportQueue(position.getX(), position.getY(), position.getZ(), location.getYaw(), location.getPitch()) : new TeleportAcceptData();
player.packetStateData.lastPacketWasTeleport = teleportData.isTeleport();
if (flying.hasRotationChanged() && !flying.hasPositionChanged() && !flying.isOnGround() && !flying.isHorizontalCollision()) {
RotationData data = player.pendingRotations.peek();
if (data != null && data.transaction() == player.getLastTransactionReceived()) {
player.pendingRotations.remove();
if (data.allowRotation(location.getYaw(), location.getPitch())) {
player.packetStateData.lastPacketWasTeleport = true;
} else {
player.checkManager.getCheck(BadPacketsB.class).flag();
}
}
}
player.packetStateData.lastPacketWasOnePointSeventeenDuplicate = isDuplicatePacket(player, flying);
if (player.packetStateData.lastPacketWasOnePointSeventeenDuplicate) {
handleDuplicatePacket(player, event, flying);
}
}
if (player.inVehicle() ? event.getPacketType() == PacketType.Play.Client.VEHICLE_MOVE : WrapperPlayClientPlayerFlying.isFlying(event.getPacketType()) && !player.packetStateData.lastPacketWasOnePointSeventeenDuplicate) {
// Update knockback and explosions immediately, before anything can setback
int kbEntityId = player.inVehicle() ? player.getRidingVehicleId() : player.entityID;
VelocityData calculatedFirstBreadKb = player.checkManager.getKnockbackHandler().calculateFirstBreadKnockback(kbEntityId, player.lastTransactionReceived.get());
VelocityData calculatedRequireKb = player.checkManager.getKnockbackHandler().calculateRequiredKB(kbEntityId, player.lastTransactionReceived.get(), false);
player.firstBreadKB = calculatedFirstBreadKb == null ? player.firstBreadKB : calculatedFirstBreadKb;
player.likelyKB = calculatedRequireKb == null ? player.likelyKB : calculatedRequireKb;
VelocityData calculateFirstBreadExplosion = player.checkManager.getExplosionHandler().getFirstBreadAddedExplosion(player.lastTransactionReceived.get());
VelocityData calculateRequiredExplosion = player.checkManager.getExplosionHandler().getPossibleExplosions(player.lastTransactionReceived.get(), false);
player.firstBreadExplosion = calculateFirstBreadExplosion == null ? player.firstBreadExplosion : calculateFirstBreadExplosion;
player.likelyExplosions = calculateRequiredExplosion == null ? player.likelyExplosions : calculateRequiredExplosion;
}
player.checkManager.onPrePredictionReceivePacket(event);
// The player flagged crasher or timer checks, therefore we must protect predictions against these attacks
if (event.isCancelled() && (WrapperPlayClientPlayerFlying.isFlying(event.getPacketType()) || event.getPacketType() == PacketType.Play.Client.VEHICLE_MOVE)) {
player.packetStateData.cancelDuplicatePacket = false;
return;
}
if (WrapperPlayClientPlayerFlying.isFlying(event.getPacketType())) {
WrapperPlayClientPlayerFlying flying = new WrapperPlayClientPlayerFlying(event);
Location pos = flying.getLocation();
boolean ignoreRotation = player.packetStateData.lastPacketWasOnePointSeventeenDuplicate && player.isIgnoreDuplicatePacketRotation();
handleFlying(player, pos.getX(), pos.getY(), pos.getZ(), ignoreRotation ? 0 : pos.getYaw(), ignoreRotation ? 0 : pos.getPitch(), flying.hasPositionChanged(), flying.hasRotationChanged() && !ignoreRotation, flying.isOnGround(), teleportData);
}
if (event.getPacketType() == PacketType.Play.Client.VEHICLE_MOVE && player.inVehicle()) {
WrapperPlayClientVehicleMove move = new WrapperPlayClientVehicleMove(event);
Vector3d position = move.getPosition();
player.lastX = player.x;
player.lastY = player.y;
player.lastZ = player.z;
Vector3d clamp = VectorUtils.clampVector(position);
player.x = clamp.getX();
player.y = clamp.getY();
player.z = clamp.getZ();
player.yaw = move.getYaw();
player.pitch = move.getPitch();
final VehiclePositionUpdate update = new VehiclePositionUpdate(clamp, position, move.getYaw(), move.getPitch(), move.isOnGround(), player.packetStateData.lastPacketWasTeleport);
player.checkManager.onVehiclePositionUpdate(update);
player.packetStateData.receivedSteerVehicle = false;
}
if (event.getPacketType() == PacketType.Play.Client.PLAYER_DIGGING) {
handleDigging(player, event);
}
if (event.getPacketType() == PacketType.Play.Client.PLAYER_BLOCK_PLACEMENT) {
WrapperPlayClientPlayerBlockPlacement packet = new WrapperPlayClientPlayerBlockPlacement(event);
player.lastBlockPlaceUseItem = System.currentTimeMillis();
ItemStack placedWith = player.inventory.getHeldItem();
if (packet.getHand() == InteractionHand.OFF_HAND) {
placedWith = player.inventory.getOffHand();
}
// This is the use item packet
if (packet.getFace() == BlockFace.OTHER && PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_9)) {
player.placeUseItemPackets.add(new BlockPlaceSnapshot(packet, player.isSneaking));
} else {
// Anti-air place
BlockPlace blockPlace = new BlockPlace(player, packet.getHand(), packet.getBlockPosition(), packet.getFaceId(), packet.getFace(), placedWith, WorldRayTrace.getNearestBlockHitResult(player, null, true, false, false), packet.getSequence());
blockPlace.cursor = packet.getCursorPosition();
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_11) && player.getClientVersion().isOlderThan(ClientVersion.V_1_11)) {
// ViaRewind is stupid and divides the byte by 15 to get the float
// We must undo this to get the correct block place... why?
if (packet.getCursorPosition().getX() * 15 % 1 == 0 && packet.getCursorPosition().getY() * 15 % 1 == 0 && packet.getCursorPosition().getZ() * 15 % 1 == 0) {
// This is impossible to occur without ViaRewind, fix their stupidity
int trueByteX = (int) (packet.getCursorPosition().getX() * 15);
int trueByteY = (int) (packet.getCursorPosition().getY() * 15);
int trueByteZ = (int) (packet.getCursorPosition().getZ() * 15);
blockPlace.cursor = new Vector3f(trueByteX / 16f, trueByteY / 16f, trueByteZ / 16f);
}
}
player.checkManager.onBlockPlace(blockPlace);
if (event.isCancelled() || blockPlace.isCancelled() || player.getSetbackTeleportUtil().shouldBlockMovement()) { // The player tried placing blocks in air/water
if (!event.isCancelled()) {
event.setCancelled(true);
player.onPacketCancel();
}
Vector3i facePos = new Vector3i(packet.getBlockPosition().getX() + packet.getFace().getModX(), packet.getBlockPosition().getY() + packet.getFace().getModY(), packet.getBlockPosition().getZ() + packet.getFace().getModZ());
// Ends the client prediction introduced in 1.19+
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_19) && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_19)) {
player.user.sendPacket(new WrapperPlayServerAcknowledgeBlockChanges(packet.getSequence()));
} else { // The client isn't smart enough to revert changes
player.resyncPosition(packet.getBlockPosition());
player.resyncPosition(facePos);
}
// Stop inventory desync from cancelling place
if (player.platformPlayer != null) {
if (packet.getHand() == InteractionHand.MAIN_HAND) {
ItemStack mainHand = player.platformPlayer.getInventory().getItemInHand();
player.user.sendPacket(new WrapperPlayServerSetSlot(0, player.inventory.stateID, 36 + player.packetStateData.lastSlotSelected, mainHand));
} else {
ItemStack offHand = player.platformPlayer.getInventory().getItemInOffHand();
player.user.sendPacket(new WrapperPlayServerSetSlot(0, player.inventory.stateID, 45, offHand));
}
}
} else { // Legit place
player.placeUseItemPackets.add(new BlockPlaceSnapshot(packet, player.isSneaking));
}
}
}
if (event.getPacketType() == PacketType.Play.Client.USE_ITEM) {
WrapperPlayClientUseItem packet = new WrapperPlayClientUseItem(event);
player.placeUseItemPackets.add(new BlockPlaceSnapshot(packet, player.isSneaking));
player.lastBlockPlaceUseItem = System.currentTimeMillis();
}
// Call the packet checks last as they can modify the contents of the packet
// Such as the NoFall check setting the player to not be on the ground
player.checkManager.onPacketReceive(event);
if (player.packetStateData.cancelDuplicatePacket) {
event.setCancelled(true);
player.packetStateData.cancelDuplicatePacket = false;
}
if (event.getPacketType() == PacketType.Play.Client.CLIENT_TICK_END && player.supportsEndTick()) {
player.serverOpenedInventoryThisTick = false;
if (!player.packetStateData.didSendMovementBeforeTickEnd) {
// The player didn't send a movement packet, so we can predict this like we had idle tick on 1.8
player.packetStateData.didLastLastMovementIncludePosition = player.packetStateData.didLastMovementIncludePosition;
player.packetStateData.didLastMovementIncludePosition = false;
// Track dash cooldown
if (!player.inVehicle()) {
player.dashableEntities.tick();
}
}
player.packetStateData.didSendMovementBeforeTickEnd = false;
}
// Finally, remove the packet state variables on this packet
player.packetStateData.lastPacketWasOnePointSeventeenDuplicate = false;
player.packetStateData.lastPacketWasTeleport = false;
}
@Override
public void onPacketSend(PacketSendEvent event) {
if (event.getConnectionState() != ConnectionState.PLAY) return;
GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getUser());
if (player == null) return;
player.checkManager.onPacketSend(event);
}
private static boolean isDuplicatePacket(@NotNull GrimPlayer player, @NotNull WrapperPlayClientPlayerFlying flying) {
// teleports are not duplicate packets
if (player.packetStateData.lastPacketWasTeleport) return false;
// duplicate packets were added in 1.17 and removed in 1.21
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_17)
// Mojang has become less stupid!
|| player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_21)) return false;
// EVEN A BUNCH OF MONKEYS ON A TYPEWRITER COULDNT WRITE WORSE NETCODE THAN MOJANG
// duplicate packets always have position and rotation
if (!flying.hasPositionChanged() || !flying.hasRotationChanged()) return false;
// if the player was in a vehicle, has position and look, and wasn't a teleport, then this was a duplicate packet
if (player.inVehicle()) return true;
final Vector3d position = flying.getLocation().getPosition();
final double threshold = player.getMovementThreshold();
// ground status will never change in duplicate packets
return flying.isOnGround() == player.packetStateData.packetPlayerOnGround
// due to 0.03, we can't check exact position, only within 0.03
&& player.filterMojangStupidityOnMojangStupidity.distanceSquared(position) < threshold * threshold;
}
private static void handleDuplicatePacket(
@NotNull GrimPlayer player,
@NotNull PacketReceiveEvent event,
@NotNull WrapperPlayClientPlayerFlying flying) {
final float yaw = flying.getLocation().getYaw();
final float pitch = flying.getLocation().getPitch();
final Vector3d position = flying.getLocation().getPosition();
// Mark that we want this packet to be cancelled from reaching the server
// Additionally, only yaw and pitch matters: https://github.com/GrimAnticheat/Grim/issues/1275#issuecomment-1872444018
// 1.9+ isn't impacted by this packet as much.
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_9) && player.isCancelDuplicatePacket()) {
player.packetStateData.cancelDuplicatePacket = true;
} else {
// Override location to force it to use the last real position of the player. Prevents position-related bypasses like NoFall.
flying.setLocation(new Location(
player.filterMojangStupidityOnMojangStupidity.getX(),
player.filterMojangStupidityOnMojangStupidity.getY(),
player.filterMojangStupidityOnMojangStupidity.getZ(),
yaw,
pitch
));
event.markForReEncode(true);
}
player.packetStateData.lastPacketWasOnePointSeventeenDuplicate = true;
if (!player.isIgnoreDuplicatePacketRotation()) {
if (player.yaw != yaw || player.pitch != pitch) {
player.lastYaw = player.yaw;
player.lastPitch = player.pitch;
}
// Take the pitch and yaw, just in case we were wrong about this being a duplicate packet
player.yaw = yaw;
player.pitch = pitch;
}
player.packetStateData.lastClaimedPosition = position;
}
private static void handleFlying(GrimPlayer player, double x, double y, double z, float yaw, float pitch, boolean hasPosition, boolean hasLook, boolean onGround, TeleportAcceptData teleportData) {
long now = System.currentTimeMillis();
if (!hasPosition) {
// This may need to be secured later, although nothing that is very important relies on this
// 1.8 ghost clients can't abuse this anyway
player.uncertaintyHandler.lastPointThree.reset();
}
// We can't set the look if this is actually a duplicate packet
// If the last packet wasn't stupid, then ignore this logic
// If it was stupid, only change the look if it's different
// Otherwise, reach and fireworks can false
if (hasLook && (!player.packetStateData.lastPacketWasOnePointSeventeenDuplicate ||
player.yaw != yaw || player.pitch != pitch)) {
player.lastYaw = player.yaw;
player.lastPitch = player.pitch;
}
CheckManagerListener.handleQueuedPlaces(player, hasLook, pitch, yaw, now);
CheckManagerListener.handleQueuedBreaks(player, hasLook, pitch, yaw, now);
// We can set the new pos after the places
if (hasPosition) {
player.packetStateData.lastClaimedPosition = new Vector3d(x, y, z);
}
// This stupid mechanic has been measured with 0.03403409022229198 y velocity... DAMN IT MOJANG, use 0.06 to be safe...
if (!hasPosition && onGround != player.packetStateData.packetPlayerOnGround && !player.inVehicle()) {
// Check for blocks within 0.03 of the player's position before allowing ground to be true - if 0.03
// Cannot use collisions like normal because stepping messes it up :(
//
// This may need to be secured better, but limiting the new setback positions seems good enough for now...
boolean canFeasiblyPointThree = Collisions.slowCouldPointThreeHitGround(player, player.x, player.y, player.z);
if (!canFeasiblyPointThree && !player.compensatedWorld.isNearHardEntity(player.boundingBox.copy().expand(4))
|| player.clientVelocity.getY() > 0.06 && !player.uncertaintyHandler.wasAffectedByStuckSpeed()) { // TODO: still needed?
// Ghost block/0.03 abuse
player.getSetbackTeleportUtil().executeForceResync();
} else {
// Accept the new ground status
player.lastOnGround = onGround;
player.clientClaimsLastOnGround = onGround;
player.uncertaintyHandler.onGroundUncertain = true;
}
}
if (!player.packetStateData.lastPacketWasTeleport) {
player.packetStateData.packetPlayerOnGround = onGround;
}
if (hasLook) {
player.yaw = yaw;
player.pitch = pitch;
player.vehicleData.playerPitch = pitch;
player.vehicleData.playerYaw = yaw;
float deltaXRot = player.yaw - player.lastYaw;
float deltaYRot = player.pitch - player.lastPitch;
final RotationUpdate update = new RotationUpdate(new HeadRotation(player.lastYaw, player.lastPitch), new HeadRotation(player.yaw, player.pitch), deltaXRot, deltaYRot);
player.checkManager.onRotationUpdate(update);
}
if (hasPosition) {
Vector3d position = new Vector3d(x, y, z);
Vector3d clampVector = VectorUtils.clampVector(position);
final PositionUpdate update = new PositionUpdate(new Vector3d(player.x, player.y, player.z), position, onGround, teleportData.getSetback(), teleportData.getTeleportData(), teleportData.isTeleport());
// Duplicate packets don't care about 0.03
if (!player.packetStateData.lastPacketWasOnePointSeventeenDuplicate) {
player.filterMojangStupidityOnMojangStupidity.copy(clampVector);
}
if (!player.inVehicle() && !player.packetStateData.lastPacketWasOnePointSeventeenDuplicate) {
player.lastX = player.x;
player.lastY = player.y;
player.lastZ = player.z;
player.x = clampVector.getX();
player.y = clampVector.getY();
player.z = clampVector.getZ();
player.checkManager.onPositionUpdate(update);
} else if (update.isTeleport()) { // Mojang doesn't use their own exit vehicle field to leave vehicles, manually call the setback handler
player.getSetbackTeleportUtil().onPredictionComplete(new PredictionComplete(0, update, true));
}
}
player.packetStateData.didLastLastMovementIncludePosition = player.packetStateData.didLastMovementIncludePosition;
player.packetStateData.didLastMovementIncludePosition = hasPosition;
if (!player.packetStateData.lastPacketWasTeleport) {
player.packetStateData.didSendMovementBeforeTickEnd = true;
}
player.packetStateData.horseInteractCausedForcedRotation = false;
}
private static void handleDigging(GrimPlayer player, PacketReceiveEvent event) {
player.lastBlockBreak = System.currentTimeMillis();
final WrapperPlayClientPlayerDigging packet = new WrapperPlayClientPlayerDigging(event);
final DiggingAction action = packet.getAction();
if (action != DiggingAction.START_DIGGING
&& action != DiggingAction.FINISHED_DIGGING
&& action != DiggingAction.CANCELLED_DIGGING) {
return;
}
final BlockBreak blockBreak = new BlockBreak(player, packet.getBlockPosition(), packet.getBlockFace(), packet.getBlockFaceId(), action, packet.getSequence(), player.compensatedWorld.getBlock(packet.getBlockPosition()));
player.checkManager.onBlockBreak(blockBreak);
if (blockBreak.isCancelled()) {
event.setCancelled(true);
player.onPacketCancel();
player.resyncPosition(blockBreak.position, packet.getSequence());
return;
}
player.queuedBreaks.add(blockBreak);
if (action == DiggingAction.FINISHED_DIGGING && BREAKABLE.test(blockBreak.block.getType())) {
player.compensatedWorld.startPredicting();
player.compensatedWorld.updateBlock(blockBreak.position.x, blockBreak.position.y, blockBreak.position.z, 0);
player.compensatedWorld.stopPredicting(packet);
}
if (action == DiggingAction.START_DIGGING) {
// FIXME: getBlockDamage might not return the correct value if the player switched slots before this
double damage = BlockBreakSpeed.getBlockDamage(player, blockBreak.block);
// Instant breaking, no damage means it is unbreakable by creative players (with swords)
if (damage >= 1) {
player.compensatedWorld.startPredicting();
player.blockHistory.add(
new BlockModification(
player.compensatedWorld.getBlock(blockBreak.position),
WrappedBlockState.getByGlobalId(0),
blockBreak.position,
GrimAPI.INSTANCE.getTickManager().currentTick,
BlockModification.Cause.START_DIGGING
)
);
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_13) && Materials.isWaterSource(player.getClientVersion(), blockBreak.block)) {
// Vanilla uses a method to grab water flowing, but as you can't break flowing water
// We can simply treat all waterlogged blocks or source blocks as source blocks
player.compensatedWorld.updateBlock(blockBreak.position, StateTypes.WATER.createBlockState(CompensatedWorld.blockVersion));
} else {
player.compensatedWorld.updateBlock(blockBreak.position.x, blockBreak.position.y, blockBreak.position.z, 0);
}
player.compensatedWorld.stopPredicting(packet);
}
}
player.compensatedWorld.handleBlockBreakPrediction(packet);
}
}
// NOTE (AI): The SetSlot send sits in the block-place handling branch and uses the inventory state id, which keeps the packet valid on 1.9+ protocol versions. The listener is the single entry point for client packets before the check manager runs.Related Packets
Wiki Cross-Reference
Clientbound 0x2F: byte windowId, short slot, then Slot ItemStack encoding.
Window -1 with slot -1 updates the cursor item; window 0 updates player inventory.
Single-slot sync; full-window resync arrives separately via S30 Window Items.
MCP 1.8.9 S2FPacketSetSlot implements Packet
1.8.9 callers: EntityPlayerMP.sendSlotContents sends new S2FPacketSetSlot (line 860) +2 more: https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/player/EntityPlayerMP.java
Cross-checked against minecraft.wiki (CC BY-SA 3.0) for 1.8.9 accuracy.
Vanilla Internals
Full 1.8.9 logic-class sources that send or handle this packet, stored verbatim.
Module Analyses Using S2FPacketSetSlot
Full source walkthroughs of the modules and anti-cheats that use this packet.