Nekoware v1 private Player ESP module 2 files, 195 lines

Nekoware v1 private Player ESP: Full Source Analysis

Player ESP is a wire-silent render overlay: on every Render3DEvent it walks mc.theWorld.loadedEntityList and draws a fixed translucent black box around every EntityPlayer except the local player.

me/nekoWare/client/module/render/ESP.java · GitHub source ↗

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

Analysis

Overview

Player ESP is a wire-silent render overlay: on every Render3DEvent it walks mc.theWorld.loadedEntityList and draws a fixed translucent black box around every EntityPlayer except the local player. The entities it draws are fed by the server spawn stream (S0C for players, S0F for mobs, both filtered to EntityPlayer), and the drawing itself is pure client-side GL11 work, so the module has no packet fingerprint and no server-side detection surface.

Render pass

The module is a single Consumer<Render3DEvent> field carrying the @Handler marker that the client's PubSub bus subscribes at toggle time. The consumer loops mc.theWorld.loadedEntityList, skips the local player and any entity that is not an EntityPlayer, and calls RenderUtils.drawEsp(o, new Color(0, 0, 0, 21).getRGB()) for the rest. drawEsp renders a 1x2x1 axis-aligned box from (posX - 0.5, posY, posZ - 0.5) to (posX + 0.5, posY + 2.0, posZ + 0.5) using the color's alpha, so the box is a barely visible 8 percent opacity black outline at fixed size, with no color, health, distance or invisibility settings.

Data source

loadedEntityList is populated entirely from the receive path: S0C spawns players into the client world, S0F spawns mobs, and the destroy, teleport and velocity packets move and remove them. The EntityPlayer filter means only S0C-fed players ever render; S0F mob spawns are skipped by the instanceof check even though they populate the same list. The module reads entity positions each frame, so the boxes track interpolation and render through walls; nothing is sent back.

Wire presence

Rendering is client-local state. The module neither sends nor cancels any packet, and it does not mutate the entity list, so the server-side entity ledger is identical to a vanilla client's. There is no packet whose content could betray the overlay. The countering entries below are therefore honest boundaries: the checks that handle the S0C and S0F spawn stream in each anticheat, none of which can observe a render-side read of the same data.

source ESP.java

ESP.java29 lines · JavaOriginal ↗
1
2
package me.nekoWare.client.module.render;
3
4
import me.hippo.api.lwjeb.annotation.Handler;
5
import me.nekoWare.client.event.events.Render3DEvent;
6
import me.nekoWare.client.module.Module;
7
import me.nekoWare.client.util.render.RenderUtils;
8
import net.minecraft.entity.Entity;
9
import net.minecraft.entity.player.EntityPlayer;
10
11
import java.awt.*;
12
import java.util.function.Consumer;
13
14
public class ESP extends Module {
15
    public ESP() {
16
        super("Player ESP", 0, Module.Category.RENDER);
17
    }
18
19
    @Handler
20
    public Consumer<Render3DEvent> onEvent = (event) -> {
21
        for (final Entity o : this.mc.theWorld.loadedEntityList) {
22
            if (o == this.mc.thePlayer || !(o instanceof EntityPlayer)) {
23
                continue;
24
            }
25
            RenderUtils.drawEsp(o, new Color(0, 0, 0, 21).getRGB());
26
        }
27
    };
28
29
}

What this file does

The module: the Render3DEvent consumer, the loadedEntityList walk, the EntityPlayer filter and the fixed-color drawEsp call that make up the entire behavior. The @Handler field is the subscription contract with the PubSub bus.

source RenderUtils.java (drawEsp)

RenderUtils.java166 lines · JavaOriginal ↗
1
/*
2
 * Decompiled with CFR 0.145.
3
 *
4
 * Could not load the following classes:
5
 *  org.lwjgl.opengl.GL11
6
 */
7
package me.nekoWare.client.util.render;
8
9
import net.minecraft.client.renderer.RenderGlobal;
10
import net.minecraft.client.renderer.Tessellator;
11
import net.minecraft.client.renderer.WorldRenderer;
12
import net.minecraft.client.renderer.entity.RenderManager;
13
import net.minecraft.entity.Entity;
14
import net.minecraft.tileentity.TileEntity;
15
import net.minecraft.util.AxisAlignedBB;
16
import org.lwjgl.opengl.GL11;
17
18
import java.awt.*;
19
20
public class RenderUtils {
21
22
    public static void box(double x, double y2, double z, double x2, double y22, double z2, final Color color) {
23
        GL11.glBlendFunc(770, 771);
24
        GL11.glEnable(3042);
25
        GL11.glLineWidth(2.0f);
26
        GL11.glDisable(3553);
27
        GL11.glDisable(2929);
28
        GL11.glDepthMask(false);
29
        final double n = x;
30
31
        final double x3 = x = n - RenderManager.renderPosX;
32
        final double n2 = y2;
33
34
        final double y3 = y2 = n2 - RenderManager.renderPosY;
35
        final double n3 = z;
36
37
        final double z3 = z = n3 - RenderManager.renderPosZ;
38
        final double n4 = x2;
39
40
        final double x4 = x2 = n4 - RenderManager.renderPosX;
41
        final double n5 = y22;
42
43
        final double y4 = y22 = n5 - RenderManager.renderPosY;
44
        final double n6 = z2;
45
46
        GL11.glColor4d(0.0, 0.0, 0.0, 0.2);
47
        z2 = n6 - RenderManager.renderPosZ;
48
        RenderUtils.drawColorBox(new AxisAlignedBB(x3, y3, z3, x4, y4, z2));
49
        RenderGlobal.drawOutlinedBoundingBox(new AxisAlignedBB(x, y2, z, x2, y22, z2), color.getRGB());
50
        GL11.glColor4d(0.0, 0.0, 0.0, 0.2);
51
        GL11.glEnable(3553);
52
        GL11.glEnable(2929);
53
        GL11.glDepthMask(true);
54
        GL11.glDisable(3042);
55
    }
56
57
    public static void drawColorBox(final AxisAlignedBB axisalignedbb) {
58
        final Tessellator ts = Tessellator.getInstance();
59
        final WorldRenderer wr = ts.getWorldRenderer();
60
        wr.startDrawingQuads();
61
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ);
62
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ);
63
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ);
64
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ);
65
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ);
66
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ);
67
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ);
68
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ);
69
        ts.draw();
70
        wr.startDrawingQuads();
71
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ);
72
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ);
73
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ);
74
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ);
75
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ);
76
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ);
77
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ);
78
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ);
79
        ts.draw();
80
        wr.startDrawingQuads();
81
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ);
82
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ);
83
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ);
84
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ);
85
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ);
86
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ);
87
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ);
88
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ);
89
        ts.draw();
90
        wr.startDrawingQuads();
91
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ);
92
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ);
93
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ);
94
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ);
95
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ);
96
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ);
97
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ);
98
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ);
99
        ts.draw();
100
        wr.startDrawingQuads();
101
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ);
102
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ);
103
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ);
104
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ);
105
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ);
106
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ);
107
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ);
108
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ);
109
        ts.draw();
110
        wr.startDrawingQuads();
111
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ);
112
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ);
113
        wr.addVertex(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ);
114
        wr.addVertex(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ);
115
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ);
116
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ);
117
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ);
118
        wr.addVertex(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ);
119
        ts.draw();
120
    }
121
122
    public static void drawGradientRect(final float x, final float y2, final float x1, final float y1,
123
                                        final int topColor, final int bottomColor) {
124
        RenderUtils.enableGL2D();
125
        GL11.glShadeModel(7425);
126
        GL11.glBegin(7);
127
        ColorUtils.glColor(topColor);
128
        GL11.glVertex2f(x, y1);
129
        GL11.glVertex2f(x1, y1);
130
        ColorUtils.glColor(bottomColor);
131
        GL11.glVertex2f(x1, y2);
132
        GL11.glVertex2f(x, y2);
133
        GL11.glEnd();
134
        GL11.glShadeModel(7425);
135
        RenderUtils.disableGL2D();
136
    }
137
138
    public static void enableGL2D() {
139
        GL11.glDisable(2929);
140
        GL11.glEnable(3042);
141
        GL11.glDisable(3553);
142
        GL11.glBlendFunc(770, 771);
143
        GL11.glDepthMask(true);
144
        GL11.glEnable(2848);
145
        GL11.glHint(3154, 4354);
146
        GL11.glHint(3155, 4354);
147
    }
148
149
    public static void disableGL2D() {
150
        GL11.glEnable(3553);
151
        GL11.glDisable(3042);
152
        GL11.glEnable(2929);
153
        GL11.glDisable(2848);
154
        GL11.glHint(3154, 4352);
155
        GL11.glHint(3155, 4352);
156
    }
157
158
    public static void drawEsp(final Entity o, final int c2) {
159
        RenderUtils.box(o.posX - 0.5, o.posY, o.posZ - 0.5, o.posX + 0.5, o.posY + 2.0, o.posZ + 0.5, new Color(c2));
160
    }
161
    public static void drawEsp(final TileEntity o, final int c2) {
162
        RenderUtils.box(o.getPos().getX() + 1, o.getPos().getY(),
163
                o.getPos().getZ() + 1, o.getPos().getX(),
164
                o.getPos().getY() + 1.0, o.getPos().getZ(), new Color(c2));
165
    }
166
}

What this file does

The drawing utility the module calls: drawEsp builds a 1x2x1 box around the entity's feet position and hands it to the GL11 quad renderer in box(); the utility shows the fixed geometry and alpha blending that define the ESP's appearance.

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 PacketEntityReplication (spawn ledger)

PacketEntityReplication.java627 lines · Java
1
package ac.grim.grimac.events.packets;
2
3
import ac.grim.grimac.GrimAPI;
4
import ac.grim.grimac.api.config.ConfigManager;
5
import ac.grim.grimac.checks.Check;
6
import ac.grim.grimac.checks.type.PacketReceiveListener;
7
import ac.grim.grimac.checks.type.PacketSendListener;
8
import ac.grim.grimac.player.GrimPlayer;
9
import ac.grim.grimac.utils.anticheat.LogUtil;
10
import ac.grim.grimac.utils.data.SprintingState;
11
import ac.grim.grimac.utils.data.TrackerData;
12
import ac.grim.grimac.utils.data.packetentity.DashableEntity;
13
import ac.grim.grimac.utils.data.packetentity.PacketEntity;
14
import ac.grim.grimac.utils.data.packetentity.PacketEntityHook;
15
import ac.grim.grimac.utils.data.packetentity.PacketEntityTrackXRot;
16
import ac.grim.grimac.utils.enums.Pose;
17
import ac.grim.grimac.utils.nmsutil.EntityMetadataPoseUtil;
18
import ac.grim.grimac.utils.viaversion.ViaVersionUtil;
19
import com.github.retrooper.packetevents.PacketEvents;
20
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
21
import com.github.retrooper.packetevents.event.PacketSendEvent;
22
import com.github.retrooper.packetevents.manager.server.ServerVersion;
23
import com.github.retrooper.packetevents.protocol.entity.EntityPositionData;
24
import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
25
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
26
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
27
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
28
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
29
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
30
import com.github.retrooper.packetevents.protocol.player.UserProfile;
31
import com.github.retrooper.packetevents.protocol.potion.PotionType;
32
import com.github.retrooper.packetevents.util.Vector3d;
33
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAttachEntity;
34
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
35
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEffect;
36
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment;
37
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
38
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityPositionSync;
39
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove;
40
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMoveAndRotation;
41
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation;
42
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus;
43
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
44
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo;
45
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoRemove;
46
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate;
47
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerRemoveEntityEffect;
48
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers;
49
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot;
50
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
51
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity;
52
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPainting;
53
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPlayer;
54
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes;
55
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowItems;
56
import org.jetbrains.annotations.NotNull;
57
58
import java.util.ArrayList;
59
import java.util.List;
60
import java.util.UUID;
61
import java.util.concurrent.atomic.AtomicBoolean;
62
63
public class PacketEntityReplication extends Check implements PacketReceiveListener, PacketSendListener {
64
65
    private final AtomicBoolean hasSentPreWavePacket = new AtomicBoolean(true);
66
67
    // Let's imagine the player is on a boat.
68
    // The player breaks this boat
69
    // If we were to despawn the boat without an extra transaction, then the boat would disappear before
70
    // it disappeared on the client side, creating a ghost boat to flag checks with
71
    //
72
    // If we were to despawn the tick after, spawning must occur the transaction before to stop the same exact
73
    // problem with ghost boats in reverse.
74
    //
75
    // Therefore, we despawn the transaction after, and spawn the tick before.
76
    //
77
    // If we despawn then spawn an entity in the same transaction, then this solution would despawn the new entity
78
    // instead of the old entity, so we wouldn't see the boat at all
79
    //
80
    // Therefore, if the server sends a despawn and then a spawn in the same transaction for the same entity,
81
    // We should simply add a transaction (which will clear this list!)
82
    //
83
    // Another valid solution is to simply spam more transactions, but let's not waste bandwidth.
84
    private final List<Integer> despawnedEntitiesThisTransaction = new ArrayList<>();
85
86
    // Maximum ping when a firework boost is removed from the player.
87
    private int maxFireworkBoostPing = 1000;
88
89
    public PacketEntityReplication(GrimPlayer player) {
90
        super(player);
91
    }
92
93
    @Override
94
    public void onPacketReceive(PacketReceiveEvent event) {
95
        // Teleports don't interpolate, duplicate 1.17 packets don't interpolate
96
        if (!isTickPacket(event.getPacketType())) return;
97
        player.compensatedEntities.entitiesRemovedThisTick.clear();
98
        boolean isTickingReliably = player.isTickingReliablyFor(3);
99
100
        PacketEntity playerVehicle = player.compensatedEntities.self.getRiding();
101
        for (PacketEntity entity : player.compensatedEntities.entityMap.values()) {
102
            if (entity == playerVehicle && !player.vehicleData.lastDummy) {
103
                // The player has this as their vehicle, so they aren't interpolating it.
104
                // And it isn't a dummy position
105
                entity.setPositionRaw(player, entity.getPossibleLocationBoxes());
106
            } else {
107
                entity.onMovement(isTickingReliably);
108
            }
109
        }
110
111
        if (player.vehicleData.camelSprintingState == SprintingState.STOPPING) {
112
            player.vehicleData.camelSprintingState = SprintingState.STOPPED;
113
        } else if (player.vehicleData.camelSprintingState == SprintingState.STOPPED && player.isSprinting) { // For sprint desyncs
114
            player.vehicleData.camelSprintingState = SprintingState.STARTED;
115
        }
116
    }
117
118
    @Override
119
    public void onPacketSend(PacketSendEvent event) {
120
        // ensure grim is the one that sent the transaction
121
        if ((event.getPacketType() == PacketType.Play.Server.PING || event.getPacketType() == PacketType.Play.Server.WINDOW_CONFIRMATION) && player.packetStateData.lastServerTransWasValid) {
122
            despawnedEntitiesThisTransaction.clear();
123
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_LIVING_ENTITY) {
124
            WrapperPlayServerSpawnLivingEntity packetOutEntity = new WrapperPlayServerSpawnLivingEntity(event);
125
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getEntityUUID(), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
126
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_ENTITY) {
127
            WrapperPlayServerSpawnEntity packetOutEntity = new WrapperPlayServerSpawnEntity(event);
128
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID().orElse(null), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), null, packetOutEntity.getData());
129
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PLAYER) {
130
            WrapperPlayServerSpawnPlayer packetOutEntity = new WrapperPlayServerSpawnPlayer(event);
131
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PLAYER, packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
132
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PAINTING) {
133
            WrapperPlayServerSpawnPainting packetOutEntity = new WrapperPlayServerSpawnPainting(event);
134
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PAINTING, packetOutEntity.getPosition().toVector3d(), 0, 0f, null, packetOutEntity.getDirection().getHorizontalIndex());
135
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE) {
136
            WrapperPlayServerEntityRelativeMove move = new WrapperPlayServerEntityRelativeMove(event);
137
            handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), null, null, true, true);
138
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE_AND_ROTATION) {
139
            WrapperPlayServerEntityRelativeMoveAndRotation move = new WrapperPlayServerEntityRelativeMoveAndRotation(event);
140
            handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, true);
141
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_TELEPORT) {
142
            WrapperPlayServerEntityTeleport move = new WrapperPlayServerEntityTeleport(event);
143
            Vector3d pos = move.getPosition();
144
            handleMoveEntity(event, move.getEntityId(), pos.getX(), pos.getY(), pos.getZ(), move.getYaw(), move.getPitch(), false, true);
145
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_POSITION_SYNC) {
146
            // ENTITY_TELEPORT but without relative flags
147
            WrapperPlayServerEntityPositionSync move = new WrapperPlayServerEntityPositionSync(event);
148
            final EntityPositionData values = move.getValues();
149
            final Vector3d pos = values.getPosition();
150
            // TODO this isn't technically correct
151
            // If the position sync is to a pos > 4096 from the entity pos, client does some special stuff without interpolation
152
            handleMoveEntity(event, move.getId(), pos.getX(), pos.getY(), pos.getZ(), values.getYaw(), values.getPitch(), false, true);
153
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_ROTATION) { // Affects interpolation
154
            WrapperPlayServerEntityRotation move = new WrapperPlayServerEntityRotation(event);
155
            handleMoveEntity(event, move.getEntityId(), 0, 0, 0, move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, false);
156
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_METADATA) {
157
            WrapperPlayServerEntityMetadata entityMetadata = new WrapperPlayServerEntityMetadata(event);
158
            schedulePoseTransition(entityMetadata, event);
159
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityMetadata(entityMetadata.getEntityId(), entityMetadata.getEntityMetadata()));
160
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EQUIPMENT) {
161
            WrapperPlayServerEntityEquipment equipment = new WrapperPlayServerEntityEquipment(event);
162
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityEquipment(equipment.getEntityId(), equipment.getEquipment()));
163
        }
164
165
        // 1.19.3+
166
        else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_UPDATE) {
167
            WrapperPlayServerPlayerInfoUpdate info = new WrapperPlayServerPlayerInfoUpdate(event);
168
            if (info.getActions().contains(WrapperPlayServerPlayerInfoUpdate.Action.ADD_PLAYER)) {
169
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
170
                    for (WrapperPlayServerPlayerInfoUpdate.PlayerInfo entry : info.getEntries()) {
171
                        final UserProfile gameProfile = entry.getGameProfile();
172
                        final UUID uuid = gameProfile.getUUID();
173
                        player.compensatedEntities.profiles.put(uuid, gameProfile);
174
                    }
175
                });
176
            }
177
        } else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_REMOVE) {
178
            WrapperPlayServerPlayerInfoRemove remove = new WrapperPlayServerPlayerInfoRemove(event);
179
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> remove.getProfileIds().forEach(player.compensatedEntities.profiles::remove));
180
        } else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO) {
181
            WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo(event);
182
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
183
                if (info.getAction() == WrapperPlayServerPlayerInfo.Action.ADD_PLAYER) {
184
                    for (WrapperPlayServerPlayerInfo.PlayerData entry : info.getPlayerDataList()) {
185
                        final UserProfile gameProfile = entry.getUserProfile();
186
                        final UUID uuid = gameProfile.getUUID();
187
                        player.compensatedEntities.profiles.put(uuid, gameProfile);
188
                    }
189
                } else if (info.getAction() == WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER) {
190
                    info.getPlayerDataList().forEach(profile -> player.compensatedEntities.profiles.remove(profile.getUserProfile().getUUID()));
191
                }
192
            });
193
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EFFECT) {
194
            WrapperPlayServerEntityEffect effect = new WrapperPlayServerEntityEffect(event);
195
196
            PotionType type = effect.getPotionType();
197
198
            // ViaVersion tries faking levitation effects and fails badly lol, flagging the anticheat
199
            // Block other effects just in case ViaVersion gets any ideas
200
            //
201
            // Set to 24 so ViaVersion blocks it
202
            // 24 is the levitation effect
203
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) > 23) {
204
                event.setCancelled(true);
205
                return;
206
            }
207
208
            // ViaVersion dolphin's grace also messes us up, set it to a potion effect that doesn't exist on 1.12
209
            // Effect 31 is bad omen
210
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_13) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) == 30) {
211
                event.setCancelled(true);
212
                return;
213
            }
214
215
            if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
216
217
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
218
                PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
219
                if (entity == null) return;
220
221
                entity.addPotionEffect(type, effect.getEffectAmplifier());
222
            });
223
        } else if (event.getPacketType() == PacketType.Play.Server.REMOVE_ENTITY_EFFECT) {
224
            WrapperPlayServerRemoveEntityEffect effect = new WrapperPlayServerRemoveEntityEffect(event);
225
226
            if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
227
228
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
229
                PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
230
                if (entity == null) return;
231
232
                entity.removePotionEffect(effect.getPotionType());
233
            });
234
        } else if (event.getPacketType() == PacketType.Play.Server.UPDATE_ATTRIBUTES) {
235
            WrapperPlayServerUpdateAttributes attributes = new WrapperPlayServerUpdateAttributes(event);
236
237
            int entityID = attributes.getEntityId();
238
239
            // The attributes for this entity is active, currently
240
            if (isDirectlyAffectingPlayer(player, entityID)) player.sendTransaction();
241
242
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(),
243
                    () -> player.compensatedEntities.updateAttributes(entityID, attributes.getProperties()));
244
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_STATUS) {
245
            WrapperPlayServerEntityStatus status = new WrapperPlayServerEntityStatus(event);
246
            // This hasn't changed from 1.7.2 to 1.17
247
            // Needed to exempt players on dead vehicles, as dead entities have strange physics.
248
            if (status.getStatus() == 3) {
249
                PacketEntity entity = player.compensatedEntities.getEntity(status.getEntityId());
250
251
                if (entity == null) return;
252
                entity.isDead = true;
253
            }
254
255
            if (status.getStatus() == 9) {
256
                if (status.getEntityId() != player.entityID) return;
257
258
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
259
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
260
            }
261
262
            if (status.getStatus() == 31) {
263
                PacketEntity hook = player.compensatedEntities.getEntity(status.getEntityId());
264
                if (!(hook instanceof PacketEntityHook hookEntity)) return;
265
266
                if (hookEntity.attached == player.entityID) {
267
                    player.sendTransaction();
268
                    // We don't transaction sandwich this, it's too rare to be a real problem.
269
                    player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.uncertaintyHandler.fishingRodPulls.add(hookEntity.owner));
270
                }
271
            }
272
273
            if (status.getStatus() >= 24 && status.getStatus() <= 28 && status.getEntityId() == player.entityID) {
274
                player.compensatedEntities.self.opLevel = status.getStatus() - 24;
275
            }
276
        } else if (event.getPacketType() == PacketType.Play.Server.SET_SLOT) {
277
            WrapperPlayServerSetSlot slot = new WrapperPlayServerSetSlot(event);
278
279
            if (slot.getWindowId() == 0) {
280
                Runnable task = () -> {
281
                    if (slot.getSlot() - 36 == player.packetStateData.lastSlotSelected && (
282
                            !player.inventory.getHeldItem().is(slot.getItem().getType()) || player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)
283
                    ) || slot.getSlot() == 45 && !player.inventory.getOffHand().is(slot.getItem().getType())) {
284
                        InteractionHand hand = slot.getSlot() == 45 ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;
285
                        if (hand == player.packetStateData.itemInUseHand) {
286
                            player.packetStateData.setSlowedByUsingItem(false);
287
                        }
288
289
                        if (player.isResetItemUsageOnItemUpdate() && hand == GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer)) {
290
                            GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
291
                        }
292
                    }
293
                };
294
295
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
296
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
297
            }
298
        } else if (event.getPacketType() == PacketType.Play.Server.WINDOW_ITEMS) {
299
            WrapperPlayServerWindowItems items = new WrapperPlayServerWindowItems(event);
300
301
            if (items.getWindowId() == 0) { // Player inventory
302
                Runnable task = () -> {
303
                    if (player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)) {
304
                        player.packetStateData.setSlowedByUsingItem(false);
305
                        if (player.isResetItemUsageOnItemUpdate()) {
306
                            GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
307
                        }
308
                    } else {
309
                        if (items.getItems().size() > 45 && !player.inventory.getOffHand().is(items.getItems().get(45).getType())) {
310
                            if (player.packetStateData.itemInUseHand == InteractionHand.OFF_HAND) {
311
                                player.packetStateData.setSlowedByUsingItem(false);
312
                            }
313
314
                            if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.OFF_HAND) {
315
                                GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
316
                            }
317
                        }
318
319
                        if (!player.inventory.getHeldItem().is(items.getItems().get(player.packetStateData.lastSlotSelected + 36).getType())) {
320
                            if (player.packetStateData.itemInUseHand == InteractionHand.MAIN_HAND) {
321
                                player.packetStateData.setSlowedByUsingItem(false);
322
                            }
323
324
                            if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.MAIN_HAND) {
325
                                GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
326
                            }
327
                        }
328
                    }
329
                };
330
331
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
332
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
333
            }
334
        }
335
336
        // 1.8 clients fail to send the RELEASE_USE_ITEM packet when a window is opened client sided while using an item
337
        else if (event.getPacketType() == PacketType.Play.Server.OPEN_WINDOW) {
338
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
339
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
340
        } else if (event.getPacketType() == PacketType.Play.Server.OPEN_HORSE_WINDOW) {
341
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
342
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
343
        } else if (event.getPacketType() == PacketType.Play.Server.SET_PASSENGERS) {
344
            WrapperPlayServerSetPassengers mount = new WrapperPlayServerSetPassengers(event);
345
346
            int vehicleID = mount.getEntityId();
347
            int[] passengers = mount.getPassengers();
348
349
            handleMountVehicle(event, vehicleID, passengers);
350
        } else if (event.getPacketType() == PacketType.Play.Server.ATTACH_ENTITY) {
351
            WrapperPlayServerAttachEntity attach = new WrapperPlayServerAttachEntity(event);
352
353
            // This packet was replaced by the mount packet on 1.9+ servers - to support multiple passengers on one vehicle
354
            if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))
355
                return;
356
357
            // If this is mounting rather than leashing
358
            if (!attach.isLeash()) {
359
                // Alright, let's convert this to the 1.9+ format to make it easier for grim
360
                int vehicleID = attach.getHoldingId();
361
                int attachID = attach.getAttachedId();
362
                TrackerData trackerData = player.compensatedEntities.getTrackedEntity(attachID);
363
364
                if (trackerData != null) {
365
                    // 1.8 sends a vehicle ID of -1 to dismount the entity from its vehicle
366
                    // This is opposite of the 1.9+ format, which sends the vehicle ID and then an empty array.
367
                    if (vehicleID == -1) { // Dismounting
368
                        vehicleID = trackerData.getLegacyPointEightMountedUpon();
369
                        handleMountVehicle(event, vehicleID, new int[]{}); // The vehicle is empty
370
                    } else { // Mounting
371
                        trackerData.setLegacyPointEightMountedUpon(vehicleID);
372
                        handleMountVehicle(event, vehicleID, new int[]{attachID});
373
                    }
374
                } else {
375
                    // I don't think we can recover from this... warn and move on as this shouldn't happen.
376
                    LogUtil.warn("Server sent an invalid attach entity packet for entity " + attach.getHoldingId() + " with passenger " + attach.getAttachedId() + "! The client ignores this.");
377
                }
378
            }
379
        } else if (event.getPacketType() == PacketType.Play.Server.DESTROY_ENTITIES) {
380
            WrapperPlayServerDestroyEntities destroy = new WrapperPlayServerDestroyEntities(event);
381
382
            int[] destroyEntityIds = destroy.getEntityIds();
383
384
            for (int entityID : destroyEntityIds) {
385
                despawnedEntitiesThisTransaction.add(entityID);
386
                player.compensatedEntities.serverPositionsMap.remove(entityID);
387
                // Remove the tracked vehicle (handling tracking knockback) if despawned
388
                if (player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == entityID) {
389
                    player.compensatedEntities.serverPlayerVehicle = null;
390
                }
391
            }
392
393
            final int destroyTransaction = player.lastTransactionSent.get() + 1;
394
            player.latencyUtils.addRealTimeTask(destroyTransaction, () -> {
395
                for (int entityId : destroyEntityIds) {
396
                    player.compensatedEntities.removeEntity(entityId);
397
                    player.dashableEntities.removeEntity(entityId);
398
                    player.fireworks.removeFirework(entityId);
399
                    player.compensatedEntities.entitiesRemovedThisTick.add(entityId);
400
                }
401
            });
402
403
            // Don't let the player freeze transactions to keep the firework boost velocity + uncertainty
404
            // Also generally prevents people with high ping gaining too high an advantage in firework use
405
            if (maxFireworkBoostPing > 0) {
406
                player.runNettyTaskInMs(() -> {
407
                    if (player.lastTransactionReceived.get() >= destroyTransaction) return;
408
                    for (int entityID : destroyEntityIds) {
409
                        // If the player has a firework boosting them, setback
410
                        if (player.fireworks.hasFirework(entityID)) {
411
                            player.getSetbackTeleportUtil().executeViolationSetback();
412
                            break;
413
                        }
414
                    }
415
                }, maxFireworkBoostPing);
416
            }
417
        }
418
    }
419
420
    private void handleMountVehicle(PacketSendEvent event, int vehicleID, int[] passengers) {
421
        boolean wasInVehicle = player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == vehicleID;
422
        boolean inThisVehicle = false;
423
424
        for (int passenger : passengers) {
425
            inThisVehicle = passenger == player.entityID;
426
            if (inThisVehicle) break;
427
        }
428
429
        if (inThisVehicle && !wasInVehicle) {
430
            player.handleMountVehicle(vehicleID);
431
        }
432
433
        if (!inThisVehicle && wasInVehicle) {
434
            player.handleDismountVehicle(event);
435
        }
436
        // Better lag compensation if we were affected by this
437
        if (wasInVehicle || inThisVehicle) {
438
            player.sendTransaction();
439
        }
440
        player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
441
            PacketEntity vehicle = player.compensatedEntities.getEntity(vehicleID);
442
443
            // Vanilla likes sending null vehicles, so we must ignore those like the client ignores them
444
            if (vehicle == null) return;
445
446
            // Eject existing passengers for this vehicle
447
            for (PacketEntity passenger : new ArrayList<>(vehicle.passengers)) {
448
                passenger.eject();
449
            }
450
451
            // Add the entities as vehicles
452
            for (int entityID : passengers) {
453
                PacketEntity passenger = player.compensatedEntities.getEntity(entityID);
454
                if (passenger == null) continue;
455
                passenger.mount(vehicle);
456
            }
457
        });
458
    }
459
460
    private void handleMoveEntity(PacketSendEvent event, int entityId, double deltaX, double deltaY, double deltaZ, Float yaw, Float pitch, boolean isRelative, boolean hasPos) {
461
        TrackerData data = player.compensatedEntities.getTrackedEntity(entityId);
462
463
        final boolean didNotSendPreWave = hasSentPreWavePacket.compareAndSet(false, true);
464
        if (didNotSendPreWave) player.sendTransaction();
465
466
        if (data != null) {
467
            // Update the tracked server's entity position
468
            if (isRelative) {
469
                // There is a bug where vehicles may start flying due to mojang setting packet position on the client
470
                // (Works at 0 ping but causes funny bugs at any higher ping)
471
                // As we don't want vehicles to fly, we need to replace it with a teleport if it is player vehicle
472
                //
473
                // Don't bother with client controlled vehicles though
474
                boolean vanillaVehicleFlight = player.compensatedEntities.serverPlayerVehicle != null
475
                        && player.compensatedEntities.serverPlayerVehicle == entityId
476
                        && player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_9)
477
                        // TODO: https://discord.com/channels/721686193061888071/721686193515003966/1310659538831020123
478
                        // Why does the server now send an entity rel move packet matching the player's vehicle movement every time?
479
                        && PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_21_2)
480
                        && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9);
481
482
                // ViaVersion sends two relative packets when moving more than 4 blocks
483
                // This is broken and causes the client to interpolate like (0, 4) and (1, 3) instead of (1, 7)
484
                // This causes impossible hits, so grim must replace this with a teleport entity packet
485
                // Not ideal, but neither is 1.8 players on a 1.9+ server.
486
                if (vanillaVehicleFlight ||
487
                        ((Math.abs(deltaX) >= 3.9375 || Math.abs(deltaY) >= 3.9375 || Math.abs(deltaZ) >= 3.9375) && player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))) {
488
                    player.user.writePacket(new WrapperPlayServerEntityTeleport(entityId, new Vector3d(data.getX() + deltaX, data.getY() + deltaY, data.getZ() + deltaZ), yaw == null ? data.getXRot() : yaw, pitch == null ? data.getYRot() : pitch, false));
489
                    event.setCancelled(true);
490
                    return;
491
                }
492
493
                data.setX(data.getX() + deltaX);
494
                data.setY(data.getY() + deltaY);
495
                data.setZ(data.getZ() + deltaZ);
496
            } else {
497
                data.setX(deltaX);
498
                data.setY(deltaY);
499
                data.setZ(deltaZ);
500
            }
501
            if (yaw != null) {
502
                data.setXRot(yaw);
503
                data.setYRot(pitch);
504
            }
505
506
            // We can't hang two relative moves on one transaction
507
            if (data.getLastTransactionHung() == player.lastTransactionSent.get()) {
508
                player.sendTransaction();
509
            }
510
            data.setLastTransactionHung(player.lastTransactionSent.get());
511
        }
512
513
        int lastTrans = player.lastTransactionSent.get();
514
515
        player.latencyUtils.addRealTimeTask(lastTrans, () -> {
516
            PacketEntity entity = player.compensatedEntities.getEntity(entityId);
517
            if (entity == null) return;
518
            if (entity instanceof PacketEntityTrackXRot xRotEntity && yaw != null) {
519
                xRotEntity.packetYaw = yaw;
520
                xRotEntity.steps = entity.isBoat ? 10 : 3;
521
            }
522
523
            entity.onFirstTransaction(isRelative, hasPos, deltaX, deltaY, deltaZ, yaw, pitch, player);
524
        });
525
526
        player.latencyUtils.addRealTimeTask(lastTrans + 1, () -> {
527
            PacketEntity entity = player.compensatedEntities.getEntity(entityId);
528
            if (entity == null) return;
529
            entity.onSecondTransaction();
530
        });
531
    }
532
533
    public void addEntity(int entityID, UUID uuid, EntityType type, Vector3d position, float xRot, float yRot, List<EntityData<?>> entityMetadata, int extraData) {
534
        if (despawnedEntitiesThisTransaction.contains(entityID)) {
535
            player.sendTransaction();
536
        }
537
538
        player.compensatedEntities.serverPositionsMap.put(entityID, new TrackerData(position.getX(), position.getY(), position.getZ(), xRot, yRot, type, player.lastTransactionSent.get()));
539
540
        player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
541
            PacketEntity entity = player.compensatedEntities.addEntity(entityID, uuid, type, position, xRot, extraData);
542
            if (entity instanceof DashableEntity dashable) {
543
                player.dashableEntities.addEntity(entityID, dashable);
544
            }
545
546
            if (entityMetadata != null) {
547
                if (EntityMetadataPoseUtil.usesPoseMetadata(entity) && player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_14)) {
548
                    Pose initialPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata);
549
                    if (initialPose != null) {
550
                        entity.currentPose = initialPose;
551
                    }
552
                }
553
554
                player.compensatedEntities.updateEntityMetadata(entityID, entityMetadata);
555
            }
556
        });
557
    }
558
559
    private void schedulePoseTransition(WrapperPlayServerEntityMetadata entityMetadata, PacketSendEvent event) {
560
        if (player.getClientVersion().isOlderThan(ClientVersion.V_1_14)) return;
561
562
        int entityId = entityMetadata.getEntityId();
563
        if (entityId == player.entityID) return;
564
565
        Pose newPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata.getEntityMetadata());
566
        if (newPose == null) return;
567
568
        boolean shouldTrackPoseTransition = false;
569
        PacketEntity entity = player.compensatedEntities.getEntity(entityId);
570
        if (entity != null) {
571
            shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(entity);
572
        } else {
573
            // If the client didn't respond to the spawn packet yet, we need to check if we should track the pose transition based on the entity type
574
            // is there a better way to do this?
575
            TrackerData trackedEntity = player.compensatedEntities.getTrackedEntity(entityId);
576
            if (trackedEntity != null) {
577
                shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(trackedEntity.getEntityType());
578
            }
579
        }
580
581
        if (!shouldTrackPoseTransition) return;
582
583
        player.sendTransaction();
584
        player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
585
            PacketEntity target = player.compensatedEntities.getEntity(entityId);
586
            if (target == null) {
587
                return;
588
            }
589
590
            target.beginPoseTransition(newPose);
591
        });
592
593
        event.getTasksAfterSend().add(() -> {
594
            player.sendTransaction();
595
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
596
                PacketEntity target = player.compensatedEntities.getEntity(entityId);
597
                if (target == null) {
598
                    return;
599
                }
600
601
                target.completePoseTransition(newPose);
602
            });
603
        });
604
    }
605
606
    private boolean isDirectlyAffectingPlayer(GrimPlayer player, int entityID) {
607
        // The attributes for this entity is active, currently
608
        return (player.compensatedEntities.serverPlayerVehicle == null && entityID == player.entityID) ||
609
                (player.compensatedEntities.serverPlayerVehicle != null && entityID == player.compensatedEntities.serverPlayerVehicle);
610
    }
611
612
    public void onEndOfTickEvent(boolean async, boolean flush) {
613
        // Only send a transaction at the end of the tick if we are tracking players
614
        player.sendTransaction(async);
615
        if (flush) player.user.flushPackets();
616
    }
617
618
    public void tickStartTick() {
619
        hasSentPreWavePacket.set(false);
620
    }
621
622
    @Override
623
    public void onReload(@NotNull ConfigManager config) {
624
        maxFireworkBoostPing = config.getIntElse("max-ping-firework-boost", 1000);
625
    }
626
627
}

How it counteracts this module

Grim mirrors every spawn into a server-side entity ledger: the S0C and S0F handlers build PacketEntity objects with tracked positions and hitboxes that feed reach, phase and prediction checks, and a spawn also clears the player's accepted-spawn-teleport flag. This is the closest thing to a spawn consumer in the corpus, and it is a one-way mirror: the ESP reads the same spawn data locally for rendering, while the replication ledger records only server-originated state. Nothing the module does alters an entity's tracked position or existence, so the ledger sees a vanilla stream. The entry is the honest statement that entity-replication machinery cannot observe a render-only read.

anticheat SetbackTeleportUtil (spawn teleport acceptance)

SetbackTeleportUtil.java471 lines · Java
1
package ac.grim.grimac.manager;
2
3
import ac.grim.grimac.GrimAPI;
4
import ac.grim.grimac.api.event.events.GrimPlayerSetbackEvent;
5
import ac.grim.grimac.api.event.events.GrimTeleportEvent;
6
import ac.grim.grimac.checks.Check;
7
import ac.grim.grimac.checks.impl.badpackets.BadPacketsN;
8
import ac.grim.grimac.checks.type.PostPredictionListener;
9
import ac.grim.grimac.platform.api.entity.GrimEntity;
10
import ac.grim.grimac.player.GrimPlayer;
11
import ac.grim.grimac.predictionengine.predictions.PredictionEngine;
12
import ac.grim.grimac.predictionengine.predictions.PredictionEngineElytra;
13
import ac.grim.grimac.predictionengine.predictions.PredictionEngineNormal;
14
import ac.grim.grimac.predictionengine.predictions.PredictionEngineWater;
15
import ac.grim.grimac.utils.anticheat.update.PredictionComplete;
16
import ac.grim.grimac.utils.chunks.Column;
17
import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox;
18
import ac.grim.grimac.utils.data.*;
19
import ac.grim.grimac.utils.math.GrimMath;
20
import ac.grim.grimac.utils.math.Location;
21
import ac.grim.grimac.utils.math.Vector3dm;
22
import ac.grim.grimac.utils.math.VectorUtils;
23
import ac.grim.grimac.utils.nmsutil.BlockProperties;
24
import ac.grim.grimac.utils.nmsutil.Collisions;
25
import ac.grim.grimac.utils.nmsutil.GetBoundingBox;
26
import ac.grim.grimac.utils.nmsutil.ReachUtils;
27
import com.github.retrooper.packetevents.PacketEvents;
28
import com.github.retrooper.packetevents.manager.server.ServerVersion;
29
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
30
import com.github.retrooper.packetevents.protocol.player.GameMode;
31
import com.github.retrooper.packetevents.protocol.teleport.RelativeFlag;
32
import com.github.retrooper.packetevents.util.Vector3d;
33
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAttachEntity;
34
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
35
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityVelocity;
36
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerPositionAndLook;
37
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers;
38
import lombok.AllArgsConstructor;
39
import lombok.Getter;
40
import lombok.Setter;
41
import org.jetbrains.annotations.Nullable;
42
43
import java.util.Collections;
44
import java.util.HashSet;
45
import java.util.Random;
46
import java.util.concurrent.ConcurrentLinkedQueue;
47
48
public class SetbackTeleportUtil extends Check implements PostPredictionListener {
49
    // Sync to netty
50
    public final ConcurrentLinkedQueue<TeleportData> pendingTeleports = new ConcurrentLinkedQueue<>();
51
    private final Random random = new Random();
52
    private static final GrimTeleportEvent.Channel TELEPORT_CHANNEL = GrimAPI.INSTANCE.getEventBus().get(GrimTeleportEvent.class);
53
    private static final GrimPlayerSetbackEvent.Channel PLAYER_SETBACK_CHANNEL = GrimAPI.INSTANCE.getEventBus().get(GrimPlayerSetbackEvent.class);
54
    // Sync to netty, a player MUST accept a teleport to spawn into the world
55
    // A teleport is used to end the loading screen.  Some cheats pretend to never end the loading screen
56
    // in an attempt to disable the anticheat.  Be careful.
57
    // We fix this by blocking serverbound movements until the player is out of the loading screen.
58
    public boolean hasAcceptedSpawnTeleport = false;
59
    // Was there a ghost block that forces us to block offsets until the player accepts their teleport?
60
    public boolean blockOffsets = false;
61
    public SetbackPosWithVector lastKnownGoodPosition;
62
    // Are we currently sending setback stuff?
63
    public boolean isSendingSetback = false;
64
    public int cheatVehicleInterpolationDelay = 0;
65
    // This required setback data is the head of the teleport.
66
    // It is set by both bukkit and netty due to going on the bukkit thread to setback players
67
    @Getter
68
    private SetBackData requiredSetBack = null;
69
    private long lastWorldResync = 0;
70
71
    public SetbackTeleportUtil(GrimPlayer player) {
72
        super(player);
73
    }
74
75
    @Override
76
    public void onPredictionComplete(final PredictionComplete predictionComplete) {
77
        // Grab friction now when we know player on ground and other variables
78
        Vector3dm afterTickFriction = player.clientVelocity.clone();
79
80
        // We must first check if the player has accepted their setback
81
        // If the setback isn't complete, then this position is illegitimate
82
        if (predictionComplete.getData().getSetback() != null) {
83
            // The player needs to now wait for their vehicle to go into the right place before getting back in
84
            if (cheatVehicleInterpolationDelay > 0) cheatVehicleInterpolationDelay = 10;
85
            // Teleport, let velocity be reset
86
            lastKnownGoodPosition = new SetbackPosWithVector(new Vector3d(player.x, player.y, player.z), afterTickFriction);
87
        } else if (requiredSetBack == null || requiredSetBack.isComplete()) {
88
            cheatVehicleInterpolationDelay--;
89
            // No simulation... we can do that later. We just need to know the valid position.
90
            // As we didn't setback here, the new position is known to be safe!
91
            lastKnownGoodPosition = new SetbackPosWithVector(new Vector3d(player.x, player.y, player.z), afterTickFriction);
92
        }
93
94
        if (requiredSetBack != null) requiredSetBack.tick();
95
    }
96
97
    public void executeForceResync() {
98
        if (player.gamemode == GameMode.SPECTATOR || player.disableGrim)
99
            return; // We don't care about spectators, they don't flag
100
        if (lastKnownGoodPosition == null) return; // Player hasn't spawned yet
101
        blockMovementsUntilResync(true, true);
102
    }
103
104
    public void executeNonSimulatingForceResync() {
105
        if (player.gamemode == GameMode.SPECTATOR || player.disableGrim)
106
            return; // We don't care about spectators, they don't flag
107
        if (lastKnownGoodPosition == null) return; // Player hasn't spawned yet
108
        blockMovementsUntilResync(false, true);
109
    }
110
111
    public void executeNonSimulatingSetback() {
112
        if (player.gamemode == GameMode.SPECTATOR || player.disableGrim)
113
            return; // We don't care about spectators, they don't flag
114
        if (lastKnownGoodPosition == null) return; // Player hasn't spawned yet
115
        blockMovementsUntilResync(false, false);
116
    }
117
118
    public boolean executeViolationSetback() {
119
        if (isExempt()) return false;
120
        blockMovementsUntilResync(true, false);
121
        return true;
122
    }
123
124
    private boolean isExempt() {
125
        // Not exempting spectators here because timer check for spectators is actually valid.
126
        // Player hasn't spawned yet
127
        if (lastKnownGoodPosition == null) return true;
128
        // Setbacks aren't allowed
129
        if (player.disableGrim) return true;
130
        // Player has permission to cheat, permission not given to OP by default.
131
        return player.platformPlayer != null && player.noSetbackPermission;
132
    }
133
134
    private void simulateFriction(Vector3dm vector) {
135
        // We must always do this before simulating positions, as this is the last actual (safe) movement
136
        // We must not do this for knockback or explosions, as they are at the start of the tick
137
        if (player.wasTouchingWater) {
138
            PredictionEngineWater.staticVectorEndOfTick(player, vector, 0.8F, player.gravity, true);
139
        } else if (player.wasTouchingLava) {
140
            vector.multiply(0.5D);
141
            if (player.hasGravity)
142
                vector.add(0.0D, -player.gravity / 4.0D, 0.0D);
143
        } else if (player.isGliding) {
144
            PredictionEngineElytra.getElytraMovement(player, vector, ReachUtils.getLook(player, player.yaw, player.pitch)).multiply(player.stuckSpeedMultiplier).multiply(0.99F, 0.98F, 0.99F);
145
            vector.setY(vector.getY() - 0.05); // Make the player fall a bit
146
        } else { // Gliding doesn't have friction, we handle it differently
147
            PredictionEngineNormal.staticVectorEndOfTick(player, vector); // Lava and normal movement
148
        }
149
150
        // Prevent abusing setbacks to move out of blocks like webs
151
        vector.multiply(player.stuckSpeedMultiplier);
152
153
        // stop 1.8 players from stepping onto 1.25 high blocks, because why not?
154
        new PredictionEngine().applyMovementThreshold(player, new HashSet<>(Collections.singletonList(new VectorData(vector, VectorData.VectorType.BestVelPicked))));
155
    }
156
157
    private void blockMovementsUntilResync(boolean simulateNextTickPosition, boolean isResync) {
158
        if (requiredSetBack == null) return; // Hasn't spawned
159
        if (player.platformPlayer != null && player.noSetbackPermission)
160
            return; // The player has permission to cheat
161
        requiredSetBack.setPlugin(false); // The player has illegal movement, block from vanilla ac override
162
        if (isPendingSetback()) return; // Don't spam setbacks
163
164
        // Only let us full resync once every five seconds to prevent unneeded bukkit load
165
        if (System.currentTimeMillis() - lastWorldResync > 5 * 1000) {
166
            player.resyncPositions(player.boundingBox.copy().expand(1));
167
            lastWorldResync = System.currentTimeMillis();
168
        }
169
170
        Vector3dm clientVel = lastKnownGoodPosition.vector.clone();
171
172
        Pair<VelocityData, Vector3dm> futureKb = player.checkManager.getKnockbackHandler().getFutureKnockback();
173
        VelocityData futureExplosion = player.checkManager.getExplosionHandler().getFutureExplosion();
174
175
        // Velocity sets
176
        // Don't let player reuse setback velocity
177
        if (futureKb.first() != null && !futureKb.first().isSetback) {
178
            clientVel = futureKb.second();
179
        }
180
181
        // Explosion adds
182
        if (futureExplosion != null && (futureKb.first() == null
183
                || (futureKb.first().transaction < futureExplosion.transaction && !futureKb.first().isSetback))) {
184
            clientVel.add(futureExplosion.vector);
185
        }
186
187
        Vector3d position = lastKnownGoodPosition.pos;
188
189
        SimpleCollisionBox oldBB = player.boundingBox;
190
        player.boundingBox = GetBoundingBox.getPlayerBoundingBox(player, position.getX(), position.getY(), position.getZ());
191
192
        // Mini prediction engine - simulate collisions
193
        if (simulateNextTickPosition) {
194
            Vector3dm collide = Collisions.collide(player, clientVel.getX(), clientVel.getY(), clientVel.getZ());
195
196
            position = position.withX(position.getX() + collide.getX());
197
            position = position.withY(position.getY() + collide.getY());
198
            // TODO: Is this even needed? Can't reproduce any phasing on vanilla 1.8 when being setback.
199
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9)) {
200
                // 1.8 players need the collision epsilon to not phase into blocks when being setback
201
                // Due to simulation, this will not allow a flight bypass by sending a billion invalid movements
202
                position = position.withY(position.getY() + SimpleCollisionBox.COLLISION_EPSILON);
203
            }
204
            position = position.withZ(position.getZ() + collide.getZ());
205
206
            if (clientVel.getX() != collide.getX()) {
207
                clientVel.setX(BlockProperties.getVelocityAfterHorizontalCollision(player, clientVel.getX()));
208
            }
209
            if (clientVel.getY() != collide.getY()) {
210
                clientVel.setY(BlockProperties.getVelocityAfterVerticalCollision(player, clientVel.getY(), collide.getY()));
211
            }
212
            if (clientVel.getZ() != collide.getZ()) {
213
                clientVel.setZ(BlockProperties.getVelocityAfterHorizontalCollision(player, clientVel.getZ()));
214
            }
215
216
            simulateFriction(clientVel);
217
        }
218
219
        player.boundingBox = oldBB; // reset back to the new bounding box
220
221
        if (!hasAcceptedSpawnTeleport || player.isFlying)
222
            clientVel = null; // if the player is flying or hasn't spawned... don't force kb
223
224
        // Something weird has occurred in the player's movement, block offsets until we resync
225
        if (isResync) {
226
            blockOffsets = true;
227
        }
228
229
        SetBackData data = new SetBackData(new TeleportData(position, 0, 0, null, RelativeFlag.YAW.or(RelativeFlag.PITCH), player.lastTransactionSent.get(), 0), player.yaw, player.pitch, clientVel, player.inVehicle(), false);
230
        sendSetback(data);
231
    }
232
233
    private void sendSetback(SetBackData data) {
234
        isSendingSetback = true;
235
        Vector3d position = data.getTeleportData().getLocation();
236
237
        try {
238
            // Player is in a vehicle
239
            if (player.inVehicle()) {
240
                int vehicleId = player.getRidingVehicleId();
241
                if (player.compensatedEntities.serverPlayerVehicle != null) {
242
                    // Dismount player from vehicle
243
                    if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9)) {
244
                        player.user.sendPacket(new WrapperPlayServerSetPassengers(vehicleId, new int[2]));
245
                    } else {
246
                        player.user.sendPacket(new WrapperPlayServerAttachEntity(vehicleId, -1, false));
247
                    }
248
249
                    // Stop the player from being able to teleport vehicles and simply re-enter them to continue,
250
                    // therefore, teleport the entity
251
                    player.user.sendPacket(new WrapperPlayServerEntityTeleport(vehicleId, new Vector3d(position.getX(), position.getY(), position.getZ()), player.yaw % 360, 0, false));
252
                    player.getSetbackTeleportUtil().cheatVehicleInterpolationDelay = Integer.MAX_VALUE; // Set to max until player accepts the new position
253
254
                    // Make sure bukkit also knows the player got teleported out of their vehicle, can't do this async
255
                    GrimAPI.INSTANCE.getScheduler().getEntityScheduler().execute(player.platformPlayer, GrimAPI.INSTANCE.getGrimPlugin(), () -> {
256
                        if (player.platformPlayer != null) {
257
                            GrimEntity vehicle = player.platformPlayer.getVehicle();
258
                            if (vehicle != null) {
259
                                vehicle.eject();
260
                            }
261
                        }
262
                    }, null, 0);
263
                }
264
            }
265
266
            double y = position.getY();
267
            if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThanOrEquals(ServerVersion.V_1_7_10)) {
268
                y += 1.62; // 1.7 teleport offset if grim ever supports 1.7 again
269
            }
270
271
            // Send a transaction now to make sure there's always transactions around teleport
272
            player.sendTransaction();
273
274
            // Min value is 10000000000000000000000000000000 in binary, this makes sure the number is always < 0
275
            int teleportId = random.nextInt() | Integer.MIN_VALUE;
276
            data.setPlugin(false);
277
            data.getTeleportData().setTeleportId(teleportId);
278
            data.getTeleportData().setTransaction(player.lastTransactionSent.get());
279
280
            // Use provided transaction ID to make sure it can never desync, although there's no reason to do this
281
            addSentTeleport(new Location(null, position.getX(), y, position.getZ()),
282
                    null, data.getTeleportData().getTransaction(), RelativeFlag.YAW.or(RelativeFlag.PITCH), false, teleportId);
283
            // This must be done after setting the sent teleport, otherwise we lose velocity data
284
            requiredSetBack = data;
285
            // Send after tracking to fix race condition
286
            PacketEvents.getAPI().getProtocolManager().sendPacketSilently(player.user.getChannel(), new WrapperPlayServerPlayerPositionAndLook(position.getX(), position.getY(), position.getZ(), 0, 0, data.getTeleportData().getFlags().getMask(), teleportId, false));
287
            // Dual fire: packet-level signal for anticheat compat (GrimTeleportEvent),
288
            // semantic signal for admin/observability consumers (GrimPlayerSetbackEvent).
289
            long now = System.currentTimeMillis();
290
            TELEPORT_CHANNEL.fire(player, teleportId, now);
291
            PLAYER_SETBACK_CHANNEL.fire(player, teleportId, position.getX(), position.getY(), position.getZ(), now);
292
            player.sendTransaction();
293
294
            if (data.getVelocity() != null && data.getVelocity().lengthSquared() > 0) {
295
                player.user.sendPacket(new WrapperPlayServerEntityVelocity(player.entityID, new Vector3d(data.getVelocity().getX(), data.getVelocity().getY(), data.getVelocity().getZ())));
296
            }
297
        } finally {
298
            isSendingSetback = false;
299
        }
300
    }
301
302
    /**
303
     * @param x - Player X position
304
     * @param y - Player Y position
305
     * @param z - Player Z position
306
     * @return - Whether the player has completed a teleport by being at this position
307
     */
308
    public TeleportAcceptData checkTeleportQueue(double x, double y, double z, float yaw, float pitch) {
309
        // Support teleports without teleport confirmations
310
        // If the player is in a vehicle when teleported, they will exit their vehicle
311
        TeleportAcceptData teleportData = new TeleportAcceptData();
312
313
        TeleportData teleportPos;
314
        while ((teleportPos = pendingTeleports.peek()) != null) {
315
            double trueTeleportX = (teleportPos.isRelativeX() ? player.x : 0) + teleportPos.getLocation().getX();
316
            double trueTeleportY = (teleportPos.isRelativeY() ? player.y : 0) + teleportPos.getLocation().getY();
317
            double trueTeleportZ = (teleportPos.isRelativeZ() ? player.z : 0) + teleportPos.getLocation().getZ();
318
319
            // There seems to be a version difference in teleports past 30 million... just clamp the vector
320
            Vector3d clamped = VectorUtils.clampVector(new Vector3d(trueTeleportX, trueTeleportY, trueTeleportZ));
321
            double threshold = teleportPos.isRelativePos() ? player.getMovementThreshold() : 0;
322
            boolean closeEnoughY = Math.abs(clamped.getY() - y) <= 1e-7 + threshold; // 1.7 rounding
323
            // rotations are updated every frame, we can't accurately check them if they're relative
324
            boolean correctRotations = (yaw == teleportPos.getYaw() || teleportPos.isRelativeYaw())
325
                    && (pitch == teleportPos.getPitch() || teleportPos.isRelativePitch());
326
327
            if (player.lastTransactionReceived.get() == teleportPos.getTransaction() && Math.abs(clamped.getX() - x) <= threshold && closeEnoughY && Math.abs(clamped.getZ() - z) <= threshold && correctRotations) {
328
                pendingTeleports.poll();
329
                hasAcceptedSpawnTeleport = true;
330
                blockOffsets = false;
331
332
                // Player has accepted their setback!
333
                // We can compare transactions to check if equals because each teleport gets its own transaction
334
                if (requiredSetBack != null && requiredSetBack.getTeleportData().getTransaction() == teleportPos.getTransaction()) {
335
                    teleportData.setSetback(requiredSetBack);
336
                    requiredSetBack.setComplete(true);
337
                }
338
339
                teleportData.setTeleportData(teleportPos);
340
                teleportData.setTeleport(true);
341
                break;
342
            } else if (player.lastTransactionReceived.get() > teleportPos.getTransaction()) {
343
                // The player ignored the teleport (and this teleport matters), resynchronize
344
                player.checkManager.getCheck(BadPacketsN.class).flag();
345
                pendingTeleports.poll();
346
                requiredSetBack.setPlugin(false);
347
                if (pendingTeleports.isEmpty()) {
348
                    sendSetback(requiredSetBack);
349
                }
350
                continue;
351
            }
352
            // No farther setbacks before the player's transaction
353
            break;
354
        }
355
356
        return teleportData;
357
    }
358
359
    /**
360
     * @param x - Player X position
361
     * @param y - Player Y position
362
     * @param z - Player Z position
363
     * @return - Whether the player has completed a teleport by being at this position
364
     */
365
    public boolean checkVehicleTeleportQueue(double x, double y, double z) {
366
        int lastTransaction = player.lastTransactionReceived.get();
367
368
        while (true) {
369
            IntToObjectPair<Vector3d> teleportPos = player.vehicleData.vehicleTeleports.peek();
370
            if (teleportPos == null) break;
371
            if (lastTransaction < teleportPos.first()) {
372
                break;
373
            }
374
375
            Vector3d position = teleportPos.second();
376
            if (position.getX() == x && position.getY() == y && position.getZ() == z) {
377
                player.vehicleData.vehicleTeleports.poll();
378
379
                return true;
380
            } else if (lastTransaction > teleportPos.first() + 1) {
381
                player.vehicleData.vehicleTeleports.poll();
382
383
                // Vehicles have terrible netcode so just ignore it if the teleport wasn't from us setting the player back
384
                // Players don't have to respond to vehicle teleports if they aren't controlling the entity anyways
385
                continue;
386
            }
387
388
            break;
389
        }
390
391
        return false;
392
    }
393
394
    /**
395
     * @return If the player is in a desync state and is waiting on information from the server
396
     */
397
    public boolean shouldBlockMovement() {
398
        // This is required to ensure protection from servers teleporting from CREATIVE to SURVIVAL
399
        // I should likely refactor
400
        return insideUnloadedChunk() || blockOffsets || (requiredSetBack != null && !requiredSetBack.isComplete());
401
    }
402
403
    private boolean isPendingSetback() {
404
        // Relative setbacks shouldn't count
405
        if (requiredSetBack != null && (requiredSetBack.getTeleportData().isRelativeX() || requiredSetBack.getTeleportData().isRelativeY() || requiredSetBack.getTeleportData().isRelativeZ())) {
406
            return false;
407
        }
408
        // The setback is not complete
409
        return requiredSetBack != null && !requiredSetBack.isComplete();
410
    }
411
412
    /**
413
     * When the player is inside an unloaded chunk, they simply fall through the void which shouldn't be checked
414
     *
415
     * @return Whether the player has loaded the chunk and accepted a teleport to correct movement or not
416
     */
417
    public boolean insideUnloadedChunk() {
418
        Column column = player.compensatedWorld.getChunk(GrimMath.floor(player.x) >> 4, GrimMath.floor(player.z) >> 4);
419
420
        // If true, the player is in an unloaded chunk
421
        return !player.disableGrim && (column == null || column.transaction() >= player.lastTransactionReceived.get() ||
422
                // The player hasn't loaded past the DOWNLOADING TERRAIN screen
423
                !player.getSetbackTeleportUtil().hasAcceptedSpawnTeleport);
424
    }
425
426
    public void addSentTeleport(Location position, @Nullable Vector3d velocity, int transaction, RelativeFlag flags, boolean plugin, int teleportId) {
427
        // Clients below 1.21.2 do not have this.
428
        if (player.getClientVersion().isOlderThan(ClientVersion.V_1_21_2)) {
429
            velocity = null;
430
        }
431
432
        TeleportData data = new TeleportData(
433
                new Vector3d(position.getX(), position.getY(), position.getZ()),
434
                position.getYaw(),
435
                position.getPitch(),
436
                velocity,
437
                flags,
438
                transaction,
439
                teleportId
440
        );
441
        pendingTeleports.add(data);
442
443
        Vector3d safePosition = new Vector3d(position.getX(), position.getY(), position.getZ());
444
445
        // We must convert relative teleports to avoid them becoming client controlled in the case of setback
446
        if (flags.has(RelativeFlag.X)) {
447
            safePosition = safePosition.withX(safePosition.getX() + lastKnownGoodPosition.pos.getX());
448
        }
449
450
        if (flags.has(RelativeFlag.Y)) {
451
            safePosition = safePosition.withY(safePosition.getY() + lastKnownGoodPosition.pos.getY());
452
        }
453
454
        if (flags.has(RelativeFlag.Z)) {
455
            safePosition = safePosition.withZ(safePosition.getZ() + lastKnownGoodPosition.pos.getZ());
456
        }
457
458
        data = new TeleportData(safePosition, 0, 0, velocity, RelativeFlag.YAW.or(RelativeFlag.PITCH), transaction, teleportId);
459
        requiredSetBack = new SetBackData(data, player.yaw, player.pitch, null, false, plugin);
460
461
        this.lastKnownGoodPosition = new SetbackPosWithVector(safePosition, new Vector3dm());
462
    }
463
464
    @AllArgsConstructor
465
    @Getter
466
    @Setter
467
    public static class SetbackPosWithVector {
468
        private final Vector3d pos;
469
        private Vector3dm vector;
470
    }
471
}

How it counteracts this module

The setback manager carries the spawn teleport acceptance flag (hasAcceptedSpawnTeleport) that gates teleport rejection and resync behavior after joins and respawns. The ESP moves nothing and sends no C03, so the acceptance state machine is driven purely by the server's own S08 and spawn traffic, exactly as for vanilla clients. The entry documents the other spawn-touching Grim surface and why a module that only draws boxes cannot reach it.

anticheat MovingUtil (spawn-location bookkeeping)

MovingUtil.java633 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.utilities.moving;
16
17
import java.util.UUID;
18
19
import org.bukkit.Chunk;
20
import org.bukkit.GameMode;
21
import org.bukkit.Location;
22
import org.bukkit.entity.Entity;
23
import org.bukkit.entity.EntityType;
24
import org.bukkit.entity.LivingEntity;
25
import org.bukkit.entity.Player;
26
import org.bukkit.event.entity.EntityToggleGlideEvent;
27
import org.bukkit.event.player.PlayerMoveEvent;
28
29
import fr.neatmonster.nocheatplus.NCPAPIProvider;
30
import fr.neatmonster.nocheatplus.checks.CheckType;
31
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
32
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
33
import fr.neatmonster.nocheatplus.checks.moving.model.MoveData;
34
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerMoveData;
35
import fr.neatmonster.nocheatplus.checks.moving.player.PlayerSetBackMethod;
36
import fr.neatmonster.nocheatplus.checks.net.NetData;
37
import fr.neatmonster.nocheatplus.checks.net.model.CountableLocation;
38
import fr.neatmonster.nocheatplus.compat.*;
39
import fr.neatmonster.nocheatplus.components.debug.IDebugPlayer;
40
import fr.neatmonster.nocheatplus.logging.StaticLog;
41
import fr.neatmonster.nocheatplus.players.DataManager;
42
import fr.neatmonster.nocheatplus.players.IPlayerData;
43
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
44
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
45
import fr.neatmonster.nocheatplus.utilities.location.LocUtil;
46
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
47
import fr.neatmonster.nocheatplus.utilities.location.RichBoundsLocation;
48
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
49
import fr.neatmonster.nocheatplus.utilities.map.MapUtil;
50
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
51
52
53
/**
54
 * Static utility methods.
55
 * @author asofold
56
 *
57
 */
58
public class MovingUtil {
59
60
    /**
61
     * Always set world to null after use, careful with nested methods. Main thread only.
62
     */
63
    private static final Location useLoc = new Location(null, 0, 0, 0);
64
    private static final Location useLoc2 = new Location(null, 0, 0, 0);
65
    //    /** Fast scan flags for 'mostly air'. */
66
    //    private static final long FLAGS_SCAN_FOR_GROUND_OR_RESETCOND = 
67
    //            BlockFlags.F_SOLID | BlockFlags.F_GROUND
68
    //            | BlockFlags.F_LIQUID | BlockFlags.F_COBWEB
69
    //            | BlockFlags.F_CLIMBABLE
70
    //            ;
71
72
73
    /**
74
     * Check if the player is to be checked by the survivalfly check.<br>
75
     * Primary thread only.
76
     * 
77
     * @param player
78
     * @param fromLocation
79
     *            The location the player is moving from or just where the
80
     *            player is.
81
     * @param toLocation
82
     *            The location the player has moved to.
83
     * @param data
84
     * @param cc
85
     * @return
86
     */
87
    public static final boolean shouldCheckSurvivalFly(final Player player, final PlayerLocation fromLocation, final PlayerLocation toLocation, 
88
                                                       final MovingData data, final MovingConfig cc, final IPlayerData pData) {
89
90
        final GameMode gameMode = player.getGameMode();
91
        return  
92
                // Sf is active (duh..)
93
                // (Full activation check - use permission caching for performance rather.)
94
                pData.isCheckActive(CheckType.MOVING_SURVIVALFLY, player) 
95
                // Spectator is handled by Cf
96
                && gameMode != BridgeMisc.GAME_MODE_SPECTATOR
97
                // Creative or ignoreCreative is off/flying - let Cf handle those.
98
                && (cc.ignoreCreative || gameMode != GameMode.CREATIVE) && !player.isFlying()
99
                // IgnoreAllowFlight is off or the player is allowed to fly (cf).
100
                && (cc.ignoreAllowFlight || !player.getAllowFlight())
101
            ;
102
    }
103
104
105
    /**
106
     * Consistency / cheat check.<br>
107
     * It assumes {@link Bridge1_9#isGliding(LivingEntity)} has already returned {@code true}, and checks whether a player can
108
     * continue to glide for this gliding phase (i.e.: the elytra breaking mid-flight would make this return {@code false}).
109
     * 
110
     * @param player
111
     * @param loc
112
     * @param data
113
     * @param cc
114
     * @return
115
     */
116
    public static boolean canStillGlide(final Player player, final PlayerLocation loc, final MovingData data) {
117
        // Only stuck-speed blocks (webs/berry bushes/powder snow?) can stop a player who isn't propelled by a rocket.
118
        return data.fireworksBoostDuration > 0 && !loc.isResetCond()
119
               || !loc.isResetCond() && !player.isDead() && !player.isSleeping() && !InventoryUtil.isItemBroken(player.getInventory().getChestplate());
120
    }
121
122
    /**
123
     * Consistency / cheat check.<br>
124
     * Unlike {@link #canStillGlide(Player, PlayerLocation, MovingData)}, this method only validates the toggle moment.<br>
125
     * To be called on {@link EntityToggleGlideEvent}(s). If the event is absent, this must be called after checking for elytra lift-off assumption conditions on {@link PlayerMoveEvent}(s) (currently, we just assume players to toggle glide on if
126
     * lastMove wasn't gliding and thisMove is. See CombinedListener -> onEventlessToggleGlide).
127
     * 
128
     * @param player
129
     * @param loc
130
     * @param data
131
     * @return False, if the player is judged to not be able to start gliding (in which case the {@link EntityToggleGlideEvent} will be canceled. If this is called on {@link PlayerMoveEvent}, {@link LivingEntity#setGliding(boolean)} is called instead, as canceling the event would mean canceling the entire movement.
132
     */
133
    public static boolean canLiftOffWithElytra(final Player player, final PlayerLocation loc, final MovingData data) {
134
        // TODO: this/firstPast- Move not touching or not explicitly on ground would be enough?
135
        return 
136
                loc.isPassableBox() // Full box as if standing for lift-off.
137
                // Durability is checked within PlayerConnection (toggling on).
138
                // We check for it anyway in case of deync states or something changes on Bukkit's side.
139
                && !InventoryUtil.isItemBroken(player.getInventory().getChestplate())
140
                && !loc.isOnGround()
141
                // Immediately stop this gliding phase if colliding with a liquid block.
142
                // Players can technically maintain the gliding _POSE_ when in a liquid, but Minecraft does not allow gliding in it. (In EntityLiving.java, travel() you can see that the game checks for gliding separately)
143
                // This results in a very glitchy interaction when players want to get out of a liquid with a gliding pose (they can bob up and down on the surface)
144
                // This effectively (and slightly) alters vanilla behaviour. Unless there are legit vanilla techniques that do make use of this stuff, we are not going to remove this fix.
145
                && (
146
                    !loc.isInLiquid() 
147
                    // Observed with head free, but feet clearly in water:
148
                    // lift off from water (not 100% easy to do).
149
                    || !BlockProperties.isLiquid(loc.getBlockType())
150
                    || !BlockProperties.isLiquid(loc.getBlockTypeAbove())
151
                )
152
                // Minecraft does not allow players to toggle glide on with levitation.
153
                && Double.isInfinite(Bridge1_9.getLevitationAmplifier(player))
154
                ;
155
    }
156
157
158
    /**
159
     * Workaround for getEyeHeight not accounting for special conditions like
160
     * gliding with elytra. (Sleeping is not checked.)
161
     * 
162
     * @param player
163
     * @return
164
     */
165
    public static double getEyeHeight(final Player player) {
166
        // TODO: Need a variant/method to test legitimate state transitions?
167
        // TODO: EntityToggleGlideEvent
168
        return Bridge1_9.isGlidingWithElytra(player) ? 0.4 : player.getEyeHeight();
169
    }
170
    
171
    /**
172
     * Handle an illegal move by a player, attempt to restore a valid location.
173
     * <br>
174
     * NOTE: event.setTo is used to not leave a gap.
175
     * 
176
     * @param event
177
     * @param player
178
     * @param data
179
     * @param cc
180
     */
181
    public static void handleIllegalMove(final PlayerMoveEvent event, final Player player, 
182
                                         final MovingData data, final MovingConfig cc) {
183
184
        // This might get extended to a check-like thing.
185
        boolean restored = false;
186
        final PlayerLocation pLoc = new PlayerLocation(NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(MCAccess.class), null);
187
        // (Mind that we don't set the block cache here).
188
        final Location loc = player.getLocation();
189
        if (!restored && data.hasSetBack()) {
190
            /*
191
             * TODO: Harmonize with MovingUtil.getApplicableSetBackLocation
192
             * (somehow include the desired set back type / loc / context).
193
             */
194
            final Location setBack = data.getSetBack(loc); // TODO
195
            pLoc.set(setBack, player);
196
            if (!pLoc.hasIllegalCoords() && (cc.ignoreStance || !pLoc.hasIllegalStance())) {
197
                event.setFrom(setBack);
198
                event.setTo(setBack);
199
                restored = true;
200
            }
201
            else {
202
                data.resetSetBack();
203
            }
204
        } 
205
        if (!restored) {
206
            pLoc.set(loc, player);
207
            if (!pLoc.hasIllegalCoords() && (cc.ignoreStance || !pLoc.hasIllegalStance())) {
208
                event.setFrom(loc);
209
                event.setTo(loc);
210
                restored = true;
211
            }
212
        }
213
        pLoc.cleanup();
214
        if (!restored) {
215
            // TODO: reset the bounding box of the player ?
216
            if (cc.tempKickIllegal) {
217
                NCPAPIProvider.getNoCheatPlusAPI().denyLogin(player.getName(), 24L * 60L * 60L * 1000L);
218
                StaticLog.logSevere("[NoCheatPlus] could not restore location for " + player.getName() + ", kicking them and deny login for 24 hours");
219
            } else {
220
                StaticLog.logSevere("[NoCheatPlus] could not restore location for " + player.getName() + ", kicking them.");
221
            }
222
            CheckUtils.kickIllegalMove(player, cc);
223
        }
224
    }
225
226
227
    /**
228
     * Check the context-independent pre-conditions for checking for untracked
229
     * locations (not the world spawn, location is not passable, passable is
230
     * enabled for the player).
231
     * 
232
     * @param player
233
     * @param loc
234
     * @return
235
     */
236
    public static boolean shouldCheckUntrackedLocation(final Player player, final Location loc, final IPlayerData pData) {
237
        return !TrigUtil.isSamePos(loc, loc.getWorld().getSpawnLocation()) 
238
                && !BlockProperties.isPassable(loc)
239
                && pData.isCheckActive(CheckType.MOVING_PASSABLE, player);
240
    }
241
242
243
    /**
244
     * Detect if the given location is an untracked spot. This is spots for
245
     * which a player is at the location, but the moving data has another
246
     * "last to" position set for that player. Note that one matching player
247
     * with "last to" being consistent is enough to let this return null, world spawn is exempted.
248
     * <hr>
249
     * Pre-conditions:<br>
250
     * <li>Context-specific (e.g. activation flags for command, teleport).</li>
251
     * <li>See MovingUtils.shouldCheckUntrackedLocation.</li>
252
     * 
253
     * @param loc
254
     * @return Corrected location, if loc is an "untracked location".
255
     */
256
    public static Location checkUntrackedLocation(final Location loc) {
257
        // TODO: More efficient method to get entities at the same position (might use MCAccess).
258
        final Chunk toChunk = loc.getChunk();
259
        final Entity[] entities = toChunk.getEntities();
260
        MovingData untrackedData = null;
261
        for (int i = 0; i < entities.length; i++) {
262
            final Entity entity = entities[i];
263
            if (entity.getType() != EntityType.PLAYER) {
264
                continue;
265
            }
266
            final Location refLoc = entity.getLocation(useLoc2);
267
            // Exempt world spawn.
268
            // TODO: Exempt other warps -> HASH based exemption (expire by time, keep high count)?
269
            if (TrigUtil.isSamePos(loc, refLoc) && (entity instanceof Player)) {
270
                final Player other = (Player) entity;
271
                final IPlayerData otherPData = DataManager.getPlayerData(other);
272
                final MovingData otherData = otherPData.getGenericInstance(MovingData.class);
273
                final PlayerMoveData otherLastMove = otherData.playerMoves.getFirstPastMove();
274
                if (!otherLastMove.toIsValid) {
275
                    // Data might have been removed.
276
                    // TODO: Consider counting as tracked?
277
                    continue;
278
                }
279
                else if (TrigUtil.isSamePos(refLoc, otherLastMove.to.getX(), otherLastMove.to.getY(), otherLastMove.to.getZ())) {
280
                    // Tracked.
281
                    return null;
282
                }
283
                else {
284
                    // Untracked location.
285
                    // TODO: Discard locations in the same block, if passable.
286
                    // TODO: Sanity check distance?
287
                    // More leniency: allow moving inside of the same block.
288
                    if (TrigUtil.isSameBlock(loc, otherLastMove.to.getX(), otherLastMove.to.getY(), otherLastMove.to.getZ()) && !BlockProperties.isPassable(refLoc.getWorld(), otherLastMove.to.getX(), otherLastMove.to.getY(), otherLastMove.to.getZ())) {
289
                        continue;
290
                    }
291
                    untrackedData = otherData;
292
                }
293
            }
294
        }
295
        useLoc2.setWorld(null); // Cleanup.
296
        if (untrackedData == null) {
297
            return null;
298
        }
299
        else {
300
            // TODO: Count and log to TRACE_FILE, if multiple locations would match (!).
301
            final PlayerMoveData lastMove = untrackedData.playerMoves.getFirstPastMove();
302
            return new Location(loc.getWorld(), lastMove.to.getX(), lastMove.to.getY(), lastMove.to.getZ(), loc.getYaw(), loc.getPitch());
303
        }
304
    }
305
306
307
    /**
308
     * Convenience method for the case that the server has already reset the
309
     * fall distance, e.g. with micro moves.
310
     * 
311
     * @param player
312
     * @param fromY
313
     * @param toY
314
     * @param data
315
     * @return
316
     */
317
    public static double getRealisticFallDistance(final Player player, final double fromY, final double toY, 
318
                                                  final MovingData data, final IPlayerData pData) {
319
        if (pData.isCheckActive(CheckType.MOVING_NOFALL, player)) {
320
            // (NoFall will not be checked, if this method is called.)
321
            if (data.noFallMaxY >= fromY) {
322
                return Math.max(0.0, data.noFallMaxY - toY);
323
            } 
324
            return Math.max(0.0, fromY - toY); // Skip to avoid exploits: + player.getFallDistance()
325
        } 
326
        return (double) player.getFallDistance() + Math.max(0.0, fromY - toY);
327
    }
328
329
330
    /**
331
     * Ensure we have a set back location set, plus allow moving from upwards
332
     * with respawn/login. Intended for MovingListener (pre-checks).
333
     * 
334
     * @param player
335
     * @param from
336
     * @param data
337
     */
338
    public static void checkSetBack(final Player player, final PlayerLocation from, 
339
                                    final MovingData data, final IPlayerData pData, final IDebugPlayer idp) {
340
341
        if (!data.hasSetBack()) {
342
            data.setSetBack(from);
343
        }
344
        else if (data.joinOrRespawn && from.getY() > data.getSetBackY() && 
345
                TrigUtil.isSamePos(from.getX(), from.getZ(), data.getSetBackX(), data.getSetBackZ()) &&
346
                (from.isOnGround() || from.isResetCond())) {
347
            // TODO: Move most to a method?
348
            // TODO: Is a margin needed for from.isOnGround()? [bukkitapionly]
349
            if (pData.isDebugActive(CheckType.MOVING)) {
350
                // TODO: Should this be info?
351
                idp.debug(player, "Adjust set back after join/respawn: " + from.getLocation());
352
            }
353
            data.setSetBack(from);
354
            data.resetPlayerPositions(from);
355
        }
356
    }
357
358
359
    public static double getJumpAmplifier(final Player player, final MCAccess mcAccess) {
360
        final double amplifier = mcAccess.getJumpAmplifier(player);
361
        if (Double.isInfinite(amplifier)) {
362
            return 0.0;
363
        }
364
        return 1.0 + amplifier;
365
    }
366
367
368
    public static void prepareFullCheck(final RichBoundsLocation from, final RichBoundsLocation to, final MoveData thisMove, final double yOnGround) {
369
        // Collect block flags.
370
        from.collectBlockFlags(yOnGround);
371
        if (from.isSamePos(to)) {
372
            // TODO: Could consider pTo = pFrom, set pitch / yaw elsewhere.
373
            // Sets all properties, but only once.
374
            to.prepare(from);
375
        }
376
        else {
377
            // Might collect block flags for small distances with the containing bounds for both. 
378
            to.collectBlockFlags(yOnGround);
379
        }
380
381
        // Set basic properties for past move bookkeeping.
382
        thisMove.setExtraProperties(from, to);
383
    }
384
385
386
    /**
387
     * Ensure nearby chunks are loaded so that the move can be processed at all.
388
     * Assume too big moves to be cancelled anyway and/or checks like passable
389
     * accounting for chunk load. Further skip chunk loading if the latest
390
     * stored past move has extra properties set and is close by.
391
     * 
392
     * @param from
393
     * @param to
394
     * @param lastMove
395
     * @param tag
396
     *            The type of context/event for debug logging.
397
     * @param data
398
     * @param cc
399
     */
400
    public static void ensureChunksLoaded(final Player player,final Location from, final Location to, final PlayerMoveData lastMove, 
401
                                          final String tag, final MovingConfig cc, final IPlayerData pData) {
402
403
        // (Worlds must be equal. Ensured in player move handling.)
404
        final double x0 = from.getX();
405
        final double z0 = from.getZ();
406
        final double x1 = to.getX();
407
        final double z1 = to.getZ();
408
        if (TrigUtil.distanceSquared(x0, z0, x1, z1) > 2.0 * Magic.CHUNK_LOAD_MARGIN_MIN) {
409
            // Assume extreme move to trigger.
410
            return;
411
        }
412
        boolean loadFrom = true;
413
        boolean loadTo = true;
414
        double margin = Magic.CHUNK_LOAD_MARGIN_MIN;
415
        // Heuristic for if loading may be necessary at all.
416
        if (lastMove.toIsValid && lastMove.to.extraPropertiesValid) {
417
            if (TrigUtil.distanceSquared(lastMove.to, x0, z0) < 1.0) {
418
                loadFrom = false;
419
            }
420
            if (TrigUtil.distanceSquared(lastMove.to, x1, z1) < 1.0) {
421
                loadTo = false;
422
            }
423
        }
424
        else if (lastMove.valid && lastMove.from.extraPropertiesValid
425
                && cc.loadChunksOnJoin) {
426
            // TODO: Might need to distinguish join/teleport/world-change later.
427
            if (TrigUtil.distanceSquared(lastMove.from, x0, z0) < 1.0) {
428
                loadFrom = false;
429
            }
430
            if (TrigUtil.distanceSquared(lastMove.from, x1, z1) < 1.0) {
431
                loadTo = false;
432
            }
433
        }
434
        int loaded = 0;
435
        if (loadFrom) {
436
            loaded += MapUtil.ensureChunksLoaded(from.getWorld(), x0, z0, margin);
437
            if (TrigUtil.distanceSquared(x0, z0, x1, z1) < 1.0) {
438
                loadTo = false;
439
            }
440
        }
441
        if (loadTo) {
442
            loaded += MapUtil.ensureChunksLoaded(to.getWorld(), x1, z1, margin);
443
        }
444
        if (loaded > 0 && pData.isDebugActive(CheckType.MOVING)) {
445
            StaticLog.logInfo("Player " + tag + ": Loaded " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + from.getWorld().getName() +  " for player: " + player.getName());
446
        }
447
    }
448
449
450
    /**
451
     * Ensure nearby chunks are loaded. Further skip chunk loading if the latest
452
     * stored past move has extra properties set and is close by.
453
     * 
454
     * @param player
455
     * @param loc
456
     * @param tag
457
     *            The type of context/event for debug logging.
458
     * @param data
459
     * @param cc
460
     */
461
    public static void ensureChunksLoaded(final Player player, final Location loc, final String tag, 
462
                                          final MovingData data, final MovingConfig cc, final IPlayerData pData) {
463
464
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
465
        final double x0 = loc.getX();
466
        final double z0 = loc.getZ();
467
        // Heuristic for if loading may be necessary at all.
468
        if (lastMove.toIsValid && lastMove.to.extraPropertiesValid) {
469
            if (TrigUtil.distanceSquared(lastMove.to, x0, z0) < 1.0) {
470
                return;
471
            }
472
        }
473
        else if (lastMove.valid && lastMove.from.extraPropertiesValid
474
                && cc.loadChunksOnJoin) {
475
            // TODO: Might need to distinguish join/teleport/world-change later.
476
            if (TrigUtil.distanceSquared(lastMove.from, x0, z0) < 1.0) {
477
                return;
478
            }
479
        }
480
        int loaded = MapUtil.ensureChunksLoaded(loc.getWorld(), loc.getX(), loc.getZ(), Magic.CHUNK_LOAD_MARGIN_MIN);
481
        if (loaded > 0 && pData.isDebugActive(CheckType.MOVING)) {
482
            StaticLog.logInfo("Player " + tag + ": Loaded " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + loc.getWorld().getName() +  " for player: " + player.getName());
483
        }
484
    }
485
486
487
    /**
488
     * Test if a set back is set in data and scheduled. <br>
489
     * Primary thread only.
490
     * 
491
     * @param player
492
     * @return
493
     */
494
    public static boolean hasScheduledPlayerSetBack(final Player player) {
495
        return hasScheduledPlayerSetBack(player.getUniqueId(), 
496
                DataManager.getGenericInstance(player, MovingData.class));
497
    }
498
499
500
    /**
501
     * Test if a set back is set in data and scheduled. <br>
502
     * Primary thread only.
503
     * @param playerId
504
     * @param data
505
     * @return
506
     */
507
    public static boolean hasScheduledPlayerSetBack(final UUID playerId, final MovingData data) {
508
        return data.hasTeleported() && isPlayersetBackScheduled(playerId);
509
    }
510
511
512
    private static boolean isPlayersetBackScheduled(final UUID playerId) {
513
        final IPlayerData pd = DataManager.getPlayerData(playerId);
514
        return pd != null  && pd.isPlayerSetBackScheduled();
515
    }
516
517
518
    /**
519
     * 
520
     * @param player
521
     * @param debugMessagePrefix
522
     * @return True, if the teleport has been successful.
523
     */
524
    public static boolean processStoredSetBack(final Player player, final String debugMessagePrefix, final IPlayerData pData) {
525
        final MovingData data = pData.getGenericInstance(MovingData.class);
526
        final boolean debug = pData.isDebugActive(CheckType.MOVING);
527
        if (!data.hasTeleported()) {
528
            if (debug) {
529
                CheckUtils.debug(player, CheckType.MOVING, debugMessagePrefix + "No stored location available.");
530
            }
531
            return false;
532
        }
533
        // (teleported is set.).
534
535
        final Location loc = player.getLocation(useLoc);
536
        if (data.isTeleportedPosition(loc)) {
537
            // Skip redundant teleport.
538
            if (debug) {
539
                CheckUtils.debug(player, CheckType.MOVING, debugMessagePrefix + "Skip teleport, player is there, already.");
540
            }
541
            data.resetTeleported(); // Not necessary to keep.
542
            useLoc.setWorld(null);
543
            return false;
544
        }
545
        useLoc.setWorld(null);
546
        // (player is somewhere else.)
547
548
        // Post-1.9 packet level workaround.
549
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
550
        // TODO: Consider to skip checking for packet level, if not available (plus optimize access).
551
        // TODO: Consider a config flag, so this can be turned off (set back method).
552
        final PlayerSetBackMethod method = cc.playerSetBackMethod;
553
        if (!method.shouldNoRisk() && (method.shouldCancel() || method.shouldSetTo()) && method.shouldUpdateFrom()) {
554
            /*
555
             * Another leniency option: Skip, if we have already received an ACK
556
             * for this position on packet level - typically the next move would
557
             * confirm the set-back, but a redundant teleport would freeze the
558
             * player for a slightly longer time. This could happen with the set
559
             * back being at the coordinates the player had just been at, but
560
             * between set back and on-tick there has been a micro move (not
561
             * firing a PlayerMoveEvent) - similarly observed on a local test
562
             * server once, HOWEVER there the micro move had been a look-only
563
             * packet, not explaining why the position of the player wasn't
564
             * reflecting the outgoing position. So here remains the uncertainty
565
             * concerning the question if a (silent) Minecraft entity teleport
566
             * always follows a cancelled PlayerMoveEvent (!), and a thinkable
567
             * potential for abuse.
568
             */
569
            // (CANCEL + UPDATE_FROM mean a certain teleport to the set back, still could be repeated tp.)
570
            // TODO: Better method, full sync reference?
571
            final CountableLocation cl = pData.getGenericInstance(NetData.class).teleportQueue.getLastAck();
572
            if (data.isTeleportedPosition(cl)) {
573
                if (debug) {
574
                    CheckUtils.debug(player, CheckType.MOVING, debugMessagePrefix + "Skip teleport, having received an ACK for the teleport on packet level. Player is at: " + LocUtil.simpleFormat(loc));
575
                }
576
                // Keep teleported in data. Subject to debug logs and/or discussion.
577
                return false;
578
            }
579
        }
580
        // (No ACK received yet.)
581
582
        // Attempt to teleport.
583
        final Location teleported = data.getTeleported();
584
        // (Data resetting is done during PlayerTeleportEvent handling.)
585
        if (SchedulerHelper.teleportEntity(player, teleported, BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION)) {
586
            return true;
587
        }
588
        else {
589
            if (debug) {
590
                CheckUtils.debug(player, CheckType.MOVING, "Player set back on tick: Teleport failed.");
591
            }
592
            return false;
593
        }
594
    }
595
596
597
    /**
598
     * Get the applicable set-back location at this moment.
599
     * <hr>
600
     * <ul>
601
     * <li>The idea is that this method call remains side effect free.</li>
602
     * <li>Because set-back policies may need scanning for ground down to the
603
     * void, calling this method can have an impact on performance, if called
604
     * excessively.</li>
605
     * </ul>
606
     * 
607
     * @param player
608
     * @param refYaw
609
     * @param refPitch
610
     * @param from
611
     *            Safe reference location, for scanning for ground/void.
612
     *            Typically a move start point. Not used for a return value
613
     *            directly.
614
     * @param data
615
     * @param cc
616
     * @return The applicable set back location
617
     */
618
    public static Location getApplicableSetBackLocation(final Player player, final float refYaw, final float refPitch, 
619
                                                        final PlayerLocation from, final MovingData data, final MovingConfig cc) {
620
        /*
621
         * TODO: Consider returning a context object (include if to deal fall
622
         * damage, otherwise / if possible use a utility method checking the
623
         * config and ground properties).
624
         */
625
        // Ordinary handling.
626
        if (data.hasSetBack()) {
627
            return data.getSetBack(refYaw, refPitch); // (OK)
628
        }
629
        // Nothing appropriate found.
630
        // (If no set back is set, should be checked before the actual check is run.)
631
        return null;
632
    }
633
}

How it counteracts this module

NCP's movement utilities touch the spawn data in one place: comparisons against the world spawn location (isSamePos against loc.getWorld().getSpawnLocation()) that feed the movement checks' world-state assumptions. The ESP produces no movement packets and mutates no world state, so every MovingUtil computation sees the same inputs as for a vanilla client. The entry is the honest gap for NCP's spawn story: its only spawn-adjacent logic is positional bookkeeping inside the movement layer, unreachable from a render module.

anticheat LivingEntityIdLookup (spawn id cache)

LivingEntityIdLookup.java89 lines · Java
1
package de.photon.anticheataddition.util.protocol;
2
3
import com.github.retrooper.packetevents.PacketEvents;
4
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
5
import com.github.retrooper.packetevents.event.PacketSendEvent;
6
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
7
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
8
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity;
9
import com.google.common.cache.Cache;
10
import com.google.common.cache.CacheBuilder;
11
import de.photon.anticheataddition.AntiCheatAddition;
12
import de.photon.anticheataddition.util.log.Log;
13
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
14
import org.bukkit.Bukkit;
15
import org.bukkit.World;
16
import org.bukkit.entity.LivingEntity;
17
import org.jspecify.annotations.NonNull;
18
19
import javax.annotation.Nullable;
20
21
public final class LivingEntityIdLookup
22
{
23
    // Track at most 1 millon entities
24
    private static final long MAXIMUM_CACHE_CAPACITY = 1 << 20;
25
    private static final int MINIMUM_CACHE_CAPACITY = 1 << 11;
26
    private static final long CACHE_TIME = 20L * 5L;
27
28
    public static final LivingEntityIdLookup INSTANCE = new LivingEntityIdLookup();
29
30
    private final Cache<Integer, EntityType> entityTypeCache = CacheBuilder.newBuilder().initialCapacity(MINIMUM_CACHE_CAPACITY).concurrencyLevel(2).maximumSize(MAXIMUM_CACHE_CAPACITY).build();
31
32
33
    private LivingEntityIdLookup()
34
    {
35
        PacketEvents.getAPI().getEventManager().registerListener(new PacketListenerAbstract()
36
        {
37
            @Override
38
            public void onPacketSend(@NonNull PacketSendEvent event)
39
            {
40
                if (event.getPacketType() == PacketType.Play.Server.SPAWN_LIVING_ENTITY) {
41
                    final WrapperPlayServerSpawnLivingEntity wrapper = new WrapperPlayServerSpawnLivingEntity(event);
42
                    cacheEntityId(wrapper.getEntityId(), wrapper.getEntityType());
43
                }
44
            }
45
        });
46
47
        // Do not immediately loop through all entities to cache them, as Bukkit may not have loaded all entities yet which leads to connection errors when players try to join.
48
        Bukkit.getScheduler().runTaskLater(AntiCheatAddition.getInstance(), this::cacheAllEntities, CACHE_TIME);
49
    }
50
51
    private void cacheAllEntities()
52
    {
53
        for (World world : Bukkit.getWorlds()) {
54
            for (LivingEntity entity : world.getLivingEntities()) cacheEntity(entity);
55
        }
56
    }
57
58
    private void cacheEntity(LivingEntity entity)
59
    {
60
        final int entityId = entity.getEntityId();
61
        final var entityType = SpigotConversionUtil.fromBukkitEntityType(entity.getType());
62
63
        if (entityType == null) {
64
            Log.fine(() -> "Attempted to cache null entityType: Entity ID " + entityId + " Raw type: " + entity.getType().name());
65
            return;
66
        }
67
68
        entityTypeCache.put(entityId, entityType);
69
    }
70
71
    public void cacheEntityId(int entityId, EntityType entityType)
72
    {
73
        if (entityType == null) {
74
            Log.fine(() -> "Attempted to cache null entityType: Entity ID " + entityId);
75
            return;
76
        }
77
78
        entityTypeCache.put(entityId, entityType);
79
    }
80
81
    /**
82
     * Gets the EntityType from a valid entityId of a living entity.
83
     */
84
    @Nullable
85
    public EntityType getEntityType(int entityId)
86
    {
87
        return entityTypeCache.getIfPresent(entityId);
88
    }
89
}

How it counteracts this module

Photon caches entity id to type from the S0C and S0F spawn sends (WrapperPlayServerSpawnPlayer and SPAWN_LIVING_ENTITY) in a time-bounded cache so its packet-rewriting modules can classify entities later. It is a server-side mirror of exactly the spawn stream the ESP reads client-side. The module neither sends nor rewrites spawn traffic, so the cache contents are identical to vanilla. The entry states plainly that the only spawn-stream machinery in the corpus is a lookup cache, which has no opinion about what the client renders.

← Back to Analysis Hub