Spicy Reach module 2 files, 702 lines

Spicy Reach: Full Source Analysis

Spicy's Reach overrides the client's block-reach distance through the EventGetBlockReach hook.

info/spicyclient/modules/combat/Reach.java · GitHub source ↗

Published 2026-08-12 · Updated 2026-08-12

Packets This Module Uses

Analysis

Overview

Spicy's Reach overrides the client's block-reach distance through the EventGetBlockReach hook. The module exposes a NumberSetting named Reach (default 3, minimum 3, maximum 6, step 0.1), updates the HUD description on EventUpdate, and on EventGetBlockReach cancels the event and sets event.reach to the configured value. The patched PlayerControllerMP.getBlockReachDistance constructs the event, fires it, and returns event.reach whenever it is not -1, falling back to the vanilla 5.0 creative or 4.5 survival distance otherwise. In 1.8 the mouse-over ray trace that decides both block interaction and entity attack targets uses this distance as its cap, so raising it extends entity attack reach up to 6 blocks; a vanilla server performs no reach validation of its own, which is exactly why anticheats must.

Event path

The fork's PlayerControllerMP.getBlockReachDistance builds an EventGetBlockReach, sets its type to PRE, fires it through SpicyClient.onEvent, and returns event.reach when the field is not -1. The Reach module listens for the event in its pre phase, cancels it, and writes the configured value into the reach field. Cancelling the event prevents later handlers from overriding the value, and the field write is what the vanilla method reads back. The module's onDisable clears the use-item key binding, a leftover unrelated to the reach mechanic itself.

Why reach works in 1.8

EntityRenderer.getMouseOver ray-traces entities with a distance cap equal to the block-reach distance, and PlayerControllerMP.attackEntity acts on the mouse-over result without any additional distance validation, so getBlockReachDistance is effectively the player's attack range. The vanilla 1.8 server does not check how far an attack reaches; the only server-side limit is the coarse bound on entity hits. Raising the client distance to 6 therefore makes C02 attacks land on targets the real 3.0 to 4.5 block envelope would never cover, with the server none the wiser. The same cap governs block interaction, so the module also extends placement and breaking ranges, though the analysis focuses on the combat consequence.

Configurable surface

The setting spans 3 to 6 in 0.1 steps with a default of 3, which is the vanilla survival value, so the module is a no-op until the user raises it. The HUD description echoes the current value on every EventUpdate, which makes the active range visible in the client's own module list. The distance is applied globally, with no per-target or per-tick randomization, so the module presents a constant extended range that server-side reach checks can measure on every single attack.

source Reach.java (module)

Reach.java60 lines · JavaOriginal ↗
1
package info.spicyclient.modules.combat;
2
3
import org.lwjgl.input.Keyboard;
4
5
import info.spicyclient.events.Event;
6
import info.spicyclient.events.listeners.EventGetBlockReach;
7
import info.spicyclient.events.listeners.EventUpdate;
8
import info.spicyclient.modules.Module;
9
import info.spicyclient.settings.NumberSetting;
10
import info.spicyclient.util.Timer;
11
12
public class Reach extends Module {
13
	
14
	public NumberSetting reach = new NumberSetting("Reach", 3, 3, 6, 0.1);
15
	
16
	public Reach() {
17
		super("Reach", Keyboard.KEY_NONE, Category.COMBAT);
18
		resetSettings();
19
	}
20
	
21
	@Override
22
	public void resetSettings() {
23
		this.settings.clear();
24
		this.addSettings(reach);
25
	}
26
	
27
	public void onEnable() {
28
		
29
	}
30
	
31
	public void onDisable() {
32
		mc.gameSettings.keyBindUseItem.pressed = false;
33
	}
34
	
35
	public Timer timer = new Timer();
36
	
37
	public void onEvent(Event e) {
38
		
39
		if (e instanceof EventUpdate) {
40
			
41
			if (e.isPre()) {
42
				
43
				this.additionalInformation = "" + reach.getValue();
44
				
45
			}
46
			
47
		}
48
		
49
		if (e instanceof EventGetBlockReach) {
50
			
51
			EventGetBlockReach event = (EventGetBlockReach) e;
52
			
53
			event.setCanceled(true);
54
			event.reach = (float) reach.getValue();
55
			
56
		}
57
		
58
	}
59
	
60
}

What this file does

The module is the Reach NumberSetting plus two handlers. The EventUpdate pre handler updates the HUD text with the current value, and the EventGetBlockReach handler cancels the event and writes the value into event.reach. The constructor registers the setting with the 3 to 6 range and 0.1 step, and resetSettings re-registers it on reset. onDisable clears the use-item binding, which does not participate in the reach mechanic. The module never sends a packet; its entire effect is the value the patched vanilla method reads.

source PlayerControllerMP.java (reach integration)

PlayerControllerMP.java642 lines · JavaOriginal ↗
1
package net.minecraft.client.multiplayer;
2
3
import info.spicyclient.SpicyClient;
4
import info.spicyclient.events.EventType;
5
import info.spicyclient.events.listeners.EventAddBlockDamage;
6
import info.spicyclient.events.listeners.EventGetBlockReach;
7
import net.minecraft.block.Block;
8
import net.minecraft.block.material.Material;
9
import net.minecraft.block.state.IBlockState;
10
import net.minecraft.client.Minecraft;
11
import net.minecraft.client.audio.PositionedSoundRecord;
12
import net.minecraft.client.entity.EntityPlayerSP;
13
import net.minecraft.client.network.NetHandlerPlayClient;
14
import net.minecraft.entity.Entity;
15
import net.minecraft.entity.passive.EntityHorse;
16
import net.minecraft.entity.player.EntityPlayer;
17
import net.minecraft.item.ItemBlock;
18
import net.minecraft.item.ItemStack;
19
import net.minecraft.item.ItemSword;
20
import net.minecraft.network.play.client.C02PacketUseEntity;
21
import net.minecraft.network.play.client.C07PacketPlayerDigging;
22
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
23
import net.minecraft.network.play.client.C09PacketHeldItemChange;
24
import net.minecraft.network.play.client.C0EPacketClickWindow;
25
import net.minecraft.network.play.client.C10PacketCreativeInventoryAction;
26
import net.minecraft.network.play.client.C11PacketEnchantItem;
27
import net.minecraft.stats.StatFileWriter;
28
import net.minecraft.util.BlockPos;
29
import net.minecraft.util.EnumFacing;
30
import net.minecraft.util.MovingObjectPosition;
31
import net.minecraft.util.ResourceLocation;
32
import net.minecraft.util.Vec3;
33
import net.minecraft.world.World;
34
import net.minecraft.world.WorldSettings;
35
36
public class PlayerControllerMP
37
{
38
    /** The Minecraft instance. */
39
    private final Minecraft mc;
40
    private final NetHandlerPlayClient netClientHandler;
41
    private BlockPos currentBlock = new BlockPos(-1, -1, -1);
42
43
    /** The Item currently being used to destroy a block */
44
    private ItemStack currentItemHittingBlock;
45
46
    /** Current block damage (MP) */
47
    public float curBlockDamageMP;
48
49
    /**
50
     * Tick counter, when it hits 4 it resets back to 0 and plays the step sound
51
     */
52
    private float stepSoundTickCounter;
53
54
    /**
55
     * Delays the first damage on the block after the first click on the block
56
     */
57
    public int blockHitDelay;
58
59
    /** Tells if the player is hitting a block */
60
    private boolean isHittingBlock;
61
62
    /** Current game type for the player */
63
    public WorldSettings.GameType currentGameType = WorldSettings.GameType.SURVIVAL;
64
65
    /** Index of the current item held by the player in the inventory hotbar */
66
    private int currentPlayerItem;
67
68
    public PlayerControllerMP(Minecraft mcIn, NetHandlerPlayClient p_i45062_2_)
69
    {
70
        this.mc = mcIn;
71
        this.netClientHandler = p_i45062_2_;
72
    }
73
74
    public static void clickBlockCreative(Minecraft mcIn, PlayerControllerMP p_178891_1_, BlockPos p_178891_2_, EnumFacing p_178891_3_)
75
    {
76
        if (!mcIn.theWorld.extinguishFire(mcIn.thePlayer, p_178891_2_, p_178891_3_))
77
        {
78
            p_178891_1_.onPlayerDestroyBlock(p_178891_2_, p_178891_3_);
79
        }
80
    }
81
82
    /**
83
     * Sets player capabilities depending on current gametype. params: player
84
     */
85
    public void setPlayerCapabilities(EntityPlayer p_78748_1_)
86
    {
87
        this.currentGameType.configurePlayerCapabilities(p_78748_1_.capabilities);
88
    }
89
90
    /**
91
     * None
92
     */
93
    public boolean isSpectator()
94
    {
95
        return this.currentGameType == WorldSettings.GameType.SPECTATOR;
96
    }
97
98
    /**
99
     * Sets the game type for the player.
100
     */
101
    public void setGameType(WorldSettings.GameType p_78746_1_)
102
    {
103
        this.currentGameType = p_78746_1_;
104
        this.currentGameType.configurePlayerCapabilities(this.mc.thePlayer.capabilities);
105
    }
106
107
    /**
108
     * Flips the player around.
109
     */
110
    public void flipPlayer(EntityPlayer playerIn)
111
    {
112
        playerIn.rotationYaw = -180.0F;
113
    }
114
115
    public boolean shouldDrawHUD()
116
    {
117
        return this.currentGameType.isSurvivalOrAdventure();
118
    }
119
120
    /**
121
     * Called when a player completes the destruction of a block
122
     */
123
    public boolean onPlayerDestroyBlock(BlockPos pos, EnumFacing side)
124
    {
125
        if (this.currentGameType.isAdventure())
126
        {
127
            if (this.currentGameType == WorldSettings.GameType.SPECTATOR)
128
            {
129
                return false;
130
            }
131
132
            if (!this.mc.thePlayer.isAllowEdit())
133
            {
134
                Block block = this.mc.theWorld.getBlockState(pos).getBlock();
135
                ItemStack itemstack = this.mc.thePlayer.getCurrentEquippedItem();
136
137
                if (itemstack == null)
138
                {
139
                    return false;
140
                }
141
142
                if (!itemstack.canDestroy(block))
143
                {
144
                    return false;
145
                }
146
            }
147
        }
148
149
        if (this.currentGameType.isCreative() && this.mc.thePlayer.getHeldItem() != null && this.mc.thePlayer.getHeldItem().getItem() instanceof ItemSword)
150
        {
151
            return false;
152
        }
153
        else
154
        {
155
            World world = this.mc.theWorld;
156
            IBlockState iblockstate = world.getBlockState(pos);
157
            Block block1 = iblockstate.getBlock();
158
159
            if (block1.getMaterial() == Material.air)
160
            {
161
                return false;
162
            }
163
            else
164
            {
165
                world.playAuxSFX(2001, pos, Block.getStateId(iblockstate));
166
                boolean flag = world.setBlockToAir(pos);
167
168
                if (flag)
169
                {
170
                    block1.onBlockDestroyedByPlayer(world, pos, iblockstate);
171
                }
172
173
                this.currentBlock = new BlockPos(this.currentBlock.getX(), -1, this.currentBlock.getZ());
174
175
                if (!this.currentGameType.isCreative())
176
                {
177
                    ItemStack itemstack1 = this.mc.thePlayer.getCurrentEquippedItem();
178
179
                    if (itemstack1 != null)
180
                    {
181
                        itemstack1.onBlockDestroyed(world, block1, pos, this.mc.thePlayer);
182
183
                        if (itemstack1.stackSize == 0)
184
                        {
185
                            this.mc.thePlayer.destroyCurrentEquippedItem();
186
                        }
187
                    }
188
                }
189
190
                return flag;
191
            }
192
        }
193
    }
194
195
    /**
196
     * Called when the player is hitting a block with an item.
197
     */
198
    public boolean clickBlock(BlockPos loc, EnumFacing face)
199
    {
200
        if (this.currentGameType.isAdventure())
201
        {
202
            if (this.currentGameType == WorldSettings.GameType.SPECTATOR)
203
            {
204
                return false;
205
            }
206
207
            if (!this.mc.thePlayer.isAllowEdit())
208
            {
209
                Block block = this.mc.theWorld.getBlockState(loc).getBlock();
210
                ItemStack itemstack = this.mc.thePlayer.getCurrentEquippedItem();
211
212
                if (itemstack == null)
213
                {
214
                    return false;
215
                }
216
217
                if (!itemstack.canDestroy(block))
218
                {
219
                    return false;
220
                }
221
            }
222
        }
223
224
        if (!this.mc.theWorld.getWorldBorder().contains(loc))
225
        {
226
            return false;
227
        }
228
        else
229
        {
230
            if (this.currentGameType.isCreative())
231
            {
232
                this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, loc, face));
233
                clickBlockCreative(this.mc, this, loc, face);
234
                this.blockHitDelay = 5;
235
            }
236
            else if (!this.isHittingBlock || !this.isHittingPosition(loc))
237
            {
238
                if (this.isHittingBlock)
239
                {
240
                    this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, face));
241
                }
242
243
                this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, loc, face));
244
                Block block1 = this.mc.theWorld.getBlockState(loc).getBlock();
245
                boolean flag = block1.getMaterial() != Material.air;
246
247
                if (flag && this.curBlockDamageMP == 0.0F)
248
                {
249
                    block1.onBlockClicked(this.mc.theWorld, loc, this.mc.thePlayer);
250
                }
251
252
                if (flag && block1.getPlayerRelativeBlockHardness(this.mc.thePlayer, this.mc.thePlayer.worldObj, loc) >= 1.0F)
253
                {
254
                    this.onPlayerDestroyBlock(loc, face);
255
                }
256
                else
257
                {
258
                    this.isHittingBlock = true;
259
                    this.currentBlock = loc;
260
                    this.currentItemHittingBlock = this.mc.thePlayer.getHeldItem();
261
                    this.curBlockDamageMP = 0.0F;
262
                    this.stepSoundTickCounter = 0.0F;
263
                    this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0F) - 1);
264
                }
265
            }
266
267
            return true;
268
        }
269
    }
270
271
    /**
272
     * Resets current block damage and isHittingBlock
273
     */
274
    public void resetBlockRemoving()
275
    {
276
        if (this.isHittingBlock)
277
        {
278
            this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, EnumFacing.DOWN));
279
            this.isHittingBlock = false;
280
            this.curBlockDamageMP = 0.0F;
281
            this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, -1);
282
        }
283
    }
284
285
    public boolean onPlayerDamageBlock(BlockPos posBlock, EnumFacing directionFacing)
286
    {
287
        this.syncCurrentPlayItem();
288
289
        if (this.blockHitDelay > 0)
290
        {
291
            --this.blockHitDelay;
292
            return true;
293
        }
294
        else if (this.currentGameType.isCreative() && this.mc.theWorld.getWorldBorder().contains(posBlock))
295
        {
296
            this.blockHitDelay = 5;
297
            this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, posBlock, directionFacing));
298
            clickBlockCreative(this.mc, this, posBlock, directionFacing);
299
            return true;
300
        }
301
        else if (this.isHittingPosition(posBlock))
302
        {
303
            Block block = this.mc.theWorld.getBlockState(posBlock).getBlock();
304
305
            if (block.getMaterial() == Material.air)
306
            {
307
                this.isHittingBlock = false;
308
                return false;
309
            }
310
            else
311
            {
312
            	
313
            	EventAddBlockDamage event = new EventAddBlockDamage();
314
            	event.Damage = 1;
315
            	event.setType(EventType.PRE);
316
            	SpicyClient.onEvent(event);
317
            	for (int i = 0; i < event.getDamage(); i++) {
318
            		
319
            		this.curBlockDamageMP += block.getPlayerRelativeBlockHardness(this.mc.thePlayer, this.mc.thePlayer.worldObj, posBlock);
320
            		
321
            	}
322
            	
323
                if (this.stepSoundTickCounter % 4.0F == 0.0F)
324
                {
325
                    this.mc.getSoundHandler().playSound(new PositionedSoundRecord(new ResourceLocation(block.stepSound.getStepSound()), (block.stepSound.getVolume() + 1.0F) / 8.0F, block.stepSound.getFrequency() * 0.5F, (float)posBlock.getX() + 0.5F, (float)posBlock.getY() + 0.5F, (float)posBlock.getZ() + 0.5F));
326
                }
327
328
                ++this.stepSoundTickCounter;
329
330
                if (this.curBlockDamageMP >= 1.0F)
331
                {
332
                    this.isHittingBlock = false;
333
                    this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.STOP_DESTROY_BLOCK, posBlock, directionFacing));
334
                    this.onPlayerDestroyBlock(posBlock, directionFacing);
335
                    this.curBlockDamageMP = 0.0F;
336
                    this.stepSoundTickCounter = 0.0F;
337
                    this.blockHitDelay = 5;
338
                }
339
340
                this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0F) - 1);
341
                return true;
342
            }
343
        }
344
        else
345
        {
346
            return this.clickBlock(posBlock, directionFacing);
347
        }
348
    }
349
350
    /**
351
     * player reach distance = 4F
352
     */
353
    public float getBlockReachDistance()
354
    {
355
    	
356
    	EventGetBlockReach event = new EventGetBlockReach();
357
    	event.setType(EventType.PRE);
358
    	SpicyClient.onEvent(event);
359
    	
360
    	if (event.reach != -1) {
361
    		return event.reach;
362
    	}else {
363
    		return this.currentGameType.isCreative() ? 5.0F : 4.5F;
364
    	}
365
    }
366
367
    public void updateController()
368
    {
369
        this.syncCurrentPlayItem();
370
371
        if (this.netClientHandler.getNetworkManager().isChannelOpen())
372
        {
373
            this.netClientHandler.getNetworkManager().processReceivedPackets();
374
        }
375
        else
376
        {
377
            this.netClientHandler.getNetworkManager().checkDisconnected();
378
        }
379
    }
380
381
    private boolean isHittingPosition(BlockPos pos)
382
    {
383
        ItemStack itemstack = this.mc.thePlayer.getHeldItem();
384
        boolean flag = this.currentItemHittingBlock == null && itemstack == null;
385
386
        if (this.currentItemHittingBlock != null && itemstack != null)
387
        {
388
            flag = itemstack.getItem() == this.currentItemHittingBlock.getItem() && ItemStack.areItemStackTagsEqual(itemstack, this.currentItemHittingBlock) && (itemstack.isItemStackDamageable() || itemstack.getMetadata() == this.currentItemHittingBlock.getMetadata());
389
        }
390
391
        return pos.equals(this.currentBlock) && flag;
392
    }
393
394
    /**
395
     * Syncs the current player item with the server
396
     */
397
    public void syncCurrentPlayItem()
398
    {
399
        int i = this.mc.thePlayer.inventory.currentItem;
400
401
        if (i != this.currentPlayerItem)
402
        {
403
            this.currentPlayerItem = i;
404
            this.netClientHandler.addToSendQueue(new C09PacketHeldItemChange(this.currentPlayerItem));
405
        }
406
    }
407
408
    public boolean onPlayerRightClick(EntityPlayerSP player, WorldClient worldIn, ItemStack heldStack, BlockPos hitPos, EnumFacing side, Vec3 hitVec)
409
    {
410
        this.syncCurrentPlayItem();
411
        float f = (float)(hitVec.xCoord - (double)hitPos.getX());
412
        float f1 = (float)(hitVec.yCoord - (double)hitPos.getY());
413
        float f2 = (float)(hitVec.zCoord - (double)hitPos.getZ());
414
        boolean flag = false;
415
416
        if (!this.mc.theWorld.getWorldBorder().contains(hitPos))
417
        {
418
            return false;
419
        }
420
        else
421
        {
422
            if (this.currentGameType != WorldSettings.GameType.SPECTATOR)
423
            {
424
                IBlockState iblockstate = worldIn.getBlockState(hitPos);
425
426
                if ((!player.isSneaking() || player.getHeldItem() == null) && iblockstate.getBlock().onBlockActivated(worldIn, hitPos, iblockstate, player, side, f, f1, f2))
427
                {
428
                    flag = true;
429
                }
430
431
                if (!flag && heldStack != null && heldStack.getItem() instanceof ItemBlock)
432
                {
433
                    ItemBlock itemblock = (ItemBlock)heldStack.getItem();
434
435
                    if (!itemblock.canPlaceBlockOnSide(worldIn, hitPos, side, player, heldStack))
436
                    {
437
                        return false;
438
                    }
439
                }
440
            }
441
            
442
            this.netClientHandler.addToSendQueue(new C08PacketPlayerBlockPlacement(hitPos, side.getIndex(), player.inventory.getCurrentItem(), f, f1, f2));
443
444
            if (!flag && this.currentGameType != WorldSettings.GameType.SPECTATOR)
445
            {
446
                if (heldStack == null)
447
                {
448
                    return false;
449
                }
450
                else if (this.currentGameType.isCreative())
451
                {
452
                    int i = heldStack.getMetadata();
453
                    int j = heldStack.stackSize;
454
                    boolean flag1 = heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2);
455
                    heldStack.setItemDamage(i);
456
                    heldStack.stackSize = j;
457
                    return flag1;
458
                }
459
                else
460
                {
461
                    return heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2);
462
                }
463
            }
464
            else
465
            {
466
                return true;
467
            }
468
        }
469
    }
470
471
    /**
472
     * Notifies the server of things like consuming food, etc...
473
     */
474
    public boolean sendUseItem(EntityPlayer playerIn, World worldIn, ItemStack itemStackIn)
475
    {
476
        if (this.currentGameType == WorldSettings.GameType.SPECTATOR)
477
        {
478
            return false;
479
        }
480
        else
481
        {
482
            this.syncCurrentPlayItem();
483
            this.netClientHandler.addToSendQueue(new C08PacketPlayerBlockPlacement(playerIn.inventory.getCurrentItem()));
484
            int i = itemStackIn.stackSize;
485
            ItemStack itemstack = itemStackIn.useItemRightClick(worldIn, playerIn);
486
487
            if (itemstack != itemStackIn || itemstack != null && itemstack.stackSize != i)
488
            {
489
                playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = itemstack;
490
491
                if (itemstack.stackSize == 0)
492
                {
493
                    playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = null;
494
                }
495
496
                return true;
497
            }
498
            else
499
            {
500
                return false;
501
            }
502
        }
503
    }
504
505
    public EntityPlayerSP func_178892_a(World worldIn, StatFileWriter p_178892_2_)
506
    {
507
        return new EntityPlayerSP(this.mc, worldIn, this.netClientHandler, p_178892_2_);
508
    }
509
510
    /**
511
     * Attacks an entity
512
     */
513
    public void attackEntity(EntityPlayer playerIn, Entity targetEntity)
514
    {
515
        this.syncCurrentPlayItem();
516
        this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.ATTACK));
517
518
        if (this.currentGameType != WorldSettings.GameType.SPECTATOR)
519
        {
520
            playerIn.attackTargetEntityWithCurrentItem(targetEntity);
521
        }
522
    }
523
524
    /**
525
     * Send packet to server - player is interacting with another entity (left click)
526
     */
527
    public boolean interactWithEntitySendPacket(EntityPlayer playerIn, Entity targetEntity)
528
    {
529
        this.syncCurrentPlayItem();
530
        this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.INTERACT));
531
        return this.currentGameType != WorldSettings.GameType.SPECTATOR && playerIn.interactWith(targetEntity);
532
    }
533
534
    public boolean func_178894_a(EntityPlayer p_178894_1_, Entity p_178894_2_, MovingObjectPosition p_178894_3_)
535
    {
536
        this.syncCurrentPlayItem();
537
        Vec3 vec3 = new Vec3(p_178894_3_.hitVec.xCoord - p_178894_2_.posX, p_178894_3_.hitVec.yCoord - p_178894_2_.posY, p_178894_3_.hitVec.zCoord - p_178894_2_.posZ);
538
        this.netClientHandler.addToSendQueue(new C02PacketUseEntity(p_178894_2_, vec3));
539
        return this.currentGameType != WorldSettings.GameType.SPECTATOR && p_178894_2_.interactAt(p_178894_1_, vec3);
540
    }
541
542
    /**
543
     * Handles slot clicks sends a packet to the server.
544
     */
545
    public ItemStack windowClick(int windowId, int slotId, int mouseButtonClicked, int mode, EntityPlayer playerIn)
546
    {
547
        short short1 = playerIn.openContainer.getNextTransactionID(playerIn.inventory);
548
        ItemStack itemstack = playerIn.openContainer.slotClick(slotId, mouseButtonClicked, mode, playerIn);
549
        this.netClientHandler.addToSendQueue(new C0EPacketClickWindow(windowId, slotId, mouseButtonClicked, mode, itemstack, short1));
550
        return itemstack;
551
    }
552
553
    /**
554
     * GuiEnchantment uses this during multiplayer to tell PlayerControllerMP to send a packet indicating the
555
     * enchantment action the player has taken.
556
     */
557
    public void sendEnchantPacket(int p_78756_1_, int p_78756_2_)
558
    {
559
        this.netClientHandler.addToSendQueue(new C11PacketEnchantItem(p_78756_1_, p_78756_2_));
560
    }
561
562
    /**
563
     * Used in PlayerControllerMP to update the server with an ItemStack in a slot.
564
     */
565
    public void sendSlotPacket(ItemStack itemStackIn, int slotId)
566
    {
567
        if (this.currentGameType.isCreative())
568
        {
569
            this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(slotId, itemStackIn));
570
        }
571
    }
572
573
    /**
574
     * Sends a Packet107 to the server to drop the item on the ground
575
     */
576
    public void sendPacketDropItem(ItemStack itemStackIn)
577
    {
578
        if (this.currentGameType.isCreative() && itemStackIn != null)
579
        {
580
            this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(-1, itemStackIn));
581
        }
582
    }
583
584
    public void onStoppedUsingItem(EntityPlayer playerIn)
585
    {
586
        this.syncCurrentPlayItem();
587
        this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
588
        playerIn.stopUsingItem();
589
    }
590
591
    public boolean gameIsSurvivalOrAdventure()
592
    {
593
        return this.currentGameType.isSurvivalOrAdventure();
594
    }
595
596
    /**
597
     * Checks if the player is not creative, used for checking if it should break a block instantly
598
     */
599
    public boolean isNotCreative()
600
    {
601
        return !this.currentGameType.isCreative();
602
    }
603
604
    /**
605
     * returns true if player is in creative mode
606
     */
607
    public boolean isInCreativeMode()
608
    {
609
        return this.currentGameType.isCreative();
610
    }
611
612
    /**
613
     * true for hitting entities far away.
614
     */
615
    public boolean extendedReach()
616
    {
617
        return this.currentGameType.isCreative();
618
    }
619
620
    /**
621
     * Checks if the player is riding a horse, used to chose the GUI to open
622
     */
623
    public boolean isRidingHorse()
624
    {
625
        return this.mc.thePlayer.isRiding() && this.mc.thePlayer.ridingEntity instanceof EntityHorse;
626
    }
627
628
    public boolean isSpectatorMode()
629
    {
630
        return this.currentGameType == WorldSettings.GameType.SPECTATOR;
631
    }
632
633
    public WorldSettings.GameType getCurrentGameType()
634
    {
635
        return this.currentGameType;
636
    }
637
638
    public boolean func_181040_m()
639
    {
640
        return this.isHittingBlock;
641
    }
642
}

What this file does

The patched getBlockReachDistance is the integration point that makes the setting effective. It constructs EventGetBlockReach with the PRE type, dispatches it through SpicyClient.onEvent, and returns event.reach when the field differs from -1, otherwise the vanilla 5.0 creative or 4.5 survival distance. Every call site of getBlockReachDistance, most importantly the EntityRenderer mouse-over ray trace, then sees the module's value, which is how a reach of 6 becomes the attack range without any change to the attack code itself. The file also shows the fork's general event dispatch pattern used by the other combat modules.

anticheat Countering Checks

The anticheat code that detects or counters the techniques this module uses. Full source, with the detection mechanism explained below each box.

anticheat Reach (eye-to-box distance)

Reach.java372 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.fight;
16
17
18
import org.bukkit.GameMode;
19
import org.bukkit.Location;
20
import org.bukkit.entity.EnderDragon;
21
import org.bukkit.entity.Entity;
22
import org.bukkit.entity.Giant;
23
import org.bukkit.entity.LivingEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.util.Vector;
26
27
import fr.neatmonster.nocheatplus.actions.ParameterName;
28
import fr.neatmonster.nocheatplus.checks.Check;
29
import fr.neatmonster.nocheatplus.checks.CheckType;
30
import fr.neatmonster.nocheatplus.checks.ViolationData;
31
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
32
import fr.neatmonster.nocheatplus.checks.moving.location.tracking.LocationTrace.ITraceEntry;
33
import fr.neatmonster.nocheatplus.permissions.Permissions;
34
import fr.neatmonster.nocheatplus.players.IPlayerData;
35
import fr.neatmonster.nocheatplus.utilities.StringUtil;
36
import fr.neatmonster.nocheatplus.utilities.TickTask;
37
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
38
39
/**
40
 * The Reach check will find out if a player interacts with something that's too far away.
41
 */
42
public class Reach extends Check {
43
44
    /** The maximum distance allowed to interact with an entity in creative mode. */
45
    public static final double CREATIVE_DISTANCE = 6D;
46
47
48
    /** Additum for distance, based on entity. */
49
    private static double getDistMod(final Entity damaged) {
50
        // Handle the EnderDragon differently.
51
        if (damaged instanceof EnderDragon)
52
            return 6.5D;
53
        else if (damaged instanceof Giant){
54
            return 1.5D;
55
        }
56
        else return 0;
57
    }
58
59
60
    /**
61
     * Instantiates a new reach check.
62
     */
63
    public Reach() {
64
        super(CheckType.FIGHT_REACH);
65
    }
66
67
68
    /**
69
     * "Classic" check.
70
     * 
71
     * @param player
72
     *            the player
73
     * @param damaged
74
     *            the damaged
75
     * @return true, if successful
76
     */
77
    public boolean check(final Player player, final Location pLoc, 
78
                         final Entity damaged, final boolean damagedIsFake, final Location dRef, 
79
                         final FightData data, final FightConfig cc, final IPlayerData pData) {
80
81
        boolean cancel = false;
82
        // The maximum distance allowed to interact with an entity in survival mode.
83
        final double SURVIVAL_DISTANCE = cc.reachSurvivalDistance; 
84
        // Amount which can be reduced by reach adaption.
85
        final double DYNAMIC_RANGE = cc.reachReduceDistance; 
86
        // Adaption amount for dynamic range.
87
        final double DYNAMIC_STEP = cc.reachReduceStep / SURVIVAL_DISTANCE; 
88
        final double distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : SURVIVAL_DISTANCE + getDistMod(damaged);
89
        final double distanceMin = (distanceLimit - DYNAMIC_RANGE) / distanceLimit;
90
        final double height = damagedIsFake ? (damaged instanceof LivingEntity ? ((LivingEntity) damaged).getEyeHeight() : 1.75) : mcAccess.getHandle().getHeight(damaged);
91
        final double width = damagedIsFake ? 0.6 : mcAccess.getHandle().getWidth(damaged);
92
        double centertoedge = 0.0;
93
        
94
        if (cc.reachPrecision) {
95
            centertoedge = getinset(pLoc, dRef, width / 2, 0.0);
96
        }
97
98
        // Refine y position.
99
        final double pY = pLoc.getY() + player.getEyeHeight();
100
        final double dY = dRef.getY();
101
        if (pY <= dY) {
102
            // Keep the foot level y.
103
        } 
104
        // Highest ref y
105
        else if (pY >= dY + height) {
106
             dRef.setY(dY + height);
107
        }
108
        // Level with damaged.
109
        else dRef.setY(pY);
110
111
        final Vector pRel = dRef.toVector().subtract(pLoc.toVector().setY(pY)); // TODO: Run calculations on numbers only :p.
112
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
113
        // than allowed, the difference will be assigned to "distance".
114
        final double lenpRel = pRel.length() - centertoedge;
115
        double violation = lenpRel - distanceLimit;
116
        final double reachMod = data.reachMod; 
117
118
119
        if (violation > 0) {
120
            if (TickTask.getLag(1000, true) < 1.5f){ // Do not increase the vl in case of server lag (1.5 is a magic value)
121
                data.reachVL += violation;
122
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
123
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
124
                // Execute whatever actions are associated with this check and the violation level and find out if we should
125
                // cancel the event.
126
                cancel = executeActions(vd).willCancel();
127
            }
128
129
            if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), "fight.reach", pData)){
130
                cancel = true;
131
            }
132
133
            if (cancel && cc.reachPenalty > 0){
134
                // Apply an attack penalty time.
135
                data.attackPenalty.applyPenalty(cc.reachPenalty);
136
            }
137
        }
138
        else if (lenpRel - distanceLimit * reachMod > 0){
139
            // Silent cancel.
140
            if (cc.reachPenalty > 0) {
141
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
142
            }
143
            cancel = true;
144
            Improbable.feed(player, (float) (lenpRel - distanceLimit * reachMod) / 4f, System.currentTimeMillis());
145
        }
146
        else data.reachVL *= 0.8D; // Player passed the check, reward them.
147
            
148
149
        if (!cc.reachReduce){
150
            data.reachMod = 1d;
151
        }
152
        else if (lenpRel > distanceLimit - DYNAMIC_RANGE){
153
            data.reachMod = Math.max(distanceMin, data.reachMod - DYNAMIC_STEP);
154
        }
155
        else data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
156
157
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
158
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ " height="+ StringUtil.fdec3.format(height) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(reachMod));
159
        }
160
161
        return cancel;
162
    }
163
164
    /**
165
     * Data context for iterating over ITraceEntry instances.
166
     * @param player
167
     * @param pLoc
168
     * @param damaged
169
     * @param damagedLoc
170
     * @param data
171
     * @param cc
172
     * @return
173
     */
174
    public ReachContext getContext(final Player player, final Location pLoc, 
175
                                   final Entity damaged, final Location damagedLoc, 
176
                                   final FightData data, final FightConfig cc) {
177
178
        final ReachContext context = new ReachContext();
179
        context.distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : cc.reachSurvivalDistance + getDistMod(damaged);
180
        context.distanceMin = (context.distanceLimit - cc.reachReduceDistance) / context.distanceLimit;
181
        //context.eyeHeight = player.getEyeHeight();
182
        context.pY = pLoc.getY() + player.getEyeHeight();
183
        return context;
184
    }
185
186
    /**
187
     * Check if the player fails the reach check, no change of FightData.
188
     * @param player
189
     * @param pLoc
190
     * @param damaged
191
     * @param dRef
192
     * @param context
193
     * @param data
194
     * @param cc
195
     * @return
196
     */
197
    public boolean loopCheck(final Player player, final Location pLoc, final Entity damaged, 
198
                             final ITraceEntry dRef, final ReachContext context, 
199
                             final FightData data, final FightConfig cc) {
200
201
        boolean cancel = false;
202
203
        // Refine y position.
204
        final double dY = dRef.getY();
205
        double y = dRef.getY();
206
207
        if (context.pY <= dY) {
208
            // Keep the foot level y.
209
        }
210
        else if (context.pY >= dY + dRef.getBoxMarginVertical()) {
211
            y = dY + dRef.getBoxMarginVertical(); // Highest ref y.
212
        }
213
        else {
214
            y = context.pY; // Level with damaged.
215
        }
216
217
        double centertoedge = 0.0;
218
        if (cc.reachPrecision) centertoedge = getinset(pLoc, new Location(null, dRef.getX(), dRef.getY(), dRef.getZ()), dRef.getBoxMarginHorizontal(), y - context.pY);
219
        
220
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
221
        // than allowed, the difference will be assigned to "distance".
222
        // TODO: Run check on squared distances (quite easy to change to stored boundary-sq values).
223
        final double lenpRel = TrigUtil.distance(dRef.getX(), y, dRef.getZ(), pLoc.getX(), context.pY, pLoc.getZ()) - centertoedge;
224
        double violation = lenpRel - context.distanceLimit;
225
226
        if (violation > 0 || lenpRel - context.distanceLimit * data.reachMod > 0){
227
            // TODO: The silent cancel parts should be sen as "no violation" ?
228
            // Set minimum violation in context
229
            context.minViolation = Math.min(context.minViolation, lenpRel);
230
            cancel = true;
231
        }
232
        context.minResult = Math.min(context.minResult, lenpRel);
233
234
        return cancel;
235
236
    }
237
238
    /**
239
     * Apply changes to FightData according to check results (context), trigger violations.
240
     * @param player
241
     * @param pLoc
242
     * @param damaged
243
     * @param context
244
     * @param forceViolation
245
     * @param data
246
     * @param cc
247
     * @return
248
     */
249
    public boolean loopFinish(final Player player, final Location pLoc, final Entity damaged, 
250
                              final ReachContext context, final ITraceEntry traceEntry, final boolean forceViolation, 
251
                              final FightData data, final FightConfig cc, final IPlayerData pData) {
252
253
        final double lenpRel = forceViolation && context.minViolation != Double.MAX_VALUE ? context.minViolation : context.minResult;
254
255
        if (lenpRel == Double.MAX_VALUE) {
256
            return false;
257
        }
258
259
        double violation = lenpRel - context.distanceLimit;
260
        boolean cancel = false;
261
262
        if (violation > 0) {    
263
            if (TickTask.getLag(1000, true) < 1.5f){
264
                data.reachVL += violation;
265
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
266
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
267
                // Execute whatever actions are associated with this check and the violation level and find out if we should
268
                // cancel the event.
269
                cancel = executeActions(vd).willCancel();
270
            }
271
            
272
            //if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), 
273
            //        "fight.reach", pData)){
274
            //    cancel = true;
275
            //}
276
            // TODO: New improbable weight calculations so that weight is not inverse to config weight
277
            if (cc.reachImprobableWeight > 0.0f) {
278
                if (!cc.reachImprobableFeedOnly && Improbable.check(player, (float) violation / cc.reachImprobableWeight, System.currentTimeMillis(), "fight.reach", pData)) {
279
                    cancel = true;
280
                }
281
            }
282
283
            if (cancel && cc.reachPenalty > 0){
284
                // Apply an attack penalty time.
285
                data.attackPenalty.applyPenalty(cc.reachPenalty);
286
            }
287
        }
288
        else if (lenpRel - context.distanceLimit * data.reachMod > 0){
289
            // Silent cancel.
290
            if (cc.reachPenalty > 0) {
291
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
292
            }
293
294
            cancel = true;
295
296
            if (cc.reachImprobableWeight > 0.0f) {
297
                Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / cc.reachImprobableWeight, System.currentTimeMillis());
298
            }
299
            // Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / 4f, System.currentTimeMillis());
300
        }
301
        else {
302
            // Player passed the check, reward them.
303
            data.reachVL *= 0.8D;
304
305
        }
306
307
        // Adaption amount for dynamic range.
308
        final double DYNAMIC_STEP = cc.reachReduceStep / cc.reachSurvivalDistance;
309
310
        if (!cc.reachReduce){
311
            data.reachMod = 1d;
312
        }
313
        else if (lenpRel > context.distanceLimit - cc.reachReduceDistance){
314
            data.reachMod = Math.max(context.distanceMin, data.reachMod - DYNAMIC_STEP);
315
        }
316
        else {
317
            data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
318
        }
319
320
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
321
            // TODO: Height: remember successful ITraceEntry
322
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ (traceEntry == null ? "" : (" height=" + traceEntry.getBoxMarginVertical())) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(data.reachMod));
323
        }
324
325
        return cancel;
326
    }
327
328
329
    private boolean isSameXZ(final Location loc1, final Location loc2) {
330
        return loc1.getX() == loc2.getX() && loc1.getZ() == loc2.getZ();
331
    }
332
333
334
    /**
335
     *
336
     * @param pLoc
337
     *            the player location
338
     * @param dRef
339
     *            the target location
340
     * @param damagedBoxMarginHorizontal
341
     *            the target Width / 2
342
     * @param diffY the Y different
343
     * @return the double represent for the distance from target location to the edge of target hitbox
344
     */
345
    private double getinset(final Location pLoc, final Location dRef, final double damagedBoxMarginHorizontal, final double diffY) {
346
347
        if (!isSameXZ(pLoc, dRef)) {
348
            final Location dRefc = dRef.clone();
349
            final Vector vec1 = new Vector(pLoc.getX() - dRef.getX(), diffY , pLoc.getZ() - dRef.getZ());
350
            if (vec1.length() < damagedBoxMarginHorizontal * Math.sqrt(2)) return 0.0;
351
            if (vec1.getZ() > 0.0) {
352
                dRefc.setZ(dRefc.getZ() + damagedBoxMarginHorizontal);
353
            } 
354
            else if (vec1.getZ() < 0.0) {
355
                dRefc.setZ(dRefc.getZ() - damagedBoxMarginHorizontal);
356
            } 
357
            else if (vec1.getX() > 0.0) {
358
                dRefc.setX(dRefc.getX() + damagedBoxMarginHorizontal);
359
            } 
360
            else dRefc.setX(dRefc.getX() - damagedBoxMarginHorizontal);
361
362
            final Vector vec2 = new Vector(dRefc.getX() - dRef.getX(), 0.0 , dRefc.getZ() - dRef.getZ());
363
            double angle = TrigUtil.angle(vec1, vec2);
364
            // Require < 45deg, if not 90deg-angel
365
            if (angle > Math.PI / 4) angle = Math.PI / 2 - angle;
366
            if (angle >= 0.0 && angle <= Math.PI / 4) { // TODO: Dose this one necessary?
367
                return damagedBoxMarginHorizontal / Math.cos(angle);
368
            }
369
        }
370
        return 0.0;
371
    }
372
}

How it counteracts this module

NoCheatPlus measures the eye-to-target distance for every attack against the survival distance limit, default 4.02, subtracting a getinset half-width when reachPrecision is on. A Spicy reach of 4.5 to 6 presents a measured distance well past the limit on every hit, so the violation fires on the first attack and the reachMod mechanism compounds it: repeated hits near the band step the modifier down and silently cancel borderline attacks even below the nominal ceiling. The check also feeds Improbable with the excess distance, so sustained extended reach accumulates on a second layer. Because the module applies the range constantly with no oscillation, there is no window of compliant attacks to reset the decay.

anticheat FightHitbox (lag-compensated ray trace)

FightHitbox.java232 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk.check.combat;
20
21
import me.islandscout.hawk.HawkPlayer;
22
import me.islandscout.hawk.check.Cancelless;
23
import me.islandscout.hawk.check.CustomCheck;
24
import me.islandscout.hawk.event.Event;
25
import me.islandscout.hawk.event.InteractEntityEvent;
26
import me.islandscout.hawk.event.MoveEvent;
27
import me.islandscout.hawk.util.*;
28
import me.islandscout.hawk.wrap.block.WrappedBlock;
29
import me.islandscout.hawk.wrap.entity.WrappedEntity;
30
import org.bukkit.GameMode;
31
import org.bukkit.Location;
32
import org.bukkit.Material;
33
import org.bukkit.block.Block;
34
import org.bukkit.entity.Entity;
35
import org.bukkit.entity.Player;
36
import org.bukkit.util.BlockIterator;
37
import org.bukkit.util.Vector;
38
39
import java.util.HashMap;
40
import java.util.Map;
41
import java.util.UUID;
42
43
/**
44
 * The hit detection in Minecraft is mostly determined by the client,
45
 * thus servers are left to trust the client. (There are a few exceptions
46
 * for the unmodified Notchian server such as preventing hits exceeding 6
47
 * blocks from the target entity). This poses a problem for players and
48
 * server owners since players can modify the client to manipulate hit
49
 * detection and allow for cheating when in combat with other players.
50
 *
51
 * Hawk’s hitbox checking aims to detect cheating during player vs.
52
 * player combat by validating hits on the server. When the server
53
 * receives an interaction packet from the client, Hawk gets the client’s
54
 * last known position and next direction, and uses it to perform a ray
55
 * trace test on the victim’s hitbox. Before the ray-trace test begins,
56
 * though, Hawk must factor in latency by rewinding the victim’s hitbox
57
 * to an appropriate time based on the client’s ping latency. To
58
 * accomplish this, Hawk keeps a history of players’ positions and
59
 * timestamps in a table and it retrieves a position that best
60
 * approximates where it appeared to the client when the client attacked
61
 * it. Hawk then performs the ray-trace test to determine whether the
62
 * client landed the hit or not. Although the system may produce false
63
 * positives with clients on unstable connections, it is a fair tradeoff
64
 * between user experience and cheat prevention.
65
 *
66
 * There are other sources of error which will probably not be accounted
67
 * for in Hawk anytime soon. Other sources of error include:
68
 *   - The client receives entity relative moves in 1/32 block precision.
69
 *   - The client holds off one tick to smoothly animate other players
70
 *     on the screen in the case of slight network jitter. It will
71
 *     linearly interpolate from the last position to the latest
72
 *     position up to 3 ticks if it doesn't receive a relative move
73
 *     packet to update the player's position.
74
 *   - The client will predict the motion of some entities, such as
75
 *     arrows. If there is latency and something unexpected happens
76
 *     to the entity, the client may desynchronize from the server.
77
 *
78
 * In most cases, the client uses the current frame's yaw and pitch to
79
 * compute the direction vector for the attack hit-scan. Fortunately,
80
 * ticking and rendering is done in the same thread. Unfortunately, in
81
 * the tick stack, attacking is done before sending yaw/pitch updates
82
 * to the server, which means that we must wait until the next flying
83
 * packet to get the direction of the hit-scan.
84
 *
85
 * For realtime protection, it's best to use the EntityInteractDirection
86
 * check. It actively enforces directions, but it extrapolates the
87
 * yaw/pitch because of how the client hit-scanning works.
88
 */
89
public class FightHitbox extends CustomCheck implements Cancelless {
90
91
    private final double MAX_REACH;
92
    private final int PING_LIMIT;
93
    private final boolean CHECK_OTHER_ENTITIES;
94
    private final boolean LAG_COMPENSATION;
95
    private final boolean DEBUG_HITBOX;
96
    private final boolean DEBUG_RAY;
97
    private final boolean CHECK_OCCLUSION;
98
    private final boolean CHECK_BOX_INTERSECTION;
99
    private final double BOX_EPSILON = 0.005;
100
101
    private Map<UUID, InteractEntityEvent> lastInteractionMap;
102
103
    public FightHitbox() {
104
        super("fighthitbox", false, 5, 10000, 0.95, 5000, "%player% failed combat hitbox. %type% VL: %vl%", null);
105
        CHECK_BOX_INTERSECTION = (boolean) customSetting("checkBoxIntersection", "", true);
106
        CHECK_OCCLUSION = (boolean) customSetting("checkOccluding", "", false);
107
        MAX_REACH = (double) customSetting("maxReach", "", 3.1);
108
        CHECK_OTHER_ENTITIES = (boolean) customSetting("checkOtherEntities", "", false);
109
        LAG_COMPENSATION = (boolean) customSetting("lagCompensation", "", true);
110
        PING_LIMIT = (int) customSetting("pingLimit", "", -1);
111
        DEBUG_HITBOX = (boolean) customSetting("hitbox", "debug", false);
112
        DEBUG_RAY = (boolean) customSetting("ray", "debug", false);
113
        lastInteractionMap = new HashMap<>();
114
    }
115
116
    @Override
117
    protected void check(Event event) {
118
        if(event instanceof InteractEntityEvent)
119
            processHit((InteractEntityEvent)event);
120
        else if(event instanceof MoveEvent) {
121
            InteractEntityEvent interactEntityEvent = lastInteractionMap.get(event.getHawkPlayer().getUuid());
122
            if(interactEntityEvent != null) {
123
                MoveEvent move = (MoveEvent) event;
124
125
                float yaw;
126
                float pitch;
127
                //In 1.8, the yaw of the cursor is behind by one tick.
128
                if(event.getHawkPlayer().getClientVersion() == 8) {
129
                    yaw = event.getHawkPlayer().getYaw();
130
                } else {
131
                    yaw = move.getTo().getYaw();
132
                }
133
                pitch = move.getTo().getPitch();
134
135
                processDirection(interactEntityEvent, yaw, pitch);
136
            }
137
            lastInteractionMap.put(event.getHawkPlayer().getUuid(), null);
138
        }
139
    }
140
141
    private void processHit(InteractEntityEvent e) {
142
        lastInteractionMap.put(e.getHawkPlayer().getUuid(), e);
143
    }
144
145
    private void processDirection(InteractEntityEvent e, float yaw, float pitch) {
146
        Entity entity = e.getEntity();
147
        if (!(entity instanceof Player) && !CHECK_OTHER_ENTITIES)
148
            return;
149
        Player attacker = e.getPlayer();
150
        int ping = ServerUtils.getPing(attacker);
151
        if (ping > PING_LIMIT && PING_LIMIT != -1)
152
            return;
153
154
        HawkPlayer att = e.getHawkPlayer();
155
        Location attackerEyeLocation = att.getPosition().clone().add(new Vector(0, 1.62, 0)).toLocation(att.getWorld());
156
        Vector attackerDirection = MathPlus.getDirection(yaw, pitch);
157
158
        double maxReach = MAX_REACH;
159
        if (attacker.getGameMode() == GameMode.CREATIVE)
160
            maxReach += 1.9;
161
162
        Vector victimLocation;
163
        if (LAG_COMPENSATION)
164
            //No need to add 50ms; the move and attack are already chronologically so close together
165
            victimLocation = hawk.getLagCompensator().getHistoryLocation(ping, e.getEntity()).toVector();
166
        else
167
            victimLocation = e.getEntity().getLocation().toVector();
168
169
        Vector eyePos;
170
        if(e.getHawkPlayer().isInVehicle()) {
171
            eyePos = hawk.getLagCompensator().getHistoryLocation(ping, e.getPlayer()).toVector();
172
            eyePos.setY(eyePos.getY() + e.getPlayer().getEyeHeight());
173
        }
174
        else {
175
            eyePos = new Vector(attackerEyeLocation.getX(), attacker.isSneaking() ? attackerEyeLocation.getY() - 0.08 : attackerEyeLocation.getY(), attackerEyeLocation.getZ());
176
        }
177
        Vector direction = new Vector(attackerDirection.getX(), attackerDirection.getY(), attackerDirection.getZ());
178
        Ray attackerRay = new Ray(eyePos, direction);
179
180
        AABB victimAABB;
181
        victimAABB = WrappedEntity.getWrappedEntity(entity).getHitbox(victimLocation);
182
        victimAABB.expand(BOX_EPSILON, BOX_EPSILON, BOX_EPSILON);
183
184
        Vector intersectVec3d = victimAABB.intersectsRay(attackerRay, 0, Float.MAX_VALUE);
185
186
        if (DEBUG_HITBOX) {
187
            victimAABB.highlight(hawk, attacker.getWorld(), 0.29);
188
        }
189
190
        if (DEBUG_RAY) {
191
            attackerRay.highlight(hawk, attacker.getWorld(), maxReach, 0.1);
192
        }
193
194
        if (intersectVec3d != null) {
195
            Location intersect = new Location(attacker.getWorld(), intersectVec3d.getX(), intersectVec3d.getY(), intersectVec3d.getZ());
196
            double interDistance = intersect.distance(attackerEyeLocation);
197
            if (interDistance > maxReach) {
198
                punish(att, 1, true, e, new Placeholder("type", "Reach: " + MathPlus.round(interDistance, 2) + "m"));
199
                return;
200
            }
201
            if (CHECK_OCCLUSION && interDistance > 1D) {
202
                BlockIterator iter = new BlockIterator(attacker.getWorld(), eyePos, attackerDirection, 0, (int) interDistance + 1);
203
                while (iter.hasNext()) {
204
                    Block bukkitBlock = iter.next();
205
206
                    if (bukkitBlock.getType() == Material.AIR || bukkitBlock.isLiquid())
207
                        continue;
208
209
                    WrappedBlock b = WrappedBlock.getWrappedBlock(bukkitBlock, att.getClientVersion());
210
                    Vector intersection = b.getHitBox().intersectsRay(new Ray(attackerEyeLocation.toVector(), attackerDirection), 0, Float.MAX_VALUE);
211
                    if (intersection != null) {
212
                        if (intersection.distance(eyePos) < interDistance) {
213
                            punish(att, 1, true, e, new Placeholder("type", "Interacted through " + b.getBukkitBlock().getType()));
214
                            return;
215
                        }
216
                    }
217
                }
218
219
            }
220
        } else if (CHECK_BOX_INTERSECTION) {
221
            punish(att, 1, true, e, new Placeholder("type", "Did not hit hitbox."));
222
            return;
223
        }
224
225
        reward(att); //reward player
226
    }
227
228
    @Override
229
    public void removeData(Player p) {
230
        lastInteractionMap.remove(p.getUniqueId());
231
    }
232
}

How it counteracts this module

Hawk re-runs the hit on the server against the victim's real hitbox. It stores the InteractEntityEvent, waits for the next MoveEvent because 1.8 sends the attack before the yaw update, builds the ray from the eye position and the move's yaw and pitch, rewinds the victim to the lag-compensated position, and intersects against the standard 0.6-wide box expanded by only 0.005. The intersect distance is compared with maxReach 3.1, plus 1.9 in creative. A 4.5 to 6 block attack either misses the box entirely, earning the Did not hit hitbox. punishment, or intersects at a distance well past 3.1, earning a reach punish. The module's constant extended range means every sampled attack fails one of the two branches.

anticheat Reach (packet-entity ray trace)

Reach.java404 lines · Java
1
// This file was designed and is an original check for GrimAC
2
// Copyright (C) 2021 DefineOutside
3
//
4
// This program is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// This program is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
package ac.grim.grimac.checks.impl.combat;
17
18
import ac.grim.grimac.api.config.ConfigManager;
19
import ac.grim.grimac.api.storage.verbose.Verbose;
20
import ac.grim.grimac.checks.Check;
21
import ac.grim.grimac.checks.CheckData;
22
import ac.grim.grimac.checks.type.PacketReceiveListener;
23
import ac.grim.grimac.player.GrimPlayer;
24
import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox;
25
import ac.grim.grimac.utils.data.packetentity.PacketEntity;
26
import ac.grim.grimac.utils.data.packetentity.PacketEntitySizeable;
27
import ac.grim.grimac.utils.data.packetentity.dragon.PacketEntityEnderDragonPart;
28
import ac.grim.grimac.utils.math.Vector3dm;
29
import ac.grim.grimac.utils.nmsutil.ReachUtils;
30
import ac.grim.grimac.utils.viaversion.ViaVersionUtil;
31
import com.github.retrooper.packetevents.PacketEvents;
32
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
33
import com.github.retrooper.packetevents.manager.server.ServerVersion;
34
import com.github.retrooper.packetevents.protocol.attribute.Attributes;
35
import com.github.retrooper.packetevents.protocol.component.ComponentTypes;
36
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemAttackRange;
37
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
38
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
39
import com.github.retrooper.packetevents.protocol.item.ItemStack;
40
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
41
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
42
import com.github.retrooper.packetevents.protocol.player.GameMode;
43
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
44
import com.github.retrooper.packetevents.util.Vector3d;
45
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientAttack;
46
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientInteractEntity;
47
import com.viaversion.viaversion.api.Via;
48
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
49
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
50
import org.jetbrains.annotations.NotNull;
51
52
import java.util.ArrayList;
53
import java.util.Arrays;
54
import java.util.Collections;
55
import java.util.List;
56
57
// You may not copy the check unless you are licensed under GPL
58
@CheckData(name = "Reach", stableKey = "grim.combat.reach", description = "Attacked an entity from too far away")
59
public class Reach extends Check implements PacketReceiveListener {
60
    private static final Verbose V = Verbose.of("{f64:%.5f} blocks, type={entity}");
61
62
    private static final List<EntityType> blacklisted = Arrays.asList(
63
            EntityTypes.BOAT,
64
            EntityTypes.CHEST_BOAT,
65
            EntityTypes.SHULKER);
66
    private static final CheckResult NONE = new CheckResult(ResultType.NONE, 0, 0, false);
67
    // Only one flag per reach attack, per entity, per tick.
68
    // We store position because lastX isn't reliable on teleports.
69
    private final Int2ObjectMap<InteractionData> playerAttackQueue = new Int2ObjectOpenHashMap<>();
70
    private boolean cancelImpossibleHits;
71
    private double threshold;
72
    private double cancelBuffer; // For the next 4 hits after using reach, we aggressively cancel reach
73
74
    public Reach(GrimPlayer player) {
75
        super(player);
76
    }
77
78
    @Override
79
    public void onPacketReceive(final PacketReceiveEvent event) {
80
        if (!player.disableGrim && event.getPacketType() == PacketType.Play.Client.ATTACK) {
81
            WrapperPlayClientAttack packet = new WrapperPlayClientAttack(event);
82
            onInteract(event, packet.getEntityId(), InteractionHand.MAIN_HAND);
83
        }
84
85
        if (!player.disableGrim && event.getPacketType() == PacketType.Play.Client.INTERACT_ENTITY) {
86
            WrapperPlayClientInteractEntity packet = new WrapperPlayClientInteractEntity(event);
87
            onInteract(event, packet.getEntityId(), packet.getAction() == WrapperPlayClientInteractEntity.InteractAction.ATTACK ? InteractionHand.MAIN_HAND : packet.getHand());
88
        }
89
90
        // If the player set their look, or we know they have a new tick
91
        if (isUpdate(event.getPacketType())) {
92
            tickBetterReachCheckWithAngle();
93
        }
94
    }
95
96
    private void onInteract(PacketReceiveEvent event, int entityId, InteractionHand hand) {
97
        // Don't let the player teleport to bypass reach
98
        if (player.getSetbackTeleportUtil().shouldBlockMovement()) {
99
            event.setCancelled(true);
100
            player.onPacketCancel();
101
            return;
102
        }
103
104
        PacketEntity entity = player.compensatedEntities.entityMap.get(entityId);
105
        // Stop people from freezing transactions before an entity spawns to bypass reach
106
        // TODO: implement dragon parts?
107
        if (entity == null || entity instanceof PacketEntityEnderDragonPart) {
108
            // Only cancel if and only if we are tracking this entity
109
            // This is because we don't track paintings.
110
            if (shouldModifyPackets() && player.compensatedEntities.serverPositionsMap.containsKey(entityId)) {
111
                event.setCancelled(true);
112
                player.onPacketCancel();
113
            }
114
            return;
115
        }
116
117
        // Dead entities cause false flags (https://github.com/GrimAnticheat/Grim/issues/546)
118
        if (entity.isDead) return;
119
120
        // TODO: Remove when in front of via
121
        if (entity.getType() == EntityTypes.ARMOR_STAND && player.getClientVersion().isOlderThan(ClientVersion.V_1_8))
122
            return;
123
        // Prevents Happy Ghast Reach false on 1.21.6+ servers with ViaBackwards set up
124
        if (entity.getType() == EntityTypes.HAPPY_GHAST && player.getClientVersion().isOlderThan(ClientVersion.V_1_21_6))
125
            return;
126
        if (player.gamemode == GameMode.CREATIVE || player.gamemode == GameMode.SPECTATOR)
127
            return;
128
        if (player.inVehicle()) return;
129
        if (entity.riding != null) return;
130
131
        ItemStack currentStack = player.inventory.getItemInHand(hand);
132
        ItemStack startStack = player.inventory.getStartOfTickStack();
133
134
        boolean hasRange = false;
135
        float maxReach = 0f;
136
        float hitboxMargin = 0f;
137
        Vector3dm attackRangeMovement = null;
138
139
        boolean clientAttackRangeExists = player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_21_11);
140
        boolean clientAndServerAgrees = clientAttackRangeExists && ATTACK_RANGE_COMPONENT_EXISTS;
141
142
        boolean viaVersionAvailable = false;
143
        if (USE_1_8_HITBOX_MARGIN && ViaVersionUtil.isAvailable) {
144
            viaVersionAvailable = Via.getConfig().getValues().containsKey("use-1_8-hitbox-margin") && Via.getConfig().use1_8HitboxMargin();
145
        }
146
147
        boolean clientAndViaVersion = clientAttackRangeExists && viaVersionAvailable;
148
        if (clientAndServerAgrees || clientAndViaVersion) {
149
            ItemAttackRange startRange = startStack.getComponentOr(ComponentTypes.ATTACK_RANGE, null);
150
            ItemAttackRange currentRange = currentStack.getComponentOr(ComponentTypes.ATTACK_RANGE, null);
151
152
            if (clientAndViaVersion) {
153
                if (startStack != ItemStack.EMPTY) {
154
                    startRange = new ItemAttackRange(0F, 3F, 0F, 4F, 0.1F, 1F);
155
                }
156
157
                if (currentStack != ItemStack.EMPTY) {
158
                    currentRange = new ItemAttackRange(0F, 3F, 0F, 4F, 0.1F, 1F);
159
                }
160
            }
161
162
            // If the start stack has no range component, the client defaults to vanilla reach behavior,
163
            // regardless of what the current stack is (No Range -> X = No Range used).
164
            if (startRange != null) {
165
                hasRange = true;
166
                if (currentRange == null) {
167
                    // Range (Start) -> No Range (Current)
168
                    // Client logic uses Start Range, including the attack_range movement projection.
169
                    if (!clientAndViaVersion) {
170
                        attackRangeMovement = player.clientVelocity.clone();
171
                    }
172
                    maxReach = startRange.getMaxRange();
173
                    hitboxMargin = startRange.getHitboxMargin();
174
                } else {
175
                    // Range (Start) -> Range (Current)
176
                    // Client logic requires satisfying BOTH constraints
177
                    maxReach = Math.min(startRange.getMaxRange(), currentRange.getMaxRange());
178
                    hitboxMargin = Math.min(startRange.getHitboxMargin(), currentRange.getHitboxMargin());
179
                }
180
            }
181
        }
182
183
        boolean tooManyAttacks = playerAttackQueue.size() > 10;
184
        if (!tooManyAttacks) {
185
            playerAttackQueue.put(entityId, new InteractionData(
186
                    player.x, player.y, player.z,
187
                    hasRange, maxReach, hitboxMargin, attackRangeMovement
188
            )); // Queue for next tick for very precise check
189
        }
190
191
        boolean knownInvalid = attackRangeMovement == null && isKnownInvalid(entity, hasRange, maxReach, hitboxMargin);
192
193
        if ((shouldModifyPackets() && cancelImpossibleHits && knownInvalid) || tooManyAttacks) {
194
            event.setCancelled(true);
195
            player.onPacketCancel();
196
        }
197
    }
198
199
    // This method finds the most optimal point at which the user should be aiming at
200
    // and then measures the distance between the player's eyes and this target point
201
    //
202
    // It will not cancel every invalid attack but should cancel 3.05+ or so in real-time
203
    // Let the post look check measure the distance, as it will always return equal or higher
204
    // than this method.  If this method flags, the other method WILL flag.
205
    //
206
    // Meaning that the other check should be the only one that flags.
207
    private boolean isKnownInvalid(PacketEntity reachEntity, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin) {
208
        // If the entity doesn't exist, or if it is exempt, or if it is dead
209
        if ((blacklisted.contains(reachEntity.getType()) || !reachEntity.isLivingEntity) && reachEntity.getType() != EntityTypes.END_CRYSTAL)
210
            return false; // exempt
211
212
        if (player.gamemode == GameMode.CREATIVE || player.gamemode == GameMode.SPECTATOR)
213
            return false;
214
        if (player.inVehicle()) return false;
215
216
        // Filter out what we assume to be cheats
217
        if (cancelBuffer != 0) {
218
            CheckResult result = checkReach(reachEntity, player.x, player.y, player.z, hasAttackRange, itemMaxReach, itemHitboxMargin, null, true);
219
            return result.isFlag();
220
        } else {
221
            SimpleCollisionBox targetBox = getTargetBox(reachEntity);
222
223
            double maxReach = applyReachModifiers(targetBox, hasAttackRange, itemMaxReach, itemHitboxMargin, !player.packetStateData.didLastMovementIncludePosition);
224
            return ReachUtils.getMinReachToBox(player, targetBox) > maxReach;
225
        }
226
    }
227
228
    private void tickBetterReachCheckWithAngle() {
229
        for (Int2ObjectMap.Entry<InteractionData> attack : playerAttackQueue.int2ObjectEntrySet()) {
230
            PacketEntity reachEntity = player.compensatedEntities.entityMap.get(attack.getIntKey());
231
            if (reachEntity == null) continue;
232
233
            InteractionData interactionData = attack.getValue();
234
            CheckResult result = checkReach(reachEntity, interactionData.x, interactionData.y, interactionData.z, interactionData.hasAttackRange, interactionData.maxReach, interactionData.hitboxMargin, interactionData.attackRangeMovement, false);
235
            switch (result.type()) {
236
                case REACH -> flag(
237
                        V.write(verbose()).f64(result.minDistance()).uint(reachEntity.getType().getId(player.getClientVersion())),
238
                        () -> {
239
                            String added = ", type=" + reachEntity.getType().getName().getKey();
240
                            if (reachEntity instanceof PacketEntitySizeable sizeable) {
241
                                added += ", size=" + sizeable.size;
242
                            }
243
                            return result.verbose() + added;
244
                        });
245
                case HITBOX -> {
246
                    String added = "type=" + reachEntity.getType().getName().getKey();
247
                    if (reachEntity instanceof PacketEntitySizeable sizeable) {
248
                        added += ", size=" + sizeable.size;
249
                    }
250
                    player.checkManager.getCheck(Hitboxes.class).flag(result.verbose() + added);
251
                }
252
            }
253
        }
254
255
        playerAttackQueue.clear();
256
    }
257
258
    @NotNull
259
    private CheckResult checkReach(PacketEntity reachEntity, double x, double y, double z, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin, Vector3dm attackRangeMovement, boolean isPrediction) {
260
        SimpleCollisionBox targetBox = getTargetBox(reachEntity);
261
262
        double movementAllowance = attackRangeMovement == null ? 0 : getAttackRangeMovementAllowance(attackRangeMovement);
263
        double maxReach = applyReachModifiers(targetBox, hasAttackRange, itemMaxReach, itemHitboxMargin, !player.packetStateData.didLastLastMovementIncludePosition) + movementAllowance;
264
        double minDistance = Double.MAX_VALUE;
265
266
        // https://bugs.mojang.com/browse/MC-67665
267
        List<Vector3dm> possibleLookDirs = new ArrayList<>(Collections.singletonList(ReachUtils.getLook(player, player.yaw, player.pitch)));
268
269
        // If we are a tick behind, we don't know their next look so don't bother doing this
270
        if (!isPrediction) {
271
            // 1.7 players do not have any of these issues! They are always on the latest look vector
272
            if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_8)) {
273
                possibleLookDirs.add(ReachUtils.getLook(player, player.lastYaw, player.pitch));
274
275
                // 1.9+ players could be a tick behind because we don't get skipped ticks
276
                if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_9)) {
277
                    possibleLookDirs.add(ReachUtils.getLook(player, player.lastYaw, player.lastPitch));
278
                }
279
            }
280
        }
281
282
        // +3 would be 3 + 3 = 6, which is the pre-1.20.5 behaviour, preventing "Missed Hitbox"
283
        final double distance = maxReach + 3;
284
285
        final double[] possibleEyeHeights = player.getPossibleEyeHeights();
286
        for (Vector3dm lookVec : possibleLookDirs) {
287
            lookVec.multiply(distance);
288
289
            for (double eye : possibleEyeHeights) {
290
                final Vector3d eyePos = new Vector3d(x, y + eye, z);
291
                Vector3d endReachPos = eyePos.add(lookVec.getX(), lookVec.getY(), lookVec.getZ());
292
293
                Vector3d intercept = ReachUtils.calculateIntercept(targetBox, eyePos, endReachPos).first();
294
295
                if (ReachUtils.isVecInside(targetBox, eyePos)) {
296
                    minDistance = 0;
297
                    break;
298
                }
299
300
                if (intercept != null) {
301
                    minDistance = Math.min(eyePos.distance(intercept), minDistance);
302
                }
303
            }
304
        }
305
306
        // if the entity is not exempt and the entity is alive
307
        if ((!blacklisted.contains(reachEntity.getType()) && reachEntity.isLivingEntity) || reachEntity.getType() == EntityTypes.END_CRYSTAL) {
308
            if (minDistance == Double.MAX_VALUE) {
309
                cancelBuffer = 1;
310
                return new CheckResult(ResultType.HITBOX, 0, 0, false);
311
            } else if (minDistance > maxReach) {
312
                cancelBuffer = 1;
313
                return new CheckResult(ResultType.REACH, minDistance, movementAllowance, attackRangeMovement != null);
314
            } else {
315
                cancelBuffer = Math.max(0, cancelBuffer - 0.25);
316
            }
317
        }
318
319
        return NONE;
320
    }
321
322
    private SimpleCollisionBox getTargetBox(PacketEntity reachEntity) {
323
        if (reachEntity.getType() == EntityTypes.END_CRYSTAL) { // Hardcode end crystal box
324
            return new SimpleCollisionBox(reachEntity.trackedServerPosition.getPos().subtract(1, 0, 1), reachEntity.trackedServerPosition.getPos().add(1, 2, 1));
325
        }
326
        return reachEntity.getPossibleCollisionBoxes();
327
    }
328
329
    private double getAttackRangeMovementAllowance(Vector3dm attackRangeMovement) {
330
        if (attackRangeMovement.lengthSquared() == 0) {
331
            return 0;
332
        }
333
334
        return getForwardMovement(attackRangeMovement, player.yaw, player.pitch);
335
    }
336
337
    private double getForwardMovement(Vector3dm movement, float yaw, float pitch) {
338
        return Math.max(0, movement.dot(ReachUtils.getLook(player, yaw, pitch)));
339
    }
340
341
    private static final boolean ATTACK_RANGE_COMPONENT_EXISTS = PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_21_11);
342
    private static final boolean USE_1_8_HITBOX_MARGIN = PacketEvents.getAPI().getServerManager().getVersion().isOlderThanOrEquals(ServerVersion.V_1_8_8);
343
344
    private double applyReachModifiers(SimpleCollisionBox targetBox, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin, boolean giveMovementThreshold) {
345
        double maxReach;
346
        double hitboxMargin = threshold;
347
348
        if (hasAttackRange) {
349
            maxReach = itemMaxReach;
350
            hitboxMargin += itemHitboxMargin;
351
        } else {
352
            maxReach = player.compensatedEntities.self.getAttributeValue(Attributes.ENTITY_INTERACTION_RANGE);
353
            // 1.7 and 1.8 players get a bit of extra hitbox (this is why you should use 1.8 on cross version servers)
354
            // Yes, this is vanilla and not uncertainty.  All reach checks have this or they are wrong.
355
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9)) {
356
                hitboxMargin += 0.1f;
357
            }
358
        }
359
360
        // This is better than adding to the reach, as 0.03 can cause a player to miss their target
361
        // Adds some more than 0.03 uncertainty in some cases, but a good trade off for simplicity
362
        //
363
        // Just give the uncertainty on 1.9+ clients as we have no way of knowing whether they had 0.03 movement
364
        // However, on 1.21.2+ we do know if they had 0.03 movement
365
        if (giveMovementThreshold || player.canSkipTicks()) {
366
            hitboxMargin += player.getMovementThreshold();
367
        }
368
369
        targetBox.expand(hitboxMargin);
370
371
        return maxReach;
372
    }
373
374
    @Override
375
    public void onReload(@NotNull ConfigManager config) {
376
        this.cancelImpossibleHits = config.getBooleanElse("Reach.block-impossible-hits", true);
377
        this.threshold = config.getDoubleElse("Reach.threshold", 0.0005);
378
    }
379
380
    private enum ResultType {
381
        REACH, HITBOX, NONE
382
    }
383
384
    private record CheckResult(ResultType type, double minDistance, double extraMovement, boolean hasExtraMovement) {
385
        public boolean isFlag() {
386
            return type != ResultType.NONE;
387
        }
388
389
        public String verbose() {
390
            if (type != ResultType.REACH) {
391
                return "";
392
            }
393
394
            String verbose = String.format("%.5f", minDistance) + " blocks";
395
            if (hasExtraMovement) {
396
                verbose += String.format(", extraMovement=%.5f", extraMovement);
397
            }
398
            return verbose;
399
        }
400
    }
401
402
    private record InteractionData(double x, double y, double z, boolean hasAttackRange,
403
                                   float maxReach, float hitboxMargin, Vector3dm attackRangeMovement) {}
404
}

How it counteracts this module

Grim queues each attack position and performs the precise ray trace on the next look update against the packet-entity box rebuilt from server teleport and rel-move data, checking all possible look directions and eye heights to cover the one-tick look lag, with a 0.1 hitbox margin for pre-1.9 clients. The trace is bounded by the server-side reach, so a 6-block Spicy attack is rejected with the intersection failing beyond the box or the distance exceeding the threshold, and the cancelBuffer then suppresses the next several attacks, which stops a killaura or autoclicker feeding hits into the extended range. The margin covers genuine knockback and lag on borderline hits, not a constant 6-block envelope.

anticheat KillAura (reach sub-check)

KillAura.java114 lines · Java
1
package me.vrekt.arc.check.combat;
2
3
import me.vrekt.arc.Arc;
4
import me.vrekt.arc.check.Check;
5
import me.vrekt.arc.check.CheckType;
6
import me.vrekt.arc.data.combat.FightData;
7
import me.vrekt.arc.utilties.LocationHelper;
8
import org.bukkit.ChatColor;
9
import org.bukkit.entity.Entity;
10
import org.bukkit.entity.Player;
11
import org.bukkit.util.Vector;
12
13
public class KillAura extends Check {
14
15
    private double maxAngle, maxReach;
16
    private int maxSwingTime, maxAttacks, maxAttackPackets;
17
18
    public KillAura() {
19
        super(CheckType.KILLAURA);
20
21
        maxAngle = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-direction-angle");
22
        maxSwingTime = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-swing-time");
23
        maxReach = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-reach");
24
        maxAttacks = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attacks");
25
        maxAttackPackets = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attack-packets");
26
27
    }
28
29
    public boolean check(FightData data, Player player) {
30
        result.reset();
31
32
        Entity last = data.getLastAttackedEntity();
33
        Entity entity = data.getAttackedEntity();
34
35
        // Calculate angle stuff.
36
        Vector playerLocation = player.getLocation().toVector();
37
        Vector entityLocation = entity.getLocation().toVector();
38
        double angle = entityLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
39
40
        if (last != null && !entity.equals(last)) {
41
            // check the angle between the two entities
42
            Vector lastLocation = last.getLocation().toVector();
43
            double angleToLast = lastLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
44
            double angleDifference = Math.abs(angleToLast - angle);
45
            double distanceDifference = LocationHelper.distance(last.getLocation(), entity.getLocation());
46
            if (angleDifference > maxAngle && distanceDifference <= maxReach) {
47
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Multi)");
48
                result.set(checkViolation(player, "Angle difference greater than allowed. a=" + angleDifference + " e=" + maxAngle));
49
            }
50
        }
51
52
        // check yaw difference.
53
        if (angle > maxAngle) {
54
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Direction)");
55
            result.set(checkViolation(player, "Angle distance greater than allowed. a=" + angle + " e=" + maxAngle));
56
        }
57
58
        // check swing time.
59
        long time = System.currentTimeMillis() - data.getLastArmSwing();
60
        if (time > maxSwingTime) {
61
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(NoSwing)");
62
            result.set(checkViolation(player, "Player did not swing their arm in time."));
63
        }
64
65
        // distance to entity excluding knockback.
66
        double distance = LocationHelper.distance(player.getLocation(), entity.getLocation().subtract(entity.getVelocity()));
67
        // check for reach
68
        if (distance > maxReach) {
69
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Reach)");
70
            result.set(checkViolation(player, "Entity is out of players range. d=" + distance + " e=" + maxReach));
71
        }
72
73
        // check max attacks
74
        if (data.getLastAttackCheck() == 0) {
75
            data.setLastAttackCheck(System.currentTimeMillis());
76
        }
77
        long lastAttack = System.currentTimeMillis() - data.getLastAttackCheck();
78
        if (lastAttack >= 1000) {
79
            // check if we exceeded the max attacks in the last second.
80
            int totalAttacks = data.getTotalAttacks();
81
            if (totalAttacks > maxAttacks) {
82
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
83
                result.set(checkViolation(player, "Attacking too fast. a=" + totalAttacks + " e=" + maxAttacks));
84
            }
85
            // reset data for next check.
86
            data.setTotalAttacks(0);
87
            data.setLastAttackCheck(System.currentTimeMillis());
88
        }
89
90
        getCheck().setCheckName("KillAura");
91
        return result.failed();
92
    }
93
94
    public boolean checkFrequency(FightData data, Player player) {
95
        if (data.getLastAttackCheck() == 0) {
96
            data.setLastAttackCheck(System.currentTimeMillis());
97
            return false;
98
        }
99
100
        long time = System.currentTimeMillis() - data.getLastAttackCheck();
101
        if (time >= 1000) {
102
            data.setLastAttackCheck(System.currentTimeMillis());
103
            int totalPackets = data.getAttackPackets();
104
            if (totalPackets > maxAttackPackets) {
105
                data.setAttackPackets(0);
106
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
107
                return checkViolation(player, "Attacking too fast a=" + totalPackets + " e=" + maxAttackPackets);
108
            }
109
        }
110
111
        return false;
112
    }
113
114
}

How it counteracts this module

Arc v2's reach sub-check computes the distance between the player and the victim's location minus the victim's current velocity, so knockback does not inflate the measurement, and compares it with max-reach 4.2 from config.yml. The client-side reach value is invisible to this math: the check measures actual server positions, and a hit at 4.5 to 6 blocks from the center exceeds 4.2 on every attack, regardless of what the client believed its range was. Because the module applies a constant range, the violation is deterministic, and the cancel action at cancel-vl 0 reverts the attacker to their original location, which both punishes the extended hit and resets the fight geometry.

← Back to Analysis Hub