Nekoware v1 private Switch Aura module 2 files, 157 lines

Nekoware v1 private Switch Aura: Full Source Analysis

SwitchAura is the multi-target mode of Nekoware's Aura module, with a randomized click-speed draw, a C07 release before each hit and a block re-arm that is a local flag only: no C08 arm packet…

me/nekoWare/client/module/combat/aura/SwitchAura.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-08-13

Packets This Module Uses

Analysis

Overview

SwitchAura is the multi-target mode of Nekoware's Aura module, with a randomized click-speed draw, a C07 release before each hit and a block re-arm that is a local flag only: no C08 arm packet is ever sent, so the server-side blocking state never exists and the releases are unsolicited. The wire carries periodic C02 attacks and C0A swings plus the stray C07s, and the pre-motion rotation keeps the C03 look aligned with each target.

Randomized cadence

The click speed is drawn per attack cycle: when the Click Speed setting (default 12, range 1-20) exceeds 2, the effective rate is MathUtils.getRandom(cps - 2, cps), a uniform draw in [cps-2, cps) via a fresh Random, so at the default the period jitters between roughly 10 and 12 attacks per second. The static Timer is a real period with reset(), anchored at class load like SingleAura's, so the first attack fires on the first expired pre-motion event after enable. On each expiry the pre-motion branch sends C07 RELEASE_USE_ITEM (BlockPos.ORIGIN, face DOWN) when autoBlock and Aura.isBlocking hold, then swings and queues a C02 ATTACK through sendQueue.addToSendQueue, which flushes at the end of the tick.

Phantom blocking

The post-motion branch re-arms blocking by setting the shared static Aura.isBlocking to true when canBlockSword passes, but nothing sends a C08PacketPlayerBlockPlacement: the server never transitions to the using-item state, so the C07 releases in the next cycle are releases without a preceding use, which vanilla processPlayerDigging just consumes as a no-op item-use clear. When the target disappears, stopServerBlocking emits one final C07 release. The Auto Block setting is therefore cosmetic: no server-side blocking, no damage reduction, and the releases are the only autoblock artifact on the wire.

Rotation

Like SingleAura, the aim comes from RotationUtils.getRotations (target eye height halved) and is written into the pre-motion update yaw and pitch, carried by that tick's C03, plus rotationYawHead, rotationPitchHead and renderYawOffset. Because the mode re-targets every cycle and getTarget returns the first in-range entity in list order, the rotation snaps between whatever entity happens to lead the list when the timer expires, giving the switch pattern its name.

source SwitchAura.java

SwitchAura.java85 lines · JavaOriginal ↗
1
2
package me.nekoWare.client.module.combat.aura;
3
4
import org.apache.commons.lang3.RandomUtils;
5
6
import me.nekoWare.client.event.events.UpdateEvent;
7
import me.nekoWare.client.module.combat.Aura;
8
import me.nekoWare.client.util.combat.CombatUtil;
9
import me.nekoWare.client.util.combat.RotationUtils;
10
import me.nekoWare.client.util.misc.Timer;
11
import net.minecraft.client.Minecraft;
12
import net.minecraft.entity.Entity;
13
import net.minecraft.entity.EntityLivingBase;
14
import net.minecraft.item.ItemSword;
15
import net.minecraft.network.play.client.C02PacketUseEntity;
16
import net.minecraft.network.play.client.C07PacketPlayerDigging;
17
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
18
import net.minecraft.util.BlockPos;
19
import net.minecraft.util.EnumFacing;
20
import optifine.MathUtils;
21
22
public class SwitchAura {
23
	private static Timer timer = new Timer();
24
	private static boolean block, stopServerBlocking;
25
26
	public static void doUpdate(final Aura aura, final UpdateEvent e, final Minecraft mc) {
27
		boolean invisible = aura.getBool("Invisibles");
28
		double range = aura.getDouble("Range");
29
		boolean players = aura.getBool("Players");
30
		boolean monsters = aura.getBool("Monsters");
31
		boolean teams = false;
32
		final Entity entity = CombatUtil.getTarget(teams, monsters, players, range, invisible);
33
		final boolean autoBlock = aura.getBool("Auto Block");
34
		final long clickSpeed = aura.getDouble("Click Speed").longValue() <= 2
35
				? aura.getDouble("Click Speed").longValue()
36
				: ((long) MathUtils.getRandom(aura.getDouble("Click Speed").longValue() - 2,
37
						aura.getDouble("Click Speed").longValue()));
38
		boolean doBlock = mc.thePlayer.getHeldItem() != null
39
				&& mc.thePlayer.getHeldItem().getItem() instanceof ItemSword && autoBlock
40
				&& CombatUtil.canBlock(teams, false, true, range + 0.3, true);
41
		boolean canBlockSword = (mc.thePlayer.getHeldItem() != null) && ((mc.thePlayer.isBlocking())
42
				|| ((mc.thePlayer.isUsingItem())
43
						&& ((mc.thePlayer.getCurrentEquippedItem().getItem() instanceof ItemSword)))
44
				|| (((mc.thePlayer.getHeldItem().getItem() instanceof ItemSword))
45
						&& (mc.gameSettings.keyBindUseItem.pressed))
46
				|| ((mc.thePlayer.getHeldItem().getItem() instanceof ItemSword)));
47
48
		Aura.currentEntity = (EntityLivingBase) entity;
49
50
		if (entity == null && stopServerBlocking && autoBlock) {
51
			mc.thePlayer.sendQueue.addToSendQueue(new C07PacketPlayerDigging(
52
					C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
53
			Aura.isBlocking = false;
54
		}
55
56
		if (entity != null) {
57
			stopServerBlocking = true;
58
        	if(Aura.Rots == true) {
59
			float[] rotations = RotationUtils.getRotations((EntityLivingBase) entity);
60
			e.setYaw(rotations[0]);
61
			e.setPitch(rotations[1]);
62
			mc.thePlayer.rotationYawHead = rotations[0];
63
			mc.thePlayer.rotationPitchHead = rotations[1];
64
			mc.thePlayer.renderYawOffset = rotations[0];
65
        	}
66
			if (e.isPre()) {
67
				if (timer.delay(1000 / clickSpeed)) {
68
					if (autoBlock && Aura.isBlocking) {
69
						mc.thePlayer.sendQueue.addToSendQueue(new C07PacketPlayerDigging(
70
								C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
71
						Aura.isBlocking = false;
72
					}
73
					mc.thePlayer.swingItem();
74
					mc.thePlayer.sendQueue
75
							.addToSendQueue(new C02PacketUseEntity(entity, C02PacketUseEntity.Action.ATTACK));
76
					timer.reset();
77
				}
78
			} else if (e.isPost()) {
79
				if (autoBlock && !Aura.isBlocking && canBlockSword) {
80
					Aura.isBlocking = true;
81
				}
82
			}
83
		}
84
	}
85
}

What this file does

The mode: the randomized click-speed draw, the pre-motion C07 release plus C02 attack, the post-motion local-only block re-arm that never sends C08, and the target-loss release cleanup.

source Aura.java (parent dispatcher)

Aura.java72 lines · JavaOriginal ↗
1
2
package me.nekoWare.client.module.combat;
3
4
import java.util.function.Consumer;
5
6
import me.hippo.api.lwjeb.annotation.Handler;
7
import me.nekoWare.client.event.events.UpdateEvent;
8
import me.nekoWare.client.module.Module;
9
import me.nekoWare.client.module.combat.aura.MultiAura;
10
import me.nekoWare.client.module.combat.aura.SingleAura;
11
import me.nekoWare.client.module.combat.aura.SwitchAura;
12
import me.nekoWare.client.util.packet.PacketUtil;
13
import net.minecraft.entity.EntityLivingBase;
14
import net.minecraft.network.play.client.C07PacketPlayerDigging;
15
import net.minecraft.util.BlockPos;
16
import net.minecraft.util.EnumFacing;
17
18
public class Aura extends Module {
19
20
	public static boolean isBlocking;
21
	public static EntityLivingBase currentEntity;
22
23
	public Aura() {
24
		super("KillAura", 19, Module.Category.COMBAT);
25
		addModes("Single", "Switch", "Multi");
26
		addInt("Click Speed", 12.0, 1.0, 20.0);
27
		addInt("Block Chance", 100.0, 1.0, 100.0);
28
		addDouble("Range", 4, 3.0, 6.0);
29
		addBoolean("Rots", true);
30
		addBoolean("Auto Block", true);
31
		addBoolean("Auto Block2", true);
32
		addBoolean("Keep Sprint", true);
33
		addBoolean("Players", true);
34
		addBoolean("Animals", true);
35
		addBoolean("Monsters", true);
36
		addBoolean("Invisibles", true);
37
		addBoolean("Teams", true);
38
	}
39
	
40
	public static boolean Rots;
41
42
	@Handler
43
	public Consumer<UpdateEvent> onUpdate = (event) -> {
44
		
45
		if(this.getBool("Rots") == true) {
46
			Rots = true;
47
		}else {
48
			Rots = false;
49
		}
50
		
51
		
52
		if (isMode("Single")) {
53
			SingleAura.doUpdate(this, event, mc);
54
		}
55
		if (isMode("Multi")) {
56
			MultiAura.doUpdate(this, event, mc);
57
		}
58
		if (isMode("Switch")) {
59
			SwitchAura.doUpdate(this, event, mc);
60
		}
61
	};
62
63
	@Override
64
	public void onDisable() {
65
		isBlocking = false;
66
		currentEntity = null;
67
		if (SingleAura.unblock) {
68
			PacketUtil.sendPacket(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM,
69
					new BlockPos(0.221, 0.221, 0.213), EnumFacing.UP));
70
		}
71
	}
72
}

What this file does

The parent module that routes modes and owns the shared state: isMode routing to SingleAura, SwitchAura and MultiAura, the settings (Click Speed, Range, Rots, Auto Block, target filters) the mode reads through getBool and getDouble, and onDisable, which reads SingleAura.unblock to emit its release packet.

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 (post-look 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's Reach queues each C02 attack with the player's position and scores it on the next look update: the eye position is ray-traced against the compensated entity box (threshold 0.0005, plus 0.1 hitbox margin for 1.8 clients and the movement threshold), and any intercept distance above the server attribute reach (3.0) flags, with a cancelBuffer that aggressively cancels the next four hits after one flag. The module's Range setting spans 3.0-6.0, so hits from the outer band flag at the attack tick while close-in hits pass. The pre-motion rotation does not help: the check measures distance, not angle.

anticheat FightHitbox (deferred combat ray)

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

FightHitbox stores each InteractEntityEvent and performs the ray trace on the next MoveEvent because 1.8 sends the attack before the yaw update; for 1.8 clients it uses the HawkPlayer's own yaw with the victim at the lag-compensated history location, and maxReach defaults to 3.1 with the eye at +1.62. The module's pre-motion rotation puts the C03 look exactly on the target, so the ray hits the box, and any hit whose eye-to-box distance exceeds 3.1 flags. At the default Range 4 this is a real counter: center-to-center distance 4 with a 0.6-wide victim leaves roughly 3.4 to the box edge, over the 3.1 bound, so the switch mode cannot attack at its configured reach without tripping it.

anticheat Fight Direction (attack-ray alignment)

Direction.java239 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
import org.bukkit.Location;
18
import org.bukkit.entity.Entity;
19
import org.bukkit.entity.LivingEntity;
20
import org.bukkit.entity.Player;
21
import org.bukkit.util.Vector;
22
23
import fr.neatmonster.nocheatplus.checks.Check;
24
import fr.neatmonster.nocheatplus.checks.CheckType;
25
import fr.neatmonster.nocheatplus.checks.moving.location.tracking.LocationTrace.ITraceEntry;
26
import fr.neatmonster.nocheatplus.compat.MCAccess;
27
import fr.neatmonster.nocheatplus.utilities.collision.CollisionUtil;
28
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
29
30
/**
31
 * The Direction check will find out if a player tried to interact with something that's not in their field of view.
32
 */
33
public class Direction extends Check {
34
35
    /**
36
     * Instantiates a new direction check.
37
     */
38
    public Direction() {
39
        super(CheckType.FIGHT_DIRECTION);
40
    }
41
42
    /**
43
     * "Classic" check.
44
     * 
45
     * @param player
46
     *            the player
47
     * @param damaged
48
     *            the damaged
49
     * @return true, if successful
50
     */
51
    public boolean check(final Player player, final Location loc, 
52
            final Entity damaged, final boolean damagedIsFake, final Location dLoc, 
53
            final FightData data, final FightConfig cc) {
54
        boolean cancel = false;
55
56
        final MCAccess mcAccess = this.mcAccess.getHandle();
57
58
        // Safeguard, if entity is complex, this check will fail due to giant and hard to define hitboxes.
59
        //        if (damaged instanceof EntityComplex || damaged instanceof EntityComplexPart)
60
        if (!damagedIsFake && mcAccess.isComplexPart(damaged)) {
61
            return false;
62
        }
63
64
        // Find out how wide the entity is.
65
        final double width = damagedIsFake ? 0.6 : mcAccess.getWidth(damaged);
66
67
        // entity.height is broken and will always be 0, therefore. Calculate height instead based on boundingBox.
68
        final double height = damagedIsFake ? (damaged instanceof LivingEntity ? ((LivingEntity) damaged).getEyeHeight() : 1.75) : mcAccess.getHeight(damaged);
69
        
70
71
        // TODO: allow any hit on the y axis (might just adapt interface to use foot position + height)!
72
73
        // How far "off" is the player with their aim. We calculate from the players eye location and view direction to
74
        // the center of the target entity. If the line of sight is more too far off, "off" will be bigger than 0.
75
        final Vector direction = loc.getDirection();
76
77
        final double off;
78
		off = CollisionUtil.directionCheck(loc, player.getEyeHeight(), direction, dLoc.getX(), dLoc.getY() + height / 2D, dLoc.getZ(), width, height, TrigUtil.DIRECTION_PRECISION);
79
        /*if (cc.directionStrict){
80
            off = CollisionUtil.combinedDirectionCheck(loc, player.getEyeHeight(), direction, dLoc.getX(), dLoc.getY() + height / 2D, dLoc.getZ(), width, height, TrigUtil.DIRECTION_PRECISION, 80.0, isPlayer);
81
        }
82
        else{
83
            // Also take into account the angle.
84
            off = CollisionUtil.directionCheck(loc, player.getEyeHeight(), direction, dLoc.getX(), dLoc.getY() + height / 2D, dLoc.getZ(), width, height, TrigUtil.DIRECTION_PRECISION);
85
        } */
86
87
        if (off > 0.1) {
88
            // Player failed the check. Let's try to guess how far they were from looking directly to the entity...
89
            final Vector blockEyes = new Vector(dLoc.getX() - loc.getX(),  dLoc.getY() + height / 2D - loc.getY() - player.getEyeHeight(), dLoc.getZ() - loc.getZ());
90
            final double distance = blockEyes.crossProduct(direction).length() / direction.length();
91
92
            // Add the overall violation level of the check.
93
            data.directionVL += distance;
94
            // Execute whatever actions are associated with this check and the violation level and find out if we should
95
            // cancel the event.
96
            cancel = executeActions(player, data.directionVL, distance, cc.directionActions).willCancel();
97
98
            if (cancel) {
99
                // Deal an attack penalty time.
100
                data.attackPenalty.applyPenalty(cc.directionPenalty);
101
            }
102
        } else {
103
            // Reward the player by lowering their violation level.
104
            data.directionVL *= 0.8D;
105
        }
106
107
        return cancel;
108
    }
109
110
    /**
111
     * Data context for iterating over TraceEntry instances.
112
     * @param player
113
     * @param loc
114
     * @param damaged
115
     * @param damagedLoc
116
     * @param data
117
     * @param cc
118
     * @return
119
     */
120
    public DirectionContext getContext(final Player player, final Location loc, 
121
            final Entity damaged, final boolean damagedIsFake, final Location damagedLoc, 
122
            final FightData data, final FightConfig cc) {
123
        final DirectionContext context = new DirectionContext();
124
        // Find out how wide the entity is.
125
        if (damagedIsFake) {
126
            // Assume player / default.
127
            context.damagedComplex = false; // Later prefer bukkit based provider.
128
        }
129
        else {
130
            final MCAccess mcAccess = this.mcAccess.getHandle();
131
            context.damagedComplex = mcAccess.isComplexPart(damaged);
132
        }
133
        context.direction = loc.getDirection();
134
        context.lengthDirection = context.direction.length();
135
        return context;
136
    }
137
138
    /**
139
     * Check if the player fails the direction check, no change of FightData.
140
     * @param player
141
     * @param loc
142
     * @param damaged
143
     * @param dLoc
144
     * @param context
145
     * @param data
146
     * @param cc
147
     * @return
148
     */
149
    public boolean loopCheck(final Player player, final Location loc, 
150
            final Entity damaged, final ITraceEntry dLoc, 
151
            final DirectionContext context, 
152
            final FightData data, final FightConfig cc) {
153
154
        // Ignore complex entities for the moment.
155
        if (context.damagedComplex) {
156
            // TODO: Revise :p
157
            return false;
158
        }
159
        boolean cancel = false;
160
        boolean isPlayer = damaged instanceof Player;
161
162
        // TODO: allow any hit on the y axis (might just adapt interface to use foot position + height)!
163
164
        // How far "off" is the player with their aim. We calculate from the players eye location and view direction to
165
        // the center of the target entity. If the line of sight is more too far off, "off" will be bigger than 0.
166
        final double damagedBoxMarginHorizontal = dLoc.getBoxMarginHorizontal();
167
        final double damagedBoxMarginVertical = dLoc.getBoxMarginVertical();
168
        final double off;
169
        if (cc.directionStrict){
170
            off = CollisionUtil.combinedDirectionCheck(loc, player.getEyeHeight(), context.direction, dLoc.getX(), dLoc.getY() + damagedBoxMarginVertical / 2D, dLoc.getZ(), damagedBoxMarginHorizontal * 2.0, damagedBoxMarginVertical, cc.directionloopprecision, cc.directionangleprecision, isPlayer);
171
        }
172
        else {
173
            // Also take into account the angle.
174
            off = CollisionUtil.directionCheck(loc, player.getEyeHeight(), 
175
                    context.direction, dLoc.getX(), 
176
                    dLoc.getY() + damagedBoxMarginVertical / 2D, dLoc.getZ(), 
177
                    damagedBoxMarginHorizontal * 2.0, damagedBoxMarginVertical, 
178
                    cc.directionloopprecision);
179
        }
180
181
        if (off > 0.0) {
182
            if (dLoc.isInside(loc.getX(), loc.getY() + player.getEyeHeight(), loc.getZ())) { // Inside box.
183
                context.minResult = 0.0;
184
            }
185
            else {
186
                if (off > 0.11) {
187
                    // Player failed the check. Let's try to guess how far they were from looking directly to the entity...
188
                    final Vector blockEyes = new Vector(dLoc.getX() - loc.getX(),  dLoc.getY() + damagedBoxMarginVertical / 2D - loc.getY() - player.getEyeHeight(), dLoc.getZ() - loc.getZ());
189
                    final double distance = blockEyes.crossProduct(context.direction).length() / context.lengthDirection;
190
                    context.minViolation = Math.min(context.minViolation, distance);
191
                    cancel = true;
192
                }
193
                context.minResult = Math.min(context.minResult, off);
194
            }
195
        } 
196
        else if (cc.directionFailAll) {
197
            context.minResult = 0.0;
198
        }
199
200
        return cancel;
201
    }
202
203
    /**
204
     * Apply changes to FightData according to check results (context), trigger violations.
205
     * @param player
206
     * @param loc
207
     * @param damaged
208
     * @param context
209
     * @param forceViolation
210
     * @param data
211
     * @param cc
212
     * @return
213
     */
214
    public boolean loopFinish(final Player player, final Location loc, final Entity damaged, final DirectionContext context, final boolean forceViolation, final FightData data, final FightConfig cc) {
215
        boolean cancel = false;
216
        final double off = forceViolation && context.minViolation != Double.MAX_VALUE ? context.minViolation : context.minResult;
217
        if (off == Double.MAX_VALUE) {
218
            return false;
219
        }
220
        else if (off > 0.1) {
221
            // Add the overall violation level of the check.
222
            data.directionVL += off;
223
224
            // Execute whatever actions are associated with this check and the violation level and find out if we should
225
            // cancel the event.
226
            cancel = executeActions(player, data.directionVL, off, cc.directionActions).willCancel();
227
228
            if (cancel) {
229
                // Deal an attack penalty time.
230
                data.attackPenalty.applyPenalty(cc.directionPenalty);
231
            }
232
        }
233
        else {
234
            // Reward the player by lowering their violation level.
235
            data.directionVL *= 0.8D;
236
        }
237
        return cancel;
238
    }
239
}

How it counteracts this module

Direction runs a combinedDirectionCheck ray from the player's eye position against the damaged entity's box with the configured loop and angle precision, and it is the alignment check for the attack stream: the C03-carried look must point at the victim. Because the module writes its aim pre-motion, each C02 lands with a matching look and the ray hits, so the check rewards while Rots is on; with Rots off, the divergence between real look and attack target accumulates violation. The entry is the honest boundary: the module's own rotation is what keeps this check and Hawk's direction checks quiet.

anticheat KillAura Speed ledger (C02 rate)

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

The Speed ledger is where this mode differs from SingleAura: checkFrequency counts C02 ATTACK packets against max-attack-packets (20/s) at receipt, and the damage-event path counts every C02 USE_ENTITY into totalAttacks against max-attacks (16/s). At Click Speed 20 the randomized draw of 18-20 attacks per second pushes totalAttacks over 16 each second once damage events land, so the maxed setting trips the Speed branch; at the default 12 the 10-12/s draw passes both ledgers. The NoSwing branch (max-swing-time 80ms) stays silent because every C02 is preceded by swingItem, and the Direction and Reach branches behave as in the single-target analysis.

← Back to Analysis Hub