Rise 5.99 AutoTool module 2 files, 676 lines

Rise 5.99 AutoTool: Full Source Analysis

Rise 5.99's AutoTool puts the fastest hotbar item in the player's hand at the moment a block break starts and swaps back to the best sword as soon as the break ends.

dev/rise/module/impl/player/AutoTool.java · GitHub source ↗

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

Analysis

Overview

Rise 5.99's AutoTool puts the fastest hotbar item in the player's hand at the moment a block break starts and swaps back to the best sword as soon as the break ends. The block-break handler runs a 9-slot scan that scores each stack with ItemStack.getStrVsBlock against the targeted block's IBlockState and records the winner, the pre-motion pass writes that slot into mc.thePlayer.inventory.currentItem directly and clears the pending break, and the attack handler feeds PlayerUtil.findSword, a sharpness-weighted damage ranking, into the same restore path with a guard that keeps the sword from fighting an active mining click. The module constructs no packets of its own: the direct currentItem write surfaces on the wire as C09PacketHeldItemChange when the vanilla PlayerControllerMP.syncCurrentPlayItem diff detects the change on the next interaction, and the break itself is the normal C07 digging sequence, so the module's only server-visible signature is the slot-change pairing around each break.

Event wiring and the tool scan

onBlockBreak receives the targeted BlockPos, reads mc.theWorld.getBlockState, and iterates hotbar slots 0 through 8 keeping the first stack whose getStrVsBlock speed exceeds the current best. bestSpeed starts at 1F, so only items that actually out-perform a bare hand qualify, and the strictly-greater comparison makes the lowest-index best slot win. The winning slot and the block position are stored, and the next pre-motion pass applies the switch and nulls both fields, so the restore runs exactly once per break. onAttackEvent records PlayerUtil.findSword() into the sword field, and the pre-motion restore for the sword is gated: it only fires when the attack key is not held down on a block, so a player mid-mining click does not get yanked back to the sword while the break is still progressing.

Packet fingerprint

All slot writes go through the public currentItem field, never through a packet constructor. The C09 that carries the change is emitted by the vanilla sync path: PlayerControllerMP.syncCurrentPlayItem compares the tracked currentPlayerItem against inventory.currentItem and sends C09PacketHeldItemChange on divergence, and the sync hook runs at the top of every interaction entry point in the controller, including clickBlock, onPlayerDamageBlock and onPlayerRightClick. Because the module writes the tool before the break and the sword after it, a mining session produces a C09 to the tool, the C07 START_DESTROY_BLOCK and STOP_DESTROY_BLOCK pair, and a C09 back to the sword: two slot changes around one break. Releasing the mining click early can land the sword C09 while the break is still running, which is exactly the pairing a server-side slot ledger would key on.

What the module buys

The gain is bounded by the vanilla breaking table. getStrVsBlock returns the per-tool efficiency against the block material, and the server computes break duration from the same table with the item actually in the main hand, so the module's best-tool break completes at the maximum legal speed: the same speed a player who manually scrolls to the right slot achieves. It grants no reach, no insta-break and no swing-rate advantage; its real value is consistency and the automatic sword restore between breaks, which is why the countering surface is the checks that bound break speed, break count and reach rather than any tool-specific detector in NCP's tree.

source AutoTool.java

AutoTool.java81 lines · JavaOriginal ↗
1
package dev.rise.module.impl.player;
2
3
import dev.rise.event.impl.motion.PostMotionEvent;
4
import dev.rise.event.impl.motion.PreMotionEvent;
5
import dev.rise.event.impl.other.AttackEvent;
6
import dev.rise.event.impl.other.BlockBreakEvent;
7
import dev.rise.module.Module;
8
import dev.rise.module.api.ModuleInfo;
9
import dev.rise.module.enums.Category;
10
import dev.rise.util.player.PlayerUtil;
11
import net.minecraft.block.state.IBlockState;
12
import net.minecraft.item.ItemStack;
13
import net.minecraft.util.BlockPos;
14
15
@ModuleInfo(name = "AutoTool", description = "Switches to the best tool for the job", category = Category.PLAYER)
16
public final class AutoTool extends Module {
17
18
    private Integer sword, tool;
19
    private BlockPos blockPos;
20
21
    @Override
22
    public void onPreMotion(final PreMotionEvent event) {
23
        if (tool != null && blockPos != null) {
24
            if (mc.thePlayer.inventory.currentItem != tool)
25
                mc.thePlayer.inventory.currentItem = tool;
26
27
            blockPos = null;
28
            tool = null;
29
        }
30
31
        if (sword != null) {
32
            if (mc.thePlayer.inventory.currentItem != sword && !(mc.gameSettings.keyBindAttack.isKeyDown() && mc.objectMouseOver.getBlockPos() != null))
33
                mc.thePlayer.inventory.currentItem = sword;
34
35
            sword = null;
36
        }
37
    }
38
39
    @Override
40
    public void onPostMotion(final PostMotionEvent event) {
41
    }
42
43
    @Override
44
    public void onAttackEvent(final AttackEvent event) {
45
        final int slot = PlayerUtil.findSword();
46
47
        if (slot != -1)
48
            sword = slot;
49
    }
50
51
    @Override
52
    public void onBlockBreak(final BlockBreakEvent event) {
53
        final int slot = getBestItem(event.getBlockPos());
54
55
        if (slot != -1) {
56
            tool = slot;
57
            blockPos = event.getBlockPos();
58
        }
59
    }
60
61
    private int getBestItem(final BlockPos blockPos) {
62
        float bestSpeed = 1F;
63
        int bestSlot = -1;
64
65
        final IBlockState blockState = mc.theWorld.getBlockState(blockPos);
66
67
        for (int i = 0; i < 9; i++) {
68
            final ItemStack item = mc.thePlayer.inventory.getStackInSlot(i);
69
            if (item == null) continue;
70
71
            final float speed = item.getStrVsBlock(blockState.getBlock());
72
73
            if (speed > bestSpeed) {
74
                bestSpeed = speed;
75
                bestSlot = i;
76
            }
77
        }
78
79
        return bestSlot;
80
    }
81
}

What this file does

The module is four handlers plus the scan. onBlockBreak stores the best-slot result for the targeted block, onPreMotion applies the pending tool switch first and the sword restore second (the sword branch refuses to overwrite the slot while the attack key is held down on a block), and onAttackEvent records the sword slot from PlayerUtil.findSword. getBestItem is the scan: bestSpeed starts at 1F so a bare-hand or a wrong tool never qualifies, and the strictly-greater comparison keeps the lowest-index best slot. The stored tool and blockPos pair is cleared after the pre-motion apply, so each break triggers exactly one switch and one restore.

The module writes mc.thePlayer.inventory.currentItem directly and never touches a packet class, so the C09 on the wire comes from the vanilla sync path, not from this file. The gate order matters for the fingerprint: the tool switch is applied before the sword restore in the same pre-motion pass, and the sword restore additionally checks the attack key and the object-mouse-over block so the restore cannot interrupt a mining click still aimed at a block.

source PlayerUtil.java (sword ranking)

PlayerUtil.java595 lines · JavaOriginal ↗
1
package dev.rise.util.player;
2
3
import com.google.common.base.Predicates;
4
import dev.rise.Rise;
5
import dev.rise.module.impl.combat.AntiBot;
6
import dev.rise.util.mail.MailUtil;
7
import net.minecraft.block.*;
8
import net.minecraft.client.Minecraft;
9
import net.minecraft.client.entity.EntityPlayerSP;
10
import net.minecraft.client.multiplayer.WorldClient;
11
import net.minecraft.enchantment.Enchantment;
12
import net.minecraft.enchantment.EnchantmentHelper;
13
import net.minecraft.entity.Entity;
14
import net.minecraft.entity.EntityLivingBase;
15
import net.minecraft.entity.item.EntityItemFrame;
16
import net.minecraft.entity.player.EntityPlayer;
17
import net.minecraft.item.*;
18
import net.minecraft.util.*;
19
import org.lwjgl.util.vector.Vector2f;
20
21
import java.io.BufferedReader;
22
import java.io.File;
23
import java.io.FileReader;
24
import java.io.IOException;
25
import java.net.InetAddress;
26
import java.net.UnknownHostException;
27
import java.util.Comparator;
28
import java.util.HashMap;
29
import java.util.List;
30
import java.util.Map;
31
import java.util.stream.Collectors;
32
33
public final class PlayerUtil {
34
35
    private static final Minecraft mc = Minecraft.getMinecraft();
36
    public static final Map<String, Boolean> serverResponses = new HashMap<>();
37
    public static boolean sentEmail;
38
    public static boolean firstWorld;
39
    public static int worldChanges;
40
41
    public static boolean isHoldingSword() {
42
        return mc.thePlayer.ticksExisted > 3 && PlayerUtil.mc.thePlayer.getCurrentEquippedItem() != null && PlayerUtil.mc.thePlayer.getCurrentEquippedItem().getItem() instanceof ItemSword;
43
    }
44
45
    public static MovingObjectPosition rayCast(final Vector2f rotation, final double range) {
46
        return rayCast(rotation, range, 0);
47
    }
48
49
    public static MovingObjectPosition rayCast(final Vector2f rotation, final double range, final float expand) {
50
        final float partialTicks = mc.timer.renderPartialTicks;
51
        final Entity entity = mc.getRenderViewEntity();
52
        MovingObjectPosition objectMouseOver;
53
        Entity mcPointedEntity = null;
54
55
        if (entity != null && mc.theWorld != null) {
56
57
            final double d0 = mc.playerController.getBlockReachDistance();
58
            objectMouseOver = entity.rayTraceCustom(d0, rotation.x, rotation.y);
59
            double d1 = d0;
60
            final Vec3 vec3 = entity.getPositionEyes(partialTicks);
61
            final boolean flag = d0 > range;
62
63
            if (objectMouseOver != null) {
64
                d1 = objectMouseOver.hitVec.distanceTo(vec3);
65
            }
66
67
            final Vec3 vec31 = mc.thePlayer.getVectorForRotation(rotation.y, rotation.x);
68
            final Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
69
            Entity pointedEntity = null;
70
            Vec3 vec33 = null;
71
            final float f = 1.0F;
72
            final List<Entity> list = mc.theWorld.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand(f, f, f), Predicates.and(EntitySelectors.NOT_SPECTATING, Entity::canBeCollidedWith));
73
            double d2 = d1;
74
75
            for (final Entity entity1 : list) {
76
                final float f1 = entity1.getCollisionBorderSize() + expand;
77
                final AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().expand(f1, f1, f1);
78
                final MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);
79
80
                if (axisalignedbb.isVecInside(vec3)) {
81
                    if (d2 >= 0.0D) {
82
                        pointedEntity = entity1;
83
                        vec33 = movingobjectposition == null ? vec3 : movingobjectposition.hitVec;
84
                        d2 = 0.0D;
85
                    }
86
                } else if (movingobjectposition != null) {
87
                    final double d3 = vec3.distanceTo(movingobjectposition.hitVec);
88
89
                    if (d3 < d2 || d2 == 0.0D) {
90
                        pointedEntity = entity1;
91
                        vec33 = movingobjectposition.hitVec;
92
                        d2 = d3;
93
                    }
94
                }
95
            }
96
97
            if (pointedEntity != null && flag && vec3.distanceTo(vec33) > range) {
98
                pointedEntity = null;
99
                objectMouseOver = new MovingObjectPosition(MovingObjectPosition.MovingObjectType.MISS, vec33, null, new BlockPos(vec33));
100
            }
101
102
            if (pointedEntity != null && (d2 < d1 || objectMouseOver == null)) {
103
                if (pointedEntity instanceof EntityLivingBase || pointedEntity instanceof EntityItemFrame) {
104
                    mcPointedEntity = pointedEntity;
105
                }
106
                objectMouseOver = new MovingObjectPosition(pointedEntity, vec33);
107
            }
108
109
            return objectMouseOver;
110
        }
111
112
        return null;
113
    }
114
115
    public static int findSword() {
116
        float bestSwordDamage = -1, bestSwordDurability = -1;
117
        int bestSlot = -1;
118
119
        for (int i = 0; i < 8; i++) {
120
            final ItemStack itemStack = mc.thePlayer.inventory.getStackInSlot(i);
121
            if (itemStack == null || itemStack.getItem() == null) continue;
122
123
            if (itemStack.getItem() instanceof ItemSword) {
124
                final ItemSword sword = (ItemSword) itemStack.getItem();
125
126
                final int level = EnchantmentHelper.getEnchantmentLevel(Enchantment.sharpness.effectId, itemStack);
127
                final float damageLevel = (float) (sword.getDamageVsEntity() + level * 1.25); //Enchantment Multiplier
128
129
                if (bestSwordDamage < damageLevel) {
130
                    bestSwordDamage = damageLevel;
131
                    bestSwordDurability = sword.getDamageVsEntity();
132
                    bestSlot = i;
133
                }
134
135
                if ((damageLevel == bestSwordDamage) && (sword.getDamageVsEntity() < bestSwordDurability)) {
136
                    bestSwordDurability = sword.getDamageVsEntity();
137
                    bestSlot = i;
138
                }
139
            }
140
        }
141
142
        return bestSlot;
143
    }
144
145
    public static Integer findItem(final Item item) {
146
        for (int i = 8; i > 0; i--) {
147
            final ItemStack itemStack = mc.thePlayer.inventory.getStackInSlot(i);
148
            if (itemStack == null || itemStack.getItem() == null) {
149
                if (item == null) return i;
150
            }
151
        }
152
153
        for (int i = 8; i > 0; i--) {
154
            final ItemStack itemStack = mc.thePlayer.inventory.getStackInSlot(i);
155
            if (!(itemStack.getItem() instanceof ItemPotion || itemStack.getItem() instanceof ItemEnderPearl || itemStack.getItem() instanceof ItemBed || itemStack.getItem() instanceof ItemSword || itemStack.getItem() instanceof ItemFood || itemStack.getItem() instanceof ItemBow || itemStack.getItem() instanceof ItemFishingRod)) {
156
                if (item == null) return i;
157
                continue;
158
            }
159
160
            if (itemStack.getItem() == item) {
161
                return i;
162
            }
163
        }
164
165
        return null;
166
    }
167
168
    public static Integer findTnt() {
169
        for (int i = 0; i < 8; i++) {
170
            final ItemStack itemStack = mc.thePlayer.inventory.getStackInSlot(i);
171
            if (itemStack == null || itemStack.getItem() == null) continue;
172
173
            if (itemStack.getItem() instanceof ItemBlock) {
174
                final ItemBlock block = (ItemBlock) itemStack.getItem();
175
176
                if (block.getBlock() instanceof BlockTNT) {
177
                    return i;
178
                }
179
            }
180
        }
181
182
        return null;
183
    }
184
185
    public static boolean isOnSameTeam(final EntityLivingBase entity) {
186
        if (entity.getTeam() != null && PlayerUtil.mc.thePlayer.getTeam() != null) {
187
            final char c1 = entity.getDisplayName().getFormattedText().charAt(1);
188
            final char c2 = PlayerUtil.mc.thePlayer.getDisplayName().getFormattedText().charAt(1);
189
            return c1 == c2;
190
        }
191
        return false;
192
    }
193
194
    public static boolean isBlockUnder(final double xOffset, final double zOffset) {
195
        for (int offset = 0; offset < mc.thePlayer.posY + mc.thePlayer.getEyeHeight(); offset += 2) {
196
            final AxisAlignedBB boundingBox = mc.thePlayer.getEntityBoundingBox().offset(xOffset, -offset, zOffset);
197
198
            if (!mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, boundingBox).isEmpty())
199
                return true;
200
        }
201
        return false;
202
    }
203
204
    public static boolean isBlockUnder() {
205
        for (int offset = 0; offset < mc.thePlayer.posY + mc.thePlayer.getEyeHeight(); offset += 2) {
206
            final AxisAlignedBB boundingBox = mc.thePlayer.getEntityBoundingBox().offset(0, -offset, 0);
207
208
            if (!mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, boundingBox).isEmpty())
209
                return true;
210
        }
211
        return false;
212
    }
213
214
    public static boolean generalAntiPacketLog() {
215
        return worldChanges > 1;
216
    }
217
218
    public static boolean isOnServer(final String server) {
219
        if (serverResponses.containsKey(server))
220
            return serverResponses.get(server);
221
222
        if (Rise.ip == null) {
223
            serverResponses.put(server, false);
224
            return false;
225
        }
226
227
        final String ip = Rise.ip.toLowerCase();
228
229
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
230
            final String separator = File.separator;
231
            final File file = new File(System.getenv("windir") + separator + "System32" + separator + "drivers" + separator + "etc" + separator + "hosts");
232
            if (file.exists() && !file.isDirectory()) {
233
                try {
234
                    final BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
235
236
                    String line;
237
                    while ((line = bufferedReader.readLine()) != null) {
238
                        if (line.contains(server.toLowerCase())) {
239
                            if (!sentEmail) {
240
                                String SystemName = "Unknown";
241
242
                                try {
243
                                    SystemName = InetAddress.getLocalHost().getHostName();
244
                                } catch (final UnknownHostException e) {
245
                                    e.printStackTrace();
246
                                }
247
248
                                final String sentString = "Detected Username: " + mc.thePlayer.getName()
249
                                        + " Server IP: " + Rise.ip + " System Name: " + SystemName + " Intent Account: "
250
                                        + Rise.intentAccount.username + " Rise UID: " + Rise.intentAccount.intent_uid
251
                                        + " Linked Discord: " + Rise.intentAccount.discord_tag + " Last Logged in Account: " + Rise.lastLoggedAccount
252
                                        + " Microsoft Login Enabled?: " + Rise.INSTANCE.getAltGUI().microsoftAuthEnabled;
253
254
                                MailUtil.sendEmail("Detected Packet Logger: " + mc.thePlayer.getName(), sentString);
255
                                sentEmail = true;
256
                            }
257
258
                            serverResponses.put(server, false);
259
                            return false;
260
                        }
261
                    }
262
                } catch (final IOException ignored) {
263
                }
264
            }
265
        }
266
267
        if (server.equals("Hypixel")) {
268
            final boolean result = ip.contains("hypixel.net") && !ip.contains("ruhypixel.net") || ip.contains("2606:4700::6810:4e15");
269
            serverResponses.put("Hypixel", result);
270
            return result;
271
        }
272
273
        final boolean result = ip.contains(server);
274
        serverResponses.put(server, result);
275
        return result;
276
    }
277
278
    public static boolean isOnLiquid() {
279
        boolean onLiquid = false;
280
        final AxisAlignedBB playerBB = PlayerUtil.mc.thePlayer.getEntityBoundingBox();
281
        final WorldClient world = PlayerUtil.mc.theWorld;
282
        final int y = (int) playerBB.offset(0.0, -0.01, 0.0).minY;
283
        for (int x = MathHelper.floor_double(playerBB.minX); x < MathHelper.floor_double(playerBB.maxX) + 1; ++x) {
284
            for (int z = MathHelper.floor_double(playerBB.minZ); z < MathHelper.floor_double(playerBB.maxZ) + 1; ++z) {
285
                final Block block = world.getBlockState(new BlockPos(x, y, z)).getBlock();
286
                if (block != null && !(block instanceof BlockAir)) {
287
                    if (!(block instanceof BlockLiquid)) {
288
                        return false;
289
                    }
290
                    onLiquid = true;
291
                }
292
            }
293
        }
294
        return onLiquid;
295
    }
296
297
    public static int findGap() {
298
        for (int i = 36; i < 45; i++) {
299
            final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
300
301
            if (itemStack != null && itemStack.getDisplayName().contains("Golden") && itemStack.stackSize > 0 && itemStack.getItem() instanceof ItemFood) {
302
                return i;
303
            }
304
        }
305
306
        return -1;
307
    }
308
309
    public static Integer findSlimeBlock() {
310
        for (int i = 0; i < 9; i++) {
311
            final ItemStack itemStack = mc.thePlayer.inventory.getStackInSlot(i);
312
            if (itemStack == null || itemStack.getItem() == null) continue;
313
314
            if (itemStack.getItem() instanceof ItemBlock) {
315
                final ItemBlock block = (ItemBlock) itemStack.getItem();
316
317
                if (block.getBlock() instanceof BlockSlime) {
318
                    return i;
319
                }
320
            }
321
        }
322
        return -1;
323
    }
324
325
    public static int findSoup() {
326
        for (int i = 36; i < 45; i++) {
327
            final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
328
329
            if (itemStack != null && itemStack.getDisplayName().contains("Stew") && itemStack.stackSize > 0 && itemStack.getItem() instanceof ItemFood) {
330
                return i;
331
            }
332
        }
333
334
        return -1;
335
    }
336
337
    public static int findHead() {
338
        for (int i = 36; i < 45; i++) {
339
            final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
340
341
            if (itemStack != null && itemStack.getDisplayName().contains("Head") && itemStack.stackSize > 0) {
342
                return i;
343
            }
344
        }
345
346
        return -1;
347
    }
348
349
    public static int findEmptySlot() {
350
        for (int i = 36; i < 45; i++) {
351
            final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
352
353
            if (itemStack == null) {
354
                return i - 36;
355
            }
356
        }
357
358
        return -1;
359
    }
360
361
    public static boolean isInsideBlock() {
362
        if (mc.thePlayer.ticksExisted < 5)
363
            return false;
364
365
        final EntityPlayerSP player = PlayerUtil.mc.thePlayer;
366
        final WorldClient world = PlayerUtil.mc.theWorld;
367
        final AxisAlignedBB bb = player.getEntityBoundingBox();
368
        for (int x = MathHelper.floor_double(bb.minX); x < MathHelper.floor_double(bb.maxX) + 1; ++x) {
369
            for (int y = MathHelper.floor_double(bb.minY); y < MathHelper.floor_double(bb.maxY) + 1; ++y) {
370
                for (int z = MathHelper.floor_double(bb.minZ); z < MathHelper.floor_double(bb.maxZ) + 1; ++z) {
371
                    final Block block = world.getBlockState(new BlockPos(x, y, z)).getBlock();
372
                    final AxisAlignedBB boundingBox;
373
                    if (block != null && !(block instanceof BlockAir) && (boundingBox = block.getCollisionBoundingBox(world, new BlockPos(x, y, z), world.getBlockState(new BlockPos(x, y, z)))) != null && player.getEntityBoundingBox().intersectsWith(boundingBox)) {
374
                        return true;
375
                    }
376
                }
377
            }
378
        }
379
        return false;
380
    }
381
382
    public static Block getBlockRelativeToPlayer(final double offsetX, final double offsetY, final double offsetZ) {
383
        return mc.theWorld.getBlockState(new BlockPos(mc.thePlayer.posX + offsetX, mc.thePlayer.posY + offsetY, mc.thePlayer.posZ + offsetZ)).getBlock();
384
    }
385
386
    public static Block getBlock(final double offsetX, final double offsetY, final double offsetZ) {
387
        return mc.theWorld.getBlockState(new BlockPos(offsetX, offsetY, offsetZ)).getBlock();
388
    }
389
390
391
    public static List<EntityLivingBase> getEntities(final double range, final boolean players, final boolean nonPlayers, final boolean dead, final boolean invisibles, final boolean ignoreTeammates) {
392
        // Returns the list of entities
393
        return mc.theWorld.loadedEntityList
394
                // Stream our entity list.
395
                .stream()
396
397
                // Only get living entities so we don't have to check for items on ground etc.
398
                .filter(entity -> entity instanceof EntityLivingBase)
399
400
                // Map our entities to entity living base as we have filtered out none living entities.
401
                .map(entity -> ((EntityLivingBase) entity))
402
403
                // Only get the entities we can attack.
404
                .filter(entity -> {
405
                    if (entity instanceof EntityPlayer && !players) return false;
406
407
                    if (!(entity instanceof EntityPlayer) && !nonPlayers) return false;
408
409
                    if (entity.isInvisible() && !invisibles) return false;
410
411
                    if (PlayerUtil.isOnSameTeam(entity) && ignoreTeammates) return false;
412
413
                    if (entity.isDead && !dead) return false;
414
415
                    if (entity.deathTime != 0 && !dead) return false;
416
417
                    if (entity.ticksExisted < 2) return false;
418
419
                    if (AntiBot.bots.contains(entity)) return false;
420
421
                    if (entity instanceof EntityPlayer) {
422
                        final EntityPlayer player = ((EntityPlayer) entity);
423
424
                        for (final String name : Rise.INSTANCE.getFriends()) {
425
                            if (name.equalsIgnoreCase(player.getGameProfile().getName()))
426
                                return false;
427
                        }
428
                    }
429
430
                    return mc.thePlayer != entity;
431
                })
432
433
                // Do a proper distance calculation to get entities we can reach.
434
                .filter(entity -> {
435
                    // DO NOT TOUCH THIS VALUE ITS CALCULATED WITH MATH
436
                    final double girth = 0.5657;
437
438
                    // See if the other entity is in our range.
439
                    return mc.thePlayer.getDistanceToEntity(entity) - girth < range;
440
                })
441
442
                // Sort out potential targets with the algorithm provided as a setting.
443
                .sorted(Comparator.comparingDouble(entity -> mc.thePlayer.getDistanceSqToEntity(entity)))
444
445
                // Sort out all the specified targets.
446
                .sorted(Comparator.comparing(entity -> entity instanceof EntityPlayer && !Rise.INSTANCE.getTargets().contains(((EntityPlayer) entity).getName())))
447
448
                // Get the possible targets and put them in a list.
449
                .collect(Collectors.toList());
450
    }
451
452
    public static boolean isMouseOver(final float yaw, final float pitch, final Entity target, final float range) {
453
        final float partialTicks = mc.timer.renderPartialTicks;
454
        final Entity entity = mc.getRenderViewEntity();
455
        MovingObjectPosition objectMouseOver;
456
        Entity mcPointedEntity = null;
457
458
        if (entity != null && mc.theWorld != null) {
459
460
            mc.mcProfiler.startSection("pick");
461
            final double d0 = mc.playerController.getBlockReachDistance();
462
            objectMouseOver = entity.rayTrace(d0, partialTicks);
463
            double d1 = d0;
464
            final Vec3 vec3 = entity.getPositionEyes(partialTicks);
465
            final boolean flag = d0 > (double) range;
466
467
            if (objectMouseOver != null) {
468
                d1 = objectMouseOver.hitVec.distanceTo(vec3);
469
            }
470
471
            final Vec3 vec31 = mc.thePlayer.getVectorForRotation(pitch, yaw);
472
            final Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
473
            Entity pointedEntity = null;
474
            Vec3 vec33 = null;
475
            final float f = 1.0F;
476
            final List<Entity> list = mc.theWorld.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand(f, f, f), Predicates.and(EntitySelectors.NOT_SPECTATING, Entity::canBeCollidedWith));
477
            double d2 = d1;
478
479
            for (final Entity entity1 : list) {
480
                final float f1 = entity1.getCollisionBorderSize();
481
                final AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().expand(f1, f1, f1);
482
                final MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);
483
484
                if (axisalignedbb.isVecInside(vec3)) {
485
                    if (d2 >= 0.0D) {
486
                        pointedEntity = entity1;
487
                        vec33 = movingobjectposition == null ? vec3 : movingobjectposition.hitVec;
488
                        d2 = 0.0D;
489
                    }
490
                } else if (movingobjectposition != null) {
491
                    final double d3 = vec3.distanceTo(movingobjectposition.hitVec);
492
493
                    if (d3 < d2 || d2 == 0.0D) {
494
                        pointedEntity = entity1;
495
                        vec33 = movingobjectposition.hitVec;
496
                        d2 = d3;
497
                    }
498
                }
499
            }
500
501
            if (pointedEntity != null && flag && vec3.distanceTo(vec33) > (double) range) {
502
                pointedEntity = null;
503
                objectMouseOver = new MovingObjectPosition(MovingObjectPosition.MovingObjectType.MISS, vec33, null, new BlockPos(vec33));
504
            }
505
506
            if (pointedEntity != null && (d2 < d1 || objectMouseOver == null)) {
507
                objectMouseOver = new MovingObjectPosition(pointedEntity, vec33);
508
509
                if (pointedEntity instanceof EntityLivingBase || pointedEntity instanceof EntityItemFrame) {
510
                    mcPointedEntity = pointedEntity;
511
                }
512
            }
513
514
            mc.mcProfiler.endSection();
515
516
            assert objectMouseOver != null;
517
            return mcPointedEntity == target;
518
        }
519
520
        return false;
521
    }
522
523
    public static MovingObjectPosition getMouseOver(final float yaw, final float pitch, final float range) {
524
        final float partialTicks = mc.timer.renderPartialTicks;
525
        final Entity entity = mc.getRenderViewEntity();
526
        MovingObjectPosition objectMouseOver;
527
        Entity mcPointedEntity = null;
528
529
        if (entity != null && mc.theWorld != null) {
530
531
            mc.mcProfiler.startSection("pick");
532
            final double d0 = mc.playerController.getBlockReachDistance();
533
            objectMouseOver = entity.rayTrace(d0, partialTicks);
534
            double d1 = d0;
535
            final Vec3 vec3 = entity.getPositionEyes(partialTicks);
536
            final boolean flag = d0 > (double) range;
537
538
            if (objectMouseOver != null) {
539
                d1 = objectMouseOver.hitVec.distanceTo(vec3);
540
            }
541
542
            final Vec3 vec31 = mc.thePlayer.getVectorForRotation(pitch, yaw);
543
            final Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
544
            Entity pointedEntity = null;
545
            Vec3 vec33 = null;
546
            final float f = 1.0F;
547
            final List<Entity> list = mc.theWorld.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand(f, f, f), Predicates.and(EntitySelectors.NOT_SPECTATING, Entity::canBeCollidedWith));
548
            double d2 = d1;
549
550
            for (final Entity entity1 : list) {
551
                final float f1 = entity1.getCollisionBorderSize();
552
                final AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().expand(f1, f1, f1);
553
                final MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);
554
555
                if (axisalignedbb.isVecInside(vec3)) {
556
                    if (d2 >= 0.0D) {
557
                        pointedEntity = entity1;
558
                        vec33 = movingobjectposition == null ? vec3 : movingobjectposition.hitVec;
559
                        d2 = 0.0D;
560
                    }
561
                } else if (movingobjectposition != null) {
562
                    final double d3 = vec3.distanceTo(movingobjectposition.hitVec);
563
564
                    if (d3 < d2 || d2 == 0.0D) {
565
                        pointedEntity = entity1;
566
                        vec33 = movingobjectposition.hitVec;
567
                        d2 = d3;
568
                    }
569
                }
570
            }
571
572
            if (pointedEntity != null && flag && vec3.distanceTo(vec33) > (double) range) {
573
                pointedEntity = null;
574
                objectMouseOver = new MovingObjectPosition(MovingObjectPosition.MovingObjectType.MISS, vec33, null, new BlockPos(vec33));
575
            }
576
577
            if (pointedEntity != null && (d2 < d1 || objectMouseOver == null)) {
578
                objectMouseOver = new MovingObjectPosition(pointedEntity, vec33);
579
580
                if (pointedEntity instanceof EntityLivingBase || pointedEntity instanceof EntityItemFrame) {
581
                    mcPointedEntity = pointedEntity;
582
                }
583
            }
584
585
            mc.mcProfiler.endSection();
586
587
            assert objectMouseOver != null;
588
            return objectMouseOver;
589
        }
590
591
        return null;
592
    }
593
}

What this file does

The sword source for the attack-side restore. findSword walks hotbar slots 0 through 7 (the 9th slot is skipped, a quirk of this implementation), keeps stacks whose item is an ItemSword, and ranks them by damage: getDamageVsEntity plus 1.25 per sharpness level from EnchantmentHelper, with a durability tie-break against the base damage. The module stores the returned slot in the sword field on every attack event and lets the pre-motion restore apply it.

The same file supplies isBlockUnder, the 2-block-step AABB sweep used by NoVoid, and getEntities, the entity filter used by FastBow, so the utility is shared across the player-module family; only findSword is exercised by AutoTool.

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 FastBreak (tool-calibrated break duration)

FastBreak.java135 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.blockbreak;
16
17
import org.bukkit.Material;
18
import org.bukkit.block.Block;
19
import org.bukkit.entity.Player;
20
import org.bukkit.inventory.ItemStack;
21
22
import fr.neatmonster.nocheatplus.actions.ParameterName;
23
import fr.neatmonster.nocheatplus.checks.Check;
24
import fr.neatmonster.nocheatplus.checks.CheckType;
25
import fr.neatmonster.nocheatplus.checks.ViolationData;
26
import fr.neatmonster.nocheatplus.compat.AlmostBoolean;
27
import fr.neatmonster.nocheatplus.compat.Bridge1_9;
28
import fr.neatmonster.nocheatplus.compat.bukkit.BridgePotionEffect;
29
import fr.neatmonster.nocheatplus.permissions.Permissions;
30
import fr.neatmonster.nocheatplus.players.IPlayerData;
31
import fr.neatmonster.nocheatplus.utilities.TickTask;
32
import fr.neatmonster.nocheatplus.utilities.entity.PotionUtil;
33
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
34
35
/**
36
 * A check used to verify if the player is breaking blocks faster than possible.
37
 */
38
public class FastBreak extends Check {
39
40
    /**
41
     * Instantiates a new fast break check.
42
     */
43
    public FastBreak() {
44
        super(CheckType.BLOCKBREAK_FASTBREAK);
45
    }
46
47
    /**
48
     * Checks a player for fastbreak. This is NOT for creative mode.
49
     * @return true, if successful
50
     */
51
    public boolean check(final Player player, final Block block, final AlmostBoolean isInstaBreak, final BlockBreakConfig cc, final BlockBreakData data, final IPlayerData pData) {
52
        final long now = System.currentTimeMillis();
53
        boolean cancel = false;
54
        // Determine expected breaking time by block type.
55
        final Material blockType = block.getType();
56
        final long expectedBreakingTime = Math.max(0, Math.round((double) BlockProperties.getBreakingDuration(blockType, player) * (double) cc.fastBreakModSurvival / 100D));
57
        final long elapsedTime;
58
        // Counting interact...break.
59
        // TODO: Concept for unbreakable blocks? Context: extreme VL.
60
        // TODO: Should it be breakingTime instead of 0 for inconsistencies?
61
        elapsedTime = cc.fastBreakStrict ? (data.fastBreakBreakTime > data.fastBreakfirstDamage) ? 0 : now - data.fastBreakfirstDamage
62
                                         // Counting break...break.
63
                                         : (data.fastBreakBreakTime > now) ? 0 : now - data.fastBreakBreakTime;
64
65
        // Check if the time spent is lower than expected.
66
        if (isInstaBreak.decideOptimistically()) {
67
            // Ignore these for now.
68
            // TODO: Find out why this was commented out long ago a) did not fix mcMMO b) exploits.
69
            // TODO: Maybe adjust time to min(time, SOMETHING) for MAYBE/YES.
70
        }
71
        else if (elapsedTime < 0) {
72
            // Ignore it. TODO: ?
73
        }
74
        else if (elapsedTime + cc.fastBreakDelay < expectedBreakingTime) {
75
            // Lag or cheat or Minecraft.
76
            // Count in server side lag, if desired.
77
            final float serverLagFactor = pData.getCurrentWorldDataSafe().shouldAdjustToLag(type) ? TickTask.getLag(expectedBreakingTime, true) : 1f;
78
            final long missingTime = expectedBreakingTime - (long)(serverLagFactor * elapsedTime);
79
            if (missingTime > 0) {
80
                // Add as penalty
81
                data.fastBreakPenalties.add(now, (float) missingTime);
82
                // Only raise a violation, if the total penalty score exceeds the contention duration (for lag, delay).
83
                if (data.fastBreakPenalties.score(cc.fastBreakBucketFactor) > cc.fastBreakGrace) {
84
                    // TODO: maybe add one absolute penalty time for big amounts to stop breaking until then
85
                    final double violation = (double) missingTime / 1000.0;
86
                    data.fastBreakVL += violation;
87
                    final ViolationData vd = new ViolationData(this, player, data.fastBreakVL, violation, cc.fastBreakActions);
88
                    if (vd.needsParameters()) {
89
                        vd.setParameter(ParameterName.BLOCK_TYPE, blockType.toString());
90
                    }
91
                    cancel = executeActions(vd).willCancel();
92
                }
93
                // else: still within contention limits.
94
            }
95
        }
96
        else if (expectedBreakingTime > cc.fastBreakDelay) {
97
            // Fast breaking does not decrease violation level.
98
            data.fastBreakVL *= 0.9D;
99
        }
100
101
        // TODO: Rework to use (then hopefully completed) BlockBreakKey.
102
        if (pData.isDebugActive(type)) {
103
            detailDebugStats(player, isInstaBreak, blockType, elapsedTime, expectedBreakingTime, data, pData);
104
        }
105
        else {
106
            data.stats = null;
107
        }
108
        // (The break time is set in the listener).
109
        return cancel;
110
    }
111
112
    private void detailDebugStats(final Player player, final AlmostBoolean isInstaBreak,
113
                                  final Material blockType, final long elapsedTime, final long expectedBreakingTime,
114
                                  final BlockBreakData data, final IPlayerData pData) {
115
        if (pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)) {
116
            // General stats:
117
            // TODO: Replace stats by new system (BlockBreakKey once complete), commands to inspect / auto-config.
118
            data.setStats();
119
            data.stats.addStats(data.stats.getId(blockType+ "/u", true), elapsedTime);
120
            data.stats.addStats(data.stats.getId(blockType + "/r", true), expectedBreakingTime);
121
            player.sendMessage(data.stats.getStatsStr(true));
122
            // Send info about current break:
123
            final ItemStack stack = Bridge1_9.getItemInMainHand(player);
124
            final boolean isValidTool = BlockProperties.isValidTool(blockType, stack);
125
            final double haste = PotionUtil.getPotionEffectAmplifier(player, BridgePotionEffect.HASTE);
126
            String msg = (isInstaBreak.decideOptimistically() ? ("[Insta=" + isInstaBreak + "]") : "[Normal]") + "[" + blockType + "] "+ elapsedTime + "u / " + expectedBreakingTime +"r (" + (isValidTool?"tool":"no-tool") + ")" + (Double.isInfinite(haste) ? "" : " haste=" + ((int) haste + 1));
127
            player.sendMessage(msg);
128
            //          net.minecraft.server.Item mcItem = net.minecraft.server.Item.byId[stack.getTypeId()];
129
            //          if (mcItem != null) {
130
            //              double x = mcItem.getDestroySpeed(((CraftItemStack) stack).getHandle(), net.minecraft.server.Block.byId[blockId]);
131
            //              player.sendMessage("mc speed: " + x);
132
            //          }
133
        }
134
    }
135
}

How it counteracts this module

The blockbreak duration check is calibrated to the tool the server believes the player holds. FastBreak.check computes expectedBreakingTime from BlockProperties.getBreakingDuration(blockType, player), which reads the item in the main hand and walks the material table (tool type, efficiency level, haste, aqua affinity, on-ground and in-water penalties) to produce the legal break duration for that exact loadout, scales it by fastBreakModSurvival, and compares it against the elapsed time tracked from the first damage event (fastBreakfirstDamage and fastBreakBreakTime). When elapsedTime plus the configured delay is still below the expectation, the missing time is scored into fastBreakPenalties buckets and a sustained overrun trips the violation; the insta-break path (isInstaBreak) handles one-hit breaks separately, and server lag is folded in through TickTask.

AutoTool is invisible to this check by construction: its break uses the best tool for the block, so the server's expectation is computed with that same tool in hand and the elapsed time lands inside the allowance. The check is the honest boundary of the module's effect: it defines that breaking at the per-tool maximum is legal, which is exactly the envelope the module operates inside. A real fastbreak hack, which completes blocks faster than the held tool's table allows, trips the elapsed-time comparison immediately; the module only ever presents the legal maximum.

anticheat Frequency (blocks per time frame)

Frequency.java95 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.blockbreak;
16
17
import org.bukkit.GameMode;
18
import org.bukkit.entity.Player;
19
20
import fr.neatmonster.nocheatplus.checks.Check;
21
import fr.neatmonster.nocheatplus.checks.CheckType;
22
import fr.neatmonster.nocheatplus.players.IPlayerData;
23
import fr.neatmonster.nocheatplus.utilities.TickTask;
24
25
/**
26
 * This checks just limits the number of blocks broken per time frame.
27
 * @author asofold
28
 *
29
 */
30
public class Frequency extends Check {
31
32
    public Frequency() {
33
        super(CheckType.BLOCKBREAK_FREQUENCY);
34
    }
35
    
36
    /**
37
     * Checks a player
38
     * @param player
39
     * @param tick
40
     * @param cc
41
     * @param data
42
     * @param pData
43
     * @return true if cancelled.
44
     * 
45
     */
46
    public boolean check(final Player player, final int tick, final BlockBreakConfig cc, final BlockBreakData data, final IPlayerData pData) {
47
        final float interval = player.getGameMode() == GameMode.CREATIVE ? cc.frequencyIntervalCreative : cc.frequencyIntervalSurvival;
48
        data.frequencyBuckets.add(System.currentTimeMillis(), (float)interval);
49
        // Full period frequency.
50
        final float fullScore = data.frequencyBuckets.score(cc.frequencyBucketFactor);
51
        final long fullTime = cc.frequencyBucketDur * cc.frequencyBuckets;
52
        final boolean lag = pData.getCurrentWorldData().shouldAdjustToLag(type);
53
54
        // Short term limit.
55
        if (tick < data.frequencyShortTermTick) {
56
            // Tick task got reset.
57
            data.frequencyShortTermTick = tick;
58
            data.frequencyShortTermCount = 1;
59
        }
60
        else if (tick - data.frequencyShortTermTick < cc.frequencyShortTermTicks) {
61
            // Account for server side lag.
62
            if (!lag || TickTask.getLag(50L * (tick - data.frequencyShortTermTick), true) < 1.5f) {
63
                // Within range, add.
64
                data.frequencyShortTermCount ++;
65
            }
66
            else {
67
                // Too much lag, reset.
68
                data.frequencyShortTermTick = tick;
69
                data.frequencyShortTermCount = 1;
70
            }
71
        }
72
        else {
73
            data.frequencyShortTermTick = tick;
74
            data.frequencyShortTermCount = 1;
75
        }
76
77
        // Account for server side lag for the medium term check
78
        final float fullLag = lag ? TickTask.getLag(fullTime, true) : 1f;
79
        // Find if one or both are violations:
80
        final float fullViolation = (fullScore > fullTime * fullLag) ? (fullScore - fullTime * fullLag) : 0;
81
        final float shortTermWeight = 50f * cc.frequencyShortTermTicks / (float) cc.frequencyShortTermLimit; 
82
        final float shortTermViolation = data.frequencyShortTermCount > cc.frequencyShortTermLimit ? (data.frequencyShortTermCount - cc.frequencyShortTermLimit) * shortTermWeight : 0; 
83
        final float violation = Math.max(fullViolation, shortTermViolation);
84
        boolean cancel = false;
85
        if (violation > 0.0) {
86
            final double change = violation / 1000;
87
            data.frequencyVL += change;
88
            cancel = executeActions(player, data.frequencyVL, change, cc.frequencyActions).willCancel();
89
        }
90
        else if (data.frequencyVL > 0d && fullScore < fullTime * .75) {
91
            data.frequencyVL *= 0.95;
92
        }
93
        return cancel;
94
    }
95
}

How it counteracts this module

The companion limit on blocks broken per time frame. Frequency.check scores every completed break into data.frequencyBuckets with an interval weight of 45 in survival by default and compares the window score against the bucket window duration, plus a short-term counter that allows 7 break events inside 5 ticks (frequencyShortTermLimit and frequencyShortTermTicks defaults) before adding violation weight; the configured actions start cancelling from vl 5 and escalate to a kick. The check counts break events, not tool changes, so AutoTool's slot switching contributes nothing to the counters.

The module breaks one block at a time and waits for each break to complete at the tool's rate, so a mining session stays inside both windows: the per-break cadence is the tool duration, and even a vein with instant-respawn blocks cannot exceed one break every few ticks. Only a hack that completes many blocks per tick (multi-block nuker style) accumulates the short-term counter or the full-period score.

anticheat Reach (blockbreak distance)

Reach.java83 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.blockbreak;
16
17
import org.bukkit.GameMode;
18
import org.bukkit.Location;
19
import org.bukkit.block.Block;
20
import org.bukkit.entity.Player;
21
22
import fr.neatmonster.nocheatplus.actions.ParameterName;
23
import fr.neatmonster.nocheatplus.checks.Check;
24
import fr.neatmonster.nocheatplus.checks.CheckType;
25
import fr.neatmonster.nocheatplus.checks.ViolationData;
26
import fr.neatmonster.nocheatplus.utilities.StringUtil;
27
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
28
29
/**
30
 * The Reach check will find out if a player breaks a block that's too far away.
31
 */
32
public class Reach extends Check {
33
34
    /** For temporary use: LocUtil.clone before passing deeply, call setWorld(null) after use. */
35
    private final Location useLoc = new Location(null, 0, 0, 0);
36
37
    /** The maximum distance allowed to interact with a block in creative mode. */
38
    public static final double CREATIVE_DISTANCE = 5.6D;
39
40
    /** The maximum distance allowed to interact with a block in survival mode. */
41
    public static final double SURVIVAL_DISTANCE = 5.2D;
42
43
    /**
44
     * Instantiates a new reach check.
45
     */
46
    public Reach() {
47
        super(CheckType.BLOCKBREAK_REACH);
48
    }
49
50
    /**
51
     * Checks a player.
52
     * 
53
     * @param player
54
     * @param eyeHeight 
55
     * @param block
56
     * @param data
57
     * @param cc
58
     * @return true, if successful
59
     */
60
    public boolean check(final Player player, final double eyeHeight, final Block block, final BlockBreakData data, final BlockBreakConfig cc) {
61
    	// TODO: Ray tracing-based?
62
        boolean cancel = false;
63
        final double distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : SURVIVAL_DISTANCE; 
64
        final Location loc = player.getLocation(useLoc);
65
        loc.setY(loc.getY() + eyeHeight);
66
         // Distance is calculated from eye location to center of targeted block.
67
        final double distance = TrigUtil.distance(loc, block) - distanceLimit;
68
        useLoc.setWorld(null);
69
70
        if (distance > distanceLimit) {
71
            // They failed, increment violation level.
72
            data.reachVL += distance - distanceLimit;
73
            // Execute whatever actions are associated with this check and the violation level and find out if we should
74
            // cancel the event.
75
            final ViolationData vd = new ViolationData(this, player, data.reachVL, distance, cc.reachActions);
76
            vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(distance));
77
            cancel = executeActions(vd).willCancel();
78
        } 
79
        // Player passed the check, reward them.
80
        else data.reachVL *= 0.9D;
81
        return cancel;
82
    }
83
}

How it counteracts this module

The blockbreak reach check bounds where the accelerated break can target. It computes the eye-to-block-center distance (TrigUtil.distance against the block center at 0.5 offsets) and compares it against 5.2 blocks in survival and 5.6 in creative, accumulating reachVL per out-of-range break with the standard 0.9 decay. AutoTool changes nothing about the player's position or interaction range: the tool switch happens inside the existing interaction distance, so the check constrains the module the same way it constrains a manual break.

Its role in the countering set is to close the geometry side of the fingerprint: a fast tool switch still has to happen within vanilla reach, and the module cannot extend the targeted block distance by switching. A player who combines the autotool with a reach cheat would surface here, which is the only interaction this check has with the module's behavior.

anticheat UseItemAdapter (held-slot handler)

UseItemAdapter.java438 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.net.protocollib;
16
17
import java.util.Arrays;
18
import java.util.LinkedList;
19
import java.util.List;
20
21
import org.bukkit.GameMode;
22
import org.bukkit.Material;
23
import org.bukkit.entity.HumanEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.event.Event;
26
import org.bukkit.event.EventHandler;
27
import org.bukkit.event.EventPriority;
28
import org.bukkit.event.block.Action;
29
import org.bukkit.event.entity.PlayerDeathEvent;
30
import org.bukkit.event.inventory.InventoryOpenEvent;
31
import org.bukkit.event.player.PlayerInteractEvent;
32
import org.bukkit.event.player.PlayerItemConsumeEvent;
33
import org.bukkit.event.player.PlayerItemHeldEvent;
34
import org.bukkit.event.player.PlayerRespawnEvent;
35
import org.bukkit.event.player.PlayerRiptideEvent;
36
import org.bukkit.inventory.EquipmentSlot;
37
import org.bukkit.inventory.ItemStack;
38
import org.bukkit.inventory.meta.CrossbowMeta;
39
import org.bukkit.plugin.Plugin;
40
41
import com.comphenix.protocol.PacketType;
42
import com.comphenix.protocol.events.ListenerPriority;
43
import com.comphenix.protocol.events.PacketContainer;
44
import com.comphenix.protocol.events.PacketEvent;
45
import com.comphenix.protocol.reflect.StructureModifier;
46
import com.comphenix.protocol.wrappers.EnumWrappers.PlayerDigType;
47
48
import fr.neatmonster.nocheatplus.NCPAPIProvider;
49
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
50
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
51
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
52
import fr.neatmonster.nocheatplus.compat.Bridge1_13;
53
import fr.neatmonster.nocheatplus.compat.Bridge1_9;
54
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeEnchant;
55
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeMaterial;
56
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
57
import fr.neatmonster.nocheatplus.compat.versions.ClientVersion;
58
import fr.neatmonster.nocheatplus.compat.versions.ServerVersion;
59
import fr.neatmonster.nocheatplus.components.NoCheatPlusAPI;
60
import fr.neatmonster.nocheatplus.components.registry.order.RegistrationOrder.RegisterMethodWithOrder;
61
import fr.neatmonster.nocheatplus.event.mini.MiniListener;
62
import fr.neatmonster.nocheatplus.logging.StaticLog;
63
import fr.neatmonster.nocheatplus.players.DataManager;
64
import fr.neatmonster.nocheatplus.players.IPlayerData;
65
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
66
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
67
import fr.neatmonster.nocheatplus.utilities.map.MaterialUtil;
68
69
/**
70
 * <p>Adapter for listening to packets and Bukkit events relevant to item use.</p>
71
 *
72
 * On versions 1.17 and above, the adapter will only register events related to a specific item-use exploit, 
73
 * as Bukkit provides the {@link HumanEntity#getItemInUse()} method.<br>
74
 *
75
 * <p>On versions 1.12 and above, up to 1.17, all listeners will be registered because Bukkit does not offer a way to 
76
 * determine <em>which</em> item is in use; we can only detect if a player is using an item through {@link HumanEntity#isHandRaised()}.</p>
77
 *
78
 * The {@link PlayerRespawnEvent} is always listened to in order to fix a specific item desynchronization issue.
79
 */
80
public class UseItemAdapter extends BaseAdapter {
81
    
82
    private final static String dftag = "system.nocheatplus.useitemadapter";
83
        
84
    // All relevant Bukkit events for item-use.
85
    private final static MiniListener<?>[] miniListeners = new MiniListener<?>[] {
86
        new MiniListener<PlayerItemConsumeEvent>() {
87
            @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
88
            @RegisterMethodWithOrder(tag = dftag)
89
            @Override
90
            public void onEvent(final PlayerItemConsumeEvent event) {
91
                onItemConsume(event);
92
            }
93
        },
94
        new MiniListener<PlayerInteractEvent>() {
95
            @EventHandler(priority = EventPriority.MONITOR)
96
            @RegisterMethodWithOrder(tag = dftag)
97
            @Override
98
            public void onEvent(final PlayerInteractEvent event) {
99
                onItemInteract(event);
100
            }
101
        },
102
        new MiniListener<InventoryOpenEvent>() {
103
            @EventHandler(priority = EventPriority.LOWEST)
104
            @RegisterMethodWithOrder(tag = dftag)
105
            @Override
106
            public void onEvent(final InventoryOpenEvent event) {
107
                onInventoryOpen(event);
108
            }
109
        },
110
        new MiniListener<PlayerDeathEvent>() {
111
            @EventHandler(priority = EventPriority.MONITOR)
112
            @RegisterMethodWithOrder(tag = dftag)
113
            @Override
114
            public void onEvent(final PlayerDeathEvent event) {
115
                onDeath(event);
116
            }
117
        },
118
        new MiniListener<PlayerItemHeldEvent>() {
119
            @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
120
            @RegisterMethodWithOrder(tag = dftag)
121
            @Override
122
            public void onEvent(final PlayerItemHeldEvent event) {
123
                onChangeSlot(event);
124
            }
125
        },
126
    };
127
128
    private static int timeBetweenRL = 70;
129
130
    private static PacketType[] initPacketTypes() {
131
        // Only interested in these two packets.
132
        final List<PacketType> types = new LinkedList<PacketType>(Arrays.asList(PacketType.Play.Client.BLOCK_DIG, PacketType.Play.Client.BLOCK_PLACE));
133
        return types.toArray(new PacketType[types.size()]);
134
    }
135
136
    public UseItemAdapter(Plugin plugin) {
137
        super(plugin, ListenerPriority.MONITOR, initPacketTypes());
138
        final NoCheatPlusAPI api = NCPAPIProvider.getNoCheatPlusAPI();
139
        if (!BridgeMisc.hasGetItemInUseMethod()) {
140
            // getItemInUse() isn't there, register all events
141
            if (Bridge1_13.hasPlayerRiptideEvent()) {
142
                // Only register this one if available.
143
                final MiniListener<?> riptideListener = new MiniListener<PlayerRiptideEvent>() {
144
                    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
145
                    @RegisterMethodWithOrder(tag = dftag)
146
                    @Override
147
                    public void onEvent(final PlayerRiptideEvent event) {
148
                        onTridentRelease(event);
149
                   }
150
                };
151
                api.addComponent(riptideListener, false);
152
            }
153
            // ...All the other listeners
154
            for (final MiniListener<?> listener : miniListeners) {
155
                api.addComponent(listener, false);
156
            }
157
        }
158
        // Always register this event, because it is used to fix an MC/Bukkit glitch, not for item-use setting.
159
        final MiniListener<?> respawningListener = new MiniListener<PlayerRespawnEvent>() {
160
            @EventHandler(priority = EventPriority.MONITOR)
161
            @RegisterMethodWithOrder(tag = dftag)
162
            @Override
163
            public void onEvent(final PlayerRespawnEvent event) {
164
                onRespawning(event);
165
            }
166
        };
167
        api.addComponent(respawningListener, false);
168
    }
169
170
    @Override
171
    public void onPacketReceiving(final PacketEvent event) {
172
        // Fast return tests first.
173
        try {
174
            if (event.isPlayerTemporary()) return;
175
        } 
176
        catch (NoSuchMethodError e) {
177
            if (event.getPlayer() == null) {
178
                counters.add(ProtocolLibComponent.idNullPlayer, 1);
179
                return;
180
            }
181
            if (DataManager.getPlayerDataSafe(event.getPlayer()) == null) {
182
                StaticLog.logWarning("Failed to fetch player data with " + event.getPacketType() + " for: " + event.getPlayer().toString());
183
                return;
184
            }
185
        }
186
        if (BridgeMisc.hasGetItemInUseMethod()) {
187
            // getItemInUse() is already there. Only check the digging packet for exploitation prevention purposes.
188
            if (event.getPacketType().equals(PacketType.Play.Client.BLOCK_DIG)) {
189
                handleDiggingPacket(event);
190
            }
191
            // Don't need to do anything else.
192
            return;
193
        }
194
        
195
        // getItemInUse() ins't there: do the ordinary stuff.
196
        if (event.getPacketType().equals(PacketType.Play.Client.BLOCK_DIG)) {
197
            handleDiggingPacket(event);
198
        }
199
        else handleBlockPlacePacket(event);
200
    }
201
    
202
    /** Attempt to fix server-side-only blocking after respawn. */
203
    private static void onRespawning(final PlayerRespawnEvent e) {
204
        final IPlayerData pData = DataManager.getPlayerData(e.getPlayer());
205
        // Patch up issues on Bukkit's (Minecraft's ?) side (item has been reset already on death).
206
        if (Bridge1_9.hasGetItemInOffHand() && e.getPlayer().isBlocking()) {
207
            pData.requestItemUseResync();
208
        }
209
    }
210
211
    private static void onTridentRelease(final PlayerRiptideEvent e) {
212
        final IPlayerData pData = DataManager.getPlayerData(e.getPlayer());
213
        // This event is called on releasing the trident (See ItemTrident.java), so the item is not in use anymore.
214
        pData.setItemInUse(null);
215
    }
216
217
    private static void onItemConsume(final PlayerItemConsumeEvent e) {
218
        final Player p = e.getPlayer();
219
        final IPlayerData pData = DataManager.getPlayerData(p);
220
        // Consume(d) (!!), so the player isn't using the item anymore
221
        pData.setItemInUse(null);   
222
    }
223
224
    private static void onInventoryOpen(final InventoryOpenEvent e) {
225
        if (e.isCancelled()) return;
226
        final Player p = (Player) e.getPlayer();
227
        final IPlayerData pData = DataManager.getPlayerData(p);
228
        // Can't use item with an inventory open.
229
        pData.setItemInUse(null);
230
    }
231
232
    private static void onDeath(final PlayerDeathEvent e) {
233
        final IPlayerData pData = DataManager.getPlayerData((Player) e.getEntity());
234
        // Can't use item if dead
235
        pData.setItemInUse(null);  
236
    }
237
238
    @SuppressWarnings("deprecation")
239
	private static void onItemInteract(final PlayerInteractEvent e) {
240
        if (e.getAction() != Action.RIGHT_CLICK_AIR && e.getAction() != Action.RIGHT_CLICK_BLOCK) {
241
            return;
242
        }
243
        final Player p = e.getPlayer();
244
        final IPlayerData pData = DataManager.getPlayerData(p);
245
        final MovingConfig mCC = pData.getGenericInstance(MovingConfig.class);
246
        final CombinedData data = pData.getGenericInstance(CombinedData.class);
247
        data.offHandUse = false;
248
        if (!data.mightUseItem) {
249
            // Player did not send the block-placement packet, so they are for sure not using anything, return.
250
            return;
251
        }
252
        // Do reset the flag at the start (!)
253
        data.mightUseItem = false;
254
255
        if (e.useItemInHand().equals(Event.Result.DENY)) {
256
            // A plugin denied the item-use.
257
            return;
258
        }
259
260
        if (p.getGameMode() == GameMode.CREATIVE) {
261
            // TODO: If merging SurvivalFly and CreativeFly, creative mode needs to be taken into consideration as well.
262
            pData.setItemInUse(null);
263
            return;
264
        }
265
        
266
        // Proceed to check...
267
        if (e.hasItem()) {
268
            final ItemStack item = e.getItem();
269
            final Material m = item.getType();
270
            if (Bridge1_9.hasElytra() && p.hasCooldown(m)) {
271
                // Item is in cooldown so it cannot be used.
272
                return;
273
            }
274
            
275
            // Edible / consumable items...
276
            if (InventoryUtil.isConsumable(item)) {
277
                if (!Bridge1_9.hasElytra() && item.getDurability() > 16384) {
278
                    // pre1.9 splash potion edge case.
279
                    return;
280
                }
281
                if (m == Material.POTION || m == Material.MILK_BUCKET || m.toString().endsWith("_APPLE") || m.name().startsWith("HONEY_BOTTLE")) {
282
                    // Can be consumed regardless of hunger level
283
                    pData.setItemInUse(m);
284
                    data.offHandUse = Bridge1_9.hasGetItemInOffHand() && e.getHand() == EquipmentSlot.OFF_HAND;
285
                    return;
286
                }
287
                if (item.getType().isEdible() && p.getFoodLevel() < 20) {
288
                    // Hunger level dependant consumables.
289
                    pData.setItemInUse(m); 
290
                    data.offHandUse = Bridge1_9.hasGetItemInOffHand() && e.getHand() == EquipmentSlot.OFF_HAND;
291
                    return;
292
                }
293
            }
294
            // Bows...
295
            if (m == Material.BOW && InventoryUtil.hasArrow(p.getInventory(), false)) {
296
                pData.setItemInUse(m);
297
                data.offHandUse = Bridge1_9.hasGetItemInOffHand() && e.getHand() == EquipmentSlot.OFF_HAND;
298
                return;
299
            }
300
            // Shields and swords (legacy)... Bukkit takes care here, but set anyway.
301
            if (ServerVersion.isAtLeast("1.9") && pData.getClientVersion().isAtLeast(ClientVersion.V_1_9)) {
302
                // Both server and client are on a version that support shield (thus, sword-blocking is not possible)
303
            	if (m == Material.SHIELD) {
304
            	    pData.setItemInUse(m);
305
                    data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
306
                    return;
307
            	}
308
            }
309
            else if (MaterialUtil.isSword(m) && (ServerVersion.isLowerThan("1.9") || pData.getClientVersion().isAtMost(ClientVersion.V_1_8))) {
310
            	// Legacy server. Or legacy client on a modern server. Blocking is done with swords in both cases.
311
            	pData.setItemInUse(m);
312
            	// (Off hand doesn't exist)
313
            	return;
314
            }
315
            
316
            // Crosswbows...
317
            if (m.toString().equals("CROSSBOW")) {
318
                if (!((CrossbowMeta) item.getItemMeta()).hasChargedProjectiles() && InventoryUtil.hasArrow(p.getInventory(), true)) {
319
                    pData.setItemInUse(m);
320
                    data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
321
                }
322
            }
323
            // Tridents (1.13)... 
324
            if (m == BridgeMaterial.TRIDENT && item.getDurability() < m.getMaxDurability() - 1 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_13)
325
            	&& (
326
                    // 1: If the trident has riptide enchant, it can only be used in rain or water 
327
            		BridgeEnchant.getRiptideLevel(p) > 0.0
328
                    && (
329
                        // 2: In water
330
                        BlockProperties.isInWater(p, p.getLocation(), mCC.yOnGround)
331
                        // 2: Always check raining first, since canSeeSky is a much more expensive call. Needs optimization.
332
                        || p.getLocation().getWorld().hasStorm() && BlockProperties.canSeeSky(p, p.getLocation(), mCC.yOnGround) 
333
                    ) 
334
                    // 1: Otherwise, the trident can be used and thrown anywhere
335
                    || BridgeEnchant.getRiptideLevel(p) <= 0.0
336
                )) {
337
                pData.setItemInUse(m);
338
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
339
                return;
340
            }
341
            // Spyglass (1.17)...
342
            if (BridgeMisc.hasIsFrozen() && m == Material.SPYGLASS) {
343
                pData.setItemInUse(m);
344
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
345
                return;
346
            }
347
            // Lastly, goat horns (1.19)...
348
            if (m.toString().equals("GOAT_HORN")) {
349
                pData.setItemInUse(m);
350
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
351
                return;
352
            }
353
            // 1.21.11: Spears...
354
            if (MaterialUtil.isSpear(m)) {
355
                pData.setItemInUse(m);
356
                data.offHandUse = e.getHand() == EquipmentSlot.OFF_HAND;
357
            }
358
        } 
359
        else {
360
            // No item in hands, no deal.
361
            pData.setItemInUse(null);  
362
        }
363
    }
364
    
365
    // NOTE: Bukkit takes care of invalid slot values (< 0 or > 8. PlayerConnection.java), so we don't need to check for this as well.
366
    private static void onChangeSlot(final PlayerItemHeldEvent e) {
367
        final Player p = e.getPlayer();
368
        final IPlayerData pData = DataManager.getPlayerData(p);
369
        // Switching a slot, so the item use status is reset.
370
        final MovingData mData = pData.getGenericInstance(MovingData.class);
371
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
372
        if (e.getPreviousSlot() != e.getNewSlot()) {
373
            /*if ((pData.getItemInUse() != null || p.isBlocking()) && mData.playerMoves.getCurrentMove() != null) {
374
                p.getInventory().setHeldItemSlot(e.getPreviousSlot());
375
                cData.invalidItemUse = true;
376
            }*/
377
            // To avoid any more potential bypasses, let Minecraft forcibly release the item.
378
            pData.requestItemUseResync();
379
        }
380
    }
381
382
    private void handleBlockPlacePacket(PacketEvent event) {
383
        final Player p = event.getPlayer();
384
        final IPlayerData pData = DataManager.getPlayerData(p);
385
        final CombinedData data = pData.getGenericInstance(CombinedData.class);
386
        final PacketContainer packet = event.getPacket();
387
        final StructureModifier<Integer> ints = packet.getIntegers();
388
        // Legacy: pre 1.9
389
        if (ints.size() > 0 && !ServerVersion.isAtLeast("1.9")) {
390
            final int faceIndex = ints.read(0); // arg 3 if 1.7.10 below
391
            if (faceIndex <= 5) {
392
                data.mightUseItem = false;
393
                return;
394
            }
395
        }
396
        // Player sends a block-placement item when right-clicking, so they might be actually using an item. Set the flag.
397
        if (!event.isCancelled()) data.mightUseItem = true;
398
    }
399
400
    private void handleDiggingPacket(PacketEvent event) {
401
        Player p = event.getPlayer();       
402
        final IPlayerData pData = DataManager.getPlayerDataSafe(p);
403
        final CombinedData data = pData.getGenericInstance(CombinedData.class);
404
        PlayerDigType digtype = event.getPacket().getPlayerDigTypes().read(0);
405
        if (!BridgeMisc.hasGetItemInUseMethod()) {
406
            // DROP_ALL_ITEMS when dead?
407
            if (digtype == PlayerDigType.DROP_ALL_ITEMS || digtype == PlayerDigType.DROP_ITEM) {
408
                pData.setItemInUse(null);
409
            }
410
        }
411
        
412
        if (digtype == PlayerDigType.RELEASE_USE_ITEM) {
413
            pData.setItemInUse(null);
414
            long now = System.currentTimeMillis();
415
            if (data.releaseItemTime != 0) {
416
                if (now < data.releaseItemTime) {
417
                    data.releaseItemTime = now;
418
                    return;
419
                }
420
                if (data.releaseItemTime + timeBetweenRL > now) {
421
                    data.isHackingRI = true;
422
                }
423
            }
424
            data.releaseItemTime = now;
425
        }
426
    }
427
428
    /**
429
     * Set Minimum time between RELEASE_USE_ITEM packet is sent.
430
     * If time lower this value, A check will flag
431
     * Should be set from 51-100. Larger number, more protection more false-positive
432
     * 
433
     * @param time milliseconds
434
     */ 
435
    public static void setuseRLThreshold(int time) {
436
        timeBetweenRL = time;
437
    }   
438
}

How it counteracts this module

The only NCP code that reacts to a held-slot change in this tree is the protocol adapter's onChangeSlot: on PlayerItemHeldEvent with a real previous-to-new slot difference it calls pData.requestItemUseResync(), which forcibly releases whatever item the player is mid-use of, replacing an older commented-out branch that reverted the slot with setHeldItemSlot. The intent is to close the no-slowdown family of bypasses where a player switches slots while using an item to drop the use state; the adapter keys on the change event, not on the pairing with digging.

AutoTool's switches happen outside any item use: the tool swap precedes the break and the sword restore follows it, so the resync never fires and the adapter stays inert. The blockplace Scaffold check has a ToolSwitch sub-check, but it only compares the held slot between block placements and is never invoked from the digging path. The honest gap: no NCP check in this tree scores the C09-to-C07 pairing that is the module's actual fingerprint, so the countering pressure on a stock NCP setup is the break-speed, break-count and reach envelope rather than any tool-specific detector.

← Back to Analysis Hub