Memeware 7.3 Tags module 2 files, 424 lines

Memeware 7.3 Tags: Full Source Analysis

A custom-nametag renderer: it cancels the vanilla nameplate render event and, each render frame, draws its own TTF tag above every non-invisible player at the interpolated position.

me/memewaredevs/client/module/render/Tags.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-10-14

Analysis

Overview

A custom-nametag renderer: it cancels the vanilla nameplate render event and, each render frame, draws its own TTF tag above every non-invisible player at the interpolated position. The positions come entirely from the entity stream the server already broadcast, S0CPacketSpawnPlayer (S0C) and S0FPacketSpawnMob (S0F) plus the entity-move packets, so the module emits no serverbound traffic.

Architecture

Two lwjeb consumers. The RenderPlayerNameEvent consumer cancels the vanilla label so only the custom tag draws; the Render3DEvent consumer walks mc.theWorld.playerEntities, skips invisible players, and for each survivor computes the interpolated position (lastTickPos blended toward posX/posY/posZ by the render tick factor, minus the render manager's offsets) and hands it to TagUtils.renderNametag. The module overrides onEnable/onDisable as no-ops, so all behavior is the two consumers.

What the tag draws

TagUtils.renderNametag builds a nameplate from the player's formatted display name with [F]/[C] badges for flying and creative players, a color-coded health percentage (green >75%, yellow >50%, orange >25%, red below), a distance-scaled background rectangle that stays a constant 8+ pixels even at range, and the player's equipped item plus armor icons. Sneaking shifts the label, and the whole thing is billboarded to the camera. It is a pure render-path replacement: every input is data the vanilla client already holds.

Detection surface

The nametag consumes spawn packets (S0C for players, S0F for mobs) and the entity-move stream that everyone receives. Nothing the module does changes what the server sees, so no anticheat check can fire on the rendering itself. The checks that matter are the ones policing the same entity-state stream server-side: entity replication ledgers (Grim), spawn/bookkeeping utilities (NCP), and interaction ray validation (Hawk). Together they mean knowing where players are (what Tags draws) confers no combat advantage the server will accept.

source Tags.java

Tags.java47 lines · JavaOriginal ↗
1
2
package me.memewaredevs.client.module.render;
3
4
import me.hippo.api.lwjeb.annotation.Handler;
5
import me.memewaredevs.client.event.events.Render3DEvent;
6
import me.memewaredevs.client.event.events.RenderPlayerNameEvent;
7
import me.memewaredevs.client.module.Module;
8
import me.memewaredevs.client.util.render.TagUtils;
9
import net.minecraft.client.renderer.entity.RenderManager;
10
import net.minecraft.entity.player.EntityPlayer;
11
12
import java.util.function.Consumer;
13
14
public class Tags extends Module {
15
    public Tags() {
16
        super("Better Tags", 0, Module.Category.RENDER);
17
    }
18
19
    @Handler
20
    public Consumer<Render3DEvent> update = e -> {
21
        for (final Object o : this.mc.theWorld.playerEntities) {
22
            final EntityPlayer player = (EntityPlayer) o;
23
            if (player.isInvisible())
24
                continue;
25
            final double x = player.lastTickPosX + (player.posX - player.lastTickPosX) * e.getRenderTick()
26
                    - RenderManager.renderPosX;
27
            final double y2 = player.lastTickPosY + (player.posY - player.lastTickPosY) * e.getRenderTick()
28
                    - RenderManager.renderPosY;
29
            final double z = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * e.getRenderTick()
30
                    - RenderManager.renderPosZ;
31
            TagUtils.renderNametag(player, x, y2, z);
32
        }
33
    };
34
35
    @Handler
36
    public Consumer<RenderPlayerNameEvent> update2 = e -> {
37
        e.cancel();
38
    };
39
40
    @Override
41
    public void onEnable() {
42
    }
43
44
    @Override
45
    public void onDisable() {
46
    }
47
}

What this file does

The module is the two consumers plus the no-op enable/disable pair. The update consumer interpolates every player's position each render frame (the lastTickPos-to-pos blend with e.getRenderTick() is the same interpolation the vanilla renderer uses, so the tag tracks the entity exactly) and skips isInvisible players because rendering over invisible entities would leak them visually. update2 cancels RenderPlayerNameEvent, Memeware's event for the vanilla label path, so the custom tag is the only one drawn.

source TagUtils.java (nametag renderer)

TagUtils.java377 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.memewaredevs.client.util.render;
8
9
import me.memewaredevs.altmanager.RenderUtil;
10
import me.memewaredevs.client.util.TTFFontRenderer;
11
import net.minecraft.client.Minecraft;
12
import net.minecraft.client.entity.EntityPlayerSP;
13
import net.minecraft.client.renderer.GlStateManager;
14
import net.minecraft.client.renderer.RenderHelper;
15
import net.minecraft.client.renderer.entity.RenderManager;
16
import net.minecraft.enchantment.Enchantment;
17
import net.minecraft.entity.player.EntityPlayer;
18
import net.minecraft.init.Items;
19
import net.minecraft.item.ItemArmor;
20
import net.minecraft.item.ItemStack;
21
import net.minecraft.item.ItemTool;
22
import net.minecraft.nbt.NBTTagList;
23
import org.lwjgl.opengl.GL11;
24
25
import java.awt.*;
26
import java.text.NumberFormat;
27
import java.util.ArrayList;
28
29
public class TagUtils {
30
	public static TTFFontRenderer mainFont;
31
32
	
33
    static Minecraft mc = Minecraft.getMinecraft();
34
35
    public static void renderNametag(final EntityPlayer player, final double x, final double y2, final double z) {
36
        double health;
37
        double percentage;
38
        String entityName = player.getDisplayName().getFormattedText();
39
        if (player == TagUtils.mc.thePlayer) {
40
            return;
41
        }
42
        if (player.isDead) {
43
            return;
44
        }
45
        if (player instanceof EntityPlayer && player.capabilities.isFlying) {
46
            entityName = "\u00a7a[F] \u00a7r" + entityName;
47
        }
48
        if (player instanceof EntityPlayer && player.capabilities.isCreativeMode) {
49
            entityName = "\u00148[C] \u00a7r" + entityName;
50
        }
51
        if (player.getDistanceToEntity(TagUtils.mc.thePlayer) >= 64.0f) {
52
            entityName = "\u00a7r" + entityName;
53
        }
54
        final String healthColor = (percentage = 100.0
55
                * ((health = (int) player.getHealth()) / (player.getMaxHealth() / 2.0f))) > 75.0 ? "2"
56
                : percentage > 50.0 ? "e" : percentage > 25.0 ? "6" : "4";
57
        final String healthDisplay = String.valueOf(health);
58
        entityName = String.format("%s \u00a7%s %s", entityName, healthColor, healthDisplay);
59
        final float distance = TagUtils.mc.thePlayer.getDistanceToEntity(player);
60
        final float var13 = (distance / 5.0f <= 2.0f ? 2.0f : distance / 5.0f) * 0.95f;
61
        final float var14 = 0.016666668f * var13;
62
        GlStateManager.pushMatrix();
63
        RenderHelper.enableStandardItemLighting();
64
        GlStateManager.translate(x + 0.0, y2 + player.height + 0.5, z);
65
        GL11.glNormal3f(0.0f, 1.0f, 0.0f);
66
        if (TagUtils.mc.gameSettings.thirdPersonView == 2) {
67
            mc.getRenderManager();
68
            GlStateManager.rotate(-RenderManager.playerViewY, 0.0f, 1.0f, 0.0f);
69
            mc.getRenderManager();
70
            GlStateManager.rotate(RenderManager.playerViewX, -1.0f, 0.0f, 0.0f);
71
        } else {
72
            mc.getRenderManager();
73
            GlStateManager.rotate(-RenderManager.playerViewY, 0.0f, 1.0f, 0.0f);
74
            mc.getRenderManager();
75
            GlStateManager.rotate(RenderManager.playerViewX, 1.0f, 0.0f, 0.0f);
76
        }
77
        GlStateManager.scale(-var14, -var14, var14);
78
        GlStateManager.disableLighting();
79
        GlStateManager.depthMask(false);
80
        GlStateManager.disableDepth();
81
        GlStateManager.enableBlend();
82
        GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
83
        int var15 = 0;
84
        if (player.isSneaking()) {
85
            var15 += 4;
86
        }
87
        if ((var15 -= (int) (distance / 5.0f)) < -8) {
88
            var15 = -8;
89
        }
90
        GlStateManager.func_179090_x();
91
        final int var16 = TagUtils.mc.fontRendererObj.getStringWidth(entityName) / 2;
92
        RenderUtil.rectangle(-var16 - 3, var15 - 3, var16 + 3, var15 + 10, new Color(32, 32, 33, 120).getRGB());
93
//		RenderUtil.drawBoundingBox(player.boundingBox;
94
        GlStateManager.func_179098_w();
95
        TagUtils.mc.fontRendererObj.func_175065_a(entityName, -var16, var15, -1, true);
96
        if (player instanceof EntityPlayer) {
97
            final ArrayList<ItemStack> items = new ArrayList<>();
98
            if (player.getCurrentEquippedItem() != null) {
99
                items.add(player.getCurrentEquippedItem());
100
            }
101
            for (int index = 3; index >= 0; --index) {
102
                final ItemStack stack = player.inventory.armorInventory[index];
103
                if (stack == null) {
104
                    continue;
105
                }
106
                items.add(stack);
107
            }
108
            final int offset = var16 - (items.size() - 1) * 9 - 9;
109
            int xPos = 0;
110
            for (final ItemStack stack2 : items) {
111
                GlStateManager.pushMatrix();
112
                RenderHelper.enableStandardItemLighting();
113
                TagUtils.mc.getRenderItem().zLevel = -100.0f;
114
                mc.getRenderItem().func_175042_a(stack2, -var16 + offset + xPos, var15 - 20);
115
                mc.getRenderItem().func_175030_a(TagUtils.mc.fontRendererObj, stack2, -var16 + offset + xPos,
116
                        var15 - 20);
117
                TagUtils.mc.getRenderItem().zLevel = 0.0f;
118
                RenderHelper.disableStandardItemLighting();
119
                GlStateManager.enableAlpha();
120
                GlStateManager.disableBlend();
121
                GlStateManager.disableLighting();
122
                GlStateManager.popMatrix();
123
                GlStateManager.pushMatrix();
124
                GlStateManager.disableLighting();
125
                GlStateManager.depthMask(false);
126
                GlStateManager.disableDepth();
127
                GlStateManager.scale(0.5f, 0.5f, 0.5f);
128
                if (stack2.getItem() == Items.golden_apple && stack2.hasEffect()) {
129
                    TagUtils.mc.fontRendererObj.drawStringWithShadow("god", (-var16 + offset + xPos) * 2,
130
                            (var15 - 20) * 2, -65536);
131
                } else {
132
                    final NBTTagList enchants = stack2.getEnchantmentTagList();
133
                    if (enchants != null) {
134
                        int encY = 0;
135
                        final Enchantment[] important = new Enchantment[]{Enchantment.field_180310_c,
136
                                Enchantment.unbreaking, Enchantment.field_180314_l, Enchantment.fireAspect,
137
                                Enchantment.efficiency, Enchantment.field_180309_e, Enchantment.power,
138
                                Enchantment.flame, Enchantment.punch, Enchantment.fortune, Enchantment.infinity,
139
                                Enchantment.thorns};
140
                        if (enchants.tagCount() >= 6) {
141
                            TagUtils.mc.fontRendererObj.drawStringWithShadow("god", (-var16 + offset + xPos) * 2,
142
                                    (var15 - 20) * 2, -65536);
143
                        } else {
144
                            block2:
145
                            for (int index2 = 0; index2 < enchants.tagCount(); ++index2) {
146
                                final short id = enchants.getCompoundTagAt(index2).getShort("id");
147
                                final short level = enchants.getCompoundTagAt(index2).getShort("lvl");
148
                                final Enchantment enc = Enchantment.func_180306_c(id);
149
                                if (enc == null) {
150
                                    continue;
151
                                }
152
                                for (final Enchantment importantEnchantment : important) {
153
                                    if (enc != importantEnchantment) {
154
                                        continue;
155
                                    }
156
                                    String encName = enc.getTranslatedName(level).substring(0, 1).toLowerCase();
157
                                    encName = level > 99
158
                                            ? String.valueOf(String.valueOf(String.valueOf(encName))) + "99+"
159
                                            : String.valueOf(String.valueOf(String.valueOf(encName))) + level;
160
                                    TagUtils.mc.fontRendererObj.drawStringWithShadow(encName,
161
                                            (-var16 + offset + xPos) * 2, (var15 - 20 + encY) * 2, -5592406);
162
                                    encY += 5;
163
                                    continue block2;
164
                                }
165
                            }
166
                        }
167
                    }
168
                }
169
                GlStateManager.enableLighting();
170
                GlStateManager.popMatrix();
171
                xPos += 18;
172
            }
173
        }
174
        GlStateManager.enableDepth();
175
        GlStateManager.depthMask(true);
176
        GlStateManager.enableLighting();
177
        GlStateManager.disableBlend();
178
        GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
179
        RenderHelper.disableStandardItemLighting();
180
        GlStateManager.popMatrix();
181
    }
182
183
    public static Color blendColors(final float[] fractions, final Color[] colors, final float progress) {
184
        Color color = null;
185
        if (fractions == null) {
186
            throw new IllegalArgumentException("Fractions can't be null");
187
        }
188
        if (colors == null) {
189
            throw new IllegalArgumentException("Colours can't be null");
190
        }
191
        if (fractions.length == colors.length) {
192
            final int[] indicies = TagUtils.getFractionIndicies(fractions, progress);
193
            final float[] range = new float[]{fractions[indicies[0]], fractions[indicies[1]]};
194
            final Color[] colorRange = new Color[]{colors[indicies[0]], colors[indicies[1]]};
195
            final float max = range[1] - range[0];
196
            final float value = progress - range[0];
197
            final float weight = value / max;
198
            color = TagUtils.blend(colorRange[0], colorRange[1], 1.0f - weight);
199
            return color;
200
        }
201
        throw new IllegalArgumentException("Fractions and colours must have equal number of elements");
202
    }
203
204
    public static int[] getFractionIndicies(final float[] fractions, final float progress) {
205
        int startPoint;
206
        final int[] range = new int[2];
207
        for (startPoint = 0; startPoint < fractions.length && fractions[startPoint] <= progress; ++startPoint) {
208
        }
209
        if (startPoint >= fractions.length) {
210
            startPoint = fractions.length - 1;
211
        }
212
        range[0] = startPoint - 1;
213
        range[1] = startPoint;
214
        return range;
215
    }
216
217
    public static Color blend(final Color color1, final Color color2, final double ratio) {
218
        final float r = (float) ratio;
219
        final float ir = 1.0f - r;
220
        final float[] rgb1 = new float[3];
221
        final float[] rgb2 = new float[3];
222
        color1.getColorComponents(rgb1);
223
        color2.getColorComponents(rgb2);
224
        float red = rgb1[0] * r + rgb2[0] * ir;
225
        float green = rgb1[1] * r + rgb2[1] * ir;
226
        float blue = rgb1[2] * r + rgb2[2] * ir;
227
        if (red < 0.0f) {
228
            red = 0.0f;
229
        } else if (red > 255.0f) {
230
            red = 255.0f;
231
        }
232
        if (green < 0.0f) {
233
            green = 0.0f;
234
        } else if (green > 255.0f) {
235
            green = 255.0f;
236
        }
237
        if (blue < 0.0f) {
238
            blue = 0.0f;
239
        } else if (blue > 255.0f) {
240
            blue = 255.0f;
241
        }
242
        Color color3 = null;
243
        try {
244
            color3 = new Color(red, green, blue);
245
        } catch (final IllegalArgumentException exp) {
246
            final NumberFormat nf = NumberFormat.getNumberInstance();
247
            System.out.println(
248
                    String.valueOf(String.valueOf(nf.format(red))) + "; " + nf.format(green) + "; " + nf.format(blue));
249
            exp.printStackTrace();
250
        }
251
        return color3;
252
    }
253
254
    public static void renderArmor(final EntityPlayer player) {
255
        int xOffset = 0;
256
        for (final ItemStack armourStack : player.inventory.armorInventory) {
257
            if (armourStack == null) {
258
                continue;
259
            }
260
            xOffset -= 8;
261
        }
262
        if (player.getHeldItem() != null) {
263
            xOffset -= 8;
264
            final ItemStack stock = player.getHeldItem().copy();
265
            if (stock.hasEffect() && (stock.getItem() instanceof ItemTool || stock.getItem() instanceof ItemArmor)) {
266
                stock.stackSize = 1;
267
            }
268
            TagUtils.renderItemStack(stock, xOffset, -20);
269
            xOffset += 16;
270
        }
271
        final ItemStack[] renderStack = player.inventory.armorInventory;
272
        for (int index = 3; index >= 0; --index) {
273
            final ItemStack armourStack2 = renderStack[index];
274
            if (armourStack2 == null) {
275
                continue;
276
            }
277
            final ItemStack renderStack2 = armourStack2;
278
            TagUtils.renderItemStack(renderStack2, xOffset, -20);
279
            xOffset += 16;
280
        }
281
    }
282
283
    private static int XD(final EntityPlayer e) {
284
        final int health = Math.round(20.0f * (e.getHealth() / e.getMaxHealth()));
285
        int color = 0;
286
        switch (health) {
287
            case 18:
288
            case 19: {
289
                color = 9108247;
290
                break;
291
            }
292
            case 16:
293
            case 17: {
294
                color = 10026904;
295
                break;
296
            }
297
            case 14:
298
            case 15: {
299
                color = 12844472;
300
                break;
301
            }
302
            case 12:
303
            case 13: {
304
                color = 16633879;
305
                break;
306
            }
307
            case 10:
308
            case 11: {
309
                color = 15313687;
310
                break;
311
            }
312
            case 8:
313
            case 9: {
314
                color = 16285719;
315
                break;
316
            }
317
            case 6:
318
            case 7: {
319
                color = 16286040;
320
                break;
321
            }
322
            case 4:
323
            case 5: {
324
                color = 15031100;
325
                break;
326
            }
327
            case 2:
328
            case 3: {
329
                color = 16711680;
330
                break;
331
            }
332
            case -1:
333
            case 0:
334
            case 1: {
335
                color = 16190746;
336
                break;
337
            }
338
            default: {
339
                color = -11746281;
340
            }
341
        }
342
        return color;
343
    }
344
345
    private static String getHealth(final EntityPlayer e) {
346
        String hp = "";
347
        final double health = 10.0 * (e.getHealth() / e.getMaxHealth());
348
        hp = Math.floor(health) == health ? String.valueOf((int) health) : String.valueOf(health);
349
        return hp;
350
    }
351
352
    private static float getSize(final EntityPlayer player) {
353
        final EntityPlayerSP ent = TagUtils.mc.thePlayer;
354
        final double dist = ent.getDistanceToEntity(player) / 5.0f;
355
        final float size = dist <= 2.0 ? 1.3f : (float) dist;
356
        return size;
357
    }
358
359
    private static void renderItemStack(final ItemStack stack, final int x, final int y2) {
360
        GlStateManager.pushMatrix();
361
        GlStateManager.disableAlpha();
362
        GlStateManager.clear(256);
363
        TagUtils.mc.getRenderItem().zLevel = -150.0f;
364
        mc.getRenderItem().func_180450_b(stack, x, y2);
365
        mc.getRenderItem().func_175030_a(TagUtils.mc.fontRendererObj, stack, x, y2);
366
        TagUtils.mc.getRenderItem().zLevel = 0.0f;
367
        GlStateManager.disableBlend();
368
        GlStateManager.scale(0.5, 0.5, 0.5);
369
        GlStateManager.disableDepth();
370
        GlStateManager.disableLighting();
371
        GlStateManager.enableLighting();
372
        GlStateManager.enableDepth();
373
        GlStateManager.scale(2.0f, 2.0f, 2.0f);
374
        GlStateManager.enableAlpha();
375
        GlStateManager.popMatrix();
376
    }
377
}

What this file does

The renderer behind the module. renderNametag guards against the local player and dead entities, decorates the display name ([F] flight, [C] creative, plain at 64+ blocks), appends the health percentage with its color, then sets up a billboarded GL matrix (camera rotation from RenderManager, distance-scaled font size via the /5.0f clamp), draws a translucent background rectangle, renders the name string, and finally draws the equipped item plus the four armor slots as icons in a row. It reads only the player's entity state and the render manager's camera, with no world queries or packets, which is why the whole feature is confined to the client's render thread.

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 (entity state handler)

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's server-side tracker for every entity packet: it consumes spawn, teleport, relative-move, rotation, metadata, effect, and equipment packets and maintains a PacketEntity model (positions, poses, attributes) that the reach and hitbox checks query when validating interactions. The spawn packets that seed a player's entity entry server-side are the same S0C/S0F packets whose data Tags reads client-side to draw its labels. Honest note: Tags is a pure consumer of that replicated state. It never sends anything, so its drawing cannot diverge from Grim's model. The check is the closest real handler of the exact packet stream the module reads, and it demonstrates why entity ESP is harmless to Grim: the AC knows precisely where every entity is, from the same broadcast.

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 own the server-side bookkeeping of spawn and respawn: world-spawn locations are exempted from certain position validations, and join/respawn positions feed the setback anchor logic that MovingListener consults to reset tracking after a spawn teleport. Honest note: this is the server-side counterpart of the spawn events that seed the client's entity list, the same event stream (S0C spawn, S08 teleport) whose results Tags interpolates into nametag positions. The connection is infrastructural: NCP canonicalizes where players are when they spawn so all downstream checks share one truth, while the module merely draws from the client's copy of that truth.

anticheat EntityInteractDirection (server ray validation)

EntityInteractDirection.java95 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk.check.interaction.entity;
20
21
import me.islandscout.hawk.HawkPlayer;
22
import me.islandscout.hawk.check.EntityInteractionCheck;
23
import me.islandscout.hawk.event.InteractEntityEvent;
24
import me.islandscout.hawk.util.*;
25
import me.islandscout.hawk.wrap.entity.WrappedEntity;
26
import org.bukkit.Location;
27
import org.bukkit.entity.Entity;
28
import org.bukkit.entity.Player;
29
import org.bukkit.util.Vector;
30
31
public class EntityInteractDirection extends EntityInteractionCheck {
32
33
    private final int PING_LIMIT;
34
    private final boolean LAG_COMPENSATION;
35
    private final boolean CHECK_OTHER_ENTITIES;
36
    private final double BOX_EXPAND;
37
38
    public EntityInteractDirection() {
39
        super("entityinteractdirection", true, 0, 10, 0.9, 5000, "%player% failed entity interact direction, VL: %vl%", null);
40
        PING_LIMIT = (int) customSetting("pingLimit", "", -1);
41
        LAG_COMPENSATION = (boolean) customSetting("lagCompensation", "", true);
42
        CHECK_OTHER_ENTITIES = (boolean) customSetting("checkOtherEntities", "", true);
43
        BOX_EXPAND = (double) customSetting("boxExpand", "", 0.2);
44
    }
45
46
    @Override
47
    protected void check(InteractEntityEvent e) {
48
        Player p = e.getPlayer();
49
        HawkPlayer pp = e.getHawkPlayer();
50
        Entity victimEntity = e.getEntity();
51
        if (!(victimEntity instanceof Player) && !CHECK_OTHER_ENTITIES)
52
            return;
53
        int ping = ServerUtils.getPing(e.getPlayer());
54
        if (PING_LIMIT > -1 && ping > PING_LIMIT)
55
            return;
56
        Vector pos;
57
        if(pp.isInVehicle()) {
58
            pos = hawk.getLagCompensator().getHistoryLocation(ping, p).toVector();
59
            pos.setY(pos.getY() + p.getEyeHeight());
60
        }
61
        else {
62
            pos = pp.getHeadPosition();
63
        }
64
        //As I always say in math class, converting polar coordinates to rectangular coordinates is a pain in
65
        //the ass. If you want to use the previous direction vector, you cannot make an accurate cut through the AABB
66
        //using only the previous and extrapolated direction vectors. You'd think you could since the extrapolation
67
        //on yaw and pitch is linear, but the current direction vector won't lie between the other two. Remember Non-
68
        //Euclidean geometry!
69
        Vector dir = MathPlus.getDirection(pp.getYaw(), pp.getPitch());
70
        //Note: in MC 1.8, the cursor yaw is not updated per frame, but rather per tick.
71
        //For ray-hitbox checks, this means that we do not need to extrapolate the yaw,
72
        //but for this check it does not matter whether we do it or not.
73
        Vector extraDir = MathPlus.getDirection(pp.getYaw() + pp.getDeltaYaw(), pp.getPitch() + pp.getDeltaPitch());
74
75
        Location victimLoc;
76
        if(LAG_COMPENSATION)
77
            victimLoc = hawk.getLagCompensator().getHistoryLocation(ping, victimEntity);
78
        else
79
            victimLoc = e.getEntity().getLocation();
80
81
        AABB victimAABB = WrappedEntity.getWrappedEntity(e.getEntity()).getHitbox(victimLoc.toVector());
82
        victimAABB.expand(BOX_EXPAND, BOX_EXPAND, BOX_EXPAND);
83
84
        //this is a crappy workaround to one of the issues with AABB#betweenRays. I'll keep this here until it is rewritten.
85
        Vector toVictim = victimLoc.toVector().setY(0).subtract(pos.clone().setY(0));
86
        boolean behind = toVictim.clone().normalize().dot(dir.clone().setY(0).normalize()) < 0 && toVictim.lengthSquared() > victimAABB.getMax().clone().setY(0).subtract(victimAABB.getMin().clone().setY(0)).lengthSquared();
87
88
        if(victimAABB.betweenRays(pos, dir, extraDir) && !behind) {
89
            reward(pp);
90
        }
91
        else {
92
            punish(pp, true, e);
93
        }
94
    }
95
}

How it counteracts this module

Hawk's interaction check replays the player's look ray against the victim entity's bounding box whenever the player attacks or interacts, with ping-based lag compensation and a configurable ping limit, and flags interactions whose direction does not intersect the victim ('failed entity interact direction'). This is the direct answer to the combat use-case of entity ESP: knowing where players are, which is precisely what Tags renders, does not help land hits, because the server validates that the client's actual look ray geometrically hit the entity's box at the lag-compensated position. Honest note: the module is still invisible to the check (it sends no interaction packets), but the check is the real enforcement that makes the module's information useless for combat.

← Back to Analysis Hub